diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..e1a5ddd00 --- /dev/null +++ b/.clang-format @@ -0,0 +1,73 @@ +--- +AlignAfterOpenBracket: AlwaysBreak +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignConsecutiveMacros: false +AlignEscapedNewlines: DontAlign +AlignOperands: false +AlignTrailingComments: false +AllowAllArgumentsOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLambdasOnASingleLine: Inline +AllowShortLoopsOnASingleLine: false +AlwaysBreakBeforeMultilineStrings: true +BinPackArguments: false +BinPackParameters: false +BreakBeforeBraces: Allman +BreakBeforeTernaryOperators: false +BreakStringLiterals: false +ColumnLimit: 128 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +ExperimentalAutoDetectBinPacking: false +IndentCaseBlocks: true +IndentPPDirectives: None +IndentWidth: 4 +MaxEmptyLinesToKeep: 1 +PenaltyBreakAssignment: 1000 +PenaltyBreakBeforeFirstCallParameter: 0 +PenaltyReturnTypeOnItsOwnLine: 1000 +PointerAlignment: Left +ReflowComments: false +SortIncludes: false +SpaceAfterCStyleCast: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +TabWidth: 4 +UseTab: Never +--- +Language: Cpp +Standard: c++17 + +AccessModifierOffset: -4 +AllowAllConstructorInitializersOnNextLine: false +AlwaysBreakAfterReturnType: None +AlwaysBreakTemplateDeclarations: Yes +BreakConstructorInitializers: BeforeComma +BreakInheritanceList: BeforeComma +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +FixNamespaceComments: true +IndentGotoLabels: false +KeepEmptyLinesAtTheStartOfBlocks: true +SortUsingDeclarations: true +SpaceAfterTemplateKeyword: false +StatementMacros: +- TR_DEFINE_QUARK +WhitespaceSensitiveMacros: +- API_HEADER +- API_HEADER_CRYPT +--- +Language: ObjC + +KeepEmptyLinesAtTheStartOfBlocks: false +ObjCBlockIndentWidth: 4 +ObjCBreakBeforeNestedBlockParam: false +ObjCSpaceBeforeProtocolList: false +PenaltyExcessCharacter: 1 diff --git a/cli/cli.c b/cli/cli.c index 35431fbdd..0fbeb8a44 100644 --- a/cli/cli.c +++ b/cli/cli.c @@ -45,14 +45,14 @@ #define MEM_T_STR "TiB" #define DISK_K 1000 -#define DISK_B_STR "B" +#define DISK_B_STR "B" #define DISK_K_STR "kB" #define DISK_M_STR "MB" #define DISK_G_STR "GB" #define DISK_T_STR "TB" #define SPEED_K 1000 -#define SPEED_B_STR "B/s" +#define SPEED_B_STR "B/s" #define SPEED_K_STR "kB/s" #define SPEED_M_STR "MB/s" #define SPEED_G_STR "GB/s" @@ -73,11 +73,10 @@ static sig_atomic_t manualUpdate = false; static char const* torrentPath = NULL; -static struct tr_option const options[] = -{ +static struct tr_option const options[] = { { 'b', "blocklist", "Enable peer blocklists", "b", false, NULL }, { 'B', "no-blocklist", "Disable peer blocklists", "B", false, NULL }, - { 'd', "downlimit", "Set max download speed in "SPEED_K_STR, "d", true, "" }, + { 'd', "downlimit", "Set max download speed in " SPEED_K_STR, "d", true, "" }, { 'D', "no-downlimit", "Don't limit the download speed", "D", false, NULL }, { 910, "encryption-required", "Encrypt all peer connections", "er", false, NULL }, { 911, "encryption-preferred", "Prefer encrypted peer connections", "ep", false, NULL }, @@ -88,7 +87,7 @@ static struct tr_option const options[] = { 'M', "no-portmap", "Disable portmapping", "M", false, NULL }, { 'p', "port", "Port for incoming peers (Default: " TR_DEFAULT_PEER_PORT_STR ")", "p", true, "" }, { 't', "tos", "Peer socket TOS (0 to 255, default=" TR_DEFAULT_PEER_SOCKET_TOS_STR ")", "t", true, "" }, - { 'u', "uplimit", "Set max upload speed in "SPEED_K_STR, "u", true, "" }, + { 'u', "uplimit", "Set max upload speed in " SPEED_K_STR, "u", true, "" }, { 'U', "no-uplimit", "Don't limit the upload speed", "U", false, NULL }, { 'v', "verify", "Verify the specified torrent", "v", false, NULL }, { 'V', "version", "Show version number and exit", "V", false, NULL }, @@ -98,9 +97,12 @@ static struct tr_option const options[] = static char const* getUsage(void) { - return "A fast and easy BitTorrent client\n" + // clang-format off + return + "A fast and easy BitTorrent client\n" "\n" "Usage: " MY_READABLE_NAME " [options] "; + // clang-format on } static int parseCommandLine(tr_variant*, int argc, char const** argv); @@ -135,8 +137,14 @@ static char* tr_strlratio(char* buf, double ratio, size_t buflen) static bool waitingOnWeb; -static void onTorrentFileDownloaded(tr_session* session, bool did_connect, bool did_timeout, long response_code, - void const* response, size_t response_byte_count, void* ctor) +static void onTorrentFileDownloaded( + tr_session* session, + bool did_connect, + bool did_timeout, + long response_code, + void const* response, + size_t response_byte_count, + void* ctor) { TR_UNUSED(session); TR_UNUSED(did_connect); @@ -155,7 +163,11 @@ static void getStatusStr(tr_stat const* st, char* buf, size_t buflen) } else if (st->activity == TR_STATUS_CHECK) { - tr_snprintf(buf, buflen, "Verifying local files (%.2f%%, %.2f%% valid)", tr_truncd(100 * st->recheckProgress, 2), + tr_snprintf( + buf, + buflen, + "Verifying local files (%.2f%%, %.2f%% valid)", + tr_truncd(100 * st->recheckProgress, 2), tr_truncd(100 * st->percentDone, 2)); } else if (st->activity == TR_STATUS_DOWNLOAD) @@ -168,8 +180,16 @@ static void getStatusStr(tr_stat const* st, char* buf, size_t buflen) tr_formatter_speed_KBps(dnStr, st->pieceDownloadSpeed_KBps, sizeof(dnStr)); tr_strlratio(ratioStr, st->ratio, sizeof(ratioStr)); - tr_snprintf(buf, buflen, "Progress: %.1f%%, dl from %d of %d peers (%s), ul to %d (%s) [%s]", - tr_truncd(100 * st->percentDone, 1), st->peersSendingToUs, st->peersConnected, dnStr, st->peersGettingFromUs, upStr, + tr_snprintf( + buf, + buflen, + "Progress: %.1f%%, dl from %d of %d peers (%s), ul to %d (%s) [%s]", + tr_truncd(100 * st->percentDone, 1), + st->peersSendingToUs, + st->peersConnected, + dnStr, + st->peersGettingFromUs, + upStr, ratioStr); } else if (st->activity == TR_STATUS_SEED) @@ -180,8 +200,14 @@ static void getStatusStr(tr_stat const* st, char* buf, size_t buflen) tr_formatter_speed_KBps(upStr, st->pieceUploadSpeed_KBps, sizeof(upStr)); tr_strlratio(ratioStr, st->ratio, sizeof(ratioStr)); - tr_snprintf(buf, buflen, "Seeding, uploading to %d of %d peer(s), %s [%s]", st->peersGettingFromUs, st->peersConnected, - upStr, ratioStr); + tr_snprintf( + buf, + buflen, + "Seeding, uploading to %d of %d peer(s), %s [%s]", + st->peersGettingFromUs, + st->peersConnected, + upStr, + ratioStr); } else { @@ -262,8 +288,7 @@ int tr_main(int argc, char* argv[]) return EXIT_FAILURE; } - if (tr_variantDictFindStr(&settings, TR_KEY_download_dir, &str, NULL) && - !tr_sys_path_exists(str, NULL)) + if (tr_variantDictFindStr(&settings, TR_KEY_download_dir, &str, NULL) && !tr_sys_path_exists(str, NULL)) { tr_error* error = NULL; @@ -337,12 +362,11 @@ int tr_main(int argc, char* argv[]) { char line[LINEWIDTH]; tr_stat const* st; - char const* messageName[] = - { + char const* messageName[] = { NULL, "Tracker gave a warning:", "Tracker gave an error:", - "Error:" + "Error:", }; tr_wait_msec(200); @@ -377,7 +401,7 @@ int tr_main(int argc, char* argv[]) } getStatusStr(st, line, sizeof(line)); - printf("\r%-*s", LINEWIDTH, line); + printf("\r%-*s", TR_ARG_TUPLE(LINEWIDTH, line)); if (messageName[st->error]) { diff --git a/code_style.sh b/code_style.sh index 699f8b909..5e3205081 100755 --- a/code_style.sh +++ b/code_style.sh @@ -3,70 +3,69 @@ # Usage: ./code_style.sh # Usage: ./code_style.sh --check +set -o noglob + if [[ "x$1" == *"check"* ]]; then echo "checking code format" else fix=1 fi -root="$(git rev-parse --show-toplevel)" -if [ -n "${root}" ]; then - cd "${root}" || exit 1 -fi +root="$(dirname "$0")" +root="$(cd "${root}" && pwd)" +cd "${root}" || exit 1 -skipfiles=( - libtransmission/ConvertUTF\.[ch] - libtransmission/jsonsl\.[ch] - libtransmission/wildmat\.c +cfile_includes=( + '*.c' + '*.cc' + '*.h' + '*.m' ) -cfile_candidates=( - cli/*\.[ch] - daemon/*\.[ch] - gtk/*\.[ch] - libtransmission/*\.[ch] - qt/*\.cc - qt/*\.h - tests/*/*\.cc - tests/*/*\.h - utils/*\.[ch] +cfile_excludes=( + 'libtransmission/ConvertUTF.*' + 'libtransmission/jsonsl.*' + 'libtransmission/wildmat.*' + 'macosx/Sparkle.framework/*' + 'macosx/VDKQueue/*' + 'third-party/*' + 'web/*' ) -for file in "${cfile_candidates[@]}"; do - if [[ ! " ${skipfiles[*]} " =~ ${file} ]]; then - cfiles+=("${file}"); - fi -done + +get_find_path_args() { + local args=$(printf " -o -path ./%s" "$@") + echo "${args:4}" +} + +find_cfiles() { + find . \( $(get_find_path_args "${cfile_includes[@]}") \) ! \( $(get_find_path_args "${cfile_excludes[@]}") \) "$@" +} # format C/C++ -cores=$(($(nproc) + 1)) -if [ -n "$fix" ]; then - printf "%s\0" "${cfiles[@]}" | xargs -0 -P$cores -I FILE uncrustify -c uncrustify.cfg --no-backup -q FILE -else - printf "%s\0" "${cfiles[@]}" | xargs -0 -P$cores -I FILE uncrustify -c uncrustify.cfg --check FILE > /dev/null - if [ "${PIPESTATUS[1]}" -ne "0" ]; then - echo 'C/C++ code needs formatting' - exitcode=1 - fi +clang_format_args="$([ -n "$fix" ] && echo '-i' || echo '--dry-run --Werror')" +if ! find_cfiles -exec clang-format $clang_format_args '{}' '+'; then + [ -n "$fix" ] || echo 'C/C++ code needs formatting' + exitcode=1 fi # enforce east const -matches="$(perl -ne 'print "west const:",$ARGV,":",$_ if /((?:^|[(,;]|\bstatic\s+)\s*)\b(const)\b(?!\s+\w+\s*\[)/' "${cfiles[@]}")" +matches="$(find_cfiles -exec perl -ne 'print "west const:",$ARGV,":",$_ if /((?:^|[(,;]|\bstatic\s+)\s*)\b(const)\b(?!\s+\w+\s*\[)/' '{}' '+')" if [ -n "$matches" ]; then echo "$matches" exitcode=1 fi if [ -n "$fix" ]; then - perl -pi -e 's/((?:^|[(,;]|\bstatic\s+)\s*)\b(const)\b(?!\s+\w+\s*\[)/\1>\2\2" }, { 'b', "blocklist", "Enable peer blocklists", "b", false, NULL }, { 'B', "no-blocklist", "Disable peer blocklists", "B", false, NULL }, @@ -134,20 +136,36 @@ static struct tr_option const options[] = { 'P', "peerport", "Port for incoming peers (Default: " TR_DEFAULT_PEER_PORT_STR ")", "P", true, "" }, { 'm', "portmap", "Enable portmapping via NAT-PMP or UPnP", "m", false, NULL }, { 'M', "no-portmap", "Disable portmapping", "M", false, NULL }, - { 'L', "peerlimit-global", "Maximum overall number of peers (Default: " TR_DEFAULT_PEER_LIMIT_GLOBAL_STR ")", "L", true, - "" }, - { 'l', "peerlimit-torrent", "Maximum number of peers per torrent (Default: " TR_DEFAULT_PEER_LIMIT_TORRENT_STR ")", "l", - true, "" }, + { 'L', + "peerlimit-global", + "Maximum overall number of peers (Default: " TR_DEFAULT_PEER_LIMIT_GLOBAL_STR ")", + "L", + true, + "" }, + { 'l', + "peerlimit-torrent", + "Maximum number of peers per torrent (Default: " TR_DEFAULT_PEER_LIMIT_TORRENT_STR ")", + "l", + true, + "" }, { 910, "encryption-required", "Encrypt all peer connections", "er", false, NULL }, { 911, "encryption-preferred", "Prefer encrypted peer connections", "ep", false, NULL }, { 912, "encryption-tolerated", "Prefer unencrypted peer connections", "et", false, NULL }, { 'i', "bind-address-ipv4", "Where to listen for peer connections", "i", true, "" }, { 'I', "bind-address-ipv6", "Where to listen for peer connections", "I", true, "" }, { 'r', "rpc-bind-address", "Where to listen for RPC connections", "r", true, "" }, - { 953, "global-seedratio", "All torrents, unless overridden by a per-torrent setting, should seed until a specific ratio", - "gsr", true, "ratio" }, - { 954, "no-global-seedratio", "All torrents, unless overridden by a per-torrent setting, should seed regardless of ratio", - "GSR", false, NULL }, + { 953, + "global-seedratio", + "All torrents, unless overridden by a per-torrent setting, should seed until a specific ratio", + "gsr", + true, + "ratio" }, + { 954, + "no-global-seedratio", + "All torrents, unless overridden by a per-torrent setting, should seed regardless of ratio", + "GSR", + false, + NULL }, { 'x', "pid-file", "Enable PID file", "x", true, "" }, { 0, NULL, NULL, NULL, false, NULL } }; @@ -156,8 +174,11 @@ static bool reopen_log_file(char const* filename) { tr_error* error = NULL; tr_sys_file_t const old_log_file = logfile; - tr_sys_file_t const new_log_file = tr_sys_file_open(filename, TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_APPEND, - 0666, &error); + tr_sys_file_t const new_log_file = tr_sys_file_open( + filename, + TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_APPEND, + 0666, + &error); if (new_log_file == TR_BAD_SYS_FILE) { @@ -359,7 +380,10 @@ static void periodicUpdate(evutil_socket_t fd, short what, void* context) reportStatus(); } -static tr_rpc_callback_status on_rpc_callback(tr_session* session, tr_rpc_callback_type type, struct tr_torrent* tor, +static tr_rpc_callback_status on_rpc_callback( + tr_session* session, + tr_rpc_callback_type type, + struct tr_torrent* tor, void* user_data) { TR_UNUSED(session); @@ -374,7 +398,13 @@ static tr_rpc_callback_status on_rpc_callback(tr_session* session, tr_rpc_callba return TR_RPC_OK; } -static bool parse_args(int argc, char const** argv, tr_variant* settings, bool* paused, bool* dump_settings, bool* foreground, +static bool parse_args( + int argc, + char const** argv, + tr_variant* settings, + bool* paused, + bool* dump_settings, + bool* foreground, int* exit_code) { int c; @@ -668,7 +698,10 @@ static int daemon_start(void* raw_arg, bool foreground) if (!tr_str_is_empty(pid_filename)) { tr_error* error = NULL; - tr_sys_file_t fp = tr_sys_file_open(pid_filename, TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE, 0666, + tr_sys_file_t fp = tr_sys_file_open( + pid_filename, + TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE, + 0666, &error); if (fp != TR_BAD_SYS_FILE) @@ -872,8 +905,7 @@ int tr_main(int argc, char* argv[]) return ret; } - dtr_callbacks const cb = - { + dtr_callbacks const cb = { .on_start = &daemon_start, .on_stop = &daemon_stop, .on_reconfigure = &daemon_reconfigure, diff --git a/daemon/daemon.h b/daemon/daemon.h index b6f9f096c..554e4dfe6 100644 --- a/daemon/daemon.h +++ b/daemon/daemon.h @@ -12,10 +12,9 @@ struct tr_error; typedef struct dtr_callbacks { - int (* on_start)(void* arg, bool foreground); - void (* on_stop)(void* arg); - void (* on_reconfigure)(void* arg); -} -dtr_callbacks; + int (*on_start)(void* arg, bool foreground); + void (*on_stop)(void* arg); + void (*on_reconfigure)(void* arg); +} dtr_callbacks; bool dtr_daemon(dtr_callbacks const* cb, void* cb_arg, bool foreground, int* exit_code, struct tr_error** error); diff --git a/docker-compose.yml b/docker-compose.yml index 82254b78d..c96d7ad22 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,7 +4,10 @@ services: code_style: build: docker/code_style volumes: - - .:/src - - ./code_style.sh:/code_style.sh:ro - - ./format:/format:ro - command: ["/bin/bash", "-c", "cd /src && ./code_style.sh --check"] + - .:/src + working_dir: /src + command: + - ./code_style.sh + - --check + environment: + HOME: /tmp diff --git a/docker/code_style/Dockerfile b/docker/code_style/Dockerfile index 5a1a58083..fbbb653f2 100644 --- a/docker/code_style/Dockerfile +++ b/docker/code_style/Dockerfile @@ -1,3 +1,20 @@ -FROM alpine +FROM mikedld/clang-format:12-debian AS clang_format -RUN apk add --no-cache bash git perl uncrustify yarn +FROM debian:bullseye-slim AS final + +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + ca-certificates \ + curl \ + gnupg2 \ + && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \ + && echo "deb https://dl.yarnpkg.com/debian/ stable main" >> /etc/apt/sources.list.d/yarn.list \ + && apt-get update \ + && apt-get install -y --no-install-recommends \ + bash \ + nodejs \ + perl \ + yarn \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=clang_format /usr/bin/clang-format /usr/bin/ diff --git a/gtk/actions.c b/gtk/actions.c index bec871397..8a4cdac4e 100644 --- a/gtk/actions.c +++ b/gtk/actions.c @@ -26,8 +26,7 @@ static void action_cb(GtkAction* a, gpointer user_data) gtr_actions_handler(gtk_action_get_name(a), user_data); } -static GtkRadioActionEntry sort_radio_entries[] = -{ +static GtkRadioActionEntry sort_radio_entries[] = { { "sort-by-activity", NULL, N_("Sort by _Activity"), NULL, NULL, 0 }, { "sort-by-name", NULL, N_("Sort by _Name"), NULL, NULL, 1 }, { "sort-by-progress", NULL, N_("Sort by _Progress"), NULL, NULL, 2 }, @@ -36,7 +35,7 @@ static GtkRadioActionEntry sort_radio_entries[] = { "sort-by-state", NULL, N_("Sort by Stat_e"), NULL, NULL, 5 }, { "sort-by-age", NULL, N_("Sort by A_ge"), NULL, NULL, 6 }, { "sort-by-time-left", NULL, N_("Sort by Time _Left"), NULL, NULL, 7 }, - { "sort-by-size", NULL, N_("Sort by Si_ze"), NULL, NULL, 8 } + { "sort-by-size", NULL, N_("Sort by Si_ze"), NULL, NULL, 8 }, }; static void sort_changed_cb(GtkAction* action, GtkRadioAction* current, gpointer user_data) @@ -51,10 +50,9 @@ static void sort_changed_cb(GtkAction* action, GtkRadioAction* current, gpointer gtr_core_set_pref(myCore, key, val); } -static GtkToggleActionEntry show_toggle_entries[] = -{ +static GtkToggleActionEntry show_toggle_entries[] = { { "toggle-main-window", NULL, N_("_Show Transmission"), NULL, NULL, G_CALLBACK(action_cb), TRUE }, - { "toggle-message-log", NULL, N_("Message _Log"), NULL, NULL, G_CALLBACK(action_cb), FALSE } + { "toggle-message-log", NULL, N_("Message _Log"), NULL, NULL, G_CALLBACK(action_cb), FALSE }, }; static void toggle_pref_cb(GtkToggleAction* action, gpointer user_data) @@ -67,18 +65,16 @@ static void toggle_pref_cb(GtkToggleAction* action, gpointer user_data) gtr_core_set_pref_bool(myCore, tr_quark_new(key, TR_BAD_SIZE), val); } -static GtkToggleActionEntry pref_toggle_entries[] = -{ +static GtkToggleActionEntry pref_toggle_entries[] = { { "alt-speed-enabled", NULL, N_("Enable Alternative Speed _Limits"), NULL, NULL, G_CALLBACK(toggle_pref_cb), FALSE }, { "compact-view", NULL, N_("_Compact View"), "C", NULL, G_CALLBACK(toggle_pref_cb), FALSE }, { "sort-reversed", NULL, N_("Re_verse Sort Order"), NULL, NULL, G_CALLBACK(toggle_pref_cb), FALSE }, { "show-filterbar", NULL, N_("_Filterbar"), NULL, NULL, G_CALLBACK(toggle_pref_cb), FALSE }, { "show-statusbar", NULL, N_("_Statusbar"), NULL, NULL, G_CALLBACK(toggle_pref_cb), FALSE }, - { "show-toolbar", NULL, N_("_Toolbar"), NULL, NULL, G_CALLBACK(toggle_pref_cb), FALSE } + { "show-toolbar", NULL, N_("_Toolbar"), NULL, NULL, G_CALLBACK(toggle_pref_cb), FALSE }, }; -static GtkActionEntry entries[] = -{ +static GtkActionEntry entries[] = { { "file-menu", NULL, N_("_File"), NULL, NULL, NULL }, { "torrent-menu", NULL, N_("_Torrent"), NULL, NULL, NULL }, { "view-menu", NULL, N_("_View"), NULL, NULL, NULL }, @@ -91,8 +87,12 @@ static GtkActionEntry entries[] = { "open-torrent-toolbar", "document-open", N_("_Open"), NULL, N_("Open a torrent"), G_CALLBACK(action_cb) }, { "open-torrent-menu", "document-open", N_("_Open"), NULL, N_("Open a torrent"), G_CALLBACK(action_cb) }, { "torrent-start", "media-playback-start", N_("_Start"), "S", N_("Start torrent"), G_CALLBACK(action_cb) }, - { "torrent-start-now", "media-playback-start", N_("Start _Now"), "S", N_("Start torrent now"), - G_CALLBACK(action_cb) }, + { "torrent-start-now", + "media-playback-start", + N_("Start _Now"), + "S", + N_("Start torrent now"), + G_CALLBACK(action_cb) }, { "show-stats", NULL, N_("_Statistics"), NULL, NULL, G_CALLBACK(action_cb) }, { "donate", NULL, N_("_Donate"), NULL, NULL, G_CALLBACK(action_cb) }, { "torrent-verify", NULL, N_("_Verify Local Data"), "V", NULL, G_CALLBACK(action_cb) }, @@ -107,8 +107,12 @@ static GtkActionEntry entries[] = { "select-all", "edit-select-all", N_("Select _All"), "A", NULL, G_CALLBACK(action_cb) }, { "deselect-all", NULL, N_("Dese_lect All"), "A", NULL, G_CALLBACK(action_cb) }, { "edit-preferences", "preferences-system", N_("_Preferences"), NULL, NULL, G_CALLBACK(action_cb) }, - { "show-torrent-properties", "document-properties", N_("_Properties"), "Return", N_("Torrent properties"), G_CALLBACK( - action_cb) }, + { "show-torrent-properties", + "document-properties", + N_("_Properties"), + "Return", + N_("Torrent properties"), + G_CALLBACK(action_cb) }, { "open-torrent-folder", "document-open", N_("Open Fold_er"), "E", NULL, G_CALLBACK(action_cb) }, { "show-about-dialog", "help-about", N_("_About"), NULL, NULL, G_CALLBACK(action_cb) }, { "help", "help-browser", N_("_Contents"), "F1", NULL, G_CALLBACK(action_cb) }, @@ -117,26 +121,24 @@ static GtkActionEntry entries[] = { "queue-move-up", "go-up", N_("Move _Up"), "Up", NULL, G_CALLBACK(action_cb) }, { "queue-move-down", "go-down", N_("Move _Down"), "Down", NULL, G_CALLBACK(action_cb) }, { "queue-move-bottom", "go-bottom", N_("Move to _Bottom"), NULL, NULL, G_CALLBACK(action_cb) }, - { "present-main-window", NULL, N_("Present Main Window"), NULL, NULL, G_CALLBACK(action_cb) } + { "present-main-window", NULL, N_("Present Main Window"), NULL, NULL, G_CALLBACK(action_cb) }, }; typedef struct { char const* filename; char const* name; -} -BuiltinIconInfo; +} BuiltinIconInfo; -static BuiltinIconInfo const my_fallback_icons[] = -{ - { "logo-48", WINDOW_ICON }, - { "logo-24", TRAY_ICON }, - { "logo-48", NOTIFICATION_ICON }, - { "lock", "transmission-lock" }, - { "utilities", "utilities" }, - { "turtle-blue", "alt-speed-on" }, - { "turtle-grey", "alt-speed-off" }, - { "ratio", "ratio" } +static BuiltinIconInfo const my_fallback_icons[] = { + { "logo-48", WINDOW_ICON }, // + { "logo-24", TRAY_ICON }, // + { "logo-48", NOTIFICATION_ICON }, // + { "lock", "transmission-lock" }, // + { "utilities", "utilities" }, // + { "turtle-blue", "alt-speed-on" }, // + { "turtle-grey", "alt-speed-off" }, // + { "ratio", "ratio" }, // }; static void register_my_icons(void) @@ -210,10 +212,18 @@ void gtr_actions_init(GtkUIManager* ui_manager, gpointer callback_user_data) } } - gtk_action_group_add_radio_actions(action_group, sort_radio_entries, G_N_ELEMENTS(sort_radio_entries), active, - G_CALLBACK(sort_changed_cb), NULL); + gtk_action_group_add_radio_actions( + action_group, + sort_radio_entries, + G_N_ELEMENTS(sort_radio_entries), + active, + G_CALLBACK(sort_changed_cb), + NULL); - gtk_action_group_add_toggle_actions(action_group, show_toggle_entries, G_N_ELEMENTS(show_toggle_entries), + gtk_action_group_add_toggle_actions( + action_group, + show_toggle_entries, + G_N_ELEMENTS(show_toggle_entries), callback_user_data); for (size_t i = 0; i < G_N_ELEMENTS(pref_toggle_entries); ++i) @@ -221,7 +231,10 @@ void gtr_actions_init(GtkUIManager* ui_manager, gpointer callback_user_data) pref_toggle_entries[i].is_active = gtr_pref_flag_get(tr_quark_new(pref_toggle_entries[i].name, TR_BAD_SIZE)); } - gtk_action_group_add_toggle_actions(action_group, pref_toggle_entries, G_N_ELEMENTS(pref_toggle_entries), + gtk_action_group_add_toggle_actions( + action_group, + pref_toggle_entries, + G_N_ELEMENTS(pref_toggle_entries), callback_user_data); gtk_action_group_add_actions(action_group, entries, n_entries, callback_user_data); diff --git a/gtk/details.c b/gtk/details.c index bc7c8b01b..22efbd51b 100644 --- a/gtk/details.c +++ b/gtk/details.c @@ -477,9 +477,9 @@ static void onComboEnumChanged(GtkComboBox* combo_box, struct DetailsImpl* di) static GtkWidget* ratio_combo_new(void) { GtkWidget* w = gtr_combo_box_new_enum( - _("Use global settings"), TR_RATIOLIMIT_GLOBAL, - _("Seed regardless of ratio"), TR_RATIOLIMIT_UNLIMITED, - _("Stop seeding at ratio:"), TR_RATIOLIMIT_SINGLE, + TR_ARG_TUPLE(_("Use global settings"), TR_RATIOLIMIT_GLOBAL), + TR_ARG_TUPLE(_("Seed regardless of ratio"), TR_RATIOLIMIT_UNLIMITED), + TR_ARG_TUPLE(_("Stop seeding at ratio:"), TR_RATIOLIMIT_SINGLE), NULL); g_object_set_qdata(G_OBJECT(w), ARG_KEY, GINT_TO_POINTER(TR_KEY_seedRatioMode)); return w; @@ -488,9 +488,9 @@ static GtkWidget* ratio_combo_new(void) static GtkWidget* idle_combo_new(void) { GtkWidget* w = gtr_combo_box_new_enum( - _("Use global settings"), TR_IDLELIMIT_GLOBAL, - _("Seed regardless of activity"), TR_IDLELIMIT_UNLIMITED, - _("Stop seeding if idle for N minutes:"), TR_IDLELIMIT_SINGLE, + TR_ARG_TUPLE(_("Use global settings"), TR_IDLELIMIT_GLOBAL), + TR_ARG_TUPLE(_("Seed regardless of activity"), TR_IDLELIMIT_UNLIMITED), + TR_ARG_TUPLE(_("Stop seeding if idle for N minutes:"), TR_IDLELIMIT_SINGLE), NULL); g_object_set_qdata(G_OBJECT(w), ARG_KEY, GINT_TO_POINTER(TR_KEY_seedIdleMode)); return w; @@ -908,8 +908,13 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) { char piecebuf[128]; tr_formatter_mem_B(piecebuf, pieceSize, sizeof(piecebuf)); - g_snprintf(buf, sizeof(buf), ngettext("%1$s (%2$'d piece @ %3$s)", "%1$s (%2$'d pieces @ %3$s)", pieces), sizebuf, - pieces, piecebuf); + g_snprintf( + buf, + sizeof(buf), + ngettext("%1$s (%2$'d piece @ %3$s)", "%1$s (%2$'d pieces @ %3$s)", pieces), + sizebuf, + pieces, + piecebuf); str = buf; } else @@ -966,7 +971,13 @@ static void refreshInfo(struct DetailsImpl* di, tr_torrent** torrents, int n) } else { - g_snprintf(buf, sizeof(buf), _("%1$s (%2$s%% of %3$s%% Available); %4$s Unverified"), total, buf2, avail, + g_snprintf( + buf, + sizeof(buf), + _("%1$s (%2$s%% of %3$s%% Available); %4$s Unverified"), + total, + buf2, + avail, unver); } @@ -1258,7 +1269,8 @@ static char const* getWebseedColumnNames(int column) static GtkListStore* webseed_model_new(void) { - return gtk_list_store_new(N_WEBSEED_COLS, + return gtk_list_store_new( + N_WEBSEED_COLS, G_TYPE_STRING, /* key */ G_TYPE_BOOLEAN, /* was-updated */ G_TYPE_STRING, /* url */ @@ -1351,7 +1363,8 @@ static char const* getPeerColumnName(int column) static GtkListStore* peer_store_new(void) { - return gtk_list_store_new(N_PEER_COLS, + return gtk_list_store_new( + N_PEER_COLS, G_TYPE_STRING, /* key */ G_TYPE_BOOLEAN, /* was-updated */ G_TYPE_STRING, /* address */ @@ -1379,7 +1392,11 @@ static GtkListStore* peer_store_new(void) G_TYPE_STRING); /* torrent name */ } -static void initPeerRow(GtkListStore* store, GtkTreeIter* iter, char const* key, char const* torrentName, +static void initPeerRow( + GtkListStore* store, + GtkTreeIter* iter, + char const* key, + char const* torrentName, tr_peer_stat const* peer) { g_return_if_fail(peer != NULL); @@ -1401,13 +1418,15 @@ static void initPeerRow(GtkListStore* store, GtkTreeIter* iter, char const* key, g_snprintf(collated_name, sizeof(collated_name), "%03d.%03d.%03d.%03d", q[0], q[1], q[2], q[3]); } - gtk_list_store_set(store, iter, - PEER_COL_ADDRESS, peer->addr, - PEER_COL_ADDRESS_COLLATED, collated_name, - PEER_COL_CLIENT, client, - PEER_COL_ENCRYPTION_STOCK_ID, peer->isEncrypted ? "transmission-lock" : NULL, - PEER_COL_KEY, key, - PEER_COL_TORRENT_NAME, torrentName, + gtk_list_store_set( + store, + iter, + TR_ARG_TUPLE(PEER_COL_ADDRESS, peer->addr), + TR_ARG_TUPLE(PEER_COL_ADDRESS_COLLATED, collated_name), + TR_ARG_TUPLE(PEER_COL_CLIENT, client), + TR_ARG_TUPLE(PEER_COL_ENCRYPTION_STOCK_ID, peer->isEncrypted ? "transmission-lock" : NULL), + TR_ARG_TUPLE(PEER_COL_KEY, key), + TR_ARG_TUPLE(PEER_COL_TORRENT_NAME, torrentName), -1); } @@ -1464,26 +1483,28 @@ static void refreshPeerRow(GtkListStore* store, GtkTreeIter* iter, tr_peer_stat g_snprintf(cancelled_by_peer, sizeof(cancelled_by_peer), "%" PRIu32, peer->cancelsToClient); } - gtk_list_store_set(store, iter, - PEER_COL_PROGRESS, (int)(100.0 * peer->progress), - PEER_COL_UPLOAD_REQUEST_COUNT_INT, peer->pendingReqsToClient, - PEER_COL_UPLOAD_REQUEST_COUNT_STRING, up_count, - PEER_COL_DOWNLOAD_REQUEST_COUNT_INT, peer->pendingReqsToPeer, - PEER_COL_DOWNLOAD_REQUEST_COUNT_STRING, down_count, - PEER_COL_DOWNLOAD_RATE_DOUBLE, peer->rateToClient_KBps, - PEER_COL_DOWNLOAD_RATE_STRING, down_speed, - PEER_COL_UPLOAD_RATE_DOUBLE, peer->rateToPeer_KBps, - PEER_COL_UPLOAD_RATE_STRING, up_speed, - PEER_COL_FLAGS, peer->flagStr, - PEER_COL_WAS_UPDATED, TRUE, - PEER_COL_BLOCKS_DOWNLOADED_COUNT_INT, (int)peer->blocksToClient, - PEER_COL_BLOCKS_DOWNLOADED_COUNT_STRING, blocks_to_client, - PEER_COL_BLOCKS_UPLOADED_COUNT_INT, (int)peer->blocksToPeer, - PEER_COL_BLOCKS_UPLOADED_COUNT_STRING, blocks_to_peer, - PEER_COL_REQS_CANCELLED_BY_CLIENT_COUNT_INT, (int)peer->cancelsToPeer, - PEER_COL_REQS_CANCELLED_BY_CLIENT_COUNT_STRING, cancelled_by_client, - PEER_COL_REQS_CANCELLED_BY_PEER_COUNT_INT, (int)peer->cancelsToClient, - PEER_COL_REQS_CANCELLED_BY_PEER_COUNT_STRING, cancelled_by_peer, + gtk_list_store_set( + store, + iter, + TR_ARG_TUPLE(PEER_COL_PROGRESS, (int)(100.0 * peer->progress)), + TR_ARG_TUPLE(PEER_COL_UPLOAD_REQUEST_COUNT_INT, peer->pendingReqsToClient), + TR_ARG_TUPLE(PEER_COL_UPLOAD_REQUEST_COUNT_STRING, up_count), + TR_ARG_TUPLE(PEER_COL_DOWNLOAD_REQUEST_COUNT_INT, peer->pendingReqsToPeer), + TR_ARG_TUPLE(PEER_COL_DOWNLOAD_REQUEST_COUNT_STRING, down_count), + TR_ARG_TUPLE(PEER_COL_DOWNLOAD_RATE_DOUBLE, peer->rateToClient_KBps), + TR_ARG_TUPLE(PEER_COL_DOWNLOAD_RATE_STRING, down_speed), + TR_ARG_TUPLE(PEER_COL_UPLOAD_RATE_DOUBLE, peer->rateToPeer_KBps), + TR_ARG_TUPLE(PEER_COL_UPLOAD_RATE_STRING, up_speed), + TR_ARG_TUPLE(PEER_COL_FLAGS, peer->flagStr), + TR_ARG_TUPLE(PEER_COL_WAS_UPDATED, TRUE), + TR_ARG_TUPLE(PEER_COL_BLOCKS_DOWNLOADED_COUNT_INT, (int)peer->blocksToClient), + TR_ARG_TUPLE(PEER_COL_BLOCKS_DOWNLOADED_COUNT_STRING, blocks_to_client), + TR_ARG_TUPLE(PEER_COL_BLOCKS_UPLOADED_COUNT_INT, (int)peer->blocksToPeer), + TR_ARG_TUPLE(PEER_COL_BLOCKS_UPLOADED_COUNT_STRING, blocks_to_peer), + TR_ARG_TUPLE(PEER_COL_REQS_CANCELLED_BY_CLIENT_COUNT_INT, (int)peer->cancelsToPeer), + TR_ARG_TUPLE(PEER_COL_REQS_CANCELLED_BY_CLIENT_COUNT_STRING, cancelled_by_client), + TR_ARG_TUPLE(PEER_COL_REQS_CANCELLED_BY_PEER_COUNT_INT, (int)peer->cancelsToClient), + TR_ARG_TUPLE(PEER_COL_REQS_CANCELLED_BY_PEER_COUNT_STRING, cancelled_by_peer), -1); } @@ -1510,8 +1531,7 @@ static void refreshPeerList(struct DetailsImpl* di, tr_torrent** torrents, int n do { gtk_list_store_set(store, &iter, PEER_COL_WAS_UPDATED, FALSE, -1); - } - while (gtk_tree_model_iter_next(model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); } /* step 3: add any new peers */ @@ -1608,8 +1628,7 @@ static void refreshWebseedList(struct DetailsImpl* di, tr_torrent** torrents, in do { gtk_list_store_set(store, &iter, WEBSEED_COL_WAS_UPDATED, FALSE, -1); - } - while (gtk_tree_model_iter_next(model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); } /* step 2: add any new webseeds */ @@ -1630,10 +1649,7 @@ static void refreshWebseedList(struct DetailsImpl* di, tr_torrent** torrents, in { GtkTreePath* p; gtk_list_store_append(store, &iter); - gtk_list_store_set(store, &iter, - WEBSEED_COL_URL, url, - WEBSEED_COL_KEY, key, - -1); + gtk_list_store_set(store, &iter, TR_ARG_TUPLE(WEBSEED_COL_URL, url), TR_ARG_TUPLE(WEBSEED_COL_KEY, key), -1); p = gtk_tree_model_get_path(model, &iter); g_hash_table_insert(hash, g_strdup(key), gtk_tree_row_reference_new(model, p)); gtk_tree_path_free(p); @@ -1664,10 +1680,12 @@ static void refreshWebseedList(struct DetailsImpl* di, tr_torrent** torrents, in tr_formatter_speed_KBps(buf, speeds_KBps[j], sizeof(buf)); } - gtk_list_store_set(store, &iter, - WEBSEED_COL_DOWNLOAD_RATE_DOUBLE, speeds_KBps[j], - WEBSEED_COL_DOWNLOAD_RATE_STRING, buf, - WEBSEED_COL_WAS_UPDATED, TRUE, + gtk_list_store_set( + store, + &iter, + TR_ARG_TUPLE(WEBSEED_COL_DOWNLOAD_RATE_DOUBLE, speeds_KBps[j]), + TR_ARG_TUPLE(WEBSEED_COL_DOWNLOAD_RATE_STRING, buf), + TR_ARG_TUPLE(WEBSEED_COL_WAS_UPDATED, TRUE), -1); gtk_tree_path_free(p); @@ -1717,7 +1735,12 @@ static void refreshPeers(struct DetailsImpl* di, tr_torrent** torrents, int n) refreshWebseedList(di, torrents, n); } -static gboolean onPeerViewQueryTooltip(GtkWidget* widget, gint x, gint y, gboolean keyboard_tip, GtkTooltip* tooltip, +static gboolean onPeerViewQueryTooltip( + GtkWidget* widget, + gint x, + gint y, + gboolean keyboard_tip, + GtkTooltip* tooltip, gpointer gdi) { GtkTreeIter iter; @@ -1732,10 +1755,12 @@ static gboolean onPeerViewQueryTooltip(GtkWidget* widget, gint x, gint y, gboole struct DetailsImpl* di = gdi; GString* gstr = di->gstr; - gtk_tree_model_get(model, &iter, - PEER_COL_TORRENT_NAME, &name, - PEER_COL_ADDRESS, &addr, - PEER_COL_FLAGS, &flagstr, + gtk_tree_model_get( + model, + &iter, + TR_ARG_TUPLE(PEER_COL_TORRENT_NAME, &name), + TR_ARG_TUPLE(PEER_COL_ADDRESS, &addr), + TR_ARG_TUPLE(PEER_COL_FLAGS, &flagstr), -1); g_string_truncate(gstr, 0); @@ -2064,11 +2089,17 @@ static GtkWidget* peer_page_new(struct DetailsImpl* di) gtk_box_pack_start(GTK_BOX(vbox), w, FALSE, FALSE, 0); /* ip-to-GtkTreeRowReference */ - di->peer_hash = g_hash_table_new_full(g_str_hash, g_str_equal, (GDestroyNotify)g_free, + di->peer_hash = g_hash_table_new_full( + g_str_hash, + g_str_equal, + (GDestroyNotify)g_free, (GDestroyNotify)gtk_tree_row_reference_free); /* url-to-GtkTreeRowReference */ - di->webseed_hash = g_hash_table_new_full(g_str_hash, g_str_equal, (GDestroyNotify)g_free, + di->webseed_hash = g_hash_table_new_full( + g_str_hash, + g_str_equal, + (GDestroyNotify)g_free, (GDestroyNotify)gtk_tree_row_reference_free); ret = vbox; return ret; @@ -2109,18 +2140,32 @@ static void appendAnnounceInfo(tr_tracker_stat const* const st, time_t const now if (st->lastAnnounceSucceeded) { - g_string_append_printf(gstr, _("Got a list of %1$s%2$'d peers%3$s %4$s ago"), - success_markup_begin, st->lastAnnouncePeerCount, success_markup_end, timebuf); + g_string_append_printf( + gstr, + _("Got a list of %1$s%2$'d peers%3$s %4$s ago"), + success_markup_begin, + st->lastAnnouncePeerCount, + success_markup_end, + timebuf); } else if (st->lastAnnounceTimedOut) { - g_string_append_printf(gstr, _("Peer list request %1$stimed out%2$s %3$s ago; will retry"), - timeout_markup_begin, timeout_markup_end, timebuf); + g_string_append_printf( + gstr, + _("Peer list request %1$stimed out%2$s %3$s ago; will retry"), + timeout_markup_begin, + timeout_markup_end, + timebuf); } else { - g_string_append_printf(gstr, _("Got an error %1$s\"%2$s\"%3$s %4$s ago"), err_markup_begin, - st->lastAnnounceResult, err_markup_end, timebuf); + g_string_append_printf( + gstr, + _("Got an error %1$s\"%2$s\"%3$s %4$s ago"), + err_markup_begin, + st->lastAnnounceResult, + err_markup_end, + timebuf); } } @@ -2161,13 +2206,24 @@ static void appendScrapeInfo(tr_tracker_stat const* const st, time_t const now, if (st->lastScrapeSucceeded) { - g_string_append_printf(gstr, _("Tracker had %s%'d seeders and %'d leechers%s %s ago"), success_markup_begin, - st->seederCount, st->leecherCount, success_markup_end, timebuf); + g_string_append_printf( + gstr, + _("Tracker had %s%'d seeders and %'d leechers%s %s ago"), + success_markup_begin, + st->seederCount, + st->leecherCount, + success_markup_end, + timebuf); } else { - g_string_append_printf(gstr, _("Got a scrape error \"%s%s%s\" %s ago"), err_markup_begin, - st->lastScrapeResult, err_markup_end, timebuf); + g_string_append_printf( + gstr, + _("Got a scrape error \"%s%s%s\" %s ago"), + err_markup_begin, + st->lastScrapeResult, + err_markup_end, + timebuf); } } @@ -2199,9 +2255,7 @@ static void buildTrackerSummary(GString* gstr, char const* key, tr_tracker_stat { // hostname g_string_append(gstr, st->isBackup ? "" : ""); - char* const str = key != NULL ? - g_markup_printf_escaped("%s - %s", st->host, key) : - g_markup_printf_escaped("%s", st->host); + char* const str = key != NULL ? g_markup_printf_escaped("%s - %s", st->host, key) : g_markup_printf_escaped("%s", st->host); g_string_append(gstr, str); g_free(str); g_string_append(gstr, st->isBackup ? "" : ""); @@ -2327,8 +2381,7 @@ static void refreshTracker(struct DetailsImpl* di, tr_torrent** torrents, int n) do { gtk_list_store_set(store, &iter, TRACKER_COL_WAS_UPDATED, FALSE, -1); - } - while (gtk_tree_model_iter_next(model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); } /* step 3: add any new trackers */ @@ -2348,10 +2401,13 @@ static void refreshTracker(struct DetailsImpl* di, tr_torrent** torrents, int n) if (g_hash_table_lookup(hash, gstr->str) == NULL) { - gtk_list_store_insert_with_values(store, &iter, -1, - TRACKER_COL_TORRENT_ID, torrent_id, - TRACKER_COL_TRACKER_ID, st->id, - TRACKER_COL_KEY, gstr->str, + gtk_list_store_insert_with_values( + store, + &iter, + -1, + TR_ARG_TUPLE(TRACKER_COL_TORRENT_ID, torrent_id), + TR_ARG_TUPLE(TRACKER_COL_TRACKER_ID, st->id), + TR_ARG_TUPLE(TRACKER_COL_KEY, gstr->str), -1); GtkTreePath* const p = gtk_tree_model_get_path(model, &iter); @@ -2384,11 +2440,13 @@ static void refreshTracker(struct DetailsImpl* di, tr_torrent** torrents, int n) /* update the row */ g_string_truncate(gstr, 0); buildTrackerSummary(gstr, summary_name, st, showScrape); - gtk_list_store_set(store, &iter, - TRACKER_COL_TEXT, gstr->str, - TRACKER_COL_IS_BACKUP, st->isBackup, - TRACKER_COL_TRACKER_ID, st->id, - TRACKER_COL_WAS_UPDATED, TRUE, + gtk_list_store_set( + store, + &iter, + TR_ARG_TUPLE(TRACKER_COL_TEXT, gstr->str), + TR_ARG_TUPLE(TRACKER_COL_IS_BACKUP, st->isBackup), + TR_ARG_TUPLE(TRACKER_COL_TRACKER_ID, st->id), + TR_ARG_TUPLE(TRACKER_COL_WAS_UPDATED, TRUE), -1); /* cleanup */ @@ -2497,10 +2555,16 @@ static void on_edit_trackers_response(GtkDialog* dialog, int response, gpointer else { char const* text = _("List contains invalid URLs"); - GtkWidget* w = gtk_message_dialog_new(GTK_WINDOW( - dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", + GtkWidget* w = gtk_message_dialog_new( + GTK_WINDOW(dialog), + GTK_DIALOG_MODAL, + GTK_MESSAGE_ERROR, + GTK_BUTTONS_CLOSE, + "%s", text); - gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(w), "%s", + gtk_message_dialog_format_secondary_text( + GTK_MESSAGE_DIALOG(w), + "%s", _("Please correct the errors and try again.")); gtk_dialog_run(GTK_DIALOG(w)); gtk_widget_destroy(w); @@ -2564,9 +2628,12 @@ static void on_edit_trackers(GtkButton* button, gpointer data) g_string_truncate(gstr, 0); g_string_append_printf(gstr, _("%s - Edit Trackers"), tr_torrentName(tor)); - d = gtk_dialog_new_with_buttons(gstr->str, win, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, - _("_Cancel"), GTK_RESPONSE_CANCEL, - _("_Save"), GTK_RESPONSE_ACCEPT, + d = gtk_dialog_new_with_buttons( + gstr->str, + win, + GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, + TR_ARG_TUPLE(_("_Cancel"), GTK_RESPONSE_CANCEL), + TR_ARG_TUPLE(_("_Save"), GTK_RESPONSE_ACCEPT), NULL); g_signal_connect(d, "response", G_CALLBACK(on_edit_trackers_response), data); @@ -2575,8 +2642,10 @@ static void on_edit_trackers(GtkButton* button, gpointer data) hig_workarea_add_section_title(t, &row, _("Tracker Announce URLs")); l = gtk_label_new(NULL); - gtk_label_set_markup(GTK_LABEL(l), _("To add a backup URL, add it on the line after the primary URL.\n" - "To add another primary URL, add it after a blank line.")); + gtk_label_set_markup( + GTK_LABEL(l), + _("To add a backup URL, add it on the line after the primary URL.\n" + "To add another primary URL, add it after a blank line.")); gtk_label_set_justify(GTK_LABEL(l), GTK_JUSTIFY_LEFT); g_object_set(l, "halign", GTK_ALIGN_START, "valign", GTK_ALIGN_CENTER, NULL); hig_workarea_add_wide_control(t, &row, l); @@ -2678,9 +2747,12 @@ static void on_tracker_list_add_button_clicked(GtkButton const* button, gpointer g_string_truncate(gstr, 0); g_string_append_printf(gstr, _("%s - Add Tracker"), tr_torrentName(tor)); - w = gtk_dialog_new_with_buttons(gstr->str, GTK_WINDOW(di->dialog), GTK_DIALOG_DESTROY_WITH_PARENT, - _("_Cancel"), GTK_RESPONSE_CANCEL, - _("_Add"), GTK_RESPONSE_ACCEPT, + w = gtk_dialog_new_with_buttons( + gstr->str, + GTK_WINDOW(di->dialog), + GTK_DIALOG_DESTROY_WITH_PARENT, + TR_ARG_TUPLE(_("_Cancel"), GTK_RESPONSE_CANCEL), + TR_ARG_TUPLE(_("_Add"), GTK_RESPONSE_ACCEPT), NULL); g_signal_connect(w, "response", G_CALLBACK(on_add_tracker_response), gdi); @@ -2716,9 +2788,11 @@ static void on_tracker_list_remove_button_clicked(GtkButton const* button, gpoin tr_variant* args; tr_variant* trackers; - gtk_tree_model_get(model, &iter, - TRACKER_COL_TRACKER_ID, &tracker_id, - TRACKER_COL_TORRENT_ID, &torrent_id, + gtk_tree_model_get( + model, + &iter, + TR_ARG_TUPLE(TRACKER_COL_TRACKER_ID, &tracker_id), + TR_ARG_TUPLE(TRACKER_COL_TORRENT_ID, &torrent_id), -1); tr_variantInitDict(&top, 2); @@ -2751,7 +2825,8 @@ static GtkWidget* tracker_page_new(struct DetailsImpl* di) vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, GUI_PAD); gtk_container_set_border_width(GTK_CONTAINER(vbox), GUI_PAD_BIG); - di->tracker_store = gtk_list_store_new(TRACKER_N_COLS, + di->tracker_store = gtk_list_store_new( + TRACKER_N_COLS, G_TYPE_INT, G_TYPE_STRING, G_TYPE_BOOLEAN, @@ -2760,7 +2835,10 @@ static GtkWidget* tracker_page_new(struct DetailsImpl* di) G_TYPE_BOOLEAN, G_TYPE_STRING); - di->tracker_hash = g_hash_table_new_full(g_str_hash, g_str_equal, (GDestroyNotify)g_free, + di->tracker_hash = g_hash_table_new_full( + g_str_hash, + g_str_equal, + (GDestroyNotify)g_free, (GDestroyNotify)gtk_tree_row_reference_free); di->trackers_filtered = gtk_tree_model_filter_new(GTK_TREE_MODEL(di->tracker_store), NULL); @@ -2913,14 +2991,13 @@ GtkWidget* gtr_torrent_details_dialog_new(GtkWindow* parent, TrCore* core) /* create the dialog */ di->core = core; di->gstr = g_string_new(NULL); - d = gtk_dialog_new_with_buttons(NULL, parent, 0, - _("_Close"), GTK_RESPONSE_CLOSE, - NULL); + d = gtk_dialog_new_with_buttons(NULL, parent, 0, TR_ARG_TUPLE(_("_Close"), GTK_RESPONSE_CLOSE), NULL); di->dialog = d; gtk_window_set_role(GTK_WINDOW(d), "tr-info"); /* return saved window size */ - gtk_window_resize(GTK_WINDOW(d), + gtk_window_resize( + GTK_WINDOW(d), (gint)gtr_pref_int_get(TR_KEY_details_window_width), (gint)gtr_pref_int_get(TR_KEY_details_window_height)); g_signal_connect(d, "size-allocate", G_CALLBACK(on_details_window_size_allocated), NULL); diff --git a/gtk/dialogs.c b/gtk/dialogs.c index 4c7821ce0..d0cabad04 100644 --- a/gtk/dialogs.c +++ b/gtk/dialogs.c @@ -101,34 +101,45 @@ void gtr_confirm_remove(GtkWindow* parent, TrCore* core, GSList* torrent_ids, gb } else { - g_string_printf(primary_text, ngettext("Delete this torrent's downloaded files?", - "Delete these %d torrents' downloaded files?", count), count); + g_string_printf( + primary_text, + ngettext("Delete this torrent's downloaded files?", "Delete these %d torrents' downloaded files?", count), + count); } secondary_text = g_string_new(NULL); if (incomplete == 0 && connected == 0) { - g_string_assign(secondary_text, - ngettext("Once removed, continuing the transfer will require the torrent file or magnet link.", - "Once removed, continuing the transfers will require the torrent files or magnet links.", count)); + g_string_assign( + secondary_text, + ngettext( + "Once removed, continuing the transfer will require the torrent file or magnet link.", + "Once removed, continuing the transfers will require the torrent files or magnet links.", + count)); } else if (count == incomplete) { - g_string_assign(secondary_text, ngettext("This torrent has not finished downloading.", - "These torrents have not finished downloading.", count)); + g_string_assign( + secondary_text, + ngettext("This torrent has not finished downloading.", "These torrents have not finished downloading.", count)); } else if (count == connected) { - g_string_assign(secondary_text, ngettext("This torrent is connected to peers.", - "These torrents are connected to peers.", count)); + g_string_assign( + secondary_text, + ngettext("This torrent is connected to peers.", "These torrents are connected to peers.", count)); } else { if (connected != 0) { - g_string_append(secondary_text, ngettext("One of these torrents is connected to peers.", - "Some of these torrents are connected to peers.", connected)); + g_string_append( + secondary_text, + ngettext( + "One of these torrents is connected to peers.", + "Some of these torrents are connected to peers.", + connected)); } if (connected != 0 && incomplete != 0) @@ -138,22 +149,32 @@ void gtr_confirm_remove(GtkWindow* parent, TrCore* core, GSList* torrent_ids, gb if (incomplete != 0) { - g_string_assign(secondary_text, ngettext("One of these torrents has not finished downloading.", - "Some of these torrents have not finished downloading.", incomplete)); + g_string_assign( + secondary_text, + ngettext( + "One of these torrents has not finished downloading.", + "Some of these torrents have not finished downloading.", + incomplete)); } } - d = gtk_message_dialog_new_with_markup(parent, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, - "%s", primary_text->str); + d = gtk_message_dialog_new_with_markup( + parent, + GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_QUESTION, + GTK_BUTTONS_NONE, + "%s", + primary_text->str); if (secondary_text->len != 0) { gtk_message_dialog_format_secondary_markup(GTK_MESSAGE_DIALOG(d), "%s", secondary_text->str); } - gtk_dialog_add_buttons(GTK_DIALOG(d), - _("_Cancel"), GTK_RESPONSE_CANCEL, - delete_files ? _("_Delete") : _("_Remove"), GTK_RESPONSE_ACCEPT, + gtk_dialog_add_buttons( + GTK_DIALOG(d), + TR_ARG_TUPLE(_("_Cancel"), GTK_RESPONSE_CANCEL), + TR_ARG_TUPLE(delete_files ? _("_Delete") : _("_Remove"), GTK_RESPONSE_ACCEPT), NULL); gtk_dialog_set_default_response(GTK_DIALOG(d), GTK_RESPONSE_CANCEL); g_signal_connect(d, "response", G_CALLBACK(on_remove_dialog_response), dd); diff --git a/gtk/favicon.c b/gtk/favicon.c index 6c11c5693..90679fc3b 100644 --- a/gtk/favicon.c +++ b/gtk/favicon.c @@ -118,8 +118,14 @@ static gboolean favicon_web_done_idle_cb(gpointer vfav) return G_SOURCE_REMOVE; } -static void favicon_web_done_cb(tr_session* session, bool did_connect, bool did_timeout, long code, void const* data, - size_t len, void* vfav) +static void favicon_web_done_cb( + tr_session* session, + bool did_connect, + bool did_timeout, + long code, + void const* data, + size_t len, + void* vfav) { TR_UNUSED(session); TR_UNUSED(did_connect); diff --git a/gtk/file-list.c b/gtk/file-list.c index 9d3dbb59d..953506847 100644 --- a/gtk/file-list.c +++ b/gtk/file-list.c @@ -56,8 +56,7 @@ typedef struct GtkTreeStore* store; /* same object as model, but recast */ int torrentId; guint timeout_tag; -} -FileData; +} FileData; static void clearData(FileData* data) { @@ -105,13 +104,15 @@ static gboolean refreshFilesForeach(GtkTreeModel* model, GtkTreePath* path, GtkT int old_enabled; gboolean const is_file = !gtk_tree_model_iter_has_child(model, iter); - gtk_tree_model_get(model, iter, - FC_ENABLED, &old_enabled, - FC_PRIORITY, &old_priority, - FC_INDEX, &index, - FC_HAVE, &old_have, - FC_SIZE, &size, - FC_PROG, &old_prog, + gtk_tree_model_get( + model, + iter, + TR_ARG_TUPLE(FC_ENABLED, &old_enabled), + TR_ARG_TUPLE(FC_PRIORITY, &old_priority), + TR_ARG_TUPLE(FC_INDEX, &index), + TR_ARG_TUPLE(FC_HAVE, &old_have), + TR_ARG_TUPLE(FC_SIZE, &size), + TR_ARG_TUPLE(FC_PROG, &old_prog), -1); if (is_file) @@ -131,19 +132,23 @@ static gboolean refreshFilesForeach(GtkTreeModel* model, GtkTreePath* path, GtkT * sorting until we finish walking the tree. */ if (!refresh_data->resort_needed && (((refresh_data->sort_column_id == FC_PRIORITY) && (priority != old_priority)) || - ((refresh_data->sort_column_id == FC_ENABLED) && (enabled != old_enabled)))) + ((refresh_data->sort_column_id == FC_ENABLED) && (enabled != old_enabled)))) { refresh_data->resort_needed = TRUE; - gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(data->model), - GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID, GTK_SORT_ASCENDING); + gtk_tree_sortable_set_sort_column_id( + GTK_TREE_SORTABLE(data->model), + GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID, + GTK_SORT_ASCENDING); } - gtk_tree_store_set(data->store, iter, - FC_PRIORITY, priority, - FC_ENABLED, enabled, - FC_HAVE, have, - FC_PROG, prog, + gtk_tree_store_set( + data->store, + iter, + TR_ARG_TUPLE(FC_PRIORITY, priority), + TR_ARG_TUPLE(FC_ENABLED, enabled), + TR_ARG_TUPLE(FC_HAVE, have), + TR_ARG_TUPLE(FC_PROG, prog), -1); } } @@ -168,11 +173,13 @@ static gboolean refreshFilesForeach(GtkTreeModel* model, GtkTreePath* path, GtkT int64_t child_have; int64_t child_size; - gtk_tree_model_get(model, &child, - FC_SIZE, &child_size, - FC_HAVE, &child_have, - FC_PRIORITY, &child_priority, - FC_ENABLED, &child_enabled, + gtk_tree_model_get( + model, + &child, + TR_ARG_TUPLE(FC_SIZE, &child_size), + TR_ARG_TUPLE(FC_HAVE, &child_have), + TR_ARG_TUPLE(FC_PRIORITY, &child_priority), + TR_ARG_TUPLE(FC_ENABLED, &child_enabled), -1); if ((child_enabled != FALSE) && (child_enabled != NOT_SET)) @@ -198,8 +205,7 @@ static gboolean refreshFilesForeach(GtkTreeModel* model, GtkTreePath* path, GtkT { priority = MIXED; } - } - while (gtk_tree_model_iter_next(model, &child)); + } while (gtk_tree_model_iter_next(model, &child)); } prog = sub_size != 0 ? (int)(100.0 * have / sub_size) : 1; @@ -208,13 +214,15 @@ static gboolean refreshFilesForeach(GtkTreeModel* model, GtkTreePath* path, GtkT { char size_str[64]; tr_strlsize(size_str, sub_size, sizeof(size_str)); - gtk_tree_store_set(data->store, iter, - FC_SIZE, sub_size, - FC_SIZE_STR, size_str, - FC_HAVE, have, - FC_PRIORITY, priority, - FC_ENABLED, enabled, - FC_PROG, prog, + gtk_tree_store_set( + data->store, + iter, + TR_ARG_TUPLE(FC_SIZE, sub_size), + TR_ARG_TUPLE(FC_SIZE_STR, size_str), + TR_ARG_TUPLE(FC_HAVE, have), + TR_ARG_TUPLE(FC_PRIORITY, priority), + TR_ARG_TUPLE(FC_ENABLED, enabled), + TR_ARG_TUPLE(FC_PROG, prog), -1); } } @@ -222,7 +230,10 @@ static gboolean refreshFilesForeach(GtkTreeModel* model, GtkTreePath* path, GtkT return FALSE; /* keep walking */ } -static void gtr_tree_model_foreach_postorder_subtree(GtkTreeModel* model, GtkTreeIter* parent, GtkTreeModelForeachFunc func, +static void gtr_tree_model_foreach_postorder_subtree( + GtkTreeModel* model, + GtkTreeIter* parent, + GtkTreeModelForeachFunc func, gpointer data) { GtkTreeIter child; @@ -232,8 +243,7 @@ static void gtr_tree_model_foreach_postorder_subtree(GtkTreeModel* model, GtkTre do { gtr_tree_model_foreach_postorder_subtree(model, &child, func, data); - } - while (gtk_tree_model_iter_next(model, &child)); + } while (gtk_tree_model_iter_next(model, &child)); } if (parent != NULL) @@ -251,8 +261,7 @@ static void gtr_tree_model_foreach_postorder(GtkTreeModel* model, GtkTreeModelFo do { gtr_tree_model_foreach_postorder_subtree(model, &iter, func, data); - } - while (gtk_tree_model_iter_next(model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); } } @@ -457,15 +466,19 @@ static void buildTree(GNode* node, gpointer gdata) tr_strlsize(size_str, child_data->length, sizeof(size_str)); - gtk_tree_store_insert_with_values(build->store, &child_iter, build->iter, INT_MAX, - FC_INDEX, child_data->index, - FC_LABEL, child_data->name, - FC_LABEL_ESC, name_esc, - FC_SIZE, child_data->length, - FC_SIZE_STR, size_str, - FC_ICON, icon, - FC_PRIORITY, priority, - FC_ENABLED, enabled, + gtk_tree_store_insert_with_values( + build->store, + &child_iter, + build->iter, + INT_MAX, + TR_ARG_TUPLE(FC_INDEX, child_data->index), + TR_ARG_TUPLE(FC_LABEL, child_data->name), + TR_ARG_TUPLE(FC_LABEL_ESC, name_esc), + TR_ARG_TUPLE(FC_SIZE, child_data->length), + TR_ARG_TUPLE(FC_SIZE_STR, size_str), + TR_ARG_TUPLE(FC_ICON, icon), + TR_ARG_TUPLE(FC_PRIORITY, priority), + TR_ARG_TUPLE(FC_ENABLED, enabled), -1); if (!isLeaf) @@ -509,7 +522,8 @@ void gtr_file_list_set_torrent(GtkWidget* w, int torrentId) clearData(data); /* instantiate the model */ - GtkTreeStore* const store = gtk_tree_store_new(N_FILE_COLS, + GtkTreeStore* const store = gtk_tree_store_new( + N_FILE_COLS, GDK_TYPE_PIXBUF, /* icon */ G_TYPE_STRING, /* label */ G_TYPE_STRING, /* label esc */ @@ -526,9 +540,7 @@ void gtr_file_list_set_torrent(GtkWidget* w, int torrentId) data->torrentId = torrentId; /* populate the model */ - tr_torrent* const tor = torrentId > 0 ? - gtr_core_find_torrent(data->core, torrentId) : - NULL; + tr_torrent* const tor = torrentId > 0 ? gtr_core_find_torrent(data->core, torrentId) : NULL; if (tor != NULL) { // build a GNode tree of the files @@ -601,7 +613,11 @@ void gtr_file_list_set_torrent(GtkWidget* w, int torrentId) **** ***/ -static void renderDownload(GtkTreeViewColumn* column, GtkCellRenderer* renderer, GtkTreeModel* model, GtkTreeIter* iter, +static void renderDownload( + GtkTreeViewColumn* column, + GtkCellRenderer* renderer, + GtkTreeModel* model, + GtkTreeIter* iter, gpointer data) { TR_UNUSED(column); @@ -612,7 +628,11 @@ static void renderDownload(GtkTreeViewColumn* column, GtkCellRenderer* renderer, g_object_set(renderer, "inconsistent", enabled == MIXED, "active", enabled == TRUE, NULL); } -static void renderPriority(GtkTreeViewColumn* column, GtkCellRenderer* renderer, GtkTreeModel* model, GtkTreeIter* iter, +static void renderPriority( + GtkTreeViewColumn* column, + GtkCellRenderer* renderer, + GtkTreeModel* model, + GtkTreeIter* iter, gpointer data) { TR_UNUSED(column); @@ -657,8 +677,7 @@ static char* buildFilename(tr_torrent const* tor, GtkTreeModel* model, GtkTreePa { child = parent; gtk_tree_model_get(model, &child, FC_LABEL, &tokens[n--], -1); - } - while (gtk_tree_model_iter_parent(model, &parent, &child)); + } while (gtk_tree_model_iter_parent(model, &parent, &child)); char* const ret = g_build_filenamev(tokens); g_strfreev(tokens); @@ -693,8 +712,7 @@ static gboolean onRowActivated(GtkTreeView* view, GtkTreePath* path, GtkTreeView char* tmp = g_path_get_dirname(filename); g_free(filename); filename = tmp; - } - while (!tr_str_is_empty(filename) && !g_file_test(filename, G_FILE_TEST_EXISTS)); + } while (!tr_str_is_empty(filename) && !g_file_test(filename, G_FILE_TEST_EXISTS)); } if ((handled = !tr_str_is_empty(filename))) @@ -772,7 +790,10 @@ static gboolean onViewPathToggled(GtkTreeView* view, GtkTreeViewColumn* col, Gtk /** * @note 'col' and 'path' are assumed not to be NULL. */ -static gboolean getAndSelectEventPath(GtkTreeView* treeview, GdkEventButton const* event, GtkTreeViewColumn** col, +static gboolean getAndSelectEventPath( + GtkTreeView* treeview, + GdkEventButton const* event, + GtkTreeViewColumn** col, GtkTreePath** path) { GtkTreeSelection* sel; @@ -847,8 +868,13 @@ static int on_rename_done_idle(struct rename_data* data) } else { - GtkWidget* w = gtk_message_dialog_new(GTK_WINDOW(gtk_widget_get_toplevel(data->file_data->top)), GTK_DIALOG_MODAL, - GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, _("Unable to rename file as \"%s\": %s"), data->newname, + GtkWidget* w = gtk_message_dialog_new( + GTK_WINDOW(gtk_widget_get_toplevel(data->file_data->top)), + GTK_DIALOG_MODAL, + GTK_MESSAGE_ERROR, + GTK_BUTTONS_CLOSE, + _("Unable to rename file as \"%s\": %s"), + data->newname, tr_strerror(data->error)); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(w), "%s", _("Please correct the errors and try again.")); gtk_dialog_run(GTK_DIALOG(w)); @@ -862,14 +888,21 @@ static int on_rename_done_idle(struct rename_data* data) return G_SOURCE_REMOVE; } -static void on_rename_done(tr_torrent const* tor G_GNUC_UNUSED, char const* oldpath G_GNUC_UNUSED, - char const* newname G_GNUC_UNUSED, int error, struct rename_data* rename_data) +static void on_rename_done( + tr_torrent const* tor G_GNUC_UNUSED, + char const* oldpath G_GNUC_UNUSED, + char const* newname G_GNUC_UNUSED, + int error, + struct rename_data* rename_data) { rename_data->error = error; gdk_threads_add_idle((GSourceFunc)on_rename_done_idle, rename_data); } -static void cell_edited_callback(GtkCellRendererText const* cell G_GNUC_UNUSED, gchar const* path_string, gchar const* newname, +static void cell_edited_callback( + GtkCellRendererText const* cell G_GNUC_UNUSED, + gchar const* path_string, + gchar const* newname, FileData* data) { tr_torrent* const tor = gtr_core_find_torrent(data->core, data->torrentId); @@ -975,8 +1008,14 @@ GtkWidget* gtr_file_list_new(TrCore* core, int torrentId) /* add "size" column */ title = _("Size"); rend = gtk_cell_renderer_text_new(); - g_object_set(rend, "alignment", PANGO_ALIGN_RIGHT, "font-desc", pango_font_description, "xpad", GUI_PAD, "xalign", 1.0F, - "yalign", 0.5F, NULL); + g_object_set( + rend, + TR_ARG_TUPLE("alignment", PANGO_ALIGN_RIGHT), + TR_ARG_TUPLE("font-desc", pango_font_description), + TR_ARG_TUPLE("xpad", GUI_PAD), + TR_ARG_TUPLE("xalign", 1.0F), + TR_ARG_TUPLE("yalign", 0.5F), + NULL); col = gtk_tree_view_column_new_with_attributes(title, rend, NULL); gtk_tree_view_column_set_sizing(col, GTK_TREE_VIEW_COLUMN_GROW_ONLY); gtk_tree_view_column_set_sort_column_id(col, FC_SIZE); diff --git a/gtk/filter.c b/gtk/filter.c index e1d5ff48f..7889f6725 100644 --- a/gtk/filter.c +++ b/gtk/filter.c @@ -173,8 +173,7 @@ static gboolean tracker_filter_model_update(gpointer gstore) g_free(keys); ++num_torrents; - } - while (gtk_tree_model_iter_next(tmodel, &iter)); + } while (gtk_tree_model_iter_next(tmodel, &iter)); } qsort(hosts->pdata, hosts->len, sizeof(char*), pstrcmp); @@ -242,11 +241,15 @@ static gboolean tracker_filter_model_update(gpointer gstore) char const* host = hosts->pdata[i]; char* name = get_name_from_host(host); int const count = *(int*)g_hash_table_lookup(hosts_hash, host); - gtk_tree_store_insert_with_values(store, &add, NULL, store_pos, - TRACKER_FILTER_COL_HOST, host, - TRACKER_FILTER_COL_NAME, name, - TRACKER_FILTER_COL_COUNT, count, - TRACKER_FILTER_COL_TYPE, TRACKER_FILTER_TYPE_HOST, + gtk_tree_store_insert_with_values( + store, + &add, + NULL, + store_pos, + TR_ARG_TUPLE(TRACKER_FILTER_COL_HOST, host), + TR_ARG_TUPLE(TRACKER_FILTER_COL_NAME, name), + TR_ARG_TUPLE(TRACKER_FILTER_COL_COUNT, count), + TR_ARG_TUPLE(TRACKER_FILTER_COL_TYPE, TRACKER_FILTER_TYPE_HOST), -1); path = gtk_tree_model_get_path(model, &add); reference = gtk_tree_row_reference_new(model, path); @@ -275,19 +278,28 @@ static gboolean tracker_filter_model_update(gpointer gstore) static GtkTreeModel* tracker_filter_model_new(GtkTreeModel* tmodel) { - GtkTreeStore* store = gtk_tree_store_new(TRACKER_FILTER_N_COLS, + GtkTreeStore* store = gtk_tree_store_new( + TRACKER_FILTER_N_COLS, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT, G_TYPE_STRING, GDK_TYPE_PIXBUF); - gtk_tree_store_insert_with_values(store, NULL, NULL, -1, - TRACKER_FILTER_COL_NAME, _("All"), - TRACKER_FILTER_COL_TYPE, TRACKER_FILTER_TYPE_ALL, + gtk_tree_store_insert_with_values( + store, + NULL, + NULL, + -1, + TR_ARG_TUPLE(TRACKER_FILTER_COL_NAME, _("All")), + TR_ARG_TUPLE(TRACKER_FILTER_COL_TYPE, TRACKER_FILTER_TYPE_ALL), -1); - gtk_tree_store_insert_with_values(store, NULL, NULL, -1, - TRACKER_FILTER_COL_TYPE, TRACKER_FILTER_TYPE_SEPARATOR, + gtk_tree_store_insert_with_values( + store, + NULL, + NULL, + -1, + TR_ARG_TUPLE(TRACKER_FILTER_COL_TYPE, TRACKER_FILTER_TYPE_SEPARATOR), -1); g_object_set_qdata(G_OBJECT(store), TORRENT_MODEL_KEY, tmodel); @@ -334,8 +346,12 @@ static void torrent_model_row_deleted_cb(GtkTreeModel* tmodel, GtkTreePath* path tracker_model_update_idle(tracker_model); } -static void render_pixbuf_func(GtkCellLayout* cell_layout, GtkCellRenderer* cell_renderer, GtkTreeModel* tree_model, - GtkTreeIter* iter, gpointer data) +static void render_pixbuf_func( + GtkCellLayout* cell_layout, + GtkCellRenderer* cell_renderer, + GtkTreeModel* tree_model, + GtkTreeIter* iter, + gpointer data) { TR_UNUSED(cell_layout); TR_UNUSED(data); @@ -348,8 +364,12 @@ static void render_pixbuf_func(GtkCellLayout* cell_layout, GtkCellRenderer* cell g_object_set(cell_renderer, "width", width, NULL); } -static void render_number_func(GtkCellLayout* cell_layout, GtkCellRenderer* cell_renderer, GtkTreeModel* tree_model, - GtkTreeIter* iter, gpointer data) +static void render_number_func( + GtkCellLayout* cell_layout, + GtkCellRenderer* cell_renderer, + GtkTreeModel* tree_model, + GtkTreeIter* iter, + gpointer data) { TR_UNUSED(cell_layout); TR_UNUSED(data); @@ -375,7 +395,12 @@ static GtkCellRenderer* number_renderer_new(void) { GtkCellRenderer* r = gtk_cell_renderer_text_new(); - g_object_set(G_OBJECT(r), "alignment", PANGO_ALIGN_RIGHT, "weight", PANGO_WEIGHT_ULTRALIGHT, "xalign", 1.0, "xpad", GUI_PAD, + g_object_set( + G_OBJECT(r), + TR_ARG_TUPLE("alignment", PANGO_ALIGN_RIGHT), + TR_ARG_TUPLE("weight", PANGO_WEIGHT_ULTRALIGHT), + TR_ARG_TUPLE("xalign", 1.0), + TR_ARG_TUPLE("xpad", GUI_PAD), NULL); return r; @@ -560,13 +585,11 @@ static gboolean activity_filter_model_update(gpointer gstore) { ++hits; } - } - while (gtk_tree_model_iter_next(tmodel, &torrent_iter)); + } while (gtk_tree_model_iter_next(tmodel, &torrent_iter)); } status_model_update_count(store, &iter, hits); - } - while (gtk_tree_model_iter_next(model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); } return G_SOURCE_REMOVE; @@ -580,9 +603,7 @@ static GtkTreeModel* activity_filter_model_new(GtkTreeModel* tmodel) char const* context; char const* name; char const* icon_name; - } - types[] = - { + } types[] = { { ACTIVITY_FILTER_ALL, NULL, N_("All"), NULL }, { ACTIVITY_FILTER_SEPARATOR, NULL, NULL, NULL }, { ACTIVITY_FILTER_ACTIVE, NULL, N_("Active"), "system-run" }, @@ -591,22 +612,21 @@ static GtkTreeModel* activity_filter_model_new(GtkTreeModel* tmodel) { ACTIVITY_FILTER_PAUSED, NULL, N_("Paused"), "media-playback-pause" }, { ACTIVITY_FILTER_FINISHED, NULL, N_("Finished"), "media-playback-stop" }, { ACTIVITY_FILTER_VERIFYING, "Verb", NC_("Verb", "Verifying"), "view-refresh" }, - { ACTIVITY_FILTER_ERROR, NULL, N_("Error"), "dialog-error" } + { ACTIVITY_FILTER_ERROR, NULL, N_("Error"), "dialog-error" }, }; - GtkListStore* store = gtk_list_store_new(ACTIVITY_FILTER_N_COLS, - G_TYPE_STRING, - G_TYPE_INT, - G_TYPE_INT, - G_TYPE_STRING); + GtkListStore* store = gtk_list_store_new(ACTIVITY_FILTER_N_COLS, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT, G_TYPE_STRING); for (size_t i = 0; i < G_N_ELEMENTS(types); ++i) { char const* name = types[i].context != NULL ? g_dpgettext2(NULL, types[i].context, types[i].name) : _(types[i].name); - gtk_list_store_insert_with_values(store, NULL, -1, - ACTIVITY_FILTER_COL_NAME, name, - ACTIVITY_FILTER_COL_TYPE, types[i].type, - ACTIVITY_FILTER_COL_ICON_NAME, types[i].icon_name, + gtk_list_store_insert_with_values( + store, + NULL, + -1, + TR_ARG_TUPLE(ACTIVITY_FILTER_COL_NAME, name), + TR_ARG_TUPLE(ACTIVITY_FILTER_COL_TYPE, types[i].type), + TR_ARG_TUPLE(ACTIVITY_FILTER_COL_ICON_NAME, types[i].icon_name), -1); } @@ -615,8 +635,12 @@ static GtkTreeModel* activity_filter_model_new(GtkTreeModel* tmodel) return GTK_TREE_MODEL(store); } -static void render_activity_pixbuf_func(GtkCellLayout* cell_layout, GtkCellRenderer* cell_renderer, GtkTreeModel* tree_model, - GtkTreeIter* iter, gpointer data) +static void render_activity_pixbuf_func( + GtkCellLayout* cell_layout, + GtkCellRenderer* cell_renderer, + GtkTreeModel* tree_model, + GtkTreeIter* iter, + gpointer data) { TR_UNUSED(cell_layout); TR_UNUSED(data); @@ -645,7 +669,10 @@ static void activity_model_update_idle(gpointer activity_model) } } -static void activity_torrent_model_row_changed(GtkTreeModel const* tmodel, GtkTreePath const* path, GtkTreeIter const* iter, +static void activity_torrent_model_row_changed( + GtkTreeModel const* tmodel, + GtkTreePath const* path, + GtkTreeIter const* iter, gpointer activity_model) { TR_UNUSED(tmodel); @@ -686,14 +713,12 @@ static GtkWidget* activity_combo_box_new(GtkTreeModel* tmodel) r = gtk_cell_renderer_pixbuf_new(); gtk_cell_layout_pack_start(c_cell_layout, r, FALSE); - gtk_cell_layout_set_attributes(c_cell_layout, r, - "icon-name", ACTIVITY_FILTER_COL_ICON_NAME, - NULL); + gtk_cell_layout_set_attributes(c_cell_layout, r, TR_ARG_TUPLE("icon-name", ACTIVITY_FILTER_COL_ICON_NAME), NULL); gtk_cell_layout_set_cell_data_func(c_cell_layout, r, render_activity_pixbuf_func, NULL, NULL); r = gtk_cell_renderer_text_new(); gtk_cell_layout_pack_start(c_cell_layout, r, TRUE); - gtk_cell_layout_set_attributes(c_cell_layout, r, "text", ACTIVITY_FILTER_COL_NAME, NULL); + gtk_cell_layout_set_attributes(c_cell_layout, r, TR_ARG_TUPLE("text", ACTIVITY_FILTER_COL_NAME), NULL); r = number_renderer_new(); gtk_cell_layout_pack_end(c_cell_layout, r, TRUE); @@ -823,9 +848,11 @@ static void selection_changed_cb(GtkComboBox* combo, gpointer vdata) if (gtk_combo_box_get_active_iter(combo, &iter)) { - gtk_tree_model_get(model, &iter, - TRACKER_FILTER_COL_TYPE, &type, - TRACKER_FILTER_COL_HOST, &host, + gtk_tree_model_get( + model, + &iter, + TR_ARG_TUPLE(TRACKER_FILTER_COL_TYPE, &type), + TR_ARG_TUPLE(TRACKER_FILTER_COL_HOST, &host), -1); } else @@ -914,7 +941,10 @@ static void update_count_label_idle(struct filter_data* data) } } -static void on_filter_model_row_inserted(GtkTreeModel const* tree_model, GtkTreePath const* path, GtkTreeIter const* iter, +static void on_filter_model_row_inserted( + GtkTreeModel const* tree_model, + GtkTreePath const* path, + GtkTreeIter const* iter, gpointer data) { TR_UNUSED(tree_model); diff --git a/gtk/hig.c b/gtk/hig.c index bfd994b62..eedb4d20a 100644 --- a/gtk/hig.c +++ b/gtk/hig.c @@ -7,6 +7,9 @@ */ #include + +#include + #include "hig.h" GtkWidget* hig_workarea_create(void) @@ -86,10 +89,11 @@ void hig_workarea_add_label_w(GtkWidget* t, guint row, GtkWidget* w) if (GTK_IS_LABEL(w)) { - g_object_set(w, - "halign", GTK_ALIGN_START, - "valign", GTK_ALIGN_CENTER, - "use-markup", TRUE, + g_object_set( + w, + TR_ARG_TUPLE("halign", GTK_ALIGN_START), + TR_ARG_TUPLE("valign", GTK_ALIGN_CENTER), + TR_ARG_TUPLE("use-markup", TRUE), NULL); } @@ -100,10 +104,7 @@ static void hig_workarea_add_tall_control(GtkWidget* t, guint row, GtkWidget* co { if (GTK_IS_LABEL(control)) { - g_object_set(control, - "halign", GTK_ALIGN_START, - "valign", GTK_ALIGN_CENTER, - NULL); + g_object_set(control, TR_ARG_TUPLE("halign", GTK_ALIGN_START), TR_ARG_TUPLE("valign", GTK_ALIGN_CENTER), NULL); } g_object_set(control, "expand", TRUE, NULL); @@ -114,10 +115,7 @@ static void hig_workarea_add_control(GtkWidget* t, guint row, GtkWidget* control { if (GTK_IS_LABEL(control)) { - g_object_set(control, - "halign", GTK_ALIGN_START, - "valign", GTK_ALIGN_CENTER, - NULL); + g_object_set(control, TR_ARG_TUPLE("halign", GTK_ALIGN_START), TR_ARG_TUPLE("valign", GTK_ALIGN_CENTER), NULL); } gtk_widget_set_hexpand(control, TRUE); @@ -145,7 +143,11 @@ GtkWidget* hig_workarea_add_row(GtkWidget* t, guint* row, char const* mnemonic_s return l; } -GtkWidget* hig_workarea_add_tall_row(GtkWidget* table, guint* row, char const* mnemonic_string, GtkWidget* control, +GtkWidget* hig_workarea_add_tall_row( + GtkWidget* table, + guint* row, + char const* mnemonic_string, + GtkWidget* control, GtkWidget* mnemonic) { GtkWidget* l = gtk_label_new_with_mnemonic(mnemonic_string); diff --git a/gtk/hig.h b/gtk/hig.h index f5894100a..828a50d87 100644 --- a/gtk/hig.h +++ b/gtk/hig.h @@ -31,13 +31,25 @@ GtkWidget* hig_workarea_add_wide_checkbutton(GtkWidget* table, guint* row, char void hig_workarea_add_label_w(GtkWidget* table, guint row, GtkWidget* label_widget); -GtkWidget* hig_workarea_add_tall_row(GtkWidget* table, guint* row, char const* mnemonic_string, GtkWidget* control, +GtkWidget* hig_workarea_add_tall_row( + GtkWidget* table, + guint* row, + char const* mnemonic_string, + GtkWidget* control, GtkWidget* mnemonic_or_null_for_control); -GtkWidget* hig_workarea_add_row(GtkWidget* table, guint* row, char const* mnemonic_string, GtkWidget* control, +GtkWidget* hig_workarea_add_row( + GtkWidget* table, + guint* row, + char const* mnemonic_string, + GtkWidget* control, GtkWidget* mnemonic_or_null_for_control); -void hig_workarea_add_row_w(GtkWidget* table, guint* row, GtkWidget* label, GtkWidget* control, +void hig_workarea_add_row_w( + GtkWidget* table, + guint* row, + GtkWidget* label, + GtkWidget* control, GtkWidget* mnemonic_or_null_for_control); enum diff --git a/gtk/icons.c b/gtk/icons.c index 20654ef56..377273d81 100644 --- a/gtk/icons.c +++ b/gtk/icons.c @@ -34,8 +34,7 @@ typedef struct GtkIconTheme* icon_theme; int icon_size; GHashTable* cache; -} -IconCache; +} IconCache; static IconCache* icon_cache[7] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL }; @@ -66,8 +65,7 @@ static IconCache* icon_cache_new(GtkWidget* for_widget, int 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, - icons->icon_size)); + g_hash_table_insert(icons->cache, (void*)VOID_PIXBUF_KEY, create_void_pixbuf(icons->icon_size, icons->icon_size)); return icons; } diff --git a/gtk/main.c b/gtk/main.c index 44bf86a90..6b2ff90cb 100644 --- a/gtk/main.c +++ b/gtk/main.c @@ -455,8 +455,11 @@ static gboolean on_rpc_changed_idle(gpointer gdata) return G_SOURCE_REMOVE; } -static tr_rpc_callback_status on_rpc_changed(tr_session* session G_GNUC_UNUSED, tr_rpc_callback_type type, - struct tr_torrent* tor, void* gdata) +static tr_rpc_callback_status on_rpc_changed( + tr_session* session G_GNUC_UNUSED, + tr_rpc_callback_type type, + struct tr_torrent* tor, + void* gdata) { struct cbdata* cbdata = gdata; struct on_rpc_changed_struct* data; @@ -547,8 +550,7 @@ static void on_startup(GApplication* application, gpointer user_data) tr_sessionSetRPCCallback(session, on_rpc_changed, cbdata); /* check & see if it's time to update the blocklist */ - if (gtr_pref_flag_get(TR_KEY_blocklist_enabled) && - gtr_pref_flag_get(TR_KEY_blocklist_updates_enabled)) + if (gtr_pref_flag_get(TR_KEY_blocklist_enabled) && gtr_pref_flag_get(TR_KEY_blocklist_updates_enabled)) { int64_t const last_time = gtr_pref_int_get(TR_KEY_blocklist_date); int const SECONDS_IN_A_WEEK = 7 * 24 * 60 * 60; @@ -623,8 +625,7 @@ int main(int argc, char** argv) GError* error = NULL; struct cbdata cbdata; - GOptionEntry option_entries[] = - { + GOptionEntry option_entries[] = { { "config-dir", 'g', 0, G_OPTION_ARG_FILENAME, &cbdata.config_dir, _("Where to look for configuration files"), NULL }, { "paused", 'p', 0, G_OPTION_ARG_NONE, &cbdata.start_paused, _("Start with all torrents paused"), NULL }, { "minimized", 'm', 0, G_OPTION_ARG_NONE, &cbdata.is_iconified, _("Start minimized in notification area"), NULL }, @@ -687,7 +688,9 @@ int main(int argc, char** argv) /* init the application for the specified config dir */ stat(cbdata.config_dir, &sb); - application_id = g_strdup_printf("com.transmissionbt.transmission_%lu_%lu", (unsigned long)sb.st_dev, + application_id = g_strdup_printf( + "com.transmissionbt.transmission_%lu_%lu", + (unsigned long)sb.st_dev, (unsigned long)sb.st_ino); app = gtk_application_new(application_id, G_APPLICATION_HANDLES_OPEN); g_signal_connect(app, "open", G_CALLBACK(on_open), &cbdata); @@ -756,9 +759,14 @@ static void app_setup(GtkWindow* wind, struct cbdata* cbdata) if (!gtr_pref_flag_get(TR_KEY_user_has_given_informed_consent)) { - GtkWidget* w = gtk_message_dialog_new(GTK_WINDOW(wind), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_OTHER, - GTK_BUTTONS_NONE, "%s", _("Transmission is a file sharing program. When you run a torrent, its data will be " - "made available to others by means of upload. Any content you share is your sole responsibility.")); + GtkWidget* w = gtk_message_dialog_new( + GTK_WINDOW(wind), + GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_OTHER, + GTK_BUTTONS_NONE, + "%s", + _("Transmission is a file sharing program. When you run a torrent, its data will be " + "made available to others by means of upload. Any content you share is your sole responsibility.")); gtk_dialog_add_button(GTK_DIALOG(w), _("_Cancel"), GTK_RESPONSE_REJECT); gtk_dialog_add_button(GTK_DIALOG(w), _("I _Agree"), GTK_RESPONSE_ACCEPT); gtk_dialog_set_default_response(GTK_DIALOG(w), GTK_RESPONSE_ACCEPT); @@ -779,10 +787,11 @@ 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), + 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)); + 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) @@ -860,8 +869,15 @@ static void rowChangedCB(GtkTreeModel const* model, GtkTreePath* path, GtkTreeIt } } -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) +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); @@ -1000,8 +1016,11 @@ static void on_app_exit(gpointer vdata) c = GTK_WIDGET(cbdata->wind); gtk_container_remove(GTK_CONTAINER(c), gtk_bin_get_child(GTK_BIN(c))); - p = - g_object_new(GTK_TYPE_GRID, "column-spacing", GUI_PAD_BIG, "halign", GTK_ALIGN_CENTER, "valign", GTK_ALIGN_CENTER, + p = g_object_new( + GTK_TYPE_GRID, + TR_ARG_TUPLE("column-spacing", GUI_PAD_BIG), + TR_ARG_TUPLE("halign", GTK_ALIGN_CENTER), + TR_ARG_TUPLE("valign", GTK_ALIGN_CENTER), NULL); gtk_container_add(GTK_CONTAINER(c), p); @@ -1066,14 +1085,21 @@ static void flush_torrent_errors(struct cbdata* cbdata) { if (cbdata->error_list != NULL) { - show_torrent_errors(cbdata->wind, ngettext("Couldn't add corrupt torrent", "Couldn't add corrupt torrents", - g_slist_length(cbdata->error_list)), &cbdata->error_list); + show_torrent_errors( + cbdata->wind, + ngettext("Couldn't add corrupt torrent", "Couldn't add corrupt torrents", g_slist_length(cbdata->error_list)), + &cbdata->error_list); } if (cbdata->duplicates_list != NULL) { - show_torrent_errors(cbdata->wind, ngettext("Couldn't add duplicate torrent", "Couldn't add duplicate torrents", - g_slist_length(cbdata->duplicates_list)), &cbdata->duplicates_list); + show_torrent_errors( + cbdata->wind, + ngettext( + "Couldn't add duplicate torrent", + "Couldn't add duplicate torrents", + g_slist_length(cbdata->duplicates_list)), + &cbdata->duplicates_list); } } @@ -1388,30 +1414,30 @@ static gboolean update_model_loop(gpointer gdata) static void show_about_dialog(GtkWindow* parent) { char const* uri = "https://transmissionbt.com/"; - char const* authors[] = - { + char const* authors[] = { "Charles Kerr (Backend; GTK+)", "Mitchell Livingston (Backend; OS X)", "Mike Gelfand", - NULL + NULL, }; - gtk_show_about_dialog(parent, - "authors", authors, - "comments", _("A fast and easy BitTorrent client"), - "copyright", _("Copyright (c) The Transmission Project"), - "logo-icon-name", MY_CONFIG_NAME, - "name", g_get_application_name(), + gtk_show_about_dialog( + parent, + TR_ARG_TUPLE("authors", authors), + TR_ARG_TUPLE("comments", _("A fast and easy BitTorrent client")), + TR_ARG_TUPLE("copyright", _("Copyright (c) The Transmission Project")), + TR_ARG_TUPLE("logo-icon-name", MY_CONFIG_NAME), + TR_ARG_TUPLE("name", g_get_application_name()), /* Translators: translate "translator-credits" as your name to have it appear in the credits in the "About" dialog */ - "translator-credits", _("translator-credits"), - "version", LONG_VERSION_STRING, - "website", uri, - "website-label", uri, + TR_ARG_TUPLE("translator-credits", _("translator-credits")), + TR_ARG_TUPLE("version", LONG_VERSION_STRING), + TR_ARG_TUPLE("website", uri), + TR_ARG_TUPLE("website-label", uri), #ifdef SHOW_LICENSE - "license", LICENSE, - "wrap-license", TRUE, + TR_ARG_TUPLE("license", LICENSE), + TR_ARG_TUPLE("wrap-license", TRUE), #endif NULL); } @@ -1605,7 +1631,8 @@ void gtr_actions_handler(char const* action_name, gpointer user_data) gtk_widget_show(w); } } - else if (g_strcmp0(action_name, "torrent-start") == 0 || g_strcmp0(action_name, "torrent-start-now") == 0 || + else if ( + g_strcmp0(action_name, "torrent-start") == 0 || g_strcmp0(action_name, "torrent-start-now") == 0 || g_strcmp0(action_name, "torrent-stop") == 0 || g_strcmp0(action_name, "torrent-reannounce") == 0 || g_strcmp0(action_name, "torrent-verify") == 0 || g_strcmp0(action_name, "queue-move-top") == 0 || g_strcmp0(action_name, "queue-move-up") == 0 || g_strcmp0(action_name, "queue-move-down") == 0 || diff --git a/gtk/makemeta-ui.c b/gtk/makemeta-ui.c index 5273752cc..7f350ec52 100644 --- a/gtk/makemeta-ui.c +++ b/gtk/makemeta-ui.c @@ -41,8 +41,7 @@ typedef struct GtkTextBuffer* announce_text_buffer; TrCore* core; tr_metainfo_builder* builder; -} -MakeMetaUI; +} MakeMetaUI; static void freeMetaUI(gpointer p) { @@ -163,7 +162,7 @@ static void onProgressDialogResponse(GtkDialog* d, int response, gpointer data) case GTK_RESPONSE_ACCEPT: addTorrent(ui); - /* fall-through */ + /* fall-through */ case GTK_RESPONSE_CLOSE: gtk_widget_destroy(ui->builder->result ? GTK_WIDGET(d) : ui->dialog); @@ -182,10 +181,13 @@ static void makeProgressDialog(GtkWidget* parent, MakeMetaUI* ui) GtkWidget* v; GtkWidget* fr; - d = gtk_dialog_new_with_buttons(_("New Torrent"), GTK_WINDOW(parent), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, - _("_Cancel"), GTK_RESPONSE_CANCEL, - _("_Close"), GTK_RESPONSE_CLOSE, - _("_Add"), GTK_RESPONSE_ACCEPT, + d = gtk_dialog_new_with_buttons( + _("New Torrent"), + GTK_WINDOW(parent), + GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, + TR_ARG_TUPLE(_("_Cancel"), GTK_RESPONSE_CANCEL), + TR_ARG_TUPLE(_("_Close"), GTK_RESPONSE_CLOSE), + TR_ARG_TUPLE(_("_Add"), GTK_RESPONSE_ACCEPT), NULL); ui->progress_dialog = d; g_signal_connect(d, "response", G_CALLBACK(onProgressDialogResponse), ui); @@ -312,13 +314,19 @@ static void updatePiecesLabel(MakeMetaUI* ui) { char buf[128]; tr_strlsize(buf, builder->totalSize, sizeof(buf)); - g_string_append_printf(gstr, ngettext("%1$s; %2$'d File", "%1$s; %2$'d Files", builder->fileCount), buf, + g_string_append_printf( + gstr, + ngettext("%1$s; %2$'d File", "%1$s; %2$'d Files", builder->fileCount), + buf, builder->fileCount); g_string_append(gstr, "; "); tr_formatter_mem_B(buf, builder->pieceSize, sizeof(buf)); - g_string_append_printf(gstr, ngettext("%1$'d Piece @ %2$s", "%1$'d Pieces @ %2$s", builder->pieceCount), - builder->pieceCount, buf); + g_string_append_printf( + gstr, + ngettext("%1$'d Piece @ %2$s", "%1$'d Pieces @ %2$s", builder->pieceCount), + builder->pieceCount, + buf); } g_string_append(gstr, ""); @@ -386,8 +394,15 @@ static char const* getDefaultSavePath(void) return g_get_user_special_dir(G_USER_DIRECTORY_DESKTOP); } -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 user_data) +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 user_data) { TR_UNUSED(widget); TR_UNUSED(x); @@ -441,9 +456,12 @@ GtkWidget* gtr_torrent_creation_dialog_new(GtkWindow* parent, TrCore* core) ui->core = core; - d = gtk_dialog_new_with_buttons(_("New Torrent"), parent, GTK_DIALOG_DESTROY_WITH_PARENT, - _("_Close"), GTK_RESPONSE_CLOSE, - _("_New"), GTK_RESPONSE_ACCEPT, + d = gtk_dialog_new_with_buttons( + _("New Torrent"), + parent, + GTK_DIALOG_DESTROY_WITH_PARENT, + TR_ARG_TUPLE(_("_Close"), GTK_RESPONSE_CLOSE), + TR_ARG_TUPLE(_("_New"), GTK_RESPONSE_ACCEPT), NULL); ui->dialog = d; g_signal_connect(d, "response", G_CALLBACK(onResponse), ui); @@ -470,7 +488,7 @@ GtkWidget* gtr_torrent_creation_dialog_new(GtkWindow* parent, TrCore* core) gtk_widget_set_sensitive(GTK_WIDGET(w), FALSE); hig_workarea_add_row_w(t, &row, l, w, NULL); - slist = gtk_radio_button_get_group(GTK_RADIO_BUTTON(l)), + slist = gtk_radio_button_get_group(GTK_RADIO_BUTTON(l)); l = gtk_radio_button_new_with_mnemonic(slist, _("Source _File:")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(l), TRUE); w = gtk_file_chooser_button_new(NULL, GTK_FILE_CHOOSER_ACTION_OPEN); @@ -502,8 +520,10 @@ GtkWidget* gtr_torrent_creation_dialog_new(GtkWindow* parent, TrCore* core) gtk_container_add(GTK_CONTAINER(fr), sw); gtk_box_pack_start(GTK_BOX(v), fr, TRUE, TRUE, 0); l = gtk_label_new(NULL); - gtk_label_set_markup(GTK_LABEL(l), _("To add a backup URL, add it on the line after the primary URL.\n" - "To add another primary URL, add it after a blank line.")); + gtk_label_set_markup( + GTK_LABEL(l), + _("To add a backup URL, add it on the line after the primary URL.\n" + "To add another primary URL, add it after a blank line.")); gtk_label_set_justify(GTK_LABEL(l), GTK_JUSTIFY_LEFT); g_object_set(l, "halign", GTK_ALIGN_START, "valign", GTK_ALIGN_CENTER, NULL); gtk_box_pack_start(GTK_BOX(v), l, FALSE, FALSE, 0); diff --git a/gtk/msgwin.c b/gtk/msgwin.c index b068be611..ff314987c 100644 --- a/gtk/msgwin.c +++ b/gtk/msgwin.c @@ -135,8 +135,8 @@ static void doSave(GtkWindow* parent, struct MsgData* data, char const* filename if (fp == NULL) { - GtkWidget* w = gtk_message_dialog_new(parent, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, _("Couldn't save \"%s\""), - filename); + GtkWidget* + w = gtk_message_dialog_new(parent, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, _("Couldn't save \"%s\""), filename); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(w), "%s", g_strerror(errno)); g_signal_connect_swapped(w, "response", G_CALLBACK(gtk_widget_destroy), w); gtk_widget_show(w); @@ -171,11 +171,15 @@ static void doSave(GtkWindow* parent, struct MsgData* data, char const* filename break; } - fprintf(fp, "%s\t%s\t%s\t%s\n", date, levelStr, node->name != NULL ? node->name : "", + fprintf( + fp, + "%s\t%s\t%s\t%s\n", + date, + levelStr, + node->name != NULL ? node->name : "", node->message != NULL ? node->message : ""); g_free(date); - } - while (gtk_tree_model_iter_next(model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); } fclose(fp); @@ -197,9 +201,12 @@ static void onSaveDialogResponse(GtkWidget* d, int response, gpointer data) static void onSaveRequest(GtkWidget* w, gpointer data) { GtkWindow* window = GTK_WINDOW(gtk_widget_get_toplevel(w)); - GtkWidget* d = gtk_file_chooser_dialog_new(_("Save Log"), window, GTK_FILE_CHOOSER_ACTION_SAVE, - _("_Cancel"), GTK_RESPONSE_CANCEL, - _("_Save"), GTK_RESPONSE_ACCEPT, + GtkWidget* d = gtk_file_chooser_dialog_new( + _("Save Log"), + window, + GTK_FILE_CHOOSER_ACTION_SAVE, + TR_ARG_TUPLE(_("_Cancel"), GTK_RESPONSE_CANCEL), + TR_ARG_TUPLE(_("_Save"), GTK_RESPONSE_ACCEPT), NULL); g_signal_connect(d, "response", G_CALLBACK(onSaveDialogResponse), data); @@ -243,7 +250,11 @@ static char const* getForegroundColor(int msgLevel) } } -static void renderText(GtkTreeViewColumn* column, GtkCellRenderer* renderer, GtkTreeModel* tree_model, GtkTreeIter* iter, +static void renderText( + GtkTreeViewColumn* column, + GtkCellRenderer* renderer, + GtkTreeModel* tree_model, + GtkTreeIter* iter, gpointer gcol) { TR_UNUSED(column); @@ -256,7 +267,11 @@ static void renderText(GtkTreeViewColumn* column, GtkCellRenderer* renderer, Gtk g_object_set(renderer, "text", str, "foreground", getForegroundColor(node->level), "ellipsize", PANGO_ELLIPSIZE_END, NULL); } -static void renderTime(GtkTreeViewColumn* column, GtkCellRenderer* renderer, GtkTreeModel* tree_model, GtkTreeIter* iter, +static void renderTime( + GtkTreeViewColumn* column, + GtkCellRenderer* renderer, + GtkTreeModel* tree_model, + GtkTreeIter* iter, gpointer data) { TR_UNUSED(column); @@ -363,11 +378,14 @@ static tr_log_message* addMessages(GtkListStore* store, struct tr_log_message* h { char const* name = i->name != NULL ? i->name : default_name; - gtk_list_store_insert_with_values(store, NULL, 0, - COL_TR_MSG, i, - COL_NAME, name, - COL_MESSAGE, i->message, - COL_SEQUENCE, ++sequence, + gtk_list_store_insert_with_values( + store, + NULL, + 0, + TR_ARG_TUPLE(COL_TR_MSG, i), + TR_ARG_TUPLE(COL_NAME, name), + TR_ARG_TUPLE(COL_MESSAGE, i->message), + TR_ARG_TUPLE(COL_SEQUENCE, ++sequence), -1); /* if it's an error message, dump it to the terminal too */ @@ -428,9 +446,9 @@ static gboolean onRefresh(gpointer gdata) static GtkWidget* debug_level_combo_new(void) { GtkWidget* w = gtr_combo_box_new_enum( - _("Error"), TR_LOG_ERROR, - _("Information"), TR_LOG_INFO, - _("Debug"), TR_LOG_DEBUG, + TR_ARG_TUPLE(_("Error"), TR_LOG_ERROR), + TR_ARG_TUPLE(_("Information"), TR_LOG_INFO), + TR_ARG_TUPLE(_("Debug"), TR_LOG_DEBUG), NULL); gtr_combo_box_set_active_enum(GTK_COMBO_BOX(w), gtr_pref_int_get(TR_KEY_message_level)); return w; @@ -469,21 +487,23 @@ GtkWidget* gtr_message_log_window_new(GtkWindow* parent, TrCore* core) gtk_style_context_add_class(gtk_widget_get_style_context(toolbar), GTK_STYLE_CLASS_PRIMARY_TOOLBAR); item = gtk_tool_button_new(NULL, NULL); - g_object_set(item, - "icon-name", "document-save-as", - "is-important", TRUE, - "label", _("Save _As"), - "use-underline", TRUE, + g_object_set( + item, + TR_ARG_TUPLE("icon-name", "document-save-as"), + TR_ARG_TUPLE("is-important", TRUE), + TR_ARG_TUPLE("label", _("Save _As")), + TR_ARG_TUPLE("use-underline", TRUE), NULL); g_signal_connect(item, "clicked", G_CALLBACK(onSaveRequest), data); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), item, -1); item = gtk_tool_button_new(NULL, NULL); - g_object_set(item, - "icon-name", "edit-clear", - "is-important", TRUE, - "label", _("Clear"), - "use-underline", TRUE, + g_object_set( + item, + TR_ARG_TUPLE("icon-name", "edit-clear"), + TR_ARG_TUPLE("is-important", TRUE), + TR_ARG_TUPLE("label", _("Clear")), + TR_ARG_TUPLE("use-underline", TRUE), NULL); g_signal_connect(item, "clicked", G_CALLBACK(onClearRequest), data); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), item, -1); @@ -492,11 +512,12 @@ GtkWidget* gtr_message_log_window_new(GtkWindow* parent, TrCore* core) gtk_toolbar_insert(GTK_TOOLBAR(toolbar), item, -1); item = gtk_toggle_tool_button_new(); - g_object_set(G_OBJECT(item), - "icon-name", "media-playback-pause", - "is-important", TRUE, - "label", _("P_ause"), - "use-underline", TRUE, + g_object_set( + G_OBJECT(item), + TR_ARG_TUPLE("icon-name", "media-playback-pause"), + TR_ARG_TUPLE("is-important", TRUE), + TR_ARG_TUPLE("label", _("P_ause")), + TR_ARG_TUPLE("use-underline", TRUE), NULL); g_signal_connect(item, "toggled", G_CALLBACK(onPauseToggled), data); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), item, -1); @@ -522,7 +543,8 @@ GtkWidget* gtr_message_log_window_new(GtkWindow* parent, TrCore* core) *** messages **/ - data->store = gtk_list_store_new(N_COLUMNS, + data->store = gtk_list_store_new( + N_COLUMNS, G_TYPE_UINT, /* sequence */ G_TYPE_POINTER, /* category */ G_TYPE_POINTER, /* message */ diff --git a/gtk/notify.c b/gtk/notify.c index 622c49120..98402abd8 100644 --- a/gtk/notify.c +++ b/gtk/notify.c @@ -26,8 +26,7 @@ typedef struct TrNotification { TrCore* core; int torrent_id; -} -TrNotification; +} TrNotification; static void tr_notification_free(gpointer data) { @@ -75,7 +74,11 @@ static void get_capabilities_callback(GObject* source, GAsyncResult* res, gpoint g_variant_unref(result); } -static void g_signal_callback(GDBusProxy const* dbus_proxy, char const* sender_name, char const* signal_name, GVariant* params, +static void g_signal_callback( + GDBusProxy const* dbus_proxy, + char const* sender_name, + char const* signal_name, + GVariant* params, gconstpointer user_data) { TR_UNUSED(dbus_proxy); @@ -139,15 +142,30 @@ static void dbus_proxy_ready_callback(GObject* source, GAsyncResult* res, gpoint } g_signal_connect(proxy, "g-signal", G_CALLBACK(g_signal_callback), NULL); - g_dbus_proxy_call(proxy, "GetCapabilities", g_variant_new("()"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, - get_capabilities_callback, NULL); + g_dbus_proxy_call( + proxy, + "GetCapabilities", + g_variant_new("()"), + G_DBUS_CALL_FLAGS_NONE, + -1, + NULL, + get_capabilities_callback, + NULL); } void gtr_notify_init(void) { active_notifications = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, tr_notification_free); - g_dbus_proxy_new_for_bus(G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES, NULL, NOTIFICATIONS_DBUS_NAME, - NOTIFICATIONS_DBUS_CORE_OBJECT, NOTIFICATIONS_DBUS_CORE_INTERFACE, NULL, dbus_proxy_ready_callback, NULL); + g_dbus_proxy_new_for_bus( + G_BUS_TYPE_SESSION, + G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES, + NULL, + NOTIFICATIONS_DBUS_NAME, + NOTIFICATIONS_DBUS_CORE_OBJECT, + NOTIFICATIONS_DBUS_CORE_INTERFACE, + NULL, + dbus_proxy_ready_callback, + NULL); } static void notify_callback(GObject* source, GAsyncResult* res, gpointer user_data) @@ -180,7 +198,8 @@ void gtr_notify_torrent_completed(TrCore* core, int torrent_id) if (gtr_pref_flag_get(TR_KEY_torrent_complete_sound_enabled)) { char** argv = gtr_pref_strv_get(TR_KEY_torrent_complete_sound_command); - g_spawn_async(NULL /*cwd*/, + g_spawn_async( + NULL /*cwd*/, argv, NULL /*envp*/, G_SPAWN_SEARCH_PATH, @@ -227,9 +246,24 @@ void gtr_notify_torrent_completed(TrCore* core, int torrent_id) g_variant_builder_init(&hints_builder, G_VARIANT_TYPE("a{sv}")); g_variant_builder_add(&hints_builder, "{sv}", "category", g_variant_new_string("transfer.complete")); - g_dbus_proxy_call(proxy, "Notify", g_variant_new("(susssasa{sv}i)", "Transmission", 0, "transmission", - _("Torrent Complete"), tr_torrentName(tor), &actions_builder, &hints_builder, -1), G_DBUS_CALL_FLAGS_NONE, -1, NULL, - notify_callback, n); + g_dbus_proxy_call( + proxy, + "Notify", + g_variant_new( + "(susssasa{sv}i)", + "Transmission", + 0, + "transmission", + _("Torrent Complete"), + tr_torrentName(tor), + &actions_builder, + &hints_builder, + -1), + G_DBUS_CALL_FLAGS_NONE, + -1, + NULL, + notify_callback, + n); } void gtr_notify_torrent_added(char const* name) @@ -244,6 +278,13 @@ void gtr_notify_torrent_added(char const* name) } n = g_new0(TrNotification, 1); - g_dbus_proxy_call(proxy, "Notify", g_variant_new("(susssasa{sv}i)", "Transmission", 0, "transmission", _("Torrent Added"), - name, NULL, NULL, -1), G_DBUS_CALL_FLAGS_NONE, -1, NULL, notify_callback, n); + g_dbus_proxy_call( + proxy, + "Notify", + g_variant_new("(susssasa{sv}i)", "Transmission", 0, "transmission", _("Torrent Added"), name, NULL, NULL, -1), + G_DBUS_CALL_FLAGS_NONE, + -1, + NULL, + notify_callback, + n); } diff --git a/gtk/open-dialog.c b/gtk/open-dialog.c index b7567a4d2..20b23be35 100644 --- a/gtk/open-dialog.c +++ b/gtk/open-dialog.c @@ -281,9 +281,12 @@ GtkWidget* gtr_torrent_options_dialog_new(GtkWindow* parent, TrCore* core, tr_ct GSList* list; /* make the dialog */ - d = gtk_dialog_new_with_buttons(_("Torrent Options"), parent, GTK_DIALOG_DESTROY_WITH_PARENT, - _("_Cancel"), GTK_RESPONSE_CANCEL, - _("_Open"), GTK_RESPONSE_ACCEPT, + d = gtk_dialog_new_with_buttons( + _("Torrent Options"), + parent, + GTK_DIALOG_DESTROY_WITH_PARENT, + TR_ARG_TUPLE(_("_Cancel"), GTK_RESPONSE_CANCEL), + TR_ARG_TUPLE(_("_Open"), GTK_RESPONSE_ACCEPT), NULL); gtk_dialog_set_default_response(GTK_DIALOG(d), GTK_RESPONSE_ACCEPT); @@ -454,9 +457,12 @@ GtkWidget* gtr_torrent_open_from_file_dialog_new(GtkWindow* parent, TrCore* core GtkWidget* c; char const* folder; - w = gtk_file_chooser_dialog_new(_("Open a Torrent"), parent, GTK_FILE_CHOOSER_ACTION_OPEN, - _("_Cancel"), GTK_RESPONSE_CANCEL, - _("_Open"), GTK_RESPONSE_ACCEPT, + w = gtk_file_chooser_dialog_new( + _("Open a Torrent"), + parent, + GTK_FILE_CHOOSER_ACTION_OPEN, + TR_ARG_TUPLE(_("_Cancel"), GTK_RESPONSE_CANCEL), + TR_ARG_TUPLE(_("_Open"), GTK_RESPONSE_ACCEPT), NULL); gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(w), TRUE); addTorrentFilters(GTK_FILE_CHOOSER(w)); @@ -519,9 +525,12 @@ GtkWidget* gtr_torrent_open_from_url_dialog_new(GtkWindow* parent, TrCore* core) GtkWidget* t; GtkWidget* w; - w = gtk_dialog_new_with_buttons(_("Open URL"), parent, GTK_DIALOG_DESTROY_WITH_PARENT, - _("_Cancel"), GTK_RESPONSE_CANCEL, - _("_Open"), GTK_RESPONSE_ACCEPT, + w = gtk_dialog_new_with_buttons( + _("Open URL"), + parent, + GTK_DIALOG_DESTROY_WITH_PARENT, + TR_ARG_TUPLE(_("_Cancel"), GTK_RESPONSE_CANCEL), + TR_ARG_TUPLE(_("_Open"), GTK_RESPONSE_ACCEPT), NULL); g_signal_connect(w, "response", G_CALLBACK(onOpenURLResponse), core); diff --git a/gtk/relocate.c b/gtk/relocate.c index a494590da..614bfc206 100644 --- a/gtk/relocate.c +++ b/gtk/relocate.c @@ -72,8 +72,13 @@ static gboolean onTimer(gpointer gdata) if (done == TR_LOC_ERROR) { int const flags = GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT; - GtkWidget* w = gtk_message_dialog_new(GTK_WINDOW(data->message_dialog), flags, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, - "%s", _("Couldn't move torrent")); + GtkWidget* w = gtk_message_dialog_new( + GTK_WINDOW(data->message_dialog), + flags, + GTK_MESSAGE_ERROR, + GTK_BUTTONS_CLOSE, + "%s", + _("Couldn't move torrent")); gtk_dialog_run(GTK_DIALOG(w)); gtk_widget_destroy(GTK_WIDGET(data->message_dialog)); } @@ -108,8 +113,12 @@ static void onResponse(GtkDialog* dialog, int response, gconstpointer user_data) data->do_move = gtk_toggle_button_get_active(move_tb); /* pop up a dialog saying that the work is in progress */ - w = gtk_message_dialog_new(GTK_WINDOW(dialog), GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, - GTK_BUTTONS_CLOSE, NULL); + w = gtk_message_dialog_new( + GTK_WINDOW(dialog), + GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL, + GTK_MESSAGE_INFO, + GTK_BUTTONS_CLOSE, + NULL); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(w), _("This may take a moment…")); gtk_dialog_set_response_sensitive(GTK_DIALOG(w), GTK_RESPONSE_CLOSE, FALSE); gtk_widget_show(w); @@ -138,9 +147,12 @@ GtkWidget* gtr_relocate_dialog_new(GtkWindow* parent, TrCore* core, GSList* torr GtkWidget* t; struct relocate_dialog_data* data; - d = gtk_dialog_new_with_buttons(_("Set Torrent Location"), parent, GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL, - _("_Cancel"), GTK_RESPONSE_CANCEL, - _("_Apply"), GTK_RESPONSE_APPLY, + d = gtk_dialog_new_with_buttons( + _("Set Torrent Location"), + parent, + GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL, + TR_ARG_TUPLE(_("_Cancel"), GTK_RESPONSE_CANCEL), + TR_ARG_TUPLE(_("_Apply"), GTK_RESPONSE_APPLY), NULL); gtk_dialog_set_default_response(GTK_DIALOG(d), GTK_RESPONSE_CANCEL); g_signal_connect(d, "response", G_CALLBACK(onResponse), NULL); diff --git a/gtk/stats.c b/gtk/stats.c index 24d27bcb2..8df5a3c53 100644 --- a/gtk/stats.c +++ b/gtk/stats.c @@ -90,13 +90,15 @@ static void dialogResponse(GtkDialog* dialog, gint response, gpointer gdata) if (response == TR_RESPONSE_RESET) { char const* primary = _("Reset your statistics?"); - char const* secondary = _("These statistics are for your information only. " + char const* secondary = _( + "These statistics are for your information only. " "Resetting them doesn't affect the statistics logged by your BitTorrent trackers."); int const flags = GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL; GtkWidget* w = gtk_message_dialog_new(GTK_WINDOW(dialog), flags, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, "%s", primary); - gtk_dialog_add_buttons(GTK_DIALOG(w), - _("_Cancel"), GTK_RESPONSE_CANCEL, - _("_Reset"), TR_RESPONSE_RESET, + gtk_dialog_add_buttons( + GTK_DIALOG(w), + TR_ARG_TUPLE(_("_Cancel"), GTK_RESPONSE_CANCEL), + TR_ARG_TUPLE(_("_Reset"), TR_RESPONSE_RESET), NULL); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(w), "%s", secondary); @@ -124,9 +126,12 @@ GtkWidget* gtr_stats_dialog_new(GtkWindow* parent, TrCore* core) guint row = 0; struct stat_ui* ui = g_new0(struct stat_ui, 1); - d = gtk_dialog_new_with_buttons(_("Statistics"), parent, GTK_DIALOG_DESTROY_WITH_PARENT, - _("_Reset"), TR_RESPONSE_RESET, - _("_Close"), GTK_RESPONSE_CLOSE, + d = gtk_dialog_new_with_buttons( + _("Statistics"), + parent, + GTK_DIALOG_DESTROY_WITH_PARENT, + TR_ARG_TUPLE(_("_Reset"), TR_RESPONSE_RESET), + TR_ARG_TUPLE(_("_Close"), GTK_RESPONSE_CLOSE), NULL); gtk_dialog_set_default_response(GTK_DIALOG(d), GTK_RESPONSE_CLOSE); t = hig_workarea_create(); diff --git a/gtk/torrent-cell-renderer.c b/gtk/torrent-cell-renderer.c index 75a7c499c..c36b34fc3 100644 --- a/gtk/torrent-cell-renderer.c +++ b/gtk/torrent-cell-renderer.c @@ -52,7 +52,8 @@ static void getProgressString(GString* gstr, tr_torrent const* tor, tr_info cons if (!isDone) /* downloading */ { - g_string_append_printf(gstr, + g_string_append_printf( + gstr, /* %1$s is how much we've got, %2$s is how much we'll have when done, %3$s%% is a percentage of the two */ @@ -65,7 +66,8 @@ static void getProgressString(GString* gstr, tr_torrent const* tor, tr_info cons { if (hasSeedRatio) { - g_string_append_printf(gstr, + g_string_append_printf( + gstr, /* %1$s is how much we've got, %2$s is the torrent's total size, %3$s%% is a percentage of the two, @@ -82,7 +84,8 @@ static void getProgressString(GString* gstr, tr_torrent const* tor, tr_info cons } else { - g_string_append_printf(gstr, + g_string_append_printf( + gstr, /* %1$s is how much we've got, %2$s is the torrent's total size, %3$s%% is a percentage of the two, @@ -100,7 +103,8 @@ static void getProgressString(GString* gstr, tr_torrent const* tor, tr_info cons { if (hasSeedRatio) { - g_string_append_printf(gstr, + g_string_append_printf( + gstr, /* %1$s is the torrent's total size, %2$s is how much we've uploaded, %3$s is our upload-to-download ratio, @@ -113,7 +117,8 @@ static void getProgressString(GString* gstr, tr_torrent const* tor, tr_info cons } else /* seeding w/o a ratio */ { - g_string_append_printf(gstr, + g_string_append_printf( + gstr, /* %1$s is the torrent's total size, %2$s is how much we've uploaded, %3$s is our upload-to-download ratio */ @@ -144,8 +149,13 @@ static void getProgressString(GString* gstr, tr_torrent const* tor, tr_info cons } } -static char* getShortTransferString(tr_torrent const* tor, tr_stat const* st, double uploadSpeed_KBps, - double downloadSpeed_KBps, char* buf, size_t buflen) +static char* getShortTransferString( + tr_torrent const* tor, + tr_stat const* st, + double uploadSpeed_KBps, + double downloadSpeed_KBps, + char* buf, + size_t buflen) { bool const haveMeta = tr_torrentHasMetadata(tor); bool const haveUp = haveMeta && st->peersGettingFromUs > 0; @@ -159,7 +169,13 @@ static char* getShortTransferString(tr_torrent const* tor, tr_stat const* st, do tr_formatter_speed_KBps(upStr, uploadSpeed_KBps, sizeof(upStr)); /* down speed, down symbol, up speed, up symbol */ - g_snprintf(buf, buflen, _("%1$s %2$s %3$s %4$s"), dnStr, gtr_get_unicode_string(GTR_UNICODE_DOWN), upStr, + g_snprintf( + buf, + buflen, + _("%1$s %2$s %3$s %4$s"), + dnStr, + gtr_get_unicode_string(GTR_UNICODE_DOWN), + upStr, gtr_get_unicode_string(GTR_UNICODE_UP)); } else if (haveUp) @@ -182,7 +198,11 @@ static char* getShortTransferString(tr_torrent const* tor, tr_stat const* st, do return buf; } -static void getShortStatusString(GString* gstr, tr_torrent const* tor, tr_stat const* st, double uploadSpeed_KBps, +static void getShortStatusString( + GString* gstr, + tr_torrent const* tor, + tr_stat const* st, + double uploadSpeed_KBps, double downloadSpeed_KBps) { switch (st->activity) @@ -204,8 +224,7 @@ static void getShortStatusString(GString* gstr, tr_torrent const* tor, tr_stat c break; case TR_STATUS_CHECK: - g_string_append_printf(gstr, _("Verifying local data (%.1f%% tested)"), - tr_truncd(st->recheckProgress * 100.0, 1)); + g_string_append_printf(gstr, _("Verifying local data (%.1f%% tested)"), tr_truncd(st->recheckProgress * 100.0, 1)); break; case TR_STATUS_DOWNLOAD: @@ -226,17 +245,20 @@ static void getShortStatusString(GString* gstr, tr_torrent const* tor, tr_stat c } } -static void getStatusString(GString* gstr, tr_torrent const* tor, tr_stat const* st, double const uploadSpeed_KBps, +static void getStatusString( + GString* gstr, + tr_torrent const* tor, + tr_stat const* st, + double const uploadSpeed_KBps, double const downloadSpeed_KBps) { if (st->error != 0) { - char const* fmt[] = - { + char const* fmt[] = { NULL, N_("Tracker gave a warning: \"%s\""), N_("Tracker gave an error: \"%s\""), - N_("Error: %s") + N_("Error: %s"), }; g_string_append_printf(gstr, _(fmt[st->error]), st->errorString); @@ -260,35 +282,57 @@ static void getStatusString(GString* gstr, tr_torrent const* tor, tr_stat const* if (!tr_torrentHasMetadata(tor)) { /* Downloading metadata from 2 peer (s)(50% done) */ - g_string_append_printf(gstr, _("Downloading metadata from %1$'d %2$s (%3$d%% done)"), st->peersConnected, - ngettext("peer", "peers", st->peersConnected), (int)(100.0 * st->metadataPercentComplete)); + g_string_append_printf( + gstr, + _("Downloading metadata from %1$'d %2$s (%3$d%% done)"), + st->peersConnected, + ngettext("peer", "peers", st->peersConnected), + (int)(100.0 * st->metadataPercentComplete)); } else if (st->peersSendingToUs != 0 && st->webseedsSendingToUs != 0) { /* Downloading from 2 of 3 peer (s) and 2 webseed (s) */ - g_string_append_printf(gstr, _("Downloading from %1$'d of %2$'d %3$s and %4$'d %5$s"), st->peersSendingToUs, - st->peersConnected, ngettext("peer", "peers", st->peersConnected), st->webseedsSendingToUs, + g_string_append_printf( + gstr, + _("Downloading from %1$'d of %2$'d %3$s and %4$'d %5$s"), + st->peersSendingToUs, + st->peersConnected, + ngettext("peer", "peers", st->peersConnected), + st->webseedsSendingToUs, ngettext("web seed", "web seeds", st->webseedsSendingToUs)); } else if (st->webseedsSendingToUs != 0) { /* Downloading from 3 web seed (s) */ - g_string_append_printf(gstr, _("Downloading from %1$'d %2$s"), st->webseedsSendingToUs, + g_string_append_printf( + gstr, + _("Downloading from %1$'d %2$s"), + st->webseedsSendingToUs, ngettext("web seed", "web seeds", st->webseedsSendingToUs)); } else { /* Downloading from 2 of 3 peer (s) */ - g_string_append_printf(gstr, _("Downloading from %1$'d of %2$'d %3$s"), st->peersSendingToUs, - st->peersConnected, ngettext("peer", "peers", st->peersConnected)); + g_string_append_printf( + gstr, + _("Downloading from %1$'d of %2$'d %3$s"), + st->peersSendingToUs, + st->peersConnected, + ngettext("peer", "peers", st->peersConnected)); } break; } case TR_STATUS_SEED: - g_string_append_printf(gstr, ngettext("Seeding to %1$'d of %2$'d connected peer", - "Seeding to %1$'d of %2$'d connected peers", st->peersConnected), st->peersGettingFromUs, st->peersConnected); + g_string_append_printf( + gstr, + ngettext( + "Seeding to %1$'d of %2$'d connected peer", + "Seeding to %1$'d of %2$'d connected peers", + st->peersConnected), + st->peersGettingFromUs, + st->peersConnected); break; } } @@ -330,8 +374,7 @@ typedef struct TorrentCellRendererPrivate double download_speed_KBps; gboolean compact; -} -TorrentCellRendererPrivate; +} TorrentCellRendererPrivate; /*** **** @@ -366,7 +409,10 @@ static GdkPixbuf* get_icon(tr_torrent const* tor, GtkIconSize icon_size, GtkWidg **** ***/ -static void gtr_cell_renderer_get_preferred_size(GtkCellRenderer* renderer, GtkWidget* widget, GtkRequisition* minimum_size, +static void gtr_cell_renderer_get_preferred_size( + GtkCellRenderer* renderer, + GtkWidget* widget, + GtkRequisition* minimum_size, GtkRequisition* natural_size) { gtk_cell_renderer_get_preferred_size(renderer, widget, minimum_size, natural_size); @@ -450,7 +496,12 @@ static void get_size_full(TorrentCellRenderer* cell, GtkWidget* widget, gint* wi /* get the idealized cell dimensions */ g_object_set(p->icon_renderer, "pixbuf", icon, NULL); gtr_cell_renderer_get_preferred_size(p->icon_renderer, widget, NULL, &icon_size); - g_object_set(p->text_renderer, "text", name, "weight", PANGO_WEIGHT_BOLD, "scale", 1.0, "ellipsize", PANGO_ELLIPSIZE_NONE, + g_object_set( + p->text_renderer, + TR_ARG_TUPLE("text", name), + TR_ARG_TUPLE("weight", PANGO_WEIGHT_BOLD), + TR_ARG_TUPLE("scale", 1.0), + TR_ARG_TUPLE("ellipsize", PANGO_ELLIPSIZE_NONE), NULL); gtr_cell_renderer_get_preferred_size(p->text_renderer, widget, NULL, &name_size); g_object_set(p->text_renderer, "text", gstr_prog->str, "weight", PANGO_WEIGHT_NORMAL, "scale", SMALL_SCALE, NULL); @@ -477,8 +528,14 @@ static void get_size_full(TorrentCellRenderer* cell, GtkWidget* widget, gint* wi g_object_unref(icon); } -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) +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 const* const self = TORRENT_CELL_RENDERER(cell); @@ -563,14 +620,23 @@ static double get_percent_done(tr_torrent const* tor, tr_stat const* st, bool* s typedef cairo_t GtrDrawable; -static void gtr_cell_renderer_render(GtkCellRenderer* renderer, GtrDrawable* drawable, GtkWidget* widget, - GdkRectangle const* area, GtkCellRendererState flags) +static void gtr_cell_renderer_render( + GtkCellRenderer* renderer, + GtrDrawable* drawable, + GtkWidget* widget, + GdkRectangle const* area, + GtkCellRendererState flags) { gtk_cell_renderer_render(renderer, drawable, widget, area, area, flags); } -static void render_compact(TorrentCellRenderer* cell, GtrDrawable* window, GtkWidget* widget, - GdkRectangle const* background_area, GdkRectangle const* cell_area, GtkCellRendererState flags) +static void render_compact( + TorrentCellRenderer* cell, + GtrDrawable* window, + GtkWidget* widget, + GdkRectangle const* background_area, + GdkRectangle const* cell_area, + GtkCellRendererState flags) { TR_UNUSED(cell_area); @@ -636,8 +702,13 @@ static void render_compact(TorrentCellRenderer* cell, GtrDrawable* window, GtkWi gtr_cell_renderer_render(p->icon_renderer, window, widget, &icon_area, flags); g_object_set(p->progress_renderer, "value", (int)(percentDone * 100.0), "text", NULL, "sensitive", sensitive, NULL); gtr_cell_renderer_render(p->progress_renderer, window, widget, &prog_area, flags); - g_object_set(p->text_renderer, "text", gstr_stat->str, "scale", SMALL_SCALE, "ellipsize", PANGO_ELLIPSIZE_END, - FOREGROUND_COLOR_KEY, &text_color, NULL); + g_object_set( + p->text_renderer, + TR_ARG_TUPLE("text", gstr_stat->str), + TR_ARG_TUPLE("scale", SMALL_SCALE), + TR_ARG_TUPLE("ellipsize", PANGO_ELLIPSIZE_END), + TR_ARG_TUPLE(FOREGROUND_COLOR_KEY, &text_color), + NULL); gtr_cell_renderer_render(p->text_renderer, window, widget, &stat_area, flags); g_object_set(p->text_renderer, "text", name, "scale", 1.0, FOREGROUND_COLOR_KEY, &text_color, NULL); gtr_cell_renderer_render(p->text_renderer, window, widget, &name_area, flags); @@ -646,8 +717,13 @@ static void render_compact(TorrentCellRenderer* cell, GtrDrawable* window, GtkWi g_object_unref(icon); } -static void render_full(TorrentCellRenderer* cell, GtrDrawable* window, GtkWidget* widget, GdkRectangle const* background_area, - GdkRectangle const* cell_area, GtkCellRendererState flags) +static void render_full( + TorrentCellRenderer* cell, + GtrDrawable* window, + GtkWidget* widget, + GdkRectangle const* background_area, + GdkRectangle const* cell_area, + GtkCellRendererState flags) { TR_UNUSED(cell_area); @@ -690,7 +766,12 @@ static void render_full(TorrentCellRenderer* cell, GtrDrawable* window, GtkWidge gtr_cell_renderer_get_preferred_size(p->icon_renderer, widget, NULL, &size); icon_area.width = size.width; icon_area.height = size.height; - g_object_set(p->text_renderer, "text", name, "weight", PANGO_WEIGHT_BOLD, "ellipsize", PANGO_ELLIPSIZE_NONE, "scale", 1.0, + g_object_set( + p->text_renderer, + TR_ARG_TUPLE("text", name), + TR_ARG_TUPLE("weight", PANGO_WEIGHT_BOLD), + TR_ARG_TUPLE("ellipsize", PANGO_ELLIPSIZE_NONE), + TR_ARG_TUPLE("scale", 1.0), NULL); gtr_cell_renderer_get_preferred_size(p->text_renderer, widget, NULL, &size); name_area.width = size.width; @@ -745,8 +826,14 @@ static void render_full(TorrentCellRenderer* cell, GtrDrawable* window, GtkWidge g_object_set(p->icon_renderer, "pixbuf", icon, "sensitive", sensitive, NULL); gtr_cell_renderer_render(p->icon_renderer, window, widget, &icon_area, flags); - g_object_set(p->text_renderer, "text", name, "scale", 1.0, FOREGROUND_COLOR_KEY, &text_color, "ellipsize", - PANGO_ELLIPSIZE_END, "weight", PANGO_WEIGHT_BOLD, NULL); + g_object_set( + p->text_renderer, + TR_ARG_TUPLE("text", name), + TR_ARG_TUPLE("scale", 1.0), + TR_ARG_TUPLE(FOREGROUND_COLOR_KEY, &text_color), + TR_ARG_TUPLE("ellipsize", PANGO_ELLIPSIZE_END), + TR_ARG_TUPLE("weight", PANGO_WEIGHT_BOLD), + NULL); gtr_cell_renderer_render(p->text_renderer, window, widget, &name_area, flags); g_object_set(p->text_renderer, "text", gstr_prog->str, "scale", SMALL_SCALE, "weight", PANGO_WEIGHT_NORMAL, NULL); gtr_cell_renderer_render(p->text_renderer, window, widget, &prog_area, flags); @@ -759,8 +846,12 @@ static void render_full(TorrentCellRenderer* cell, GtrDrawable* window, GtkWidge g_object_unref(icon); } -static void torrent_cell_renderer_render(GtkCellRenderer* cell, GtrDrawable* window, GtkWidget* widget, - GdkRectangle const* background_area, GdkRectangle const* cell_area, +static void torrent_cell_renderer_render( + GtkCellRenderer* cell, + GtrDrawable* window, + GtkWidget* widget, + GdkRectangle const* background_area, + GdkRectangle const* cell_area, GtkCellRendererState flags) { TorrentCellRenderer* self = TORRENT_CELL_RENDERER(cell); @@ -885,19 +976,29 @@ static void torrent_cell_renderer_class_init(TorrentCellRendererClass* klass) gobject_class->get_property = torrent_cell_renderer_get_property; gobject_class->dispose = torrent_cell_renderer_dispose; - g_object_class_install_property(gobject_class, P_TORRENT, + g_object_class_install_property( + gobject_class, + P_TORRENT, g_param_spec_pointer("torrent", NULL, "tr_torrent*", G_PARAM_READWRITE)); - g_object_class_install_property(gobject_class, P_UPLOAD_SPEED, + g_object_class_install_property( + gobject_class, + P_UPLOAD_SPEED, g_param_spec_double("piece-upload-speed", NULL, "tr_stat.pieceUploadSpeed_KBps", 0, INT_MAX, 0, G_PARAM_READWRITE)); - g_object_class_install_property(gobject_class, P_DOWNLOAD_SPEED, + g_object_class_install_property( + gobject_class, + P_DOWNLOAD_SPEED, g_param_spec_double("piece-download-speed", NULL, "tr_stat.pieceDownloadSpeed_KBps", 0, INT_MAX, 0, G_PARAM_READWRITE)); - g_object_class_install_property(gobject_class, P_BAR_HEIGHT, + g_object_class_install_property( + gobject_class, + P_BAR_HEIGHT, g_param_spec_int("bar-height", NULL, "Bar Height", 1, INT_MAX, DEFAULT_BAR_HEIGHT, G_PARAM_READWRITE)); - g_object_class_install_property(gobject_class, P_COMPACT, + g_object_class_install_property( + gobject_class, + P_COMPACT, g_param_spec_boolean("compact", NULL, "Compact Mode", FALSE, G_PARAM_READWRITE)); } diff --git a/gtk/tr-core.c b/gtk/tr-core.c index 4438b61e7..556e63d07 100644 --- a/gtk/tr-core.c +++ b/gtk/tr-core.c @@ -79,8 +79,7 @@ typedef struct TrCorePrivate GtkTreeModel* sorted_model; tr_session* session; GStringChunk* string_chunk; -} -TrCorePrivate; +} TrCorePrivate; static int core_is_disposed(TrCore const* core) { @@ -121,23 +120,78 @@ static void tr_core_class_init(TrCoreClass* core_class) gobject_class->dispose = core_dispose; gobject_class->finalize = core_finalize; - signals[ADD_ERROR_SIGNAL] = g_signal_new("add-error", core_type, G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET(TrCoreClass, add_error), - NULL, NULL, g_cclosure_marshal_VOID__UINT_POINTER, G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_POINTER); + signals[ADD_ERROR_SIGNAL] = g_signal_new( + "add-error", + core_type, + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET(TrCoreClass, add_error), + NULL, + NULL, + g_cclosure_marshal_VOID__UINT_POINTER, + G_TYPE_NONE, + 2, + G_TYPE_UINT, + G_TYPE_POINTER); - signals[ADD_PROMPT_SIGNAL] = g_signal_new("add-prompt", core_type, G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET(TrCoreClass, - add_prompt), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); + signals[ADD_PROMPT_SIGNAL] = g_signal_new( + "add-prompt", + core_type, + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET(TrCoreClass, add_prompt), + NULL, + NULL, + g_cclosure_marshal_VOID__POINTER, + G_TYPE_NONE, + 1, + G_TYPE_POINTER); - signals[BUSY_SIGNAL] = g_signal_new("busy", core_type, G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(TrCoreClass, busy), NULL, NULL, - g_cclosure_marshal_VOID__BOOLEAN, G_TYPE_NONE, 1, G_TYPE_BOOLEAN); + signals[BUSY_SIGNAL] = g_signal_new( + "busy", + core_type, + G_SIGNAL_RUN_FIRST, + G_STRUCT_OFFSET(TrCoreClass, busy), + NULL, + NULL, + g_cclosure_marshal_VOID__BOOLEAN, + G_TYPE_NONE, + 1, + G_TYPE_BOOLEAN); - signals[BLOCKLIST_SIGNAL] = g_signal_new("blocklist-updated", core_type, G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(TrCoreClass, - blocklist_updated), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); + signals[BLOCKLIST_SIGNAL] = g_signal_new( + "blocklist-updated", + core_type, + G_SIGNAL_RUN_FIRST, + G_STRUCT_OFFSET(TrCoreClass, blocklist_updated), + NULL, + NULL, + g_cclosure_marshal_VOID__INT, + G_TYPE_NONE, + 1, + G_TYPE_INT); - signals[PORT_SIGNAL] = g_signal_new("port-tested", core_type, G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET(TrCoreClass, port_tested), - NULL, NULL, g_cclosure_marshal_VOID__BOOLEAN, G_TYPE_NONE, 1, G_TYPE_BOOLEAN); + signals[PORT_SIGNAL] = g_signal_new( + "port-tested", + core_type, + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET(TrCoreClass, port_tested), + NULL, + NULL, + g_cclosure_marshal_VOID__BOOLEAN, + G_TYPE_NONE, + 1, + G_TYPE_BOOLEAN); - signals[PREFS_SIGNAL] = g_signal_new("prefs-changed", core_type, G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET(TrCoreClass, - prefs_changed), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); + signals[PREFS_SIGNAL] = g_signal_new( + "prefs-changed", + core_type, + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET(TrCoreClass, prefs_changed), + NULL, + NULL, + g_cclosure_marshal_VOID__INT, + G_TYPE_NONE, + 1, + G_TYPE_INT); } static void tr_core_init(TrCore* core) @@ -147,8 +201,7 @@ static void tr_core_init(TrCore* core) /* column types for the model used to store torrent information */ /* keep this in sync with the enum near the bottom of tr_core.h */ - GType types[] = - { + GType types[] = { G_TYPE_POINTER, /* collated name */ G_TYPE_POINTER, /* tr_torrent* */ G_TYPE_INT, /* torrent id */ @@ -801,8 +854,12 @@ static void core_watchdir_monitor_file(TrCore* core, GFile* file) } /* GFileMonitor noticed a file was created */ -static void on_file_changed_in_watchdir(GFileMonitor const* monitor, GFile* file, GFile const* other_type, - GFileMonitorEvent event_type, gpointer core) +static void on_file_changed_in_watchdir( + GFileMonitor const* monitor, + GFile* file, + GFile const* other_type, + GFileMonitorEvent event_type, + gpointer core) { TR_UNUSED(monitor); TR_UNUSED(other_type); @@ -1009,8 +1066,7 @@ static gboolean find_row_from_torrent_id(GtkTreeModel* model, int id, GtkTreeIte int row_id; gtk_tree_model_get(model, &iter, MC_TORRENT_ID, &row_id, -1); match = id == row_id; - } - while (!match && gtk_tree_model_iter_next(model, &iter)); + } while (!match && gtk_tree_model_iter_next(model, &iter)); } if (match) @@ -1095,21 +1151,24 @@ void gtr_core_add_torrent(TrCore* core, tr_torrent* tor, gboolean do_notify) unsigned int const trackers_hash = build_torrent_trackers_hash(tor); GtkListStore* store = GTK_LIST_STORE(core_raw_model(core)); - gtk_list_store_insert_with_values(store, &unused, 0, - MC_NAME_COLLATED, collated, - MC_TORRENT, tor, - MC_TORRENT_ID, tr_torrentId(tor), - MC_SPEED_UP, st->pieceUploadSpeed_KBps, - MC_SPEED_DOWN, st->pieceDownloadSpeed_KBps, - MC_ACTIVE_PEERS_UP, st->peersGettingFromUs, - MC_ACTIVE_PEERS_DOWN, st->peersSendingToUs + st->webseedsSendingToUs, - MC_RECHECK_PROGRESS, st->recheckProgress, - MC_ACTIVE, is_torrent_active(st), - MC_ACTIVITY, st->activity, - MC_FINISHED, st->finished, - MC_PRIORITY, tr_torrentGetPriority(tor), - MC_QUEUE_POSITION, st->queuePosition, - MC_TRACKERS, trackers_hash, + gtk_list_store_insert_with_values( + store, + &unused, + 0, + TR_ARG_TUPLE(MC_NAME_COLLATED, collated), + TR_ARG_TUPLE(MC_TORRENT, tor), + TR_ARG_TUPLE(MC_TORRENT_ID, tr_torrentId(tor)), + TR_ARG_TUPLE(MC_SPEED_UP, st->pieceUploadSpeed_KBps), + TR_ARG_TUPLE(MC_SPEED_DOWN, st->pieceDownloadSpeed_KBps), + TR_ARG_TUPLE(MC_ACTIVE_PEERS_UP, st->peersGettingFromUs), + TR_ARG_TUPLE(MC_ACTIVE_PEERS_DOWN, st->peersSendingToUs + st->webseedsSendingToUs), + TR_ARG_TUPLE(MC_RECHECK_PROGRESS, st->recheckProgress), + TR_ARG_TUPLE(MC_ACTIVE, is_torrent_active(st)), + TR_ARG_TUPLE(MC_ACTIVITY, st->activity), + TR_ARG_TUPLE(MC_FINISHED, st->finished), + TR_ARG_TUPLE(MC_PRIORITY, tr_torrentGetPriority(tor)), + TR_ARG_TUPLE(MC_QUEUE_POSITION, st->queuePosition), + TR_ARG_TUPLE(MC_TRACKERS, trackers_hash), -1); if (do_notify) @@ -1324,8 +1383,8 @@ static bool add_file(TrCore* core, GFile* file, gboolean do_start, gboolean do_p handled = true; core_add_ctor(core, ctor, do_prompt, do_notify); } - else if (g_file_has_uri_scheme(file, "http") || g_file_has_uri_scheme(file, "https") || - g_file_has_uri_scheme(file, "ftp")) + else if ( + g_file_has_uri_scheme(file, "http") || g_file_has_uri_scheme(file, "https") || g_file_has_uri_scheme(file, "ftp")) { struct add_from_url_data* data; @@ -1501,21 +1560,23 @@ static void update_foreach(GtkTreeModel* model, GtkTreeIter* iter) tr_torrent* tor; /* get the old states */ - gtk_tree_model_get(model, iter, - MC_TORRENT, &tor, - MC_ACTIVE, &oldActive, - MC_ACTIVE_PEER_COUNT, &oldActivePeerCount, - MC_ACTIVE_PEERS_UP, &oldUploadPeerCount, - MC_ACTIVE_PEERS_DOWN, &oldDownloadPeerCount, - MC_ERROR, &oldError, - MC_ACTIVITY, &oldActivity, - MC_FINISHED, &oldFinished, - MC_PRIORITY, &oldPriority, - MC_QUEUE_POSITION, &oldQueuePosition, - MC_TRACKERS, &oldTrackers, - MC_SPEED_UP, &oldUpSpeed, - MC_RECHECK_PROGRESS, &oldRecheckProgress, - MC_SPEED_DOWN, &oldDownSpeed, + gtk_tree_model_get( + model, + iter, + TR_ARG_TUPLE(MC_TORRENT, &tor), + TR_ARG_TUPLE(MC_ACTIVE, &oldActive), + TR_ARG_TUPLE(MC_ACTIVE_PEER_COUNT, &oldActivePeerCount), + TR_ARG_TUPLE(MC_ACTIVE_PEERS_UP, &oldUploadPeerCount), + TR_ARG_TUPLE(MC_ACTIVE_PEERS_DOWN, &oldDownloadPeerCount), + TR_ARG_TUPLE(MC_ERROR, &oldError), + TR_ARG_TUPLE(MC_ACTIVITY, &oldActivity), + TR_ARG_TUPLE(MC_FINISHED, &oldFinished), + TR_ARG_TUPLE(MC_PRIORITY, &oldPriority), + TR_ARG_TUPLE(MC_QUEUE_POSITION, &oldQueuePosition), + TR_ARG_TUPLE(MC_TRACKERS, &oldTrackers), + TR_ARG_TUPLE(MC_SPEED_UP, &oldUpSpeed), + TR_ARG_TUPLE(MC_RECHECK_PROGRESS, &oldRecheckProgress), + TR_ARG_TUPLE(MC_SPEED_DOWN, &oldDownSpeed), -1); /* get the new states */ @@ -1543,20 +1604,22 @@ static void update_foreach(GtkTreeModel* model, GtkTreeIter* iter) gtr_compare_double(newDownSpeed, oldDownSpeed, 2) != 0 || gtr_compare_double(newRecheckProgress, oldRecheckProgress, 2) != 0) { - gtk_list_store_set(GTK_LIST_STORE(model), iter, - MC_ACTIVE, newActive, - MC_ACTIVE_PEER_COUNT, newActivePeerCount, - MC_ACTIVE_PEERS_UP, newUploadPeerCount, - MC_ACTIVE_PEERS_DOWN, newDownloadPeerCount, - MC_ERROR, newError, - MC_ACTIVITY, newActivity, - MC_FINISHED, newFinished, - MC_PRIORITY, newPriority, - MC_QUEUE_POSITION, newQueuePosition, - MC_TRACKERS, newTrackers, - MC_SPEED_UP, newUpSpeed, - MC_SPEED_DOWN, newDownSpeed, - MC_RECHECK_PROGRESS, newRecheckProgress, + gtk_list_store_set( + GTK_LIST_STORE(model), + iter, + TR_ARG_TUPLE(MC_ACTIVE, newActive), + TR_ARG_TUPLE(MC_ACTIVE_PEER_COUNT, newActivePeerCount), + TR_ARG_TUPLE(MC_ACTIVE_PEERS_UP, newUploadPeerCount), + TR_ARG_TUPLE(MC_ACTIVE_PEERS_DOWN, newDownloadPeerCount), + TR_ARG_TUPLE(MC_ERROR, newError), + TR_ARG_TUPLE(MC_ACTIVITY, newActivity), + TR_ARG_TUPLE(MC_FINISHED, newFinished), + TR_ARG_TUPLE(MC_PRIORITY, newPriority), + TR_ARG_TUPLE(MC_QUEUE_POSITION, newQueuePosition), + TR_ARG_TUPLE(MC_TRACKERS, newTrackers), + TR_ARG_TUPLE(MC_SPEED_UP, newUpSpeed), + TR_ARG_TUPLE(MC_SPEED_DOWN, newDownSpeed), + TR_ARG_TUPLE(MC_RECHECK_PROGRESS, newRecheckProgress), -1); } } @@ -1574,8 +1637,7 @@ void gtr_core_update(TrCore* core) do { update_foreach(model, &iter); - } - while (gtk_tree_model_iter_next(model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); } /* update hibernation */ @@ -1603,9 +1665,18 @@ static gboolean gtr_inhibit_hibernation(guint* cookie) connection = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &err); - response = g_dbus_connection_call_sync(connection, SESSION_MANAGER_SERVICE_NAME, SESSION_MANAGER_OBJECT_PATH, - SESSION_MANAGER_INTERFACE, "Inhibit", g_variant_new("(susu)", application, toplevel_xid, reason, flags), NULL, - G_DBUS_CALL_FLAGS_NONE, 1000, NULL, &err); + response = g_dbus_connection_call_sync( + connection, + SESSION_MANAGER_SERVICE_NAME, + SESSION_MANAGER_OBJECT_PATH, + SESSION_MANAGER_INTERFACE, + "Inhibit", + g_variant_new("(susu)", application, toplevel_xid, reason, flags), + NULL, + G_DBUS_CALL_FLAGS_NONE, + 1000, + NULL, + &err); if (response != NULL) { @@ -1647,8 +1718,17 @@ static void gtr_uninhibit_hibernation(guint inhibit_cookie) connection = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &err); - response = g_dbus_connection_call_sync(connection, SESSION_MANAGER_SERVICE_NAME, SESSION_MANAGER_OBJECT_PATH, - SESSION_MANAGER_INTERFACE, "Uninhibit", g_variant_new("(u)", inhibit_cookie), NULL, G_DBUS_CALL_FLAGS_NONE, 1000, NULL, + response = g_dbus_connection_call_sync( + connection, + SESSION_MANAGER_SERVICE_NAME, + SESSION_MANAGER_OBJECT_PATH, + SESSION_MANAGER_INTERFACE, + "Uninhibit", + g_variant_new("(u)", inhibit_cookie), + NULL, + G_DBUS_CALL_FLAGS_NONE, + 1000, + NULL, &err); /* logging */ @@ -1759,7 +1839,7 @@ void gtr_core_set_pref_double(TrCore* self, tr_quark const key, double newval) static int nextTag = 1; -typedef void (* server_response_func)(TrCore* core, tr_variant* response, gpointer user_data); +typedef void (*server_response_func)(TrCore* core, tr_variant* response, gpointer user_data); struct pending_request_data { @@ -1809,7 +1889,11 @@ static void core_read_rpc_response(tr_session* session, tr_variant* response, vo gdk_threads_add_idle(core_read_rpc_response_idle, response_copy); } -static void core_send_rpc_request(TrCore* core, tr_variant const* request, int tag, server_response_func response_func, +static void core_send_rpc_request( + TrCore* core, + tr_variant const* request, + int tag, + server_response_func response_func, void* response_func_user_data) { tr_session* session = gtr_core_session(core); @@ -1838,7 +1922,7 @@ static void core_send_rpc_request(TrCore* core, tr_variant const* request, int t { struct evbuffer* buf = tr_variantToBuf(request, TR_VARIANT_FMT_JSON_LEAN); size_t const buf_len = evbuffer_get_length(buf); - g_message("request: [%*.*s]", (int)buf_len, (int)buf_len, evbuffer_pullup(buf, -1)); + g_message("request: [%*.*s]", TR_ARG_TUPLE((int)buf_len, (int)buf_len, evbuffer_pullup(buf, -1))); evbuffer_free(buf); } #endif @@ -1956,8 +2040,7 @@ size_t gtr_core_get_active_torrent_count(TrCore* core) { ++activeCount; } - } - while (gtk_tree_model_iter_next(model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); } return activeCount; diff --git a/gtk/tr-core.h b/gtk/tr-core.h index f8a282dec..89671a34d 100644 --- a/gtk/tr-core.h +++ b/gtk/tr-core.h @@ -40,8 +40,7 @@ typedef struct _TrCore /*< private >*/ struct TrCorePrivate* priv; -} -TrCore; +} TrCore; enum tr_core_err { @@ -54,15 +53,14 @@ typedef struct _TrCoreClass { GObjectClass parent_class; - void (* add_error)(TrCore*, enum tr_core_err, char const* name); - void (* add_prompt)(TrCore*, gpointer ctor); - void (* blocklist_updated)(TrCore*, int ruleCount); - void (* busy)(TrCore*, gboolean is_busy); - void (* prefs_changed)(TrCore*, tr_quark const key); - void (* port_tested)(TrCore*, gboolean is_open); - void (* quit)(TrCore*); -} -TrCoreClass; + void (*add_error)(TrCore*, enum tr_core_err, char const* name); + void (*add_prompt)(TrCore*, gpointer ctor); + void (*blocklist_updated)(TrCore*, int ruleCount); + void (*busy)(TrCore*, gboolean is_busy); + void (*prefs_changed)(TrCore*, tr_quark const key); + void (*port_tested)(TrCore*, gboolean is_open); + void (*quit)(TrCore*); +} TrCoreClass; GType tr_core_get_type(void) G_GNUC_CONST; diff --git a/gtk/tr-prefs.c b/gtk/tr-prefs.c index 0eadee1bb..fda8c9fdf 100644 --- a/gtk/tr-prefs.c +++ b/gtk/tr-prefs.c @@ -463,8 +463,13 @@ static void onBlocklistUpdate(GtkButton* w, gpointer gdata) { GtkWidget* d; struct blocklist_data* data = gdata; - d = gtk_message_dialog_new(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(w))), GTK_DIALOG_DESTROY_WITH_PARENT, - GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "%s", _("Update Blocklist")); + d = gtk_message_dialog_new( + GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(w))), + GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_INFO, + GTK_BUTTONS_CLOSE, + "%s", + _("Update Blocklist")); gtk_widget_set_sensitive(data->updateBlocklistButton, FALSE); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(d), "%s", _("Getting new blocklist…")); data->updateBlocklistDialog = d; @@ -491,8 +496,11 @@ static void onIntComboChanged(GtkComboBox* combo_box, gpointer core) static GtkWidget* new_encryption_combo(GObject* core, tr_quark const key) { - GtkWidget* w = gtr_combo_box_new_enum(_("Allow encryption"), TR_CLEAR_PREFERRED, _("Prefer encryption"), - TR_ENCRYPTION_PREFERRED, _("Require encryption"), TR_ENCRYPTION_REQUIRED, NULL); + GtkWidget* w = gtr_combo_box_new_enum( + TR_ARG_TUPLE(_("Allow encryption"), TR_CLEAR_PREFERRED), + TR_ARG_TUPLE(_("Prefer encryption"), TR_ENCRYPTION_PREFERRED), + TR_ARG_TUPLE(_("Require encryption"), TR_ENCRYPTION_REQUIRED), + NULL); gtr_combo_box_set_active_enum(GTK_COMBO_BOX(w), gtr_pref_int_get(key)); g_object_set_data(G_OBJECT(w), PREF_KEY, GINT_TO_POINTER(key)); g_signal_connect(w, "changed", G_CALLBACK(onIntComboChanged), core); @@ -572,9 +580,7 @@ enum static GtkTreeModel* whitelist_tree_model_new(char const* whitelist) { char** rules; - GtkListStore* store = gtk_list_store_new(N_COLS, - G_TYPE_STRING, - G_TYPE_STRING); + GtkListStore* store = gtk_list_store_new(N_COLS, G_TYPE_STRING, G_TYPE_STRING); rules = g_strsplit(whitelist, ",", 0); @@ -625,8 +631,7 @@ static void refreshWhitelist(struct remote_page* page) g_string_append(gstr, address); g_string_append(gstr, ","); g_free(address); - } - while (gtk_tree_model_iter_next(model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); } g_string_truncate(gstr, gstr->len - 1); /* remove the trailing comma */ @@ -832,8 +837,7 @@ static GtkWidget* remotePage(GObject* core) v = page->view = GTK_TREE_VIEW(w); gtk_widget_set_tooltip_text(w, _("IP addresses may use wildcards, such as 192.168.*.*")); sel = gtk_tree_view_get_selection(v); - g_signal_connect(sel, "changed", - G_CALLBACK(onWhitelistSelectionChanged), page); + g_signal_connect(sel, "changed", G_CALLBACK(onWhitelistSelectionChanged), page); g_object_unref(G_OBJECT(m)); gtk_tree_view_set_headers_visible(v, TRUE); w = gtk_frame_new(NULL); @@ -851,7 +855,12 @@ static GtkWidget* remotePage(GObject* core) s = _("Addresses:"); w = hig_workarea_add_row(t, &row, s, w, NULL); - g_object_set(w, "halign", GTK_ALIGN_START, "valign", GTK_ALIGN_START, "margin-top", GUI_PAD, "margin-bottom", GUI_PAD, + g_object_set( + w, + TR_ARG_TUPLE("halign", GTK_ALIGN_START), + TR_ARG_TUPLE("valign", GTK_ALIGN_START), + TR_ARG_TUPLE("margin-top", GUI_PAD), + TR_ARG_TUPLE("margin-bottom", GUI_PAD), NULL); page->whitelist_widgets = g_slist_prepend(page->whitelist_widgets, w); @@ -951,16 +960,16 @@ static GtkWidget* new_time_combo(GObject* core, tr_quark const key) static GtkWidget* new_week_combo(GObject* core, tr_quark const key) { GtkWidget* w = gtr_combo_box_new_enum( - _("Every Day"), TR_SCHED_ALL, - _("Weekdays"), TR_SCHED_WEEKDAY, - _("Weekends"), TR_SCHED_WEEKEND, - _("Sunday"), TR_SCHED_SUN, - _("Monday"), TR_SCHED_MON, - _("Tuesday"), TR_SCHED_TUES, - _("Wednesday"), TR_SCHED_WED, - _("Thursday"), TR_SCHED_THURS, - _("Friday"), TR_SCHED_FRI, - _("Saturday"), TR_SCHED_SAT, + TR_ARG_TUPLE(_("Every Day"), TR_SCHED_ALL), + TR_ARG_TUPLE(_("Weekdays"), TR_SCHED_WEEKDAY), + TR_ARG_TUPLE(_("Weekends"), TR_SCHED_WEEKEND), + TR_ARG_TUPLE(_("Sunday"), TR_SCHED_SUN), + TR_ARG_TUPLE(_("Monday"), TR_SCHED_MON), + TR_ARG_TUPLE(_("Tuesday"), TR_SCHED_TUES), + TR_ARG_TUPLE(_("Wednesday"), TR_SCHED_WED), + TR_ARG_TUPLE(_("Thursday"), TR_SCHED_THURS), + TR_ARG_TUPLE(_("Friday"), TR_SCHED_FRI), + TR_ARG_TUPLE(_("Saturday"), TR_SCHED_SAT), NULL); gtr_combo_box_set_active_enum(GTK_COMBO_BOX(w), gtr_pref_int_get(key)); g_object_set_data(G_OBJECT(w), PREF_KEY, GINT_TO_POINTER(key)); @@ -1266,9 +1275,12 @@ GtkWidget* gtr_prefs_dialog_new(GtkWindow* parent, GObject* core) data->core = TR_CORE(core); data->core_prefs_tag = g_signal_connect(TR_CORE(core), "prefs-changed", G_CALLBACK(on_core_prefs_changed), data); - d = gtk_dialog_new_with_buttons(_("Transmission Preferences"), parent, GTK_DIALOG_DESTROY_WITH_PARENT, - _("_Help"), GTK_RESPONSE_HELP, - _("_Close"), GTK_RESPONSE_CLOSE, + d = gtk_dialog_new_with_buttons( + _("Transmission Preferences"), + parent, + GTK_DIALOG_DESTROY_WITH_PARENT, + TR_ARG_TUPLE(_("_Help"), GTK_RESPONSE_HELP), + TR_ARG_TUPLE(_("_Close"), GTK_RESPONSE_CLOSE), NULL); g_object_weak_ref(G_OBJECT(d), on_prefs_dialog_destroyed, data); gtk_window_set_role(GTK_WINDOW(d), "transmission-preferences-dialog"); diff --git a/gtk/tr-window.c b/gtk/tr-window.c index 5cea452d1..2fec213e7 100644 --- a/gtk/tr-window.c +++ b/gtk/tr-window.c @@ -61,12 +61,11 @@ typedef struct GtkTreeModel* filter_model; TrCore* core; gulong pref_handler_id; -} -PrivateData; +} PrivateData; static TR_DEFINE_QUARK(private_data, private_data) -static PrivateData* get_private_data(GtkWindow * w) +static PrivateData* get_private_data(GtkWindow* w) { return g_object_get_qdata(G_OBJECT(w), private_data_quark()); } @@ -98,7 +97,11 @@ static void view_row_activated(GtkTreeView* tree_view, GtkTreePath* path, GtkTre gtr_action_activate("show-torrent-properties"); } -static gboolean tree_view_search_equal_func(GtkTreeModel* model, gint column, gchar const* key, GtkTreeIter* iter, +static gboolean tree_view_search_equal_func( + GtkTreeModel* model, + gint column, + gchar const* key, + GtkTreeIter* iter, gpointer search_data) { TR_UNUSED(column); @@ -133,8 +136,12 @@ static GtkWidget* makeview(PrivateData* p) p->selection = gtk_tree_view_get_selection(tree_view); - p->column = col = GTK_TREE_VIEW_COLUMN(g_object_new(GTK_TYPE_TREE_VIEW_COLUMN, "title", _("Torrent"), "resizable", TRUE, - "sizing", GTK_TREE_VIEW_COLUMN_FIXED, NULL)); + p->column = col = GTK_TREE_VIEW_COLUMN(g_object_new( + GTK_TYPE_TREE_VIEW_COLUMN, + TR_ARG_TUPLE("title", _("Torrent")), + TR_ARG_TUPLE("resizable", TRUE), + TR_ARG_TUPLE("sizing", GTK_TREE_VIEW_COLUMN_FIXED), + NULL)); p->renderer = r = torrent_cell_renderer_new(); gtk_tree_view_column_pack_start(col, r, FALSE); @@ -234,13 +241,11 @@ static struct { char const* val; char const* i18n; -} -stats_modes[] = -{ +} stats_modes[] = { { "total-ratio", N_("Total Ratio") }, { "session-ratio", N_("Session Ratio") }, { "total-transfer", N_("Total Transfer") }, - { "session-transfer", N_("Session Transfer") } + { "session-transfer", N_("Session Transfer") }, }; static void status_menu_toggled_cb(GtkCheckMenuItem* menu_item, gpointer vprivate) @@ -264,9 +269,8 @@ static void syncAltSpeedButton(PrivateData* p) char d[32]; tr_formatter_speed_KBps(d, gtr_pref_int_get(TR_KEY_alt_speed_down), sizeof(d)); - char* const str = b ? - g_strdup_printf(_("Click to disable Alternative Speed Limits\n (%1$s down, %2$s up)"), d, u) : - g_strdup_printf(_("Click to enable Alternative Speed Limits\n (%1$s down, %2$s up)"), d, u); + char* const str = b ? g_strdup_printf(_("Click to disable Alternative Speed Limits\n (%1$s down, %2$s up)"), d, u) : + g_strdup_printf(_("Click to enable Alternative Speed Limits\n (%1$s down, %2$s up)"), d, u); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), b); gtk_image_set_from_stock(GTK_IMAGE(p->alt_speed_image), stock, -1); @@ -300,7 +304,12 @@ static void findMaxAnnounceTime(GtkTreeModel* model, GtkTreePath* path, GtkTreeI *maxTime = MAX(*maxTime, torStat->manualAnnounceTime); } -static gboolean onAskTrackerQueryTooltip(GtkWidget* widget, gint x, gint y, gboolean keyboard_tip, GtkTooltip* tooltip, +static gboolean onAskTrackerQueryTooltip( + GtkWidget* widget, + gint x, + gint y, + gboolean keyboard_tip, + GtkTooltip* tooltip, gpointer gdata) { TR_UNUSED(widget); @@ -560,7 +569,11 @@ static void onOptionsClicked(GtkButton* button, gpointer vp) gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(b ? p->ratio_on_item : p->ratio_off_item), TRUE); #if GTK_CHECK_VERSION(3, 22, 0) - gtk_menu_popup_at_widget(GTK_MENU(p->options_menu), GTK_WIDGET(button), GDK_GRAVITY_NORTH_WEST, GDK_GRAVITY_SOUTH_WEST, + gtk_menu_popup_at_widget( + GTK_MENU(p->options_menu), + GTK_WIDGET(button), + GDK_GRAVITY_NORTH_WEST, + GDK_GRAVITY_SOUTH_WEST, NULL); #else gtk_menu_popup(GTK_MENU(p->options_menu), NULL, NULL, NULL, NULL, 0, gtk_get_current_event_time()); @@ -615,7 +628,9 @@ GtkWidget* gtr_window_new(GtkApplication* app, GtkUIManager* ui_mgr, TrCore* cor style = ".tr-workarea.frame {border-left-width: 0; border-right-width: 0; border-radius: 0;}"; css_provider = gtk_css_provider_new(); gtk_css_provider_load_from_data(css_provider, style, strlen(style), NULL); - gtk_style_context_add_provider_for_screen(gdk_screen_get_default(), GTK_STYLE_PROVIDER(css_provider), + gtk_style_context_add_provider_for_screen( + gdk_screen_get_default(), + GTK_STYLE_PROVIDER(css_provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); /* window's main container */ @@ -835,18 +850,19 @@ static void updateSpeeds(PrivateData* p) int dc; double us; double ds; - gtk_tree_model_get(model, &iter, - MC_SPEED_UP, &us, - MC_SPEED_DOWN, &ds, - MC_ACTIVE_PEERS_UP, &uc, - MC_ACTIVE_PEERS_DOWN, &dc, + gtk_tree_model_get( + model, + &iter, + TR_ARG_TUPLE(MC_SPEED_UP, &us), + TR_ARG_TUPLE(MC_SPEED_DOWN, &ds), + TR_ARG_TUPLE(MC_ACTIVE_PEERS_UP, &uc), + TR_ARG_TUPLE(MC_ACTIVE_PEERS_DOWN, &dc), -1); upSpeed += us; upCount += uc; downSpeed += ds; downCount += dc; - } - while (gtk_tree_model_iter_next(model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); } tr_formatter_speed_KBps(speed_str, downSpeed, sizeof(speed_str)); diff --git a/gtk/util.c b/gtk/util.c index bc320f892..0f87138b1 100644 --- a/gtk/util.c +++ b/gtk/util.c @@ -202,8 +202,8 @@ void gtr_get_host_from_url(char* buf, size_t buflen, char const* url) static gboolean gtr_is_supported_url(char const* str) { - return str != NULL && (g_str_has_prefix(str, "ftp://") || g_str_has_prefix(str, "http://") || - g_str_has_prefix(str, "https://")); + return str != NULL && + (g_str_has_prefix(str, "ftp://") || g_str_has_prefix(str, "http://") || g_str_has_prefix(str, "https://")); } gboolean gtr_is_magnet_link(char const* str) @@ -256,7 +256,9 @@ void gtr_add_torrent_error_dialog(GtkWidget* child, int err, tr_torrent* duplica } else if (err == TR_PARSE_DUPLICATE) { - secondary = g_strdup_printf(_("The torrent file \"%s\" is already in use by \"%s.\""), filename, + secondary = g_strdup_printf( + _("The torrent file \"%s\" is already in use by \"%s.\""), + filename, tr_torrentName(duplicate_torrent)); } else @@ -264,7 +266,12 @@ void gtr_add_torrent_error_dialog(GtkWidget* child, int err, tr_torrent* duplica secondary = g_strdup_printf(_("The torrent file \"%s\" encountered an unknown error."), filename); } - w = gtk_message_dialog_new(win, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", + w = gtk_message_dialog_new( + win, + GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_ERROR, + GTK_BUTTONS_CLOSE, + "%s", _("Error opening torrent")); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(w), "%s", secondary); g_signal_connect_swapped(w, "response", G_CALLBACK(gtk_widget_destroy), w); @@ -272,7 +279,7 @@ void gtr_add_torrent_error_dialog(GtkWidget* child, int err, tr_torrent* duplica g_free(secondary); } -typedef void (* PopupFunc)(GtkWidget*, GdkEventButton*); +typedef void (*PopupFunc)(GtkWidget*, GdkEventButton*); /* pop up the context menu if a user right-clicks. if the row they right-click on isn't selected, select it. */ @@ -373,8 +380,7 @@ char const* gtr_get_help_uri(void) if (uri == NULL) { - uri = g_strdup_printf("https://transmissionbt.com/help/gtk/%d.%dx", - MAJOR_VERSION, MINOR_VERSION / 10); + uri = g_strdup_printf("https://transmissionbt.com/help/gtk/%d.%dx", MAJOR_VERSION, MINOR_VERSION / 10); } return uri; @@ -484,8 +490,7 @@ GtkWidget* gtr_combo_box_new_enum(char const* text_1, ...) int const val = va_arg(vl, int); gtk_list_store_insert_with_values(store, NULL, INT_MAX, 0, val, 1, text, -1); text = va_arg(vl, char const*); - } - while (text != NULL); + } while (text != NULL); va_end(vl); } @@ -516,9 +521,9 @@ int gtr_combo_box_get_active_enum(GtkComboBox* combo_box) GtkWidget* gtr_priority_combo_new(void) { return gtr_combo_box_new_enum( - _("High"), TR_PRI_HIGH, - _("Normal"), TR_PRI_NORMAL, - _("Low"), TR_PRI_LOW, + TR_ARG_TUPLE(_("High"), TR_PRI_HIGH), + TR_ARG_TUPLE(_("Normal"), TR_PRI_NORMAL), + TR_ARG_TUPLE(_("Low"), TR_PRI_LOW), NULL); } @@ -597,8 +602,11 @@ void gtr_unrecognized_url_dialog(GtkWidget* parent, char const* url) if (gtr_is_magnet_link(url) && strstr(url, xt) == NULL) { g_string_append_printf(gstr, "\n \n"); - g_string_append_printf(gstr, _("This magnet link appears to be intended for something other than BitTorrent. " - "BitTorrent magnet links have a section containing \"%s\"."), xt); + g_string_append_printf( + gstr, + _("This magnet link appears to be intended for something other than BitTorrent. " + "BitTorrent magnet links have a section containing \"%s\"."), + xt); } gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(w), "%s", gstr->str); @@ -613,10 +621,9 @@ void gtr_unrecognized_url_dialog(GtkWidget* parent, char const* url) void gtr_paste_clipboard_url_into_entry(GtkWidget* e) { - char* text[] = - { + char* text[] = { g_strstrip(gtk_clipboard_wait_for_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY))), - g_strstrip(gtk_clipboard_wait_for_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD))) + g_strstrip(gtk_clipboard_wait_for_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD))), }; for (size_t i = 0; i < G_N_ELEMENTS(text); ++i) diff --git a/gtk/util.h b/gtk/util.h index d943f5631..286351dcd 100644 --- a/gtk/util.h +++ b/gtk/util.h @@ -13,6 +13,7 @@ #include #include +#include extern int const mem_K; extern char const* mem_K_str; @@ -39,15 +40,15 @@ extern char const* speed_T_str; #else #define TR_DEFINE_QUARK(QN, q_n) \ - GQuark q_n ## _quark(void) \ + GQuark q_n##_quark(void) \ { \ static GQuark q; \ - \ +\ if (G_UNLIKELY(q == 0)) \ { \ q = g_quark_from_static_string(#QN); \ } \ - \ +\ return q; \ } diff --git a/libtransmission/announcer-common.h b/libtransmission/announcer-common.h index f75058171..5d778dd1f 100644 --- a/libtransmission/announcer-common.h +++ b/libtransmission/announcer-common.h @@ -46,8 +46,7 @@ typedef struct /* how many hashes to use in the info_hash field */ int info_hash_count; -} -tr_scrape_request; +} tr_scrape_request; struct tr_scrape_response_row { @@ -92,15 +91,20 @@ typedef struct /* minimum interval (in seconds) allowed between scrapes. * this is an unofficial extension that some trackers won't support. */ int min_request_interval; -} -tr_scrape_response; +} tr_scrape_response; -typedef void (* tr_scrape_response_func)(tr_scrape_response const* response, void* user_data); +typedef void (*tr_scrape_response_func)(tr_scrape_response const* response, void* user_data); -void tr_tracker_http_scrape(tr_session* session, tr_scrape_request const* req, tr_scrape_response_func response_func, +void tr_tracker_http_scrape( + tr_session* session, + tr_scrape_request const* req, + tr_scrape_response_func response_func, void* user_data); -void tr_tracker_udp_scrape(tr_session* session, tr_scrape_request const* req, tr_scrape_response_func response_func, +void tr_tracker_udp_scrape( + tr_session* session, + tr_scrape_request const* req, + tr_scrape_response_func response_func, void* user_data); /*** @@ -113,8 +117,7 @@ typedef enum TR_ANNOUNCE_EVENT_COMPLETED, TR_ANNOUNCE_EVENT_STARTED, TR_ANNOUNCE_EVENT_STOPPED -} -tr_announce_event; +} tr_announce_event; char const* tr_announce_event_get_string(tr_announce_event); @@ -160,8 +163,7 @@ typedef struct /* the name to use when deep logging is enabled */ char log_name[128]; -} -tr_announce_request; +} tr_announce_request; struct tr_pex; @@ -214,15 +216,20 @@ typedef struct /* key generated by and returned from an http tracker. * if this is provided, subsequent http announces must include this. */ char* tracker_id_str; -} -tr_announce_response; +} tr_announce_response; -typedef void (* tr_announce_response_func)(tr_announce_response const* response, void* userdata); +typedef void (*tr_announce_response_func)(tr_announce_response const* response, void* userdata); -void tr_tracker_http_announce(tr_session* session, tr_announce_request const* req, tr_announce_response_func response_func, +void tr_tracker_http_announce( + tr_session* session, + tr_announce_request const* req, + tr_announce_response_func response_func, void* user_data); -void tr_tracker_udp_announce(tr_session* session, tr_announce_request const* req, tr_announce_response_func response_func, +void tr_tracker_udp_announce( + tr_session* session, + tr_announce_request const* req, + tr_announce_response_func response_func, void* user_data); void tr_tracker_udp_start_shutdown(tr_session* session); diff --git a/libtransmission/announcer-http.c b/libtransmission/announcer-http.c index 8f99dfce6..4ec517236 100644 --- a/libtransmission/announcer-http.c +++ b/libtransmission/announcer-http.c @@ -36,9 +36,7 @@ static char const* get_event_string(tr_announce_request const* req) { - return req->partial_seed && (req->event != TR_ANNOUNCE_EVENT_STOPPED) ? - "paused" : - tr_announce_event_get_string(req->event); + return req->partial_seed && (req->event != TR_ANNOUNCE_EVENT_STOPPED) ? "paused" : tr_announce_event_get_string(req->event); } static char* announce_url_new(tr_session const* session, tr_announce_request const* req) @@ -52,14 +50,15 @@ static char* announce_url_new(tr_session const* session, tr_announce_request con evbuffer_expand(buf, 1024); - evbuffer_add_printf(buf, + evbuffer_add_printf( + buf, "%s" "%c" "info_hash=%s" "&peer_id=%*.*s" "&port=%d" - "&uploaded=%" PRIu64 - "&downloaded=%" PRIu64 + "&uploaded=%" PRIu64 // + "&downloaded=%" PRIu64 // "&left=%" PRIu64 "&numwant=%d" "&key=%x" @@ -68,7 +67,7 @@ static char* announce_url_new(tr_session const* session, tr_announce_request con req->url, strchr(req->url, '?') != NULL ? '&' : '?', escaped_info_hash, - PEER_ID_LEN, PEER_ID_LEN, req->peer_id, + TR_ARG_TUPLE(PEER_ID_LEN, PEER_ID_LEN, req->peer_id), req->port, req->up, req->down, @@ -199,8 +198,14 @@ static void on_announce_done_eventthread(void* vdata) tr_free(data); } -static void on_announce_done(tr_session* session, bool did_connect, bool did_timeout, long response_code, void const* msg, - size_t msglen, void* vdata) +static void on_announce_done( + tr_session* session, + bool did_connect, + bool did_timeout, + long response_code, + void const* msg, + size_t msglen, + void* vdata) { tr_announce_response* response; struct announce_data* data = vdata; @@ -318,7 +323,10 @@ static void on_announce_done(tr_session* session, bool did_connect, bool did_tim tr_runInEventThread(session, on_announce_done_eventthread, data); } -void tr_tracker_http_announce(tr_session* session, tr_announce_request const* request, tr_announce_response_func response_func, +void tr_tracker_http_announce( + tr_session* session, + tr_announce_request const* request, + tr_announce_response_func response_func, void* response_func_user_data) { struct announce_data* d; @@ -367,8 +375,14 @@ static void on_scrape_done_eventthread(void* vdata) tr_free(data); } -static void on_scrape_done(tr_session* session, bool did_connect, bool did_timeout, long response_code, void const* msg, - size_t msglen, void* vdata) +static void on_scrape_done( + tr_session* session, + bool did_connect, + bool did_timeout, + long response_code, + void const* msg, + size_t msglen, + void* vdata) { tr_scrape_response* response; struct scrape_data* data = vdata; @@ -423,8 +437,8 @@ static void on_scrape_done(tr_session* session, bool did_connect, bool did_timeo response->errmsg = tr_strndup(str, len); } - if (tr_variantDictFindDict(&top, TR_KEY_flags, - &flags) && tr_variantDictFindInt(flags, TR_KEY_min_request_interval, &intVal)) + if (tr_variantDictFindDict(&top, TR_KEY_flags, &flags) && + tr_variantDictFindInt(flags, TR_KEY_min_request_interval, &intVal)) { response->min_request_interval = intVal; } @@ -495,7 +509,10 @@ static char* scrape_url_new(tr_scrape_request const* req) return evbuffer_free_to_str(buf, NULL); } -void tr_tracker_http_scrape(tr_session* session, tr_scrape_request const* request, tr_scrape_response_func response_func, +void tr_tracker_http_scrape( + tr_session* session, + tr_scrape_request const* request, + tr_scrape_response_func response_func, void* response_func_user_data) { struct scrape_data* d; diff --git a/libtransmission/announcer-udp.c b/libtransmission/announcer-udp.c index d4506d9a9..b4572f636 100644 --- a/libtransmission/announcer-udp.c +++ b/libtransmission/announcer-udp.c @@ -117,8 +117,7 @@ typedef enum TAU_ACTION_ANNOUNCE = 1, TAU_ACTION_SCRAPE = 2, TAU_ACTION_ERROR = 3 -} -tau_action_t; +} tau_action_t; static bool is_tau_response_message(tau_action_t action, size_t msglen) { @@ -170,7 +169,9 @@ struct tau_scrape_request void* user_data; }; -static struct tau_scrape_request* tau_scrape_request_new(tr_scrape_request const* in, tr_scrape_response_func callback, +static struct tau_scrape_request* tau_scrape_request_new( + tr_scrape_request const* in, + tr_scrape_response_func callback, void* user_data) { struct evbuffer* buf; @@ -305,8 +306,7 @@ typedef enum TAU_ANNOUNCE_EVENT_COMPLETED = 1, TAU_ANNOUNCE_EVENT_STARTED = 2, TAU_ANNOUNCE_EVENT_STOPPED = 3 -} -tau_announce_event; +} tau_announce_event; static tau_announce_event get_tau_announce_event(tr_announce_event e) { @@ -326,7 +326,9 @@ static tau_announce_event get_tau_announce_event(tr_announce_event e) } } -static struct tau_announce_request* tau_announce_request_new(tr_announce_request const* in, tr_announce_response_func callback, +static struct tau_announce_request* tau_announce_request_new( + tr_announce_request const* in, + tr_announce_response_func callback, void* user_data) { struct evbuffer* buf; @@ -384,7 +386,10 @@ static void tau_announce_request_finished(struct tau_announce_request const* req } } -static void tau_announce_request_fail(struct tau_announce_request* request, bool did_connect, bool did_timeout, +static void tau_announce_request_fail( + struct tau_announce_request* request, + bool did_connect, + bool did_timeout, char const* errmsg) { request->response.did_connect = did_connect; @@ -406,7 +411,11 @@ static void on_announce_response(struct tau_announce_request* request, tau_actio resp->interval = evbuffer_read_ntoh_32(buf); resp->leechers = evbuffer_read_ntoh_32(buf); resp->seeders = evbuffer_read_ntoh_32(buf); - resp->pex = tr_peerMgrCompactToPex(evbuffer_pullup(buf, -1), evbuffer_get_length(buf), NULL, 0, + resp->pex = tr_peerMgrCompactToPex( + evbuffer_pullup(buf, -1), + evbuffer_get_length(buf), + NULL, + 0, &request->response.pex_count); tau_announce_request_finished(request); } @@ -703,13 +712,23 @@ static void tau_tracker_upkeep_ex(struct tau_tracker* tracker, bool timeout_reqs hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; dbgmsg(tracker->host, "Trying a new DNS lookup"); - tracker->dns_request = evdns_getaddrinfo(tracker->session->evdns_base, tracker->host, NULL, &hints, tau_tracker_on_dns, + tracker->dns_request = evdns_getaddrinfo( + tracker->session->evdns_base, + tracker->host, + NULL, + &hints, + tau_tracker_on_dns, tracker); return; } - dbgmsg(tracker->key, "addr %p -- connected %d (%zu %zu) -- connecting_at %zu", (void*)tracker->addr, - (int)(tracker->connection_expiration_time > now), (size_t)tracker->connection_expiration_time, (size_t)now, + dbgmsg( + tracker->key, + "addr %p -- connected %d (%zu %zu) -- connecting_at %zu", + (void*)tracker->addr, + (int)(tracker->connection_expiration_time > now), + (size_t)tracker->connection_expiration_time, + (size_t)now, (size_t)tracker->connecting_at); /* also need a valid connection ID... */ @@ -980,7 +999,10 @@ bool tau_handle_message(tr_session* session, uint8_t const* msg, size_t msglen) return false; } -void tr_tracker_udp_announce(tr_session* session, tr_announce_request const* request, tr_announce_response_func response_func, +void tr_tracker_udp_announce( + tr_session* session, + tr_announce_request const* request, + tr_announce_response_func response_func, void* user_data) { struct tr_announcer_udp* tau = announcer_udp_get(session); @@ -990,7 +1012,10 @@ void tr_tracker_udp_announce(tr_session* session, tr_announce_request const* req tau_tracker_upkeep_ex(tracker, false); } -void tr_tracker_udp_scrape(tr_session* session, tr_scrape_request const* request, tr_scrape_response_func response_func, +void tr_tracker_udp_scrape( + tr_session* session, + tr_scrape_request const* request, + tr_scrape_response_func response_func, void* user_data) { struct tr_announcer_udp* tau = announcer_udp_get(session); diff --git a/libtransmission/announcer.c b/libtransmission/announcer.c index 91a0543c2..ccd3a64e3 100644 --- a/libtransmission/announcer.c +++ b/libtransmission/announcer.c @@ -41,8 +41,7 @@ static void tier_build_log_name(struct tr_tier const* tier, char* buf, size_t bu tier_build_log_name(tier, name, TR_N_ELEMENTS(name)); \ tr_logAddDeep(__FILE__, __LINE__, name, __VA_ARGS__); \ } \ - } \ - while (0) + } while (0) enum { @@ -176,8 +175,7 @@ typedef struct tr_announcer int slotsAvailable; int key; time_t tauUpkeepAt; -} -tr_announcer; +} tr_announcer; static struct tr_scrape_info* tr_announcerGetScrapeInfo(struct tr_announcer* announcer, char const* url) { @@ -262,8 +260,7 @@ typedef struct int consecutiveFailures; uint32_t id; -} -tr_tracker; +} tr_tracker; /* format: host+':'+ port */ static char* getKey(char const* url) @@ -353,8 +350,7 @@ typedef struct tr_tier char lastAnnounceStr[128]; char lastScrapeStr[128]; -} -tr_tier; +} tr_tier; static time_t get_next_scrape_time(tr_session const* session, tr_tier const* tier, int interval) { @@ -404,7 +400,11 @@ static void tierDestruct(tr_tier* tier) static void tier_build_log_name(tr_tier const* tier, char* buf, size_t buflen) { - tr_snprintf(buf, buflen, "[%s---%s]", (tier != NULL && tier->tor != NULL) ? tr_torrentName(tier->tor) : "?", + tr_snprintf( + buf, + buflen, + "[%s---%s]", + (tier != NULL && tier->tor != NULL) ? tr_torrentName(tier->tor) : "?", (tier != NULL && tier->currentTracker != NULL) ? tier->currentTracker->key : "?"); } @@ -444,8 +444,7 @@ typedef struct tr_torrent_tiers tr_tracker_callback callback; void* callbackData; -} -tr_torrent_tiers; +} tr_torrent_tiers; static tr_torrent_tiers* tiersNew(void) { @@ -505,14 +504,13 @@ static tr_tier* getTier(tr_announcer* announcer, uint8_t const* info_hash, int t **** PUBLISH ***/ -static tr_tracker_event const TRACKER_EVENT_INIT = -{ +static tr_tracker_event const TRACKER_EVENT_INIT = { .messageType = TR_TRACKER_WARNING, .text = NULL, .tracker = NULL, .pex = NULL, .pexCount = 0, - .seedProbability = 0 + .seedProbability = 0, }; static void publishMessage(tr_tier* tier, char const* msg, int type) @@ -964,7 +962,10 @@ void tr_announcerAddBytes(tr_torrent* tor, int type, uint32_t byteCount) **** ***/ -static tr_announce_request* announce_request_new(tr_announcer const* announcer, tr_torrent* tor, tr_tier const* tier, +static tr_announce_request* announce_request_new( + tr_announcer const* announcer, + tr_torrent* tor, + tr_tier const* tier, tr_announce_event event) { tr_announce_request* req = tr_new0(tr_announce_request, 1); @@ -1098,7 +1099,8 @@ static void on_announce_done(tr_announce_response const* response, void* vdata) { tr_tracker* tracker; - dbgmsg(tier, + dbgmsg( + tier, "Got announce response: " "connected:%d " "timeout:%d " @@ -1229,8 +1231,11 @@ static void on_announce_done(tr_announce_response const* response, void* vdata) then a separate scrape isn't needed */ if (scrape_fields >= 3 || (scrape_fields >= 1 && tracker->scrape_info == NULL)) { - tr_logAddTorDbg(tier->tor, "Announce response contained scrape info; " - "rescheduling next scrape to %d seconds from now.", tier->scrapeIntervalSec); + tr_logAddTorDbg( + tier->tor, + "Announce response contained scrape info; " + "rescheduling next scrape to %d seconds from now.", + tier->scrapeIntervalSec); tier->scrapeAt = get_next_scrape_time(announcer->session, tier, tier->scrapeIntervalSec); tier->lastScrapeTime = now; tier->lastScrapeSucceeded = true; @@ -1273,7 +1278,10 @@ static void announce_request_free(tr_announce_request* req) tr_free(req); } -static void announce_request_delegate(tr_announcer* announcer, tr_announce_request* request, tr_announce_response_func callback, +static void announce_request_delegate( + tr_announcer* announcer, + tr_announce_request* request, + tr_announce_response_func callback, void* callback_data) { tr_session* session = announcer->session; @@ -1339,11 +1347,10 @@ static bool multiscrape_too_big(char const* errmsg) { /* Found a tracker that returns some bespoke string for this case? Add your patch here and open a PR */ - static char const* const too_long_errors[] = - { + static char const* const too_long_errors[] = { "Bad Request", "GET string too long", - "Request-URI Too Long" + "Request-URI Too Long", }; if (errmsg == NULL) @@ -1396,9 +1403,7 @@ static tr_tier* find_tier(tr_torrent* tor, char const* scrape) { tr_tracker const* const tracker = tt->tiers[i].currentTracker; - if (tracker != NULL && - tracker->scrape_info != NULL && - tr_strcmp0(scrape, tracker->scrape_info->url) == 0) + if (tracker != NULL && tracker->scrape_info != NULL && tr_strcmp0(scrape, tracker->scrape_info->url) == 0) { return &tt->tiers[i]; } @@ -1424,7 +1429,8 @@ static void on_scrape_done(tr_scrape_response const* response, void* vsession) if (tier != NULL) { - dbgmsg(tier, + dbgmsg( + tier, "scraped url:%s -- " "did_connect:%d " "did_timeout:%d " @@ -1537,7 +1543,10 @@ static void on_scrape_done(tr_scrape_response const* response, void* vsession) } } -static void scrape_request_delegate(tr_announcer* announcer, tr_scrape_request const* request, tr_scrape_response_func callback, +static void scrape_request_delegate( + tr_announcer* announcer, + tr_scrape_request const* request, + tr_scrape_response_func callback, void* callback_data) { tr_session* session = announcer->session; @@ -1647,7 +1656,10 @@ static int compareTiers(void const* va, void const* vb) tr_tier const* b = *(tr_tier const* const*)vb; /* primary key: larger stats come before smaller */ - ret = compareTransfer(a->byteCounts[TR_ANN_UP], a->byteCounts[TR_ANN_DOWN], b->byteCounts[TR_ANN_UP], + ret = compareTransfer( + a->byteCounts[TR_ANN_UP], + a->byteCounts[TR_ANN_DOWN], + b->byteCounts[TR_ANN_UP], b->byteCounts[TR_ANN_DOWN]); /* secondary key: announcements that have been waiting longer go first */ diff --git a/libtransmission/announcer.h b/libtransmission/announcer.h index 72a69b86d..15e0f0f36 100644 --- a/libtransmission/announcer.h +++ b/libtransmission/announcer.h @@ -27,8 +27,7 @@ typedef enum TR_TRACKER_ERROR, TR_TRACKER_ERROR_CLEAR, TR_TRACKER_PEERS -} -TrackerEventType; +} TrackerEventType; struct tr_pex; @@ -48,10 +47,9 @@ typedef struct /* [0...100] for probability a peer is a seed. calculated by the leecher/seeder ratio */ int8_t seedProbability; -} -tr_tracker_event; +} tr_tracker_event; -typedef void (* tr_tracker_callback)(tr_torrent* tor, tr_tracker_event const* event, void* client_data); +typedef void (*tr_tracker_callback)(tr_torrent* tor, tr_tracker_event const* event, void* client_data); /** *** Session ctor/dtor diff --git a/libtransmission/bandwidth.c b/libtransmission/bandwidth.c index 48f6cb614..1c9a9ceba 100644 --- a/libtransmission/bandwidth.c +++ b/libtransmission/bandwidth.c @@ -149,7 +149,11 @@ void tr_bandwidthSetParent(tr_bandwidth* b, tr_bandwidth* parent) **** ***/ -static void allocateBandwidth(tr_bandwidth* b, tr_priority_t parent_priority, tr_direction dir, unsigned int period_msec, +static void allocateBandwidth( + tr_bandwidth* b, + tr_priority_t parent_priority, + tr_direction dir, + unsigned int period_msec, tr_ptrArray* peer_pool) { TR_ASSERT(tr_isBandwidth(b)); @@ -386,8 +390,14 @@ void tr_bandwidthUsed(tr_bandwidth* b, tr_direction dir, size_t byteCount, bool if (dir == DEBUG_DIRECTION && band->isLimited) { - fprintf(stderr, "%p consumed %5zu bytes of %5s data... was %6zu, now %6zu left\n", b, byteCount, - isPieceData ? "piece" : "raw", oldBytesLeft, band->bytesLeft); + fprintf( + stderr, + "%p consumed %5zu bytes of %5s data... was %6zu, now %6zu left\n", + b, + byteCount, + isPieceData ? "piece" : "raw", + oldBytesLeft, + band->bytesLeft); } #endif diff --git a/libtransmission/bandwidth.h b/libtransmission/bandwidth.h index 27b570852..5397e06dd 100644 --- a/libtransmission/bandwidth.h +++ b/libtransmission/bandwidth.h @@ -44,8 +44,7 @@ struct bratecontrol { uint64_t date; uint64_t size; - } - transfers[HISTORY_SIZE]; + } transfers[HISTORY_SIZE]; uint64_t cache_time; unsigned int cache_val; }; @@ -114,8 +113,7 @@ typedef struct tr_bandwidth tr_session* session; tr_ptrArray children; /* struct tr_bandwidth */ struct tr_peerIo* peer; -} -tr_bandwidth; +} tr_bandwidth; /** *** diff --git a/libtransmission/bitfield.c b/libtransmission/bitfield.c index 3fe9e9947..c4ed85b70 100644 --- a/libtransmission/bitfield.c +++ b/libtransmission/bitfield.c @@ -13,38 +13,36 @@ #include "tr-assert.h" #include "utils.h" /* tr_new0() */ -tr_bitfield const TR_BITFIELD_INIT = -{ +tr_bitfield const TR_BITFIELD_INIT = { .bits = NULL, .alloc_count = 0, .bit_count = 0, .true_count = 0, .have_all_hint = false, - .have_none_hint = false + .have_none_hint = false, }; /**** ***** ****/ -static int8_t const trueBitCount[256] = -{ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 +static int8_t const trueBitCount[256] = { + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, // + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, // }; static size_t countArray(tr_bitfield const* b) diff --git a/libtransmission/bitfield.h b/libtransmission/bitfield.h index 05c7883aa..070ee7f63 100644 --- a/libtransmission/bitfield.h +++ b/libtransmission/bitfield.h @@ -31,8 +31,7 @@ typedef struct tr_bitfield This occurs when a magnet link's peers send have all / have none */ bool have_all_hint; bool have_none_hint; -} -tr_bitfield; +} tr_bitfield; /*** **** diff --git a/libtransmission/blocklist.c b/libtransmission/blocklist.c index b6942fc43..653687033 100644 --- a/libtransmission/blocklist.c +++ b/libtransmission/blocklist.c @@ -235,12 +235,16 @@ static bool parseLine1(char const* line, struct tr_ipv4_range* range) ++walk; /* walk past the colon */ - if (sscanf(walk, "%d.%d.%d.%d-%d.%d.%d.%d", &b[0], &b[1], &b[2], &b[3], &e[0], &e[1], &e[2], &e[3]) != 8) + if (sscanf( + walk, + "%d.%d.%d.%d-%d.%d.%d.%d", + TR_ARG_TUPLE(&b[0], &b[1], &b[2], &b[3]), + TR_ARG_TUPLE(&e[0], &e[1], &e[2], &e[3])) != 8) { return false; } - tr_snprintf(str, sizeof(str), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]); + tr_snprintf(str, sizeof(str), "%d.%d.%d.%d", TR_ARG_TUPLE(b[0], b[1], b[2], b[3])); if (!tr_address_from_string(&addr, str)) { @@ -249,7 +253,7 @@ static bool parseLine1(char const* line, struct tr_ipv4_range* range) range->begin = ntohl(addr.addr.addr4.s_addr); - tr_snprintf(str, sizeof(str), "%d.%d.%d.%d", e[0], e[1], e[2], e[3]); + tr_snprintf(str, sizeof(str), "%d.%d.%d.%d", TR_ARG_TUPLE(e[0], e[1], e[2], e[3])); if (!tr_address_from_string(&addr, str)) { @@ -273,13 +277,17 @@ static bool parseLine2(char const* line, struct tr_ipv4_range* range) char str[32]; tr_address addr; - if (sscanf(line, "%3d.%3d.%3d.%3d - %3d.%3d.%3d.%3d , %3d , ", &a[0], &a[1], &a[2], &a[3], &b[0], &b[1], &b[2], &b[3], - &unk) != 9) + if (sscanf( + line, + "%3d.%3d.%3d.%3d - %3d.%3d.%3d.%3d , %3d , ", + TR_ARG_TUPLE(&a[0], &a[1], &a[2], &a[3]), + TR_ARG_TUPLE(&b[0], &b[1], &b[2], &b[3]), + &unk) != 9) { return false; } - tr_snprintf(str, sizeof(str), "%d.%d.%d.%d", a[0], a[1], a[2], a[3]); + tr_snprintf(str, sizeof(str), "%d.%d.%d.%d", TR_ARG_TUPLE(a[0], a[1], a[2], a[3])); if (!tr_address_from_string(&addr, str)) { @@ -288,7 +296,7 @@ static bool parseLine2(char const* line, struct tr_ipv4_range* range) range->begin = ntohl(addr.addr.addr4.s_addr); - tr_snprintf(str, sizeof(str), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]); + tr_snprintf(str, sizeof(str), "%d.%d.%d.%d", TR_ARG_TUPLE(b[0], b[1], b[2], b[3])); if (!tr_address_from_string(&addr, str)) { @@ -311,7 +319,7 @@ static bool parseLine3(char const* line, struct tr_ipv4_range* range) uint32_t ip_u; uint32_t mask = 0xffffffff; - if (sscanf(line, "%u.%u.%u.%u/%u", &ip[0], &ip[1], &ip[2], &ip[3], &pflen) != 5) + if (sscanf(line, "%u.%u.%u.%u/%u", TR_ARG_TUPLE(&ip[0], &ip[1], &ip[2], &ip[3]), &pflen) != 5) { return false; } diff --git a/libtransmission/cache.c b/libtransmission/cache.c index db2fa9261..c8af2980d 100644 --- a/libtransmission/cache.c +++ b/libtransmission/cache.c @@ -312,7 +312,12 @@ static struct cache_block* findBlock(tr_cache* cache, tr_torrent* torrent, tr_pi return tr_ptrArrayFindSorted(&cache->blocks, &key, cache_block_compare); } -int tr_cacheWriteBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t piece, uint32_t offset, uint32_t length, +int tr_cacheWriteBlock( + tr_cache* cache, + tr_torrent* torrent, + tr_piece_index_t piece, + uint32_t offset, + uint32_t length, struct evbuffer* writeme) { TR_ASSERT(tr_amInEventThread(torrent->session)); @@ -344,7 +349,12 @@ int tr_cacheWriteBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t pi return cacheTrim(cache); } -int tr_cacheReadBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len, +int tr_cacheReadBlock( + tr_cache* cache, + tr_torrent* torrent, + tr_piece_index_t piece, + uint32_t offset, + uint32_t len, uint8_t* setme) { int err = 0; diff --git a/libtransmission/cache.h b/libtransmission/cache.h index c91e4c9ef..eceb7795d 100644 --- a/libtransmission/cache.h +++ b/libtransmission/cache.h @@ -36,10 +36,20 @@ int tr_cacheSetLimit(tr_cache* cache, int64_t max_bytes); int64_t tr_cacheGetLimit(tr_cache const*); -int tr_cacheWriteBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len, +int tr_cacheWriteBlock( + tr_cache* cache, + tr_torrent* torrent, + tr_piece_index_t piece, + uint32_t offset, + uint32_t len, struct evbuffer* writeme); -int tr_cacheReadBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len, +int tr_cacheReadBlock( + tr_cache* cache, + tr_torrent* torrent, + tr_piece_index_t piece, + uint32_t offset, + uint32_t len, uint8_t* setme); int tr_cachePrefetchBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len); diff --git a/libtransmission/clients.c b/libtransmission/clients.c index 08e2b3b33..634f2be6a 100644 --- a/libtransmission/clients.c +++ b/libtransmission/clients.c @@ -100,7 +100,14 @@ static void three_digits(char* buf, size_t buflen, char const* name, uint8_t con static void four_digits(char* buf, size_t buflen, char const* name, uint8_t const* digits) { - tr_snprintf(buf, buflen, "%s %d.%d.%d.%d", name, charint(digits[0]), charint(digits[1]), charint(digits[2]), + tr_snprintf( + buf, + buflen, + "%s %d.%d.%d.%d", + name, + charint(digits[0]), + charint(digits[1]), + charint(digits[2]), charint(digits[3])); } @@ -210,34 +217,69 @@ char* tr_clientForId(char* buf, size_t buflen, void const* id_in) } else /* current client style: -TR111Z- is 1.11+ */ { - tr_snprintf(buf, buflen, "Transmission %d.%02d%s", strint(id + 3, 1), strint(id + 4, 2), + tr_snprintf( + buf, + buflen, + "Transmission %d.%02d%s", + strint(id + 3, 1), + strint(id + 4, 2), (id[6] == 'Z' || id[6] == 'X') ? "+" : ""); } } else if (strncmp(chid + 1, "UT", 2) == 0) { - tr_snprintf(buf, buflen, "\xc2\xb5Torrent %d.%d.%d%s", strint(id + 3, 1), strint(id + 4, 1), strint(id + 5, 1), + tr_snprintf( + buf, + buflen, + "\xc2\xb5Torrent %d.%d.%d%s", + strint(id + 3, 1), + strint(id + 4, 1), + strint(id + 5, 1), getMnemonicEnd(id[6])); } else if (strncmp(chid + 1, "BT", 2) == 0) { - tr_snprintf(buf, buflen, "BitTorrent %d.%d.%d%s", strint(id + 3, 1), strint(id + 4, 1), strint(id + 5, 1), + tr_snprintf( + buf, + buflen, + "BitTorrent %d.%d.%d%s", + strint(id + 3, 1), + strint(id + 4, 1), + strint(id + 5, 1), getMnemonicEnd(id[6])); } else if (strncmp(chid + 1, "UM", 2) == 0) { - tr_snprintf(buf, buflen, "\xc2\xb5Torrent Mac %d.%d.%d%s", strint(id + 3, 1), strint(id + 4, 1), strint(id + 5, 1), + tr_snprintf( + buf, + buflen, + "\xc2\xb5Torrent Mac %d.%d.%d%s", + strint(id + 3, 1), + strint(id + 4, 1), + strint(id + 5, 1), getMnemonicEnd(id[6])); } else if (strncmp(chid + 1, "UE", 2) == 0) { - tr_snprintf(buf, buflen, "\xc2\xb5Torrent Embedded %d.%d.%d%s", strint(id + 3, 1), strint(id + 4, 1), - strint(id + 5, 1), getMnemonicEnd(id[6])); + tr_snprintf( + buf, + buflen, + "\xc2\xb5Torrent Embedded %d.%d.%d%s", + strint(id + 3, 1), + strint(id + 4, 1), + strint(id + 5, 1), + getMnemonicEnd(id[6])); } else if (strncmp(chid + 1, "UW", 2) == 0) { - tr_snprintf(buf, buflen, "\xc2\xb5Torrent Web %d.%d.%d%s", strint(id + 3, 1), strint(id + 4, 1), strint(id + 5, - 1), getMnemonicEnd(id[6])); + tr_snprintf( + buf, + buflen, + "\xc2\xb5Torrent Web %d.%d.%d%s", + strint(id + 3, 1), + strint(id + 4, 1), + strint(id + 5, 1), + getMnemonicEnd(id[6])); } /* */ else if (strncmp(chid + 1, "AZ", 2) == 0) @@ -655,23 +697,47 @@ char* tr_clientForId(char* buf, size_t buflen, void const* id_in) { if (strncmp(chid + 1, "UT", 2) == 0) { - tr_snprintf(buf, buflen, "\xc2\xb5Torrent %d.%d.%d%s", strint(id + 3, 1), strint(id + 4, 1), strint(id + 5, 2), + tr_snprintf( + buf, + buflen, + "\xc2\xb5Torrent %d.%d.%d%s", + strint(id + 3, 1), + strint(id + 4, 1), + strint(id + 5, 2), getMnemonicEnd(id[7])); } else if (strncmp(chid + 1, "UM", 2) == 0) { - tr_snprintf(buf, buflen, "\xc2\xb5Torrent Mac %d.%d.%d%s", strint(id + 3, 1), strint(id + 4, 1), strint(id + 5, 2), + tr_snprintf( + buf, + buflen, + "\xc2\xb5Torrent Mac %d.%d.%d%s", + strint(id + 3, 1), + strint(id + 4, 1), + strint(id + 5, 2), getMnemonicEnd(id[7])); } else if (strncmp(chid + 1, "UE", 2) == 0) { - tr_snprintf(buf, buflen, "\xc2\xb5Torrent Embedded %d.%d.%d%s", strint(id + 3, 1), strint(id + 4, 1), - strint(id + 5, 2), getMnemonicEnd(id[7])); + tr_snprintf( + buf, + buflen, + "\xc2\xb5Torrent Embedded %d.%d.%d%s", + strint(id + 3, 1), + strint(id + 4, 1), + strint(id + 5, 2), + getMnemonicEnd(id[7])); } else if (strncmp(chid + 1, "UW", 2) == 0) { - tr_snprintf(buf, buflen, "\xc2\xb5Torrent Web %d.%d.%d%s", strint(id + 3, 1), strint(id + 4, 1), strint(id + 5, - 2), getMnemonicEnd(id[7])); + tr_snprintf( + buf, + buflen, + "\xc2\xb5Torrent Web %d.%d.%d%s", + strint(id + 3, 1), + strint(id + 4, 1), + strint(id + 5, 2), + getMnemonicEnd(id[7])); } if (!tr_str_is_empty(buf)) diff --git a/libtransmission/completion.h b/libtransmission/completion.h index b167292ed..d2161af63 100644 --- a/libtransmission/completion.h +++ b/libtransmission/completion.h @@ -40,8 +40,7 @@ typedef struct tr_completion /* number of bytes we want or have now. [0..sizeWhenDone] */ uint64_t sizeNow; -} -tr_completion; +} tr_completion; /** *** Life Cycle diff --git a/libtransmission/crypto-utils-cyassl.c b/libtransmission/crypto-utils-cyassl.c index bcbef0852..d8bee12c7 100644 --- a/libtransmission/crypto-utils-cyassl.c +++ b/libtransmission/crypto-utils-cyassl.c @@ -6,11 +6,10 @@ * */ -/* *INDENT-OFF* */ #if defined(CYASSL_IS_WOLFSSL) #define API_HEADER(x) #define API_HEADER_CRYPT(x) API_HEADER(wolfcrypt/x) -#define API(x) wc_ ## x +#define API(x) wc_##x #define API_VERSION_HEX LIBWOLFSSL_VERSION_HEX #else #define API_HEADER(x) @@ -25,7 +24,6 @@ #include API_HEADER_CRYPT(random.h) #include API_HEADER_CRYPT(sha.h) #include API_HEADER(version.h) -/* *INDENT-ON* */ #include "transmission.h" #include "crypto-utils.h" @@ -204,7 +202,10 @@ void tr_rc4_process(tr_rc4_ctx_t handle, void const* input, void* output, size_t **** ***/ -tr_dh_ctx_t tr_dh_new(uint8_t const* prime_num, size_t prime_num_length, uint8_t const* generator_num, +tr_dh_ctx_t tr_dh_new( + uint8_t const* prime_num, + size_t prime_num_length, + uint8_t const* generator_num, size_t generator_num_length) { TR_ASSERT(prime_num != NULL); @@ -258,8 +259,13 @@ bool tr_dh_make_key(tr_dh_ctx_t raw_handle, size_t private_key_length, uint8_t* tr_lockLock(rng_lock); - if (!check_result(API(DhGenerateKeyPair)(&handle->dh, get_rng(), handle->private_key, &my_private_key_length, public_key, - &my_public_key_length))) + if (!check_result(API(DhGenerateKeyPair)( + &handle->dh, + get_rng(), + handle->private_key, + &my_private_key_length, + public_key, + &my_public_key_length))) { tr_lockUnlock(rng_lock); return false; @@ -290,8 +296,14 @@ tr_dh_secret_t tr_dh_agree(tr_dh_ctx_t raw_handle, uint8_t const* other_public_k ret = tr_dh_secret_new(handle->key_length); - if (check_result(API(DhAgree)(&handle->dh, ret->key, &my_secret_key_length, handle->private_key, handle->private_key_length, - other_public_key, other_public_key_length))) + if (check_result(API(DhAgree)( + &handle->dh, + ret->key, + &my_secret_key_length, + handle->private_key, + handle->private_key_length, + other_public_key, + other_public_key_length))) { tr_dh_secret_align(ret, my_secret_key_length); } diff --git a/libtransmission/crypto-utils-fallback.c b/libtransmission/crypto-utils-fallback.c index f356e725d..40fe2de16 100644 --- a/libtransmission/crypto-utils-fallback.c +++ b/libtransmission/crypto-utils-fallback.c @@ -43,16 +43,28 @@ static void tr_dh_secret_align(struct tr_dh_secret* handle, size_t current_key_l tr_dh_align_key(handle->key, current_key_length, handle->key_length); } -bool tr_dh_secret_derive(tr_dh_secret_t raw_handle, void const* prepend_data, size_t prepend_data_size, void const* append_data, - size_t append_data_size, uint8_t* hash) +bool tr_dh_secret_derive( + tr_dh_secret_t raw_handle, + void const* prepend_data, + size_t prepend_data_size, + void const* append_data, + size_t append_data_size, + uint8_t* hash) { TR_ASSERT(raw_handle != NULL); TR_ASSERT(hash != NULL); struct tr_dh_secret* handle = raw_handle; - return tr_sha1(hash, prepend_data == NULL ? "" : prepend_data, prepend_data == NULL ? 0 : (int)prepend_data_size, - handle->key, (int)handle->key_length, append_data, append_data == NULL ? 0 : (int)append_data_size, NULL); + return tr_sha1( + hash, + prepend_data == NULL ? "" : prepend_data, + prepend_data == NULL ? 0 : (int)prepend_data_size, + handle->key, + (int)handle->key_length, + append_data, + append_data == NULL ? 0 : (int)append_data_size, + NULL); } void tr_dh_secret_free(tr_dh_secret_t handle) diff --git a/libtransmission/crypto-utils-openssl.c b/libtransmission/crypto-utils-openssl.c index 78ffd377b..66840ef14 100644 --- a/libtransmission/crypto-utils-openssl.c +++ b/libtransmission/crypto-utils-openssl.c @@ -297,7 +297,10 @@ static inline void DH_get0_key(DH const* dh, BIGNUM const** pub_key, BIGNUM cons #endif -tr_dh_ctx_t tr_dh_new(uint8_t const* prime_num, size_t prime_num_length, uint8_t const* generator_num, +tr_dh_ctx_t tr_dh_new( + uint8_t const* prime_num, + size_t prime_num_length, + uint8_t const* generator_num, size_t generator_num_length) { TR_ASSERT(prime_num != NULL); diff --git a/libtransmission/crypto-utils-polarssl.c b/libtransmission/crypto-utils-polarssl.c index cec46ce16..c1eb9daa8 100644 --- a/libtransmission/crypto-utils-polarssl.c +++ b/libtransmission/crypto-utils-polarssl.c @@ -6,17 +6,15 @@ * */ -/* *INDENT-OFF* */ #if defined(POLARSSL_IS_MBEDTLS) #define API_HEADER(x) -#define API(x) mbedtls_ ## x +#define API(x) mbedtls_##x #define API_VERSION_NUMBER MBEDTLS_VERSION_NUMBER #else #define API_HEADER(x) #define API(x) x #define API_VERSION_NUMBER POLARSSL_VERSION_NUMBER #endif -/* *INDENT-ON* */ #include API_HEADER(arc4.h) #include API_HEADER(base64.h) @@ -43,10 +41,10 @@ #define MY_NAME "tr_crypto_utils" -typedef API (ctr_drbg_context) api_ctr_drbg_context; -typedef API (sha1_context) api_sha1_context; -typedef API (arc4_context) api_arc4_context; -typedef API (dhm_context) api_dhm_context; +typedef API(ctr_drbg_context) api_ctr_drbg_context; +typedef API(sha1_context) api_sha1_context; +typedef API(arc4_context) api_arc4_context; +typedef API(dhm_context) api_dhm_context; static void log_polarssl_error(int error_code, char const* file, int line) { @@ -235,7 +233,10 @@ void tr_rc4_process(tr_rc4_ctx_t handle, void const* input, void* output, size_t **** ***/ -tr_dh_ctx_t tr_dh_new(uint8_t const* prime_num, size_t prime_num_length, uint8_t const* generator_num, +tr_dh_ctx_t tr_dh_new( + uint8_t const* prime_num, + size_t prime_num_length, + uint8_t const* generator_num, size_t generator_num_length) { TR_ASSERT(prime_num != NULL); diff --git a/libtransmission/crypto-utils.h b/libtransmission/crypto-utils.h index 3d7c9496d..2b827b3e8 100644 --- a/libtransmission/crypto-utils.h +++ b/libtransmission/crypto-utils.h @@ -81,7 +81,10 @@ void tr_rc4_process(tr_rc4_ctx_t handle, void const* input, void* output, size_t /** * @brief Allocate and initialize new Diffie-Hellman (DH) key exchange context. */ -tr_dh_ctx_t tr_dh_new(uint8_t const* prime_num, size_t prime_num_length, uint8_t const* generator_num, +tr_dh_ctx_t tr_dh_new( + uint8_t const* prime_num, + size_t prime_num_length, + uint8_t const* generator_num, size_t generator_num_length); /** @@ -103,8 +106,13 @@ tr_dh_secret_t tr_dh_agree(tr_dh_ctx_t handle, uint8_t const* other_public_key, * @brief Calculate SHA1 hash of DH secret key, prepending and/or appending * given data to the key during calculation. */ -bool tr_dh_secret_derive(tr_dh_secret_t handle, void const* prepend_data, size_t prepend_data_size, void const* append_data, - size_t append_data_size, uint8_t* hash); +bool tr_dh_secret_derive( + tr_dh_secret_t handle, + void const* prepend_data, + size_t prepend_data_size, + void const* append_data, + size_t append_data_size, + uint8_t* hash); /** * @brief Free DH secret key returned by @ref tr_dh_agree. diff --git a/libtransmission/crypto.c b/libtransmission/crypto.c index 231bd4d8a..6cdb81d92 100644 --- a/libtransmission/crypto.c +++ b/libtransmission/crypto.c @@ -21,16 +21,15 @@ #define PRIME_LEN 96 #define DH_PRIVKEY_LEN 20 -static uint8_t const dh_P[PRIME_LEN] = -{ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, - 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, - 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, - 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, - 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, - 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, - 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, - 0xA6, 0x3A, 0x36, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x05, 0x63, +static uint8_t const dh_P[PRIME_LEN] = { + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, // + 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, // + 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, // + 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, // + 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, // + 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, // + 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, // + 0xA6, 0x3A, 0x36, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x05, 0x63, // }; static uint8_t const dh_G[] = { 2 }; @@ -157,8 +156,13 @@ void tr_cryptoEncrypt(tr_crypto* crypto, size_t buf_len, void const* buf_in, voi tr_rc4_process(crypto->enc_key, buf_in, buf_out, buf_len); } -bool tr_cryptoSecretKeySha1(tr_crypto const* crypto, void const* prepend_data, size_t prepend_data_size, - void const* append_data, size_t append_data_size, uint8_t* hash) +bool tr_cryptoSecretKeySha1( + tr_crypto const* crypto, + void const* prepend_data, + size_t prepend_data_size, + void const* append_data, + size_t append_data_size, + uint8_t* hash) { TR_ASSERT(crypto != NULL); TR_ASSERT(crypto->mySecret != NULL); diff --git a/libtransmission/crypto.h b/libtransmission/crypto.h index 22a4775f3..ec1046224 100644 --- a/libtransmission/crypto.h +++ b/libtransmission/crypto.h @@ -43,8 +43,7 @@ typedef struct uint8_t torrentHash[SHA_DIGEST_LENGTH]; bool isIncoming; bool torrentHashIsSet; -} -tr_crypto; +} tr_crypto; /** @brief construct a new tr_crypto object */ void tr_cryptoConstruct(tr_crypto* crypto, uint8_t const* torrentHash, bool isIncoming); @@ -70,8 +69,13 @@ void tr_cryptoEncryptInit(tr_crypto* crypto); void tr_cryptoEncrypt(tr_crypto* crypto, size_t buflen, void const* buf_in, void* buf_out); -bool tr_cryptoSecretKeySha1(tr_crypto const* crypto, void const* prepend_data, size_t prepend_data_size, - void const* append_data, size_t append_data_size, uint8_t* hash); +bool tr_cryptoSecretKeySha1( + tr_crypto const* crypto, + void const* prepend_data, + size_t prepend_data_size, + void const* append_data, + size_t append_data_size, + uint8_t* hash); /* @} */ diff --git a/libtransmission/error.h b/libtransmission/error.h index 3bfc07d71..75a54e6d8 100644 --- a/libtransmission/error.h +++ b/libtransmission/error.h @@ -26,8 +26,7 @@ typedef struct tr_error int code; /** @brief Error message */ char* message; -} -tr_error; +} tr_error; /** * @brief Create new error object using literal error message. @@ -126,8 +125,8 @@ void tr_error_prefix(tr_error** error, char const* prefix_format, ...) TR_GNUC_P * @param[in] prefix_format Prefix format string. * @param[in] ... Format arguments. */ -void tr_error_propagate_prefixed(tr_error** new_error, tr_error** old_error, char const* prefix_format, ...) TR_GNUC_PRINTF(3, - 4); +void tr_error_propagate_prefixed(tr_error** new_error, tr_error** old_error, char const* prefix_format, ...) + TR_GNUC_PRINTF(3, 4); /** @} */ diff --git a/libtransmission/fdlimit.c b/libtransmission/fdlimit.c index 21521e54d..e06ee4885 100644 --- a/libtransmission/fdlimit.c +++ b/libtransmission/fdlimit.c @@ -146,7 +146,11 @@ static void cached_file_close(struct tr_cached_file* o) * errno values include ENOENT if the parent folder doesn't exist, * plus the errno values set by tr_sys_dir_create () and tr_sys_file_open (). */ -static int cached_file_open(struct tr_cached_file* o, char const* filename, bool writable, tr_preallocation_mode allocation, +static int cached_file_open( + struct tr_cached_file* o, + char const* filename, + bool writable, + tr_preallocation_mode allocation, uint64_t file_size) { int flags; @@ -214,8 +218,12 @@ static int cached_file_open(struct tr_cached_file* o, char const* filename, bool if (!success) { - tr_logAddError(_("Couldn't preallocate file \"%1$s\" (%2$s, size: %3$" PRIu64 "): %4$s"), - filename, type, file_size, error->message); + tr_logAddError( + _("Couldn't preallocate file \"%1$s\" (%2$s, size: %3$" PRIu64 "): %4$s"), + filename, + type, + file_size, + error->message); goto FAIL; } @@ -263,13 +271,12 @@ struct tr_fileset static void fileset_construct(struct tr_fileset* set, int n) { - struct tr_cached_file const TR_CACHED_FILE_INIT = - { + struct tr_cached_file const TR_CACHED_FILE_INIT = { .is_writable = false, .fd = TR_BAD_SYS_FILE, .torrent_id = 0, .file_index = 0, - .used_at = 0 + .used_at = 0, }; set->begin = tr_new(struct tr_cached_file, n); @@ -468,8 +475,14 @@ void tr_fdTorrentClose(tr_session* session, int torrent_id) } /* returns an fd on success, or a TR_BAD_SYS_FILE on failure and sets errno */ -tr_sys_file_t tr_fdFileCheckout(tr_session* session, int torrent_id, tr_file_index_t i, char const* filename, bool writable, - tr_preallocation_mode allocation, uint64_t file_size) +tr_sys_file_t tr_fdFileCheckout( + tr_session* session, + int torrent_id, + tr_file_index_t i, + char const* filename, + bool writable, + tr_preallocation_mode allocation, + uint64_t file_size) { struct tr_fileset* set = get_fileset(session); struct tr_cached_file* o = fileset_lookup(set, torrent_id, i); diff --git a/libtransmission/fdlimit.h b/libtransmission/fdlimit.h index ab3a4503f..721e6ea35 100644 --- a/libtransmission/fdlimit.h +++ b/libtransmission/fdlimit.h @@ -40,8 +40,14 @@ * * @see tr_fdFileClose */ -tr_sys_file_t tr_fdFileCheckout(tr_session* session, int torrent_id, tr_file_index_t file_num, char const* filename, - bool do_write, tr_preallocation_mode preallocation_mode, uint64_t preallocation_file_size); +tr_sys_file_t tr_fdFileCheckout( + tr_session* session, + int torrent_id, + tr_file_index_t file_num, + char const* filename, + bool do_write, + tr_preallocation_mode preallocation_mode, + uint64_t preallocation_file_size); tr_sys_file_t tr_fdFileGetCached(tr_session* session, int torrent_id, tr_file_index_t file_num, bool doWrite); diff --git a/libtransmission/file-posix.c b/libtransmission/file-posix.c index 29ce0a4da..c27f42b34 100644 --- a/libtransmission/file-posix.c +++ b/libtransmission/file-posix.c @@ -30,23 +30,23 @@ /* OS-specific file copy (copy_file_range, sendfile64, or copyfile). */ #if defined(__linux__) -# include +#include /* Linux's copy_file_range(2) is buggy prior to 5.3. */ -# if defined(HAVE_COPY_FILE_RANGE) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 3, 0) -# define USE_COPY_FILE_RANGE -# elif defined(HAVE_SENDFILE64) -# include -# define USE_SENDFILE64 -# endif +#if defined(HAVE_COPY_FILE_RANGE) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 3, 0) +#define USE_COPY_FILE_RANGE +#elif defined(HAVE_SENDFILE64) +#include +#define USE_SENDFILE64 +#endif #elif defined(__APPLE__) && defined(HAVE_COPYFILE) -# include -# ifndef COPYFILE_CLONE /* macos < 10.12 */ -# define COPYFILE_CLONE 0 -# endif -# define USE_COPYFILE +#include +#ifndef COPYFILE_CLONE /* macos < 10.12 */ +#define COPYFILE_CLONE 0 +#endif +#define USE_COPYFILE #elif defined(HAVE_COPY_FILE_RANGE) /* Presently this is only FreeBSD 13+. */ -# define USE_COPY_FILE_RANGE +#define USE_COPY_FILE_RANGE #endif /* __linux__ */ #include "transmission.h" @@ -622,12 +622,12 @@ tr_sys_file_t tr_sys_file_open(char const* path, int flags, int permissions, tr_ native_flags |= O_WRONLY; } - native_flags |= - ((flags & TR_SYS_FILE_CREATE) != 0 ? O_CREAT : 0) | - ((flags & TR_SYS_FILE_CREATE_NEW) != 0 ? O_CREAT | O_EXCL : 0) | - ((flags & TR_SYS_FILE_APPEND) != 0 ? O_APPEND : 0) | - ((flags & TR_SYS_FILE_TRUNCATE) != 0 ? O_TRUNC : 0) | - ((flags & TR_SYS_FILE_SEQUENTIAL) != 0 ? O_SEQUENTIAL : 0) | + native_flags |= // + ((flags & TR_SYS_FILE_CREATE) != 0 ? O_CREAT : 0) | // + ((flags & TR_SYS_FILE_CREATE_NEW) != 0 ? O_CREAT | O_EXCL : 0) | // + ((flags & TR_SYS_FILE_APPEND) != 0 ? O_APPEND : 0) | // + ((flags & TR_SYS_FILE_TRUNCATE) != 0 ? O_TRUNC : 0) | // + ((flags & TR_SYS_FILE_SEQUENTIAL) != 0 ? O_SEQUENTIAL : 0) | // O_BINARY | O_LARGEFILE | O_CLOEXEC; ret = open(path, native_flags, permissions); @@ -759,7 +759,12 @@ bool tr_sys_file_read(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_ return ret; } -bool tr_sys_file_read_at(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_t offset, uint64_t* bytes_read, +bool tr_sys_file_read_at( + tr_sys_file_t handle, + void* buffer, + uint64_t size, + uint64_t offset, + uint64_t* bytes_read, tr_error** error) { TR_ASSERT(handle != TR_BAD_SYS_FILE); @@ -835,7 +840,12 @@ bool tr_sys_file_write(tr_sys_file_t handle, void const* buffer, uint64_t size, return ret; } -bool tr_sys_file_write_at(tr_sys_file_t handle, void const* buffer, uint64_t size, uint64_t offset, uint64_t* bytes_written, +bool tr_sys_file_write_at( + tr_sys_file_t handle, + void const* buffer, + uint64_t size, + uint64_t offset, + uint64_t* bytes_written, tr_error** error) { TR_ASSERT(handle != TR_BAD_SYS_FILE); @@ -920,7 +930,8 @@ bool tr_sys_file_advise(tr_sys_file_t handle, uint64_t offset, uint64_t size, tr #if defined(HAVE_POSIX_FADVISE) - int const native_advice = advice == TR_SYS_FILE_ADVICE_WILL_NEED ? POSIX_FADV_WILLNEED : + int const native_advice = advice == TR_SYS_FILE_ADVICE_WILL_NEED ? + POSIX_FADV_WILLNEED : (advice == TR_SYS_FILE_ADVICE_DONT_NEED ? POSIX_FADV_DONTNEED : POSIX_FADV_NORMAL); TR_ASSERT(native_advice != POSIX_FADV_NORMAL); @@ -940,10 +951,9 @@ bool tr_sys_file_advise(tr_sys_file_t handle, uint64_t offset, uint64_t size, tr goto skip_darwin_fcntl; } - struct radvisory const radv = - { + struct radvisory const radv = { .ra_offset = offset, - .ra_count = size + .ra_count = size, }; ret = fcntl(handle, F_RDADVISE, &radv) != -1; @@ -1109,8 +1119,8 @@ bool tr_sys_file_lock(tr_sys_file_t handle, int operation, tr_error** error) { TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT((operation & ~(TR_SYS_FILE_LOCK_SH | TR_SYS_FILE_LOCK_EX | TR_SYS_FILE_LOCK_NB | TR_SYS_FILE_LOCK_UN)) == 0); - TR_ASSERT(!!(operation & TR_SYS_FILE_LOCK_SH) + !!(operation & TR_SYS_FILE_LOCK_EX) + - !!(operation & TR_SYS_FILE_LOCK_UN) == 1); + TR_ASSERT( + !!(operation & TR_SYS_FILE_LOCK_SH) + !!(operation & TR_SYS_FILE_LOCK_EX) + !!(operation & TR_SYS_FILE_LOCK_UN) == 1); bool ret; @@ -1138,8 +1148,7 @@ bool tr_sys_file_lock(tr_sys_file_t handle, int operation, tr_error** error) do { ret = fcntl(handle, (operation & TR_SYS_FILE_LOCK_NB) != 0 ? F_OFD_SETLK : F_OFD_SETLKW, &fl) != -1; - } - while (!ret && errno == EINTR); + } while (!ret && errno == EINTR); if (!ret && errno == EAGAIN) { @@ -1173,8 +1182,7 @@ bool tr_sys_file_lock(tr_sys_file_t handle, int operation, tr_error** error) do { ret = flock(handle, native_operation) != -1; - } - while (!ret && errno == EINTR); + } while (!ret && errno == EINTR); #else @@ -1216,8 +1224,7 @@ char* tr_sys_dir_get_current(tr_error** error) ret = getcwd(tmp, size); size += 2048; - } - while (ret == NULL && errno == ERANGE); + } while (ret == NULL && errno == ERANGE); if (ret == NULL) { diff --git a/libtransmission/file-win32.c b/libtransmission/file-win32.c index e47acbe0d..a1e39ccb9 100644 --- a/libtransmission/file-win32.c +++ b/libtransmission/file-win32.c @@ -19,7 +19,7 @@ #include "utils.h" #ifndef MAXSIZE_T -#define MAXSIZE_T ((SIZE_T)~((SIZE_T)0)) +#define MAXSIZE_T ((SIZE_T) ~((SIZE_T)0)) #endif /* MSDN (http://msdn.microsoft.com/en-us/library/2k2xf226.aspx) only mentions @@ -81,7 +81,11 @@ static time_t filetime_to_unix_time(FILETIME const* t) return tmp / 1000000UL; } -static void stat_to_sys_path_info(DWORD attributes, DWORD size_low, DWORD size_high, FILETIME const* mtime, +static void stat_to_sys_path_info( + DWORD attributes, + DWORD size_low, + DWORD size_high, + FILETIME const* mtime, tr_sys_path_info* info) { TR_ASSERT(mtime != NULL); @@ -153,8 +157,9 @@ static wchar_t* path_to_native_path_ex(char const* path, int extra_chars_after, bool const is_unc = is_unc_path(path); /* `-2` for UNC since we overwrite existing prefix slashes */ - int const extra_chars_before = is_relative ? 0 : (is_unc ? TR_N_ELEMENTS(native_unc_path_prefix) - 2 : - TR_N_ELEMENTS(native_local_path_prefix)); + int const extra_chars_before = is_relative ? + 0 : + (is_unc ? TR_N_ELEMENTS(native_unc_path_prefix) - 2 : TR_N_ELEMENTS(native_local_path_prefix)); /* TODO (?): TR_ASSERT(!is_relative); */ @@ -213,7 +218,7 @@ static char* native_path_to_path(wchar_t const* wide_path) bool const is_local = !is_unc && wcsncmp(wide_path, native_local_path_prefix, TR_N_ELEMENTS(native_local_path_prefix)) == 0; size_t const skip_chars = is_unc ? TR_N_ELEMENTS(native_unc_path_prefix) : - (is_local ? TR_N_ELEMENTS(native_local_path_prefix) : 0); + (is_local ? TR_N_ELEMENTS(native_local_path_prefix) : 0); char* const path = tr_win32_native_to_utf8_ex(wide_path + skip_chars, -1, is_unc ? 2 : 0, 0, NULL); @@ -235,7 +240,13 @@ static tr_sys_file_t open_file(char const* path, DWORD access, DWORD disposition if (wide_path != NULL) { - ret = CreateFileW(wide_path, access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, disposition, flags, + ret = CreateFileW( + wide_path, + access, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, + disposition, + flags, NULL); } @@ -294,8 +305,11 @@ static bool create_dir(char const* path, int flags, int permissions, bool okay_i return ret; } -static void create_temp_path(char* path_template, void (* callback)(char const* path, void* param, - tr_error** error), void* callback_param, tr_error** error) +static void create_temp_path( + char* path_template, + void (*callback)(char const* path, void* param, tr_error** error), + void* callback_param, + tr_error** error) { TR_ASSERT(path_template != NULL); TR_ASSERT(callback != NULL); @@ -428,8 +442,12 @@ bool tr_sys_path_get_info(char const* path, int flags, tr_sys_path_info* info, t if (ret) { - stat_to_sys_path_info(attributes.dwFileAttributes, attributes.nFileSizeLow, attributes.nFileSizeHigh, - &attributes.ftLastWriteTime, info); + stat_to_sys_path_info( + attributes.dwFileAttributes, + attributes.nFileSizeLow, + attributes.nFileSizeHigh, + &attributes.ftLastWriteTime, + info); } else { @@ -543,8 +561,14 @@ char* tr_sys_path_resolve(char const* path, tr_error** error) goto fail; } - handle = CreateFileW(wide_path, FILE_READ_EA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); + handle = CreateFileW( + wide_path, + FILE_READ_EA, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, + NULL); if (handle == INVALID_HANDLE_VALUE) { @@ -961,8 +985,12 @@ bool tr_sys_file_get_info(tr_sys_file_t handle, tr_sys_path_info* info, tr_error if (ret) { - stat_to_sys_path_info(attributes.dwFileAttributes, attributes.nFileSizeLow, attributes.nFileSizeHigh, - &attributes.ftLastWriteTime, info); + stat_to_sys_path_info( + attributes.dwFileAttributes, + attributes.nFileSizeLow, + attributes.nFileSizeHigh, + &attributes.ftLastWriteTime, + info); } else { @@ -1035,7 +1063,12 @@ bool tr_sys_file_read(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_ return ret; } -bool tr_sys_file_read_at(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_t offset, uint64_t* bytes_read, +bool tr_sys_file_read_at( + tr_sys_file_t handle, + void* buffer, + uint64_t size, + uint64_t offset, + uint64_t* bytes_read, tr_error** error) { TR_ASSERT(handle != TR_BAD_SYS_FILE); @@ -1104,7 +1137,12 @@ bool tr_sys_file_write(tr_sys_file_t handle, void const* buffer, uint64_t size, return ret; } -bool tr_sys_file_write_at(tr_sys_file_t handle, void const* buffer, uint64_t size, uint64_t offset, uint64_t* bytes_written, +bool tr_sys_file_write_at( + tr_sys_file_t handle, + void const* buffer, + uint64_t size, + uint64_t offset, + uint64_t* bytes_written, tr_error** error) { TR_ASSERT(handle != TR_BAD_SYS_FILE); @@ -1264,8 +1302,8 @@ bool tr_sys_file_lock(tr_sys_file_t handle, int operation, tr_error** error) { TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT((operation & ~(TR_SYS_FILE_LOCK_SH | TR_SYS_FILE_LOCK_EX | TR_SYS_FILE_LOCK_NB | TR_SYS_FILE_LOCK_UN)) == 0); - TR_ASSERT(!!(operation & TR_SYS_FILE_LOCK_SH) + !!(operation & TR_SYS_FILE_LOCK_EX) + - !!(operation & TR_SYS_FILE_LOCK_UN) == 1); + TR_ASSERT( + !!(operation & TR_SYS_FILE_LOCK_SH) + !!(operation & TR_SYS_FILE_LOCK_EX) + !!(operation & TR_SYS_FILE_LOCK_UN) == 1); bool ret; OVERLAPPED overlapped = { .Pointer = 0, .hEvent = NULL }; diff --git a/libtransmission/file.h b/libtransmission/file.h index cc85ef479..a0c081044 100644 --- a/libtransmission/file.h +++ b/libtransmission/file.h @@ -57,8 +57,7 @@ typedef enum TR_STD_SYS_FILE_IN, TR_STD_SYS_FILE_OUT, TR_STD_SYS_FILE_ERR -} -tr_std_sys_file_t; +} tr_std_sys_file_t; typedef enum { @@ -69,16 +68,14 @@ typedef enum TR_SYS_FILE_APPEND = (1 << 4), TR_SYS_FILE_TRUNCATE = (1 << 5), TR_SYS_FILE_SEQUENTIAL = (1 << 6) -} -tr_sys_file_open_flags_t; +} tr_sys_file_open_flags_t; typedef enum { TR_SEEK_SET, TR_SEEK_CUR, TR_SEEK_END -} -tr_seek_origin_t; +} tr_seek_origin_t; typedef enum { @@ -86,49 +83,42 @@ typedef enum TR_SYS_FILE_LOCK_EX = (1 << 1), TR_SYS_FILE_LOCK_NB = (1 << 2), TR_SYS_FILE_LOCK_UN = (1 << 3) -} -tr_sys_file_lock_flags_t; +} tr_sys_file_lock_flags_t; typedef enum { TR_SYS_PATH_NO_FOLLOW = (1 << 0) -} -tr_sys_path_get_info_flags_t; +} tr_sys_path_get_info_flags_t; typedef enum { TR_SYS_FILE_ADVICE_WILL_NEED, TR_SYS_FILE_ADVICE_DONT_NEED -} -tr_sys_file_advice_t; +} tr_sys_file_advice_t; typedef enum { TR_SYS_FILE_PREALLOC_SPARSE = (1 << 0) -} -tr_sys_file_preallocate_flags_t; +} tr_sys_file_preallocate_flags_t; typedef enum { TR_SYS_DIR_CREATE_PARENTS = (1 << 0) -} -tr_sys_dir_create_flags_t; +} tr_sys_dir_create_flags_t; typedef enum { TR_SYS_PATH_IS_FILE, TR_SYS_PATH_IS_DIRECTORY, TR_SYS_PATH_IS_OTHER -} -tr_sys_path_type_t; +} tr_sys_path_type_t; typedef struct tr_sys_path_info { tr_sys_path_type_t type; uint64_t size; time_t last_modified_at; -} -tr_sys_path_info; +} tr_sys_path_info; /** * @name Platform-specific wrapper functions @@ -369,7 +359,11 @@ bool tr_sys_file_get_info(tr_sys_file_t handle, tr_sys_path_info* info, struct t * * @return `True` on success, `false` otherwise (with `error` set accordingly). */ -bool tr_sys_file_seek(tr_sys_file_t handle, int64_t offset, tr_seek_origin_t origin, uint64_t* new_offset, +bool tr_sys_file_seek( + tr_sys_file_t handle, + int64_t offset, + tr_seek_origin_t origin, + uint64_t* new_offset, struct tr_error** error); /** @@ -402,7 +396,12 @@ bool tr_sys_file_read(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_ * * @return `True` on success, `false` otherwise (with `error` set accordingly). */ -bool tr_sys_file_read_at(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_t offset, uint64_t* bytes_read, +bool tr_sys_file_read_at( + tr_sys_file_t handle, + void* buffer, + uint64_t size, + uint64_t offset, + uint64_t* bytes_read, struct tr_error** error); /** @@ -418,7 +417,11 @@ bool tr_sys_file_read_at(tr_sys_file_t handle, void* buffer, uint64_t size, uint * * @return `True` on success, `false` otherwise (with `error` set accordingly). */ -bool tr_sys_file_write(tr_sys_file_t handle, void const* buffer, uint64_t size, uint64_t* bytes_written, +bool tr_sys_file_write( + tr_sys_file_t handle, + void const* buffer, + uint64_t size, + uint64_t* bytes_written, struct tr_error** error); /** @@ -436,7 +439,12 @@ bool tr_sys_file_write(tr_sys_file_t handle, void const* buffer, uint64_t size, * * @return `True` on success, `false` otherwise (with `error` set accordingly). */ -bool tr_sys_file_write_at(tr_sys_file_t handle, void const* buffer, uint64_t size, uint64_t offset, uint64_t* bytes_written, +bool tr_sys_file_write_at( + tr_sys_file_t handle, + void const* buffer, + uint64_t size, + uint64_t offset, + uint64_t* bytes_written, struct tr_error** error); /** @@ -473,7 +481,11 @@ bool tr_sys_file_truncate(tr_sys_file_t handle, uint64_t size, struct tr_error** * * @return `True` on success, `false` otherwise (with `error` set accordingly). */ -bool tr_sys_file_advise(tr_sys_file_t handle, uint64_t offset, uint64_t size, tr_sys_file_advice_t advice, +bool tr_sys_file_advise( + tr_sys_file_t handle, + uint64_t offset, + uint64_t size, + tr_sys_file_advice_t advice, struct tr_error** error); /** diff --git a/libtransmission/handshake.c b/libtransmission/handshake.c index 7b5471c33..811438311 100644 --- a/libtransmission/handshake.c +++ b/libtransmission/handshake.c @@ -103,8 +103,7 @@ typedef enum AWAITING_PAD_D, /* */ N_STATES -} -handshake_state_t; +} handshake_state_t; struct tr_handshake { @@ -132,16 +131,16 @@ struct tr_handshake **/ #define dbgmsg(handshake, ...) \ - do { \ + do \ + { \ char addrstr[TR_ADDRSTRLEN]; \ tr_peerIoGetAddrStr(handshake->io, addrstr, sizeof(addrstr)); \ tr_logAddDeepNamed(addrstr, __VA_ARGS__); \ - } while(0) + } while (0) static char const* getStateName(handshake_state_t const state) { - static char const* const state_strings[N_STATES] = - { + static char const* const state_strings[N_STATES] = { "awaiting handshake", /* AWAITING_HANDSHAKE */ "awaiting peer id", /* AWAITING_PEER_ID */ "awaiting ya", /* AWAITING_YA */ @@ -215,8 +214,7 @@ typedef enum HANDSHAKE_ENCRYPTION_WRONG, HANDSHAKE_BAD_TORRENT, HANDSHAKE_PEER_IS_SELF, -} -handshake_parse_err_t; +} handshake_parse_err_t; static handshake_parse_err_t parseHandshake(tr_handshake* handshake, struct evbuffer* inbuf) { @@ -261,7 +259,7 @@ static handshake_parse_err_t parseHandshake(tr_handshake* handshake, struct evbu /* peer id */ handshake->havePeerID = true; - dbgmsg(handshake, "peer-id is [%*.*s]", PEER_ID_LEN, PEER_ID_LEN, peer_id); + dbgmsg(handshake, "peer-id is [%*.*s]", TR_ARG_TUPLE(PEER_ID_LEN, PEER_ID_LEN, peer_id)); tor = tr_torrentFindFromHash(handshake->session, hash); @@ -1093,8 +1091,13 @@ static ReadState canRead(struct tr_peerIo* io, void* arg, size_t* piece) static bool fireDoneFunc(tr_handshake* handshake, bool isConnected) { uint8_t const* peer_id = (isConnected && handshake->havePeerID) ? tr_peerIoGetPeersId(handshake->io) : NULL; - bool const success = (*handshake->doneCB)(handshake, handshake->io, handshake->haveReadAnythingFromPeer, isConnected, - peer_id, handshake->doneUserData); + bool const success = (*handshake->doneCB)( + handshake, + handshake->io, + handshake->haveReadAnythingFromPeer, + isConnected, + peer_id, + handshake->doneUserData); return success; } diff --git a/libtransmission/handshake.h b/libtransmission/handshake.h index 5a2aef601..b6ae1f130 100644 --- a/libtransmission/handshake.h +++ b/libtransmission/handshake.h @@ -25,11 +25,19 @@ struct tr_peerIo; typedef struct tr_handshake tr_handshake; /* returns true on success, false on error */ -typedef bool (* handshakeDoneCB)(struct tr_handshake* handshake, struct tr_peerIo* io, bool readAnythingFromPeer, - bool isConnected, uint8_t const* peerId, void* userData); +typedef bool (*handshakeDoneCB)( + struct tr_handshake* handshake, + struct tr_peerIo* io, + bool readAnythingFromPeer, + bool isConnected, + uint8_t const* peerId, + void* userData); /** @brief instantiate a new handshake */ -tr_handshake* tr_handshakeNew(struct tr_peerIo* io, tr_encryption_mode encryptionMode, handshakeDoneCB doneCB, +tr_handshake* tr_handshakeNew( + struct tr_peerIo* io, + tr_encryption_mode encryptionMode, + handshakeDoneCB doneCB, void* doneUserData); tr_address const* tr_handshakeGetAddr(struct tr_handshake const* handshake, tr_port* port); diff --git a/libtransmission/history.h b/libtransmission/history.h index 8263f5cd5..d4fd8f656 100644 --- a/libtransmission/history.h +++ b/libtransmission/history.h @@ -42,10 +42,8 @@ typedef struct tr_recentHistory { unsigned int n; time_t date; - } - slices[TR_RECENT_HISTORY_PERIOD_SEC]; -} -tr_recentHistory; + } slices[TR_RECENT_HISTORY_PERIOD_SEC]; +} tr_recentHistory; /** * @brief add a counter to the recent history object. diff --git a/libtransmission/inout.c b/libtransmission/inout.c index 58be75bad..adebabd77 100644 --- a/libtransmission/inout.c +++ b/libtransmission/inout.c @@ -37,8 +37,14 @@ enum }; /* returns 0 on success, or an errno on failure */ -static int readOrWriteBytes(tr_session* session, tr_torrent* tor, int ioMode, tr_file_index_t fileIndex, uint64_t fileOffset, - void* buf, size_t buflen) +static int readOrWriteBytes( + tr_session* session, + tr_torrent* tor, + int ioMode, + tr_file_index_t fileIndex, + uint64_t fileOffset, + void* buf, + size_t buflen) { tr_sys_file_t fd; int err = 0; @@ -79,7 +85,7 @@ static int readOrWriteBytes(tr_session* session, tr_torrent* tor, int ioMode, tr /* figure out where the file should go, so we can create it */ base = tr_torrentGetCurrentDir(tor); subpath = tr_sessionIsIncompleteFileNamingEnabled(tor->session) ? tr_torrentBuildPartial(tor, fileIndex) : - tr_strdup(file->name); + tr_strdup(file->name); } if (err == 0) @@ -88,8 +94,8 @@ static int readOrWriteBytes(tr_session* session, tr_torrent* tor, int ioMode, tr char* filename = tr_buildPath(base, subpath, NULL); int const prealloc = (file->dnd || !doWrite) ? TR_PREALLOCATE_NONE : tor->session->preallocationMode; - if ((fd = tr_fdFileCheckout(session, tor->uniqueId, fileIndex, filename, doWrite, prealloc, - file->length)) == TR_BAD_SYS_FILE) + if ((fd = tr_fdFileCheckout(session, tor->uniqueId, fileIndex, filename, doWrite, prealloc, file->length)) == + TR_BAD_SYS_FILE) { err = errno; tr_logAddTorErr(tor, "tr_fdFileCheckout failed for \"%s\": %s", filename, tr_strerror(err)); @@ -163,7 +169,11 @@ static int compareOffsetToFile(void const* a, void const* b) return 0; } -void tr_ioFindFileLocation(tr_torrent const* tor, tr_piece_index_t pieceIndex, uint32_t pieceOffset, tr_file_index_t* fileIndex, +void tr_ioFindFileLocation( + tr_torrent const* tor, + tr_piece_index_t pieceIndex, + uint32_t pieceOffset, + tr_file_index_t* fileIndex, uint64_t* fileOffset) { TR_ASSERT(tr_isTorrent(tor)); @@ -185,7 +195,12 @@ void tr_ioFindFileLocation(tr_torrent const* tor, tr_piece_index_t pieceIndex, u } /* returns 0 on success, or an errno on failure */ -static int readOrWritePiece(tr_torrent* tor, int ioMode, tr_piece_index_t pieceIndex, uint32_t pieceOffset, uint8_t* buf, +static int readOrWritePiece( + tr_torrent* tor, + int ioMode, + tr_piece_index_t pieceIndex, + uint32_t pieceOffset, + uint8_t* buf, size_t buflen) { int err = 0; diff --git a/libtransmission/inout.h b/libtransmission/inout.h index 616191ae8..cb215fdbf 100644 --- a/libtransmission/inout.h +++ b/libtransmission/inout.h @@ -41,7 +41,11 @@ bool tr_ioTestPiece(tr_torrent* tor, tr_piece_index_t piece); /** * Converts a piece index + offset into a file index + offset. */ -void tr_ioFindFileLocation(tr_torrent const* tor, tr_piece_index_t pieceIndex, uint32_t pieceOffset, tr_file_index_t* fileIndex, +void tr_ioFindFileLocation( + tr_torrent const* tor, + tr_piece_index_t pieceIndex, + uint32_t pieceOffset, + tr_file_index_t* fileIndex, uint64_t* fileOffset); /* @} */ diff --git a/libtransmission/list.c b/libtransmission/list.c index 3404633d3..1f2e44f43 100644 --- a/libtransmission/list.c +++ b/libtransmission/list.c @@ -11,11 +11,10 @@ #include "platform.h" #include "utils.h" -static tr_list const TR_LIST_CLEAR = -{ +static tr_list const TR_LIST_CLEAR = { .data = NULL, .next = NULL, - .prev = NULL + .prev = NULL, }; static tr_list* recycled_nodes = NULL; diff --git a/libtransmission/list.h b/libtransmission/list.h index 3065b3612..722e5b856 100644 --- a/libtransmission/list.h +++ b/libtransmission/list.h @@ -25,11 +25,10 @@ typedef struct tr_list void* data; struct tr_list* next; struct tr_list* prev; -} -tr_list; +} tr_list; typedef tr_voidptr_compare_func TrListCompareFunc; -typedef void (* TrListForeachFunc)(void*); +typedef void (*TrListForeachFunc)(void*); /** * @brief return the number of items in the list diff --git a/libtransmission/log.h b/libtransmission/log.h index af7722017..966015b0d 100644 --- a/libtransmission/log.h +++ b/libtransmission/log.h @@ -25,7 +25,7 @@ static inline bool tr_logLevelIsActive(tr_log_level level) return tr_logGetLevel() >= level; } -void tr_logAddMessage(char const* file, int line, tr_log_level level, char const* torrent, char const* fmt, ...) \ +void tr_logAddMessage(char const* file, int line, tr_log_level level, char const* torrent, char const* fmt, ...) TR_GNUC_PRINTF(5, 6); #define tr_logAddNamed(level, name, ...) \ @@ -35,8 +35,7 @@ void tr_logAddMessage(char const* file, int line, tr_log_level level, char const { \ tr_logAddMessage(__FILE__, __LINE__, level, name, __VA_ARGS__); \ } \ - } \ - while (0) + } while (0) #define tr_logAddNamedError(name, ...) tr_logAddNamed(TR_LOG_ERROR, name, __VA_ARGS__) #define tr_logAddNamedInfo(name, ...) tr_logAddNamed(TR_LOG_INFO, name, __VA_ARGS__) @@ -59,7 +58,7 @@ tr_sys_file_t tr_logGetFile(void); /** @brief return true if deep logging has been enabled by the user, false otherwise */ bool tr_logGetDeepEnabled(void); -void tr_logAddDeep(char const* file, int line, char const* name, char const* fmt, ...) TR_GNUC_PRINTF(4, 5) \ +void tr_logAddDeep(char const* file, int line, char const* name, char const* fmt, ...) TR_GNUC_PRINTF(4, 5) TR_GNUC_NONNULL(1, 4); #define tr_logAddDeepNamed(name, ...) \ @@ -69,8 +68,7 @@ void tr_logAddDeep(char const* file, int line, char const* name, char const* fmt { \ tr_logAddDeep(__FILE__, __LINE__, name, __VA_ARGS__); \ } \ - } \ - while (0) + } while (0) /** @brief set the buffer with the current time formatted for deep logging. */ char* tr_logGetTimeStr(char* buf, size_t buflen) TR_GNUC_NONNULL(1); diff --git a/libtransmission/magnet.c b/libtransmission/magnet.c index bdc1ce558..369a3ccbd 100644 --- a/libtransmission/magnet.c +++ b/libtransmission/magnet.c @@ -24,8 +24,7 @@ /* this base32 code converted from code by Robert Kaye and Gordon Mohr * and is public domain. see http://bitzi.com/publicdomain for more info */ -static int const base32Lookup[] = -{ +static int const base32Lookup[] = { 0xFF, 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, /* '0', '1', '2', '3', '4', '5', '6', '7' */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* '8', '9', ':', ';', '<', '=', '>', '?' */ 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G' */ diff --git a/libtransmission/magnet.h b/libtransmission/magnet.h index 38f3cd93f..d2917e132 100644 --- a/libtransmission/magnet.h +++ b/libtransmission/magnet.h @@ -29,8 +29,7 @@ typedef struct tr_magnet_info int webseedCount; char** webseeds; -} -tr_magnet_info; +} tr_magnet_info; tr_magnet_info* tr_magnetParse(char const* uri); diff --git a/libtransmission/makemeta.c b/libtransmission/makemeta.c index 21095c1ed..4dc4f9c58 100644 --- a/libtransmission/makemeta.c +++ b/libtransmission/makemeta.c @@ -349,7 +349,10 @@ static uint8_t* getHashInfo(tr_metainfo_builder* b) return ret; } -static void getFileInfo(char const* topFile, tr_metainfo_builder_file const* file, tr_variant* uninitialized_length, +static void getFileInfo( + char const* topFile, + tr_metainfo_builder_file const* file, + tr_variant* uninitialized_length, tr_variant* uninitialized_path) { size_t offset; @@ -491,8 +494,7 @@ static void tr_realMakeMetaInfo(tr_metainfo_builder* builder) } /* save the file */ - if ((builder->result == TR_MAKEMETA_OK) && - (!builder->abortFlag) && + if ((builder->result == TR_MAKEMETA_OK) && (!builder->abortFlag) && (tr_variantToFile(&top, TR_VARIANT_FMT_BENC, builder->outputFile) != 0)) { builder->my_errno = errno; @@ -565,8 +567,13 @@ static void makeMetaWorkerFunc(void* user_data) workerThread = NULL; } -void tr_makeMetaInfo(tr_metainfo_builder* builder, char const* outputFile, tr_tracker_info const* trackers, int trackerCount, - char const* comment, bool isPrivate) +void tr_makeMetaInfo( + tr_metainfo_builder* builder, + char const* outputFile, + tr_tracker_info const* trackers, + int trackerCount, + char const* comment, + bool isPrivate) { tr_lock* lock; diff --git a/libtransmission/makemeta.h b/libtransmission/makemeta.h index 2cfe87db2..28885b468 100644 --- a/libtransmission/makemeta.h +++ b/libtransmission/makemeta.h @@ -17,8 +17,7 @@ typedef struct tr_metainfo_builder_file { char* filename; uint64_t size; -} -tr_metainfo_builder_file; +} tr_metainfo_builder_file; typedef enum { @@ -27,8 +26,7 @@ typedef enum TR_MAKEMETA_CANCELLED, TR_MAKEMETA_IO_READ, /* see builder.errfile, builder.my_errno */ TR_MAKEMETA_IO_WRITE /* see builder.errfile, builder.my_errno */ -} -tr_metainfo_builder_err; +} tr_metainfo_builder_err; typedef struct tr_metainfo_builder { @@ -82,8 +80,7 @@ typedef struct tr_metainfo_builder **/ struct tr_metainfo_builder* nextBuilder; -} -tr_metainfo_builder; +} tr_metainfo_builder; tr_metainfo_builder* tr_metaInfoBuilderCreate(char const* topFile); @@ -114,7 +111,12 @@ void tr_metaInfoBuilderFree(tr_metainfo_builder*); * * @param trackerCount size of the `trackers' array */ -void tr_makeMetaInfo(tr_metainfo_builder* builder, char const* outputFile, tr_tracker_info const* trackers, int trackerCount, - char const* comment, bool isPrivate); +void tr_makeMetaInfo( + tr_metainfo_builder* builder, + char const* outputFile, + tr_tracker_info const* trackers, + int trackerCount, + char const* comment, + bool isPrivate); TR_END_DECLS diff --git a/libtransmission/metainfo.c b/libtransmission/metainfo.c index bf7d2d909..a7a0cc3aa 100644 --- a/libtransmission/metainfo.c +++ b/libtransmission/metainfo.c @@ -97,11 +97,10 @@ char* tr_metainfo_sanitize_path_component(char const* str, size_t len, bool* is_ /* https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file */ char const* const reserved_chars = "<>:\"/\\|?*"; - char const* const reserved_names[] = - { - "CON", "PRN", "AUX", "NUL", - "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", - "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" + char const* const reserved_names[] = { + "CON", "PRN", "AUX", "NUL", // + "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", // + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", // }; char* const ret = tr_new(char, len + 2); @@ -265,8 +264,7 @@ static char const* parseFiles(tr_info* inf, tr_variant* files, tr_variant const* break; } - if (!tr_variantDictFindList(file, TR_KEY_path_utf_8, &path) && - !tr_variantDictFindList(file, TR_KEY_path, &path)) + if (!tr_variantDictFindList(file, TR_KEY_path_utf_8, &path) && !tr_variantDictFindList(file, TR_KEY_path, &path)) { result = "path"; break; @@ -473,7 +471,7 @@ static char* fix_webseed_url(tr_info const* inf, char const* url_in) { if (inf->fileCount > 1 && len > 0 && url[len - 1] != '/') { - ret = tr_strdup_printf("%*.*s/", (int)len, (int)len, url); + ret = tr_strdup_printf("%*.*s/", TR_ARG_TUPLE((int)len, (int)len, url)); } else { @@ -523,7 +521,11 @@ static void geturllist(tr_info* inf, tr_variant* meta) } } -static char const* tr_metainfoParseImpl(tr_session const* session, tr_info* inf, bool* hasInfoDict, size_t* infoDictLength, +static char const* tr_metainfoParseImpl( + tr_session const* session, + tr_info* inf, + bool* hasInfoDict, + size_t* infoDictLength, tr_variant const* meta_in) { int64_t i; @@ -661,8 +663,7 @@ static char const* tr_metainfoParseImpl(tr_session const* session, tr_info* inf, inf->dateCreated = i; /* private */ - if (!tr_variantDictFindInt(infoDict, TR_KEY_private, &i) && - !tr_variantDictFindInt(meta, TR_KEY_private, &i)) + if (!tr_variantDictFindInt(infoDict, TR_KEY_private, &i) && !tr_variantDictFindInt(meta, TR_KEY_private, &i)) { i = 0; } @@ -705,8 +706,8 @@ static char const* tr_metainfoParseImpl(tr_session const* session, tr_info* inf, /* files */ if (!isMagnet) { - if ((str = parseFiles(inf, tr_variantDictFind(infoDict, TR_KEY_files), tr_variantDictFind(infoDict, - TR_KEY_length))) != NULL) + if ((str = parseFiles(inf, tr_variantDictFind(infoDict, TR_KEY_files), tr_variantDictFind(infoDict, TR_KEY_length))) != + NULL) { return str; } @@ -738,7 +739,11 @@ static char const* tr_metainfoParseImpl(tr_session const* session, tr_info* inf, return NULL; } -bool tr_metainfoParse(tr_session const* session, tr_variant const* meta_in, tr_info* inf, bool* hasInfoDict, +bool tr_metainfoParse( + tr_session const* session, + tr_variant const* meta_in, + tr_info* inf, + bool* hasInfoDict, size_t* infoDictLength) { char const* badTag = tr_metainfoParseImpl(session, inf, hasInfoDict, infoDictLength, meta_in); @@ -798,7 +803,10 @@ void tr_metainfoRemoveSaved(tr_session const* session, tr_info const* inf) tr_free(filename); } -void tr_metainfoMigrateFile(tr_session const* session, tr_info const* info, enum tr_metainfo_basename_format old_format, +void tr_metainfoMigrateFile( + tr_session const* session, + tr_info const* info, + enum tr_metainfo_basename_format old_format, enum tr_metainfo_basename_format new_format) { char* old_filename = getTorrentFilename(session, info, old_format); diff --git a/libtransmission/metainfo.h b/libtransmission/metainfo.h index 118fa4c02..5ef410302 100644 --- a/libtransmission/metainfo.h +++ b/libtransmission/metainfo.h @@ -24,14 +24,21 @@ enum tr_metainfo_basename_format TR_METAINFO_BASENAME_HASH }; -bool tr_metainfoParse(tr_session const* session, tr_variant const* variant, tr_info* setmeInfo, bool* setmeHasInfoDict, +bool tr_metainfoParse( + tr_session const* session, + tr_variant const* variant, + tr_info* setmeInfo, + bool* setmeHasInfoDict, size_t* setmeInfoDictLength); void tr_metainfoRemoveSaved(tr_session const* session, tr_info const* info); char* tr_metainfoGetBasename(tr_info const*, enum tr_metainfo_basename_format format); -void tr_metainfoMigrateFile(tr_session const* session, tr_info const* info, enum tr_metainfo_basename_format old_format, +void tr_metainfoMigrateFile( + tr_session const* session, + tr_info const* info, + enum tr_metainfo_basename_format old_format, enum tr_metainfo_basename_format new_format); /** @brief Private function that's exposed here only for unit tests */ diff --git a/libtransmission/mime-types.c b/libtransmission/mime-types.c index fab5092ba..7e3a0b611 100644 --- a/libtransmission/mime-types.c +++ b/libtransmission/mime-types.c @@ -7,8 +7,7 @@ #include "mime-types.h" -struct mime_type_suffix const mime_type_suffixes[MIME_TYPE_SUFFIX_COUNT] = -{ +struct mime_type_suffix const mime_type_suffixes[MIME_TYPE_SUFFIX_COUNT] = { { "123", "application/vnd.lotus-1-2-3" }, { "1km", "application/vnd.1000minds.decision-model+xml" }, { "3dml", "text/vnd.in3d.3dml" }, diff --git a/libtransmission/natpmp.c b/libtransmission/natpmp.c index 6c2dac29a..bf5d70c93 100644 --- a/libtransmission/natpmp.c +++ b/libtransmission/natpmp.c @@ -40,8 +40,7 @@ typedef enum TR_NATPMP_RECV_MAP, TR_NATPMP_SEND_UNMAP, TR_NATPMP_RECV_UNMAP -} -tr_natpmp_state; +} tr_natpmp_state; struct tr_natpmp { @@ -74,7 +73,13 @@ static void logVal(char const* func, int ret) } else { - tr_logAddNamedDbg(getKey(), "%s failed. Natpmp returned %d (%s); errno is %d (%s)", func, ret, strnatpmperr(ret), errno, + tr_logAddNamedDbg( + getKey(), + "%s failed. Natpmp returned %d (%s); errno is %d (%s)", + func, + ret, + strnatpmperr(ret), + errno, tr_strerror(errno)); } } @@ -144,8 +149,7 @@ int tr_natpmpPulse(struct tr_natpmp* nat, tr_port private_port, bool is_enabled, } } - if ((nat->state == TR_NATPMP_IDLE || nat->state == TR_NATPMP_ERR) && - (nat->is_mapped) && + if ((nat->state == TR_NATPMP_IDLE || nat->state == TR_NATPMP_ERR) && (nat->is_mapped) && (!is_enabled || nat->private_port != private_port)) { nat->state = TR_NATPMP_SEND_UNMAP; diff --git a/libtransmission/net.c b/libtransmission/net.c index 2f65e27e2..0def9cab1 100644 --- a/libtransmission/net.c +++ b/libtransmission/net.c @@ -49,19 +49,17 @@ #include "utils.h" /* tr_time(), tr_logAddDebug() */ #ifndef IN_MULTICAST -#define IN_MULTICAST(a) (((a) & 0xf0000000) == 0xe0000000) +#define IN_MULTICAST(a) (((a)&0xf0000000) == 0xe0000000) #endif -tr_address const tr_in6addr_any = -{ +tr_address const tr_in6addr_any = { .type = TR_AF_INET6, - .addr.addr6 = IN6ADDR_ANY_INIT + .addr.addr6 = IN6ADDR_ANY_INIT, }; -tr_address const tr_inaddr_any = -{ +tr_address const tr_inaddr_any = { .type = TR_AF_INET, - .addr.addr4.s_addr = INADDR_ANY + .addr.addr4.s_addr = INADDR_ANY, }; char* tr_net_strerror(char* buf, size_t buflen, int err) @@ -153,9 +151,8 @@ int tr_address_compare(tr_address const* a, tr_address const* b) return a->type == TR_AF_INET ? 1 : -1; } - return a->type == TR_AF_INET ? - memcmp(&a->addr.addr4, &b->addr.addr4, sizeof(a->addr.addr4)) : - memcmp(&a->addr.addr6.s6_addr, &b->addr.addr6.s6_addr, sizeof(a->addr.addr6.s6_addr)); + return a->type == TR_AF_INET ? memcmp(&a->addr.addr4, &b->addr.addr4, sizeof(a->addr.addr4)) : + memcmp(&a->addr.addr6.s6_addr, &b->addr.addr6.s6_addr, sizeof(a->addr.addr6.s6_addr)); } /*********************************************************************** @@ -213,8 +210,11 @@ void tr_netSetCongestionControl(tr_socket_t s, char const* algorithm) if (setsockopt(s, IPPROTO_TCP, TCP_CONGESTION, (void const*)algorithm, strlen(algorithm) + 1) == -1) { char err_buf[512]; - tr_logAddNamedInfo("Net", "Can't set congestion control algorithm '%s': %s", algorithm, tr_net_strerror(err_buf, - sizeof(err_buf), sockerrno)); + tr_logAddNamedInfo( + "Net", + "Can't set congestion control algorithm '%s': %s", + algorithm, + tr_net_strerror(err_buf, sizeof(err_buf), sockerrno)); } #else @@ -309,7 +309,9 @@ struct tr_peer_socket tr_netOpenPeerSocket(tr_session* session, tr_address const if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void const*)&n, sizeof(n)) == -1) { - tr_logAddInfo("Unable to set SO_RCVBUF on socket %" PRIdMAX ": %s", (intmax_t)s, + tr_logAddInfo( + "Unable to set SO_RCVBUF on socket %" PRIdMAX ": %s", + (intmax_t)s, tr_net_strerror(err_buf, sizeof(err_buf), sockerrno)); } } @@ -329,7 +331,10 @@ struct tr_peer_socket tr_netOpenPeerSocket(tr_session* session, tr_address const if (bind(s, (struct sockaddr*)&source_sock, sourcelen) == -1) { - tr_logAddError(_("Couldn't set source address %s on %" PRIdMAX ": %s"), tr_address_to_string(source_addr), (intmax_t)s, + tr_logAddError( + _("Couldn't set source address %s on %" PRIdMAX ": %s"), + tr_address_to_string(source_addr), + (intmax_t)s, tr_net_strerror(err_buf, sizeof(err_buf), sockerrno)); tr_netClose(session, s); return ret; @@ -345,8 +350,13 @@ struct tr_peer_socket tr_netOpenPeerSocket(tr_session* session, tr_address const if ((tmperrno != ENETUNREACH && tmperrno != EHOSTUNREACH) || addr->type == TR_AF_INET) { - tr_logAddError(_("Couldn't connect socket %" PRIdMAX " to %s, port %d (errno %d - %s)"), (intmax_t)s, - tr_address_to_string(addr), (int)ntohs(port), tmperrno, tr_net_strerror(err_buf, sizeof(err_buf), tmperrno)); + tr_logAddError( + _("Couldn't connect socket %" PRIdMAX " to %s, port %d (errno %d - %s)"), + (intmax_t)s, + tr_address_to_string(addr), + (int)ntohs(port), + tmperrno, + tr_net_strerror(err_buf, sizeof(err_buf), tmperrno)); } tr_netClose(session, s); diff --git a/libtransmission/net.h b/libtransmission/net.h index 8f2abdf7f..f83fb4548 100644 --- a/libtransmission/net.h +++ b/libtransmission/net.h @@ -83,8 +83,7 @@ typedef enum tr_address_type TR_AF_INET, TR_AF_INET6, NUM_TR_AF_INET_TYPES -} -tr_address_type; +} tr_address_type; typedef struct tr_address { @@ -93,10 +92,8 @@ typedef struct tr_address { struct in6_addr addr6; struct in_addr addr4; - } - addr; -} -tr_address; + } addr; +} tr_address; extern tr_address const tr_inaddr_any; extern tr_address const tr_in6addr_any; diff --git a/libtransmission/peer-common.h b/libtransmission/peer-common.h index 59fefe590..71d45aa69 100644 --- a/libtransmission/peer-common.h +++ b/libtransmission/peer-common.h @@ -52,8 +52,7 @@ typedef enum TR_PEER_CLIENT_GOT_HAVE_NONE, TR_PEER_PEER_GOT_PIECE_DATA, TR_PEER_ERROR -} -PeerEventType; +} PeerEventType; typedef struct { @@ -65,20 +64,19 @@ typedef struct uint32_t length; /* for GOT_BLOCK + GOT_PIECE_DATA */ int err; /* errno for GOT_ERROR */ tr_port port; /* for GOT_PORT */ -} -tr_peer_event; +} tr_peer_event; extern tr_peer_event const TR_PEER_EVENT_INIT; -typedef void (* tr_peer_callback)(struct tr_peer* peer, tr_peer_event const* event, void* client_data); +typedef void (*tr_peer_callback)(struct tr_peer* peer, tr_peer_event const* event, void* client_data); /*** **** ***/ -typedef void (* tr_peer_destruct_func)(struct tr_peer* peer); -typedef bool (* tr_peer_is_transferring_pieces_func)(struct tr_peer const* peer, uint64_t now, tr_direction direction, - unsigned int* Bps); +typedef void (*tr_peer_destruct_func)(struct tr_peer* peer); +typedef bool ( + *tr_peer_is_transferring_pieces_func)(struct tr_peer const* peer, uint64_t now, tr_direction direction, unsigned int* Bps); struct tr_peer_virtual_funcs { @@ -129,8 +127,7 @@ typedef struct tr_peer tr_recentHistory cancelsSentToPeer; struct tr_peer_virtual_funcs const* funcs; -} -tr_peer; +} tr_peer; void tr_peerConstruct(struct tr_peer* peer, tr_torrent const* tor); @@ -151,8 +148,7 @@ typedef struct tr_swarm_stats int activeWebseedCount; int peerCount; int peerFromCount[TR_PEER_FROM__MAX]; -} -tr_swarm_stats; +} tr_swarm_stats; extern tr_swarm_stats const TR_SWARM_STATS_INIT; diff --git a/libtransmission/peer-io.c b/libtransmission/peer-io.c index 15cef7a88..58c89bc28 100644 --- a/libtransmission/peer-io.c +++ b/libtransmission/peer-io.c @@ -71,11 +71,12 @@ static size_t guessPacketOverhead(size_t d) **/ #define dbgmsg(io, ...) \ - do { \ + do \ + { \ char addrstr[TR_ADDRSTRLEN]; \ tr_peerIoGetAddrStr(io, addrstr, sizeof(addrstr)); \ tr_logAddDeepNamed(addrstr, __VA_ARGS__); \ - } while(0) + } while (0) /** *** @@ -90,11 +91,10 @@ struct tr_datatype static struct tr_datatype* datatype_pool = NULL; -static struct tr_datatype const TR_DATATYPE_INIT = -{ +static struct tr_datatype const TR_DATATYPE_INIT = { .next = NULL, .length = 0, - .isPieceData = false + .isPieceData = false, }; static struct tr_datatype* datatype_new(void) @@ -329,7 +329,12 @@ static void event_read_cb(evutil_socket_t fd, short event, void* vio) what |= BEV_EVENT_ERROR; } - dbgmsg(io, "event_read_cb got an error. res is %d, what is %hd, errno is %d (%s)", res, what, e, + dbgmsg( + io, + "event_read_cb got an error. res is %d, what is %hd, errno is %d (%s)", + res, + what, + e, tr_net_strerror(errstr, sizeof(errstr), e)); if (io->gotError != NULL) @@ -577,14 +582,13 @@ static void utp_on_overhead(void* closure, uint8_t /* bool */ send, size_t count tr_bandwidthUsed(&io->bandwidth, send ? TR_UP : TR_DOWN, count, false, tr_time_msec()); } -static struct UTPFunctionTable utp_function_table = -{ +static struct UTPFunctionTable utp_function_table = { .on_read = utp_on_read, .on_write = utp_on_write, .get_rb_size = utp_get_rb_size, .on_state = utp_on_state_change, .on_error = utp_on_error, - .on_overhead = utp_on_overhead + .on_overhead = utp_on_overhead, }; /* Dummy UTP callbacks. */ @@ -638,20 +642,26 @@ static void dummy_on_overhead(void* closure, uint8_t /* bool */ send, size_t cou TR_UNUSED(type); } -static struct UTPFunctionTable dummy_utp_function_table = -{ +static struct UTPFunctionTable dummy_utp_function_table = { .on_read = dummy_read, .on_write = dummy_write, .get_rb_size = dummy_get_rb_size, .on_state = dummy_on_state_change, .on_error = dummy_on_error, - .on_overhead = dummy_on_overhead + .on_overhead = dummy_on_overhead, }; #endif /* #ifdef WITH_UTP */ -static tr_peerIo* tr_peerIoNew(tr_session* session, tr_bandwidth* parent, tr_address const* addr, tr_port port, - uint8_t const* torrentHash, bool isIncoming, bool isSeed, struct tr_peer_socket const socket) +static tr_peerIo* tr_peerIoNew( + tr_session* session, + tr_bandwidth* parent, + tr_address const* addr, + tr_port port, + uint8_t const* torrentHash, + bool isIncoming, + bool isSeed, + struct tr_peer_socket const socket) { TR_ASSERT(session != NULL); TR_ASSERT(session->events != NULL); @@ -719,7 +729,11 @@ static tr_peerIo* tr_peerIoNew(tr_session* session, tr_bandwidth* parent, tr_add return io; } -tr_peerIo* tr_peerIoNewIncoming(tr_session* session, tr_bandwidth* parent, tr_address const* addr, tr_port port, +tr_peerIo* tr_peerIoNewIncoming( + tr_session* session, + tr_bandwidth* parent, + tr_address const* addr, + tr_port port, struct tr_peer_socket const socket) { TR_ASSERT(session != NULL); @@ -728,8 +742,14 @@ tr_peerIo* tr_peerIoNewIncoming(tr_session* session, tr_bandwidth* parent, tr_ad return tr_peerIoNew(session, parent, addr, port, NULL, true, false, socket); } -tr_peerIo* tr_peerIoNewOutgoing(tr_session* session, tr_bandwidth* parent, tr_address const* addr, tr_port port, - uint8_t const* torrentHash, bool isSeed, bool utp) +tr_peerIo* tr_peerIoNewOutgoing( + tr_session* session, + tr_bandwidth* parent, + tr_address const* addr, + tr_port port, + uint8_t const* torrentHash, + bool isSeed, + bool utp) { TR_ASSERT(session != NULL); TR_ASSERT(tr_address_is_valid(addr)); @@ -745,8 +765,10 @@ tr_peerIo* tr_peerIoNewOutgoing(tr_session* session, tr_bandwidth* parent, tr_ad if (socket.type == TR_PEER_SOCKET_TYPE_NONE) { socket = tr_netOpenPeerSocket(session, addr, port, isSeed); - dbgmsg(NULL, "tr_netOpenPeerSocket returned fd %" PRIdMAX, (intmax_t)(socket.type != TR_PEER_SOCKET_TYPE_NONE ? - socket.handle.tcp : TR_BAD_SOCKET)); + dbgmsg( + NULL, + "tr_netOpenPeerSocket returned fd %" PRIdMAX, + (intmax_t)(socket.type != TR_PEER_SOCKET_TYPE_NONE ? socket.handle.tcp : TR_BAD_SOCKET)); } if (socket.type == TR_PEER_SOCKET_TYPE_NONE) @@ -1121,8 +1143,12 @@ void tr_peerIoSetEncryption(tr_peerIo* io, tr_encryption_type encryption_type) *** **/ -static inline void processBuffer(tr_crypto* crypto, struct evbuffer* buffer, size_t offset, size_t size, void (* callback)( - tr_crypto*, size_t, void const*, void*)) +static inline void processBuffer( + tr_crypto* crypto, + struct evbuffer* buffer, + size_t offset, + size_t size, + void (*callback)(tr_crypto*, size_t, void const*, void*)) { struct evbuffer_ptr pos; struct evbuffer_iovec iovec; @@ -1140,8 +1166,7 @@ static inline void processBuffer(tr_crypto* crypto, struct evbuffer* buffer, siz TR_ASSERT(size >= iovec.iov_len); size -= iovec.iov_len; - } - while (evbuffer_ptr_set(buffer, &pos, iovec.iov_len, EVBUFFER_PTR_ADD) == 0); + } while (evbuffer_ptr_set(buffer, &pos, iovec.iov_len, EVBUFFER_PTR_ADD) == 0); TR_ASSERT(size == 0); } @@ -1343,7 +1368,12 @@ static int tr_peerIoTryRead(tr_peerIo* io, size_t howmuch) what |= BEV_EVENT_EOF; } - dbgmsg(io, "tr_peerIoTryRead got an error. res is %d, what is %hd, errno is %d (%s)", res, what, e, + dbgmsg( + io, + "tr_peerIoTryRead got an error. res is %d, what is %hd, errno is %d (%s)", + res, + what, + e, tr_net_strerror(err_buf, sizeof(err_buf), e)); io->gotError(io, what, io->userData); @@ -1398,7 +1428,12 @@ static int tr_peerIoTryWrite(tr_peerIo* io, size_t howmuch) char errstr[512]; short const what = BEV_EVENT_WRITING | BEV_EVENT_ERROR; - dbgmsg(io, "tr_peerIoTryWrite got an error. res is %d, what is %hd, errno is %d (%s)", n, what, e, + dbgmsg( + io, + "tr_peerIoTryWrite got an error. res is %d, what is %hd, errno is %d (%s)", + n, + what, + e, tr_net_strerror(errstr, sizeof(errstr), e)); io->gotError(io, what, io->userData); diff --git a/libtransmission/peer-io.h b/libtransmission/peer-io.h index cd347e10f..e60476330 100644 --- a/libtransmission/peer-io.h +++ b/libtransmission/peer-io.h @@ -40,22 +40,20 @@ typedef enum READ_NOW, READ_LATER, READ_ERR -} -ReadState; +} ReadState; typedef enum { /* these match the values in MSE's crypto_select */ PEER_ENCRYPTION_NONE = (1 << 0), PEER_ENCRYPTION_RC4 = (1 << 1) -} -tr_encryption_type; +} tr_encryption_type; -typedef ReadState (* tr_can_read_cb)(struct tr_peerIo* io, void* user_data, size_t* setme_piece_byte_count); +typedef ReadState (*tr_can_read_cb)(struct tr_peerIo* io, void* user_data, size_t* setme_piece_byte_count); -typedef void (* tr_did_write_cb)(struct tr_peerIo* io, size_t bytesWritten, bool wasPieceData, void* userData); +typedef void (*tr_did_write_cb)(struct tr_peerIo* io, size_t bytesWritten, bool wasPieceData, void* userData); -typedef void (* tr_net_error_cb)(struct tr_peerIo* io, short what, void* userData); +typedef void (*tr_net_error_cb)(struct tr_peerIo* io, short what, void* userData); typedef struct tr_peerIo { @@ -102,17 +100,26 @@ typedef struct tr_peerIo struct event* event_read; struct event* event_write; -} -tr_peerIo; +} tr_peerIo; /** *** **/ -tr_peerIo* tr_peerIoNewOutgoing(tr_session* session, struct tr_bandwidth* parent, struct tr_address const* addr, tr_port port, - uint8_t const* torrentHash, bool isSeed, bool utp); +tr_peerIo* tr_peerIoNewOutgoing( + tr_session* session, + struct tr_bandwidth* parent, + struct tr_address const* addr, + tr_port port, + uint8_t const* torrentHash, + bool isSeed, + bool utp); -tr_peerIo* tr_peerIoNewIncoming(tr_session* session, struct tr_bandwidth* parent, struct tr_address const* addr, tr_port port, +tr_peerIo* tr_peerIoNewIncoming( + tr_session* session, + struct tr_bandwidth* parent, + struct tr_address const* addr, + tr_port port, struct tr_peer_socket const socket); void tr_peerIoRefImpl(char const* file, int line, tr_peerIo* io); diff --git a/libtransmission/peer-mgr.c b/libtransmission/peer-mgr.c index 99de75453..1bbf8fbf9 100644 --- a/libtransmission/peer-mgr.c +++ b/libtransmission/peer-mgr.c @@ -82,23 +82,21 @@ enum CANCEL_HISTORY_SEC = 60 }; -tr_peer_event const TR_PEER_EVENT_INIT = -{ +tr_peer_event const TR_PEER_EVENT_INIT = { .eventType = TR_PEER_CLIENT_GOT_BLOCK, .pieceIndex = 0, .bitfield = NULL, .offset = 0, .length = 0, .err = 0, - .port = 0 + .port = 0, }; -tr_swarm_stats const TR_SWARM_STATS_INIT = -{ +tr_swarm_stats const TR_SWARM_STATS_INIT = { .activePeerCount = { 0, 0 }, .activeWebseedCount = 0, .peerCount = 0, - .peerFromCount = { 0, 0, 0, 0, 0, 0, 0 } + .peerFromCount = { 0, 0, 0, 0, 0, 0, 0 }, }; /** @@ -156,9 +154,7 @@ static bool tr_isAtom(struct peer_atom const* atom) static char const* tr_atomAddrStr(struct peer_atom const* atom) { static char addrstr[TR_ADDRSTRLEN]; - return atom != NULL ? - tr_address_and_port_to_string(addrstr, sizeof(addrstr), &atom->addr, atom->port) : - "[no atom]"; + return atom != NULL ? tr_address_and_port_to_string(addrstr, sizeof(addrstr), &atom->addr, atom->port) : "[no atom]"; } struct block_request @@ -225,8 +221,7 @@ typedef struct tr_swarm * requests are considered 'fast' are allowed to request a block that's * already been requested from another (slower?) peer. */ int endgame; -} -tr_swarm; +} tr_swarm; struct tr_peerMgr { @@ -735,8 +730,8 @@ static void requestListAdd(tr_swarm* s, tr_block_index_t block, tr_peer* peer) /* insert the request to our array... */ { bool exact; - int const pos = tr_lowerBound(&key, s->requests, s->requestCount, sizeof(struct block_request), compareReqByBlock, - &exact); + int const + pos = tr_lowerBound(&key, s->requests, s->requestCount, sizeof(struct block_request), compareReqByBlock, &exact); TR_ASSERT(!exact); memmove(s->requests + pos + 1, s->requests + pos, sizeof(struct block_request) * (s->requestCount++ - pos)); s->requests[pos] = key; @@ -787,8 +782,7 @@ static void getBlockRequestPeers(tr_swarm* s, tr_block_index_t block, tr_ptrArra static void decrementPendingReqCount(struct block_request const* b) { - if ((b->peer != NULL) && - (b->peer->pendingReqsToPeer > 0)) + if ((b->peer != NULL) && (b->peer->pendingReqsToPeer > 0)) { --b->peer->pendingReqsToPeer; } @@ -1335,7 +1329,12 @@ void tr_peerMgrRebuildRequests(tr_torrent* tor) pieceListRebuild(tor->swarm); } -void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_block_index_t* setme, int* numgot, +void tr_peerMgrGetNextRequests( + tr_torrent* tor, + tr_peer* peer, + int numwant, + tr_block_index_t* setme, + int* numgot, bool get_intervals) { /* sanity clause */ @@ -1382,7 +1381,7 @@ void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_b tr_torGetPieceBlockRange(tor, p->index, &first, &last); for (tr_block_index_t b = first; b <= last && (got < numwant || (get_intervals && setme[2 * got - 1] == b - 1)); - ++b) + ++b) { int peerCount; tr_peer** peers; @@ -1474,8 +1473,13 @@ void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_b bool exact; /* relative position! */ - int const newpos = tr_lowerBound(&s->pieces[i], &s->pieces[i + 1], s->pieceCount - (i + 1), - sizeof(struct weighted_piece), comparePieceByWeight, &exact); + int const newpos = tr_lowerBound( + &s->pieces[i], + &s->pieces[i + 1], + s->pieceCount - (i + 1), + sizeof(struct weighted_piece), + comparePieceByWeight, + &exact); if (newpos > 0) { @@ -1887,8 +1891,10 @@ static void peerCallbackFunc(tr_peer* peer, tr_peer_event const* e, void* vs) { /* some protocol error from the peer */ peer->doPurge = true; - tordbg(s, "setting %s doPurge flag because we got an ERANGE, EMSGSIZE, or ENOTCONN error", tr_atomAddrStr( - peer->atom)); + tordbg( + s, + "setting %s doPurge flag because we got an ERANGE, EMSGSIZE, or ENOTCONN error", + tr_atomAddrStr(peer->atom)); } else { @@ -1936,8 +1942,13 @@ static int getDefaultShelfLife(uint8_t from) } } -static void ensureAtomExists(tr_swarm* s, tr_address const* addr, tr_port const port, uint8_t const flags, - int8_t const seedProbability, uint8_t const from) +static void ensureAtomExists( + tr_swarm* s, + tr_address const* addr, + tr_port const port, + uint8_t const flags, + int8_t const seedProbability, + uint8_t const from) { TR_ASSERT(tr_address_is_valid(addr)); TR_ASSERT(from < TR_PEER_FROM__MAX); @@ -2012,8 +2023,13 @@ static void createBitTorrentPeer(tr_torrent* tor, struct tr_peerIo* io, struct p } /* FIXME: this is kind of a mess. */ -static bool myHandshakeDoneCB(tr_handshake* handshake, tr_peerIo* io, bool readAnythingFromPeer, bool isConnected, - uint8_t const* peer_id, void* vmanager) +static bool myHandshakeDoneCB( + tr_handshake* handshake, + tr_peerIo* io, + bool readAnythingFromPeer, + bool isConnected, + uint8_t const* peer_id, + void* vmanager) { TR_ASSERT(io != NULL); @@ -2114,7 +2130,8 @@ static bool myHandshakeDoneCB(tr_handshake* handshake, tr_peerIo* io, bool readA client = TR_KEY_NONE; } - tr_peerIo* stolen = tr_handshakeStealIO(handshake); /* this steals its refcount too, which is balanced by our unref in peerDelete() */ + /* this steals its refcount too, which is balanced by our unref in peerDelete() */ + tr_peerIo* stolen = tr_handshakeStealIO(handshake); tr_peerIoSetParent(stolen, &s->tor->bandwidth); createBitTorrentPeer(s->tor, stolen, atom, client); @@ -2206,7 +2223,11 @@ void tr_peerMgrAddPex(tr_torrent* tor, uint8_t from, tr_pex const* pex, int8_t s } } -tr_pex* tr_peerMgrCompactToPex(void const* compact, size_t compactLen, uint8_t const* added_f, size_t added_f_len, +tr_pex* tr_peerMgrCompactToPex( + void const* compact, + size_t compactLen, + uint8_t const* added_f, + size_t added_f_len, size_t* pexCount) { size_t n = compactLen / 6; @@ -2231,7 +2252,11 @@ tr_pex* tr_peerMgrCompactToPex(void const* compact, size_t compactLen, uint8_t c return pex; } -tr_pex* tr_peerMgrCompact6ToPex(void const* compact, size_t compactLen, uint8_t const* added_f, size_t added_f_len, +tr_pex* tr_peerMgrCompact6ToPex( + void const* compact, + size_t compactLen, + uint8_t const* added_f, + size_t added_f_len, size_t* pexCount) { size_t n = compactLen / 18; @@ -2271,7 +2296,11 @@ void tr_peerMgrGotBadPiece(tr_torrent* tor, tr_piece_index_t pieceIndex) if (tr_bitfieldHas(&peer->blame, pieceIndex)) { - tordbg(s, "peer %s contributed to corrupt piece (%d); now has %d strikes", tr_atomAddrStr(peer->atom), pieceIndex, + tordbg( + s, + "peer %s contributed to corrupt piece (%d); now has %d strikes", + tr_atomAddrStr(peer->atom), + pieceIndex, (int)peer->strikes + 1); addStrike(s, peer); } @@ -2932,8 +2961,7 @@ typedef enum RECHOKE_STATE_GOOD, RECHOKE_STATE_UNTESTED, RECHOKE_STATE_BAD -} -tr_rechoke_state; +} tr_rechoke_state; struct tr_rechoke_info { @@ -3018,7 +3046,10 @@ static void rechokeDownloads(tr_swarm* s) double const cancelRate = cancels / (double)(cancels + blocks); double const mult = 1 - MIN(cancelRate, 0.5); maxPeers = s->interestedCount * mult; - tordbg(s, "cancel rate is %.3f -- reducing the number of peers we're interested in by %.0f percent", cancelRate, + tordbg( + s, + "cancel rate is %.3f -- reducing the number of peers we're interested in by %.0f percent", + cancelRate, mult * 100); s->lastCancel = now; } @@ -3032,8 +3063,11 @@ static void rechokeDownloads(tr_swarm* s) double const mult = MIN(timeSinceCancel, maxHistory) / (double)maxHistory; int const inc = maxIncrease * mult; maxPeers = s->maxPeers + inc; - tordbg(s, "time since last cancel is %jd -- increasing the number of peers we're interested in by %d", - (intmax_t)timeSinceCancel, inc); + tordbg( + s, + "time since last cancel is %jd -- increasing the number of peers we're interested in by %d", + (intmax_t)timeSinceCancel, + inc); } } @@ -3189,8 +3223,8 @@ static int getRate(tr_torrent const* tor, struct peer_atom* atom, uint64_t now) * because there may only be a small window of opportunity to share */ else if (tr_torrentIsPrivate(tor)) { - Bps = tr_peerGetPieceSpeed_Bps(atom->peer, now, TR_PEER_TO_CLIENT) + tr_peerGetPieceSpeed_Bps(atom->peer, now, - TR_CLIENT_TO_PEER); + Bps = tr_peerGetPieceSpeed_Bps(atom->peer, now, TR_PEER_TO_CLIENT) + + tr_peerGetPieceSpeed_Bps(atom->peer, now, TR_CLIENT_TO_PEER); } /* downloading a public torrent */ else @@ -3403,7 +3437,7 @@ static bool shouldPeerBeClosed(tr_swarm const* s, tr_peer const* peer, int peerC /* if we have >= relaxIfFewerThan, strictness is 100%. * if we have zero connections, strictness is 0% */ float const strictness = peerCount >= relaxStrictnessIfFewerThanN ? 1.0 : - peerCount / (float)relaxStrictnessIfFewerThanN; + peerCount / (float)relaxStrictnessIfFewerThanN; int const lo = MIN_UPLOAD_IDLE_SECS; int const hi = MAX_UPLOAD_IDLE_SECS; int const limit = hi - (hi - lo) * strictness; @@ -4324,8 +4358,14 @@ static void initiateConnection(tr_peerMgr* mgr, tr_swarm* s, struct peer_atom* a tordbg(s, "Starting an OUTGOING%s connection with %s", utp ? " µTP" : "", tr_atomAddrStr(atom)); - io = tr_peerIoNewOutgoing(mgr->session, &mgr->session->bandwidth, &atom->addr, atom->port, s->tor->info.hash, - s->tor->completeness == TR_SEED, utp); + io = tr_peerIoNewOutgoing( + mgr->session, + &mgr->session->bandwidth, + &atom->addr, + atom->port, + s->tor->info.hash, + s->tor->completeness == TR_SEED, + utp); if (io == NULL) { diff --git a/libtransmission/peer-mgr.h b/libtransmission/peer-mgr.h index b4f3215d0..55fe6a253 100644 --- a/libtransmission/peer-mgr.h +++ b/libtransmission/peer-mgr.h @@ -54,8 +54,7 @@ typedef struct tr_pex tr_address addr; tr_port port; /* this field is in network byte order */ uint8_t flags; -} -tr_pex; +} tr_pex; struct peer_atom; struct tr_peerIo; @@ -81,7 +80,12 @@ void tr_peerMgrSetUtpSupported(tr_torrent* tor, tr_address const* addr); void tr_peerMgrSetUtpFailed(tr_torrent* tor, tr_address const* addr, bool failed); -void tr_peerMgrGetNextRequests(tr_torrent* torrent, tr_peer* peer, int numwant, tr_block_index_t* setme, int* numgot, +void tr_peerMgrGetNextRequests( + tr_torrent* torrent, + tr_peer* peer, + int numwant, + tr_block_index_t* setme, + int* numgot, bool get_intervals); bool tr_peerMgrDidPeerRequest(tr_torrent const* torrent, tr_peer const* peer, tr_block_index_t block); @@ -90,10 +94,18 @@ void tr_peerMgrRebuildRequests(tr_torrent* torrent); void tr_peerMgrAddIncoming(tr_peerMgr* manager, tr_address* addr, tr_port port, struct tr_peer_socket const socket); -tr_pex* tr_peerMgrCompactToPex(void const* compact, size_t compactLen, uint8_t const* added_f, size_t added_f_len, +tr_pex* tr_peerMgrCompactToPex( + void const* compact, + size_t compactLen, + uint8_t const* added_f, + size_t added_f_len, size_t* setme_pex_count); -tr_pex* tr_peerMgrCompact6ToPex(void const* compact, size_t compactLen, uint8_t const* added_f, size_t added_f_len, +tr_pex* tr_peerMgrCompact6ToPex( + void const* compact, + size_t compactLen, + uint8_t const* added_f, + size_t added_f_len, size_t* pexCount); /** @@ -107,7 +119,11 @@ enum TR_PEERS_INTERESTING }; -int tr_peerMgrGetPeers(tr_torrent const* tor, tr_pex** setme_pex, uint8_t address_type, uint8_t peer_list_mode, +int tr_peerMgrGetPeers( + tr_torrent const* tor, + tr_pex** setme_pex, + uint8_t address_type, + uint8_t peer_list_mode, int max_peer_count); void tr_peerMgrStartTorrent(tr_torrent* tor); diff --git a/libtransmission/peer-msgs.c b/libtransmission/peer-msgs.c index e0b8b11a5..1e8f0554f 100644 --- a/libtransmission/peer-msgs.c +++ b/libtransmission/peer-msgs.c @@ -110,8 +110,7 @@ typedef enum ENCRYPTION_PREFERENCE_UNKNOWN, ENCRYPTION_PREFERENCE_YES, ENCRYPTION_PREFERENCE_NO -} -encryption_preference_t; +} encryption_preference_t; /** *** @@ -269,7 +268,9 @@ static void myDebug(char const* file, int line, struct tr_peerMsgs const* msgs, char* base = tr_sys_path_basename(file, NULL); char* message; - evbuffer_add_printf(buf, "[%s] %s - %s [%s]: ", + evbuffer_add_printf( + buf, + "[%s] %s - %s [%s]: ", tr_logGetTimeStr(timestr, sizeof(timestr)), tr_torrentName(msgs->torrent), tr_peerIoGetAddrStr(msgs->io, addrstr, sizeof(addrstr)), @@ -294,8 +295,7 @@ static void myDebug(char const* file, int line, struct tr_peerMsgs const* msgs, { \ myDebug(__FILE__, __LINE__, msgs, __VA_ARGS__); \ } \ - } \ - while (0) + } while (0) /** *** @@ -968,7 +968,7 @@ static void parseLtepHandshake(tr_peerMsgs* msgs, uint32_t len, struct evbuffer* /* arbitrary limit, should be more than enough */ if (len <= 4096) { - dbgmsg(msgs, "here is the handshake: [%*.*s]", (int)len, (int)len, tmp); + dbgmsg(msgs, "here is the handshake: [%*.*s]", TR_ARG_TUPLE((int)len, (int)len, tmp)); } else { @@ -1015,8 +1015,7 @@ static void parseLtepHandshake(tr_peerMsgs* msgs, uint32_t len, struct evbuffer* } /* look for metainfo size (BEP 9) */ - if (tr_variantDictFindInt(&val, TR_KEY_metadata_size, &i) && - tr_torrentSetMetadataSizeHint(msgs->torrent, i)) + if (tr_variantDictFindInt(&val, TR_KEY_metadata_size, &i) && tr_torrentSetMetadataSizeHint(msgs->torrent, i)) { msgs->metadata_size_hint = (size_t)i; } @@ -1035,18 +1034,14 @@ static void parseLtepHandshake(tr_peerMsgs* msgs, uint32_t len, struct evbuffer* dbgmsg(msgs, "peer's port is now %d", (int)i); } - if (tr_peerIoIsIncoming(msgs->io) && - tr_variantDictFindRaw(&val, TR_KEY_ipv4, &addr, &addr_len) && - addr_len == 4) + if (tr_peerIoIsIncoming(msgs->io) && tr_variantDictFindRaw(&val, TR_KEY_ipv4, &addr, &addr_len) && addr_len == 4) { pex.addr.type = TR_AF_INET; memcpy(&pex.addr.addr.addr4, addr, 4); tr_peerMgrAddPex(msgs->torrent, TR_PEER_FROM_LTEP, &pex, seedProbability); } - if (tr_peerIoIsIncoming(msgs->io) && - tr_variantDictFindRaw(&val, TR_KEY_ipv6, &addr, &addr_len) && - addr_len == 16) + if (tr_peerIoIsIncoming(msgs->io) && tr_variantDictFindRaw(&val, TR_KEY_ipv6, &addr, &addr_len) && addr_len == 16) { pex.addr.type = TR_AF_INET6; memcpy(&pex.addr.addr.addr6, addr, 16); @@ -1483,7 +1478,13 @@ static int readBtPiece(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen, fireClientGotPieceData(msgs, n); *setme_piece_bytes_read += n; - dbgmsg(msgs, "got %zu bytes for block %u:%u->%u ... %d remain", n, req->index, req->offset, req->length, + dbgmsg( + msgs, + "got %zu bytes for block %u:%u->%u ... %d remain", + n, + req->index, + req->offset, + req->length, (int)(req->length - evbuffer_get_length(block_buffer))); if (evbuffer_get_length(block_buffer) < req->length) @@ -1624,7 +1625,10 @@ static int readBtMessage(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen if (req->index == r.index && req->offset == r.offset && req->length == r.length) { - tr_removeElementFromArray(msgs->peerAskedFor, i, sizeof(struct peer_request), + tr_removeElementFromArray( + msgs->peerAskedFor, + i, + sizeof(struct peer_request), msgs->peer.pendingReqsToClient); --msgs->peer.pendingReqsToClient; break; @@ -2104,8 +2108,13 @@ static size_t fillOutputBuffer(tr_peerMsgs* msgs, time_t now) evbuffer_add_uint32(out, req.offset); evbuffer_reserve_space(out, req.length, iovec, 1); - err = tr_cacheReadBlock(getSession(msgs)->cache, msgs->torrent, req.index, req.offset, req.length, - iovec[0].iov_base) != 0; + err = tr_cacheReadBlock( + getSession(msgs)->cache, + msgs->torrent, + req.index, + req.offset, + req.length, + iovec[0].iov_base) != 0; iovec[0].iov_len = req.length; evbuffer_commit_space(out, iovec, 1); @@ -2116,7 +2125,9 @@ static size_t fillOutputBuffer(tr_peerMsgs* msgs, time_t now) if (err) { - tr_torrentSetLocalError(msgs->torrent, _("Please Verify Local Data! Piece #%zu is corrupt."), + tr_torrentSetLocalError( + msgs->torrent, + _("Please Verify Local Data! Piece #%zu is corrupt."), (size_t)req.index); } } @@ -2272,8 +2283,7 @@ typedef struct int addedCount; int droppedCount; int elementCount; -} -PexDiffs; +} PexDiffs; static void pexAddedCb(void const* vpex, void* userData) { @@ -2306,7 +2316,7 @@ static inline void pexElementCb(void const* vpex, void* userData) diffs->elements[diffs->elementCount++] = *pex; } -typedef void (* tr_set_func)(void const* element, void* userData); +typedef void (*tr_set_func)(void const* element, void* userData); /** * @brief find the differences and commonalities in two sorted sets @@ -2321,8 +2331,17 @@ typedef void (* tr_set_func)(void const* element, void* userData); * @param in_both called for items that are in both sets * @param userData user data passed along to in_a, in_b, and in_both */ -static void tr_set_compare(void const* va, size_t aCount, void const* vb, size_t bCount, tr_voidptr_compare_func compare, - size_t elementSize, tr_set_func in_a_cb, tr_set_func in_b_cb, tr_set_func in_both_cb, void* userData) +static void tr_set_compare( + void const* va, + size_t aCount, + void const* vb, + size_t bCount, + tr_voidptr_compare_func compare, + size_t elementSize, + tr_set_func in_a_cb, + tr_set_func in_b_cb, + tr_set_func in_both_cb, + void* userData) { uint8_t const* a = va; uint8_t const* b = vb; @@ -2383,18 +2402,45 @@ static void sendPex(tr_peerMsgs* msgs) diffs.droppedCount = 0; diffs.elements = tr_new(tr_pex, newCount + msgs->pexCount); diffs.elementCount = 0; - tr_set_compare(msgs->pex, msgs->pexCount, newPex, newCount, tr_pexCompare, sizeof(tr_pex), pexDroppedCb, pexAddedCb, - pexElementCb, &diffs); + tr_set_compare( + msgs->pex, + msgs->pexCount, + newPex, + newCount, + tr_pexCompare, + sizeof(tr_pex), + pexDroppedCb, + pexAddedCb, + pexElementCb, + &diffs); diffs6.added = tr_new(tr_pex, newCount6); diffs6.addedCount = 0; diffs6.dropped = tr_new(tr_pex, msgs->pexCount6); diffs6.droppedCount = 0; diffs6.elements = tr_new(tr_pex, newCount6 + msgs->pexCount6); diffs6.elementCount = 0; - tr_set_compare(msgs->pex6, msgs->pexCount6, newPex6, newCount6, tr_pexCompare, sizeof(tr_pex), pexDroppedCb, pexAddedCb, - pexElementCb, &diffs6); - dbgmsg(msgs, "pex: old peer count %d+%d, new peer count %d+%d, added %d+%d, removed %d+%d", msgs->pexCount, - msgs->pexCount6, newCount, newCount6, diffs.addedCount, diffs6.addedCount, diffs.droppedCount, diffs6.droppedCount); + tr_set_compare( + msgs->pex6, + msgs->pexCount6, + newPex6, + newCount6, + tr_pexCompare, + sizeof(tr_pex), + pexDroppedCb, + pexAddedCb, + pexElementCb, + &diffs6); + dbgmsg( + msgs, + "pex: old peer count %d+%d, new peer count %d+%d, added %d+%d, removed %d+%d", + msgs->pexCount, + msgs->pexCount6, + newCount, + newCount6, + diffs.addedCount, + diffs6.addedCount, + diffs.droppedCount, + diffs6.droppedCount); if (diffs.addedCount == 0 && diffs.droppedCount == 0 && diffs6.addedCount == 0 && diffs6.droppedCount == 0) { @@ -2559,7 +2605,10 @@ static void pexPulse(evutil_socket_t fd, short what, void* vmsgs) **** tr_peer virtual functions ***/ -static bool peermsgs_is_transferring_pieces(struct tr_peer const* peer, uint64_t now, tr_direction direction, +static bool peermsgs_is_transferring_pieces( + struct tr_peer const* peer, + uint64_t now, + tr_direction direction, unsigned int* setme_Bps) { unsigned int Bps = 0; @@ -2613,10 +2662,9 @@ static void peermsgs_destruct(tr_peer* peer) } } -static struct tr_peer_virtual_funcs const my_funcs = -{ +static struct tr_peer_virtual_funcs const my_funcs = { .destruct = peermsgs_destruct, - .is_transferring_pieces = peermsgs_is_transferring_pieces + .is_transferring_pieces = peermsgs_is_transferring_pieces, }; /*** diff --git a/libtransmission/peer-msgs.h b/libtransmission/peer-msgs.h index 934c00332..d0516e915 100644 --- a/libtransmission/peer-msgs.h +++ b/libtransmission/peer-msgs.h @@ -68,7 +68,11 @@ void tr_peerMsgsPulse(tr_peerMsgs* msgs); void tr_peerMsgsCancel(tr_peerMsgs* msgs, tr_block_index_t block); -size_t tr_generateAllowedSet(tr_piece_index_t* setmePieces, size_t desiredSetSize, size_t pieceCount, uint8_t const* infohash, +size_t tr_generateAllowedSet( + tr_piece_index_t* setmePieces, + size_t desiredSetSize, + size_t pieceCount, + uint8_t const* infohash, struct tr_address const* addr); /* @} */ diff --git a/libtransmission/platform-quota.c b/libtransmission/platform-quota.c index 1bc081220..9b6a7599f 100644 --- a/libtransmission/platform-quota.c +++ b/libtransmission/platform-quota.c @@ -326,8 +326,10 @@ static int64_t getquota(char const* device) int64_t spaceused; #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__) - if (quotactl(device, QCMD(Q_GETQUOTA, USRQUOTA), getuid(), (caddr_t)&dq) == 0) + if (quotactl(device, QCMD(Q_GETQUOTA, USRQUOTA), getuid(), (caddr_t)&dq) != 0) { + return -1; + } #elif defined(__sun) struct quotctl op; int fd = open(device, O_RDONLY); @@ -341,55 +343,54 @@ static int64_t getquota(char const* device) op.uid = getuid(); op.addr = (caddr_t)&dq; - if (ioctl(fd, Q_QUOTACTL, &op) == 0) + if (ioctl(fd, Q_QUOTACTL, &op) != 0) { close(fd); -#else - if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device, getuid(), (caddr_t)&dq) == 0) - { -#endif - if (dq.dqb_bsoftlimit > 0) - { - /* Use soft limit first */ - limit = dq.dqb_bsoftlimit; - } - else if (dq.dqb_bhardlimit > 0) - { - limit = dq.dqb_bhardlimit; - } - else - { - /* No quota enabled for this user */ - return -1; - } - -#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) - spaceused = (int64_t)dq.dqb_curblocks >> 1; -#elif defined(__APPLE__) - spaceused = (int64_t)dq.dqb_curbytes; -#elif defined(__UCLIBC__) && !TR_UCLIBC_CHECK_VERSION(1, 0, 18) - spaceused = (int64_t)btodb(dq.dqb_curblocks); -#elif defined(__sun) || (defined(_LINUX_QUOTA_VERSION) && _LINUX_QUOTA_VERSION < 2) - spaceused = (int64_t)dq.dqb_curblocks >> 1; -#else - spaceused = btodb(dq.dqb_curspace); -#endif - - freespace = limit - spaceused; - -#ifdef __APPLE__ - return freespace < 0 ? 0 : freespace; -#else - return freespace < 0 ? 0 : (freespace * 1024); -#endif + return -1; } -#if defined(__sun) close(fd); +#else + if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device, getuid(), (caddr_t)&dq) != 0) + { + return -1; + } #endif - /* something went wrong */ - return -1; + if (dq.dqb_bsoftlimit > 0) + { + /* Use soft limit first */ + limit = dq.dqb_bsoftlimit; + } + else if (dq.dqb_bhardlimit > 0) + { + limit = dq.dqb_bhardlimit; + } + else + { + /* No quota enabled for this user */ + return -1; + } + +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) + spaceused = (int64_t)dq.dqb_curblocks >> 1; +#elif defined(__APPLE__) + spaceused = (int64_t)dq.dqb_curbytes; +#elif defined(__UCLIBC__) && !TR_UCLIBC_CHECK_VERSION(1, 0, 18) + spaceused = (int64_t)btodb(dq.dqb_curblocks); +#elif defined(__sun) || (defined(_LINUX_QUOTA_VERSION) && _LINUX_QUOTA_VERSION < 2) + spaceused = (int64_t)dq.dqb_curblocks >> 1; +#else + spaceused = btodb(dq.dqb_curspace); +#endif + + freespace = limit - spaceused; + +#ifdef __APPLE__ + return freespace < 0 ? 0 : freespace; +#else + return freespace < 0 ? 0 : (freespace * 1024); +#endif } #endif diff --git a/libtransmission/platform.c b/libtransmission/platform.c index 288ba21de..3fea3db6e 100644 --- a/libtransmission/platform.c +++ b/libtransmission/platform.c @@ -73,7 +73,7 @@ static bool tr_areThreadsEqual(tr_thread_id a, tr_thread_id b) /** @brief portability wrapper around OS-dependent threads */ struct tr_thread { - void (* func)(void*); + void (*func)(void*); void* arg; tr_thread_id thread; @@ -113,7 +113,7 @@ static ThreadFuncReturnType ThreadFunc(void* _t) #endif } -tr_thread* tr_threadNew(void (* func)(void*), void* arg) +tr_thread* tr_threadNew(void (*func)(void*), void* arg) { tr_thread* t = tr_new0(tr_thread, 1); @@ -529,11 +529,10 @@ char const* tr_getWebClientDir(tr_session const* session) /* Generally, Web interface should be stored in a Web subdir of * calling executable dir. */ - static REFKNOWNFOLDERID known_folder_ids[] = - { + static REFKNOWNFOLDERID known_folder_ids[] = { &FOLDERID_LocalAppData, &FOLDERID_RoamingAppData, - &FOLDERID_ProgramData + &FOLDERID_ProgramData, }; for (size_t i = 0; s == NULL && i < TR_N_ELEMENTS(known_folder_ids); ++i) diff --git a/libtransmission/platform.h b/libtransmission/platform.h index 4cffc5e52..51d27654e 100644 --- a/libtransmission/platform.h +++ b/libtransmission/platform.h @@ -50,7 +50,7 @@ char* tr_getSessionIdDir(void); typedef struct tr_thread tr_thread; /** @brief Instantiate a new process thread */ -tr_thread* tr_threadNew(void (* func)(void*), void* arg); +tr_thread* tr_threadNew(void (*func)(void*), void* arg); /** @brief Return nonzero if this function is being called from `thread' @param thread the thread being tested */ diff --git a/libtransmission/port-forwarding.c b/libtransmission/port-forwarding.c index f6e60dd63..6e1146117 100644 --- a/libtransmission/port-forwarding.c +++ b/libtransmission/port-forwarding.c @@ -103,7 +103,10 @@ static void natPulse(tr_shared* s, bool do_check) if (newStatus != oldStatus) { - tr_logAddNamedInfo(getKey(), _("State changed from \"%1$s\" to \"%2$s\""), getNatStateStr(oldStatus), + tr_logAddNamedInfo( + getKey(), + _("State changed from \"%1$s\" to \"%2$s\""), + getNatStateStr(oldStatus), getNatStateStr(newStatus)); } } diff --git a/libtransmission/ptrarray.h b/libtransmission/ptrarray.h index bfbc42cd4..1d25e111d 100644 --- a/libtransmission/ptrarray.h +++ b/libtransmission/ptrarray.h @@ -28,14 +28,16 @@ typedef struct tr_ptrArray void** items; int n_items; int n_alloc; -} -tr_ptrArray; +} tr_ptrArray; typedef tr_voidptr_compare_func PtrArrayCompareFunc; -typedef void (* PtrArrayForeachFunc)(void*); +typedef void (*PtrArrayForeachFunc)(void*); -#define TR_PTR_ARRAY_INIT_STATIC { NULL, 0, 0 } +#define TR_PTR_ARRAY_INIT_STATIC \ + { \ + NULL, 0, 0, \ + } extern tr_ptrArray const TR_PTR_ARRAY_INIT; diff --git a/libtransmission/quark.c b/libtransmission/quark.c index a1cfd9b5c..58f0d9ceb 100644 --- a/libtransmission/quark.c +++ b/libtransmission/quark.c @@ -21,10 +21,12 @@ struct tr_key_struct size_t len; }; -#define Q(name) { "" name "", sizeof("" name "") - 1 } +#define Q(name) \ + { \ + "" name "", sizeof("" name "") - 1, \ + } -static struct tr_key_struct const my_static[] = -{ +static struct tr_key_struct const my_static[] = { Q(""), Q("activeTorrentCount"), Q("activity-date"), @@ -412,7 +414,7 @@ static struct tr_key_struct const my_static[] = Q("watch-dir"), Q("watch-dir-enabled"), Q("webseeds"), - Q("webseedsSendingToUs") + Q("webseedsSendingToUs"), }; #undef Q diff --git a/libtransmission/resume.c b/libtransmission/resume.c index bbc0fe698..cd9bb3d7d 100644 --- a/libtransmission/resume.c +++ b/libtransmission/resume.c @@ -207,8 +207,13 @@ static uint64_t loadDND(tr_variant* dict, tr_torrent* tor) } else { - tr_logAddTorDbg(tor, "Couldn't load DND flags. DND list (%p) has %zu" " children; torrent has %d files", (void*)list, - tr_variantListSize(list), (int)n); + tr_logAddTorDbg( + tor, + "Couldn't load DND flags. DND list (%p) has %zu" + " children; torrent has %d files", + (void*)list, + tr_variantListSize(list), + (int)n); } return ret; @@ -930,8 +935,8 @@ static uint64_t loadFromFile(tr_torrent* tor, uint64_t fieldsToLoad, bool* didRe fieldsLoaded |= TR_FR_TIME_DOWNLOADING; } - if ((fieldsToLoad & TR_FR_BANDWIDTH_PRIORITY) != 0 && - tr_variantDictFindInt(&top, TR_KEY_bandwidth_priority, &i) && tr_isPriority(i)) + if ((fieldsToLoad & TR_FR_BANDWIDTH_PRIORITY) != 0 && tr_variantDictFindInt(&top, TR_KEY_bandwidth_priority, &i) && + tr_isPriority(i)) { tr_torrentSetPriority(tor, i); fieldsLoaded |= TR_FR_BANDWIDTH_PRIORITY; diff --git a/libtransmission/rpc-server.c b/libtransmission/rpc-server.c index b8b3a6a41..45bb989a2 100644 --- a/libtransmission/rpc-server.c +++ b/libtransmission/rpc-server.c @@ -272,9 +272,7 @@ static char const* mimetype_guess(char const* path) { char const* suffix; char const* mime_type; - } - const types[] = - { + } const types[] = { /* these are the ones we need for serving the web client's files... */ { "css", "text/css" }, { "gif", "image/gif" }, @@ -282,7 +280,7 @@ static char const* mimetype_guess(char const* path) { "ico", "image/vnd.microsoft.icon" }, { "js", "application/javascript" }, { "png", "image/png" }, - { "svg", "image/svg+xml" } + { "svg", "image/svg+xml" }, }; char const* dot = strrchr(path, '.'); @@ -297,7 +295,10 @@ static char const* mimetype_guess(char const* path) return "application/octet-stream"; } -static void add_response(struct evhttp_request* req, struct tr_rpc_server* server, struct evbuffer* out, +static void add_response( + struct evhttp_request* req, + struct tr_rpc_server* server, + struct evbuffer* out, struct evbuffer* content) { char const* key = "Accept-Encoding"; @@ -439,7 +440,9 @@ static void handle_web_client(struct evhttp_request* req, struct tr_rpc_server* if (tr_str_is_empty(webClientDir)) { - send_simple_response(req, HTTP_NOTFOUND, + send_simple_response( + req, + HTTP_NOTFOUND, "

Couldn't find Transmission's web interface files!

" "

Users: to tell Transmission where to look, " "set the TRANSMISSION_WEB_HOME environment " @@ -467,7 +470,10 @@ static void handle_web_client(struct evhttp_request* req, struct tr_rpc_server* } else { - char* filename = tr_strdup_printf("%s%s%s", webClientDir, TR_PATH_DELIMITER_STR, + char* filename = tr_strdup_printf( + "%s%s%s", + webClientDir, + TR_PATH_DELIMITER_STR, tr_str_is_empty(subpath) ? "index.html" : subpath); serve_file(req, server, filename); tr_free(filename); @@ -522,7 +528,10 @@ static void handle_rpc(struct evhttp_request* req, struct tr_rpc_server* server) { if (req->type == EVHTTP_REQ_POST) { - handle_rpc_from_json(req, server, (char const*)evbuffer_pullup(req->input_buffer, -1), + handle_rpc_from_json( + req, + server, + (char const*)evbuffer_pullup(req->input_buffer, -1), evbuffer_get_length(req->input_buffer)); return; } @@ -651,7 +660,9 @@ static void handle_request(struct evhttp_request* req, void* arg) if (!isAddressAllowed(server, req->remote_host)) { - send_simple_response(req, 403, + send_simple_response( + req, + 403, "

Unauthorized IP Address.

" "

Either disable the IP address whitelist or add your address to it.

" "

If you're editing settings.json, see the 'rpc-whitelist' and 'rpc-whitelist-enabled' entries.

" @@ -679,8 +690,8 @@ static void handle_request(struct evhttp_request* req, void* arg) } } - if (server->isPasswordEnabled && (pass == NULL || user == NULL || strcmp(server->username, user) != 0 || - !tr_ssha1_matches(server->password, pass))) + if (server->isPasswordEnabled && + (pass == NULL || user == NULL || strcmp(server->username, user) != 0 || !tr_ssha1_matches(server->password, pass))) { evhttp_add_header(req->output_headers, "WWW-Authenticate", "Basic realm=\"" MY_REALM "\""); if (server->isAntiBruteForceEnabled) @@ -688,7 +699,8 @@ static void handle_request(struct evhttp_request* req, void* arg) server->loginattempts++; } - char* unauthuser = tr_strdup_printf("

Unauthorized User. %d unsuccessful login attempts.

", + char* unauthuser = tr_strdup_printf( + "

Unauthorized User. %d unsuccessful login attempts.

", server->loginattempts); send_simple_response(req, 401, unauthuser); tr_free(unauthuser); @@ -746,7 +758,8 @@ static void handle_request(struct evhttp_request* req, void* arg) "CSRF " "attacks.

" "

%s: %s

", - TR_RPC_SESSION_ID_HEADER, sessionId); + TR_RPC_SESSION_ID_HEADER, + sessionId); evhttp_add_header(req->output_headers, TR_RPC_SESSION_ID_HEADER, sessionId); send_simple_response(req, 409, tmp); tr_free(tmp); @@ -839,7 +852,11 @@ static void startServer(void* vserver) return; } - tr_logAddNamedError(MY_NAME, "Unable to bind to %s:%d after %d attempts, giving up", address, port, + tr_logAddNamedError( + MY_NAME, + "Unable to bind to %s:%d after %d attempts, giving up", + address, + port, SERVER_START_RETRY_COUNT); } else @@ -964,8 +981,10 @@ static void tr_rpcSetList(char const* whitelistStr, tr_list** list) if (strcspn(token, "+-") < len) { - tr_logAddNamedInfo(MY_NAME, - "Adding address to whitelist: %s (And it has a '+' or '-'! Are you using an old ACL by mistake?)", token); + tr_logAddNamedInfo( + MY_NAME, + "Adding address to whitelist: %s (And it has a '+' or '-'! Are you using an old ACL by mistake?)", + token); } else { @@ -1302,7 +1321,11 @@ tr_rpc_server* tr_rpcInit(tr_session* session, tr_variant* settings) if (s->isEnabled) { - tr_logAddNamedInfo(MY_NAME, _("Serving RPC and Web requests on %s:%d%s"), tr_rpcGetBindAddress(s), (int)s->port, + tr_logAddNamedInfo( + MY_NAME, + _("Serving RPC and Web requests on %s:%d%s"), + tr_rpcGetBindAddress(s), + (int)s->port, s->url); tr_runInEventThread(session, startServer, s); diff --git a/libtransmission/rpcimpl.c b/libtransmission/rpcimpl.c index 2772d32b7..553312862 100644 --- a/libtransmission/rpcimpl.c +++ b/libtransmission/rpcimpl.c @@ -53,8 +53,7 @@ typedef enum { TR_FORMAT_OBJECT = 0, TR_FORMAT_TABLE -} -tr_format; +} tr_format; /*** **** @@ -204,7 +203,10 @@ static void notifyBatchQueueChange(tr_session* session, tr_torrent** torrents, i notify(session, TR_RPC_SESSION_QUEUE_POSITIONS_CHANGED, NULL); } -static char const* queueMoveTop(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* queueMoveTop( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -218,7 +220,10 @@ static char const* queueMoveTop(tr_session* session, tr_variant* args_in, tr_var return NULL; } -static char const* queueMoveUp(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* queueMoveUp( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -232,7 +237,10 @@ static char const* queueMoveUp(tr_session* session, tr_variant* args_in, tr_vari return NULL; } -static char const* queueMoveDown(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* queueMoveDown( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -246,7 +254,10 @@ static char const* queueMoveDown(tr_session* session, tr_variant* args_in, tr_va return NULL; } -static char const* queueMoveBottom(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* queueMoveBottom( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -268,7 +279,10 @@ static int compareTorrentByQueuePosition(void const* va, void const* vb) return a->queuePosition - b->queuePosition; } -static char const* torrentStart(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentStart( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -296,7 +310,10 @@ static char const* torrentStart(tr_session* session, tr_variant* args_in, tr_var return NULL; } -static char const* torrentStartNow(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentStartNow( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -324,7 +341,10 @@ static char const* torrentStartNow(tr_session* session, tr_variant* args_in, tr_ return NULL; } -static char const* torrentStop(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentStop( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -350,7 +370,10 @@ static char const* torrentStop(tr_session* session, tr_variant* args_in, tr_vari return NULL; } -static char const* torrentRemove(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentRemove( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -385,7 +408,10 @@ static char const* torrentRemove(tr_session* session, tr_variant* args_in, tr_va return NULL; } -static char const* torrentReannounce(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentReannounce( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -411,7 +437,10 @@ static char const* torrentReannounce(tr_session* session, tr_variant* args_in, t return NULL; } -static char const* torrentVerify(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentVerify( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -572,7 +601,11 @@ static void addPeers(tr_torrent* tor, tr_variant* list) tr_torrentPeersFree(peers, peerCount); } -static void initField(tr_torrent* const tor, tr_info const* const inf, tr_stat const* const st, tr_variant* const initme, +static void initField( + tr_torrent* const tor, + tr_info const* const inf, + tr_stat const* const st, + tr_variant* const initme, tr_quark key) { char* str; @@ -936,16 +969,17 @@ static void addTorrentInfo(tr_torrent* tor, tr_format format, tr_variant* entry, for (size_t i = 0; i < fieldCount; ++i) { - tr_variant* child = format == TR_FORMAT_TABLE ? - tr_variantListAdd(entry) : - tr_variantDictAdd(entry, fields[i]); + tr_variant* child = format == TR_FORMAT_TABLE ? tr_variantListAdd(entry) : tr_variantDictAdd(entry, fields[i]); initField(tor, inf, st, child, fields[i]); } } } -static char const* torrentGet(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentGet( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(idle_data); @@ -982,8 +1016,7 @@ static char const* torrentGet(tr_session* session, tr_variant* args_in, tr_varia int64_t date; int64_t id; - if (tr_variantDictFindInt(d, TR_KEY_date, &date) && - date >= now - interval && + if (tr_variantDictFindInt(d, TR_KEY_date, &date) && date >= now - interval && tr_variantDictFindInt(d, TR_KEY_id, &id)) { tr_variantListAddInt(removed_out, id); @@ -1297,8 +1330,8 @@ static char const* replaceTrackers(tr_torrent* tor, tr_variant* urls) char const* newval; if (tr_variantGetInt(tr_variantListChild(urls, i), &pos) && - tr_variantGetStr(tr_variantListChild(urls, i + 1), &newval, &len) && - tr_urlIsValidTracker(newval) && pos < n && pos >= 0) + tr_variantGetStr(tr_variantListChild(urls, i + 1), &newval, &len) && tr_urlIsValidTracker(newval) && pos < n && + pos >= 0) { tr_free(trackers[pos].announce); trackers[pos].announce = tr_strndup(newval, len); @@ -1379,7 +1412,10 @@ static char const* removeTrackers(tr_torrent* tor, tr_variant* ids) return errmsg; } -static char const* torrentSet(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentSet( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -1519,7 +1555,10 @@ static char const* torrentSet(tr_session* session, tr_variant* args_in, tr_varia return errmsg; } -static char const* torrentSetLocation(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentSetLocation( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -1585,7 +1624,10 @@ static void torrentRenamePathDone(tr_torrent* tor, char const* oldpath, char con tr_idle_function_done(data, result); } -static char const* torrentRenamePath(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentRenamePath( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -1617,8 +1659,14 @@ static char const* torrentRenamePath(tr_session* session, tr_variant* args_in, t **** ***/ -static void portTested(tr_session* session, bool did_connect, bool did_timeout, long response_code, void const* response, - size_t response_byte_count, void* user_data) +static void portTested( + tr_session* session, + bool did_connect, + bool did_timeout, + long response_code, + void const* response, + size_t response_byte_count, + void* user_data) { TR_UNUSED(session); TR_UNUSED(did_connect); @@ -1629,7 +1677,11 @@ static void portTested(tr_session* session, bool did_connect, bool did_timeout, if (response_code != 200) { - tr_snprintf(result, sizeof(result), "portTested: http error %ld: %s", response_code, + tr_snprintf( + result, + sizeof(result), + "portTested: http error %ld: %s", + response_code, tr_webGetResponseStr(response_code)); } else /* success */ @@ -1658,8 +1710,14 @@ static char const* portTest(tr_session* session, tr_variant* args_in, tr_variant **** ***/ -static void gotNewBlocklist(tr_session* session, bool did_connect, bool did_timeout, long response_code, void const* response, - size_t response_byte_count, void* user_data) +static void gotNewBlocklist( + tr_session* session, + bool did_connect, + bool did_timeout, + long response_code, + void const* response, + size_t response_byte_count, + void* user_data) { TR_UNUSED(did_connect); TR_UNUSED(did_timeout); @@ -1671,7 +1729,11 @@ static void gotNewBlocklist(tr_session* session, bool did_connect, bool did_time if (response_code != 200) { - tr_snprintf(result, sizeof(result), "gotNewBlocklist: http error %ld: %s", response_code, + tr_snprintf( + result, + sizeof(result), + "gotNewBlocklist: http error %ld: %s", + response_code, tr_webGetResponseStr(response_code)); } else /* successfully fetched the blocklist... */ @@ -1709,8 +1771,7 @@ static void gotNewBlocklist(tr_session* session, bool did_connect, bool did_time stream.avail_out = buflen; err = inflate(&stream, Z_NO_FLUSH); - if ((stream.avail_out < buflen) && - (!tr_sys_file_write(fd, buf, buflen - stream.avail_out, NULL, &error))) + if ((stream.avail_out < buflen) && (!tr_sys_file_write(fd, buf, buflen - stream.avail_out, NULL, &error))) { tr_snprintf(result, sizeof(result), _("Couldn't save file \"%1$s\": %2$s"), filename, error->message); tr_error_clear(&error); @@ -1759,7 +1820,10 @@ static void gotNewBlocklist(tr_session* session, bool did_connect, bool did_time tr_idle_function_done(data, result); } -static char const* blocklistUpdate(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* blocklistUpdate( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_in); @@ -1805,11 +1869,10 @@ static void addTorrentImpl(struct tr_rpc_idle_data* data, tr_ctor* ctor) if (tor != NULL && key != 0) { - tr_quark const fields[] = - { + tr_quark const fields[] = { TR_KEY_id, TR_KEY_name, - TR_KEY_hashString + TR_KEY_hashString, }; addTorrentInfo(tor, TR_FORMAT_OBJECT, tr_variantDictAdd(data->args_out, key), fields, TR_N_ELEMENTS(fields)); @@ -1831,8 +1894,14 @@ struct add_torrent_idle_data tr_ctor* ctor; }; -static void gotMetadataFromURL(tr_session* session, bool did_connect, bool did_timeout, long response_code, - void const* response, size_t response_byte_count, void* user_data) +static void gotMetadataFromURL( + tr_session* session, + bool did_connect, + bool did_timeout, + long response_code, + void const* response, + size_t response_byte_count, + void* user_data) { TR_UNUSED(session); TR_UNUSED(did_connect); @@ -1840,8 +1909,11 @@ static void gotMetadataFromURL(tr_session* session, bool did_connect, bool did_t struct add_torrent_idle_data* data = user_data; - dbgmsg("torrentAdd: HTTP response code was %ld (%s); response length was %zu bytes", response_code, - tr_webGetResponseStr(response_code), response_byte_count); + dbgmsg( + "torrentAdd: HTTP response code was %ld (%s); response length was %zu bytes", + response_code, + tr_webGetResponseStr(response_code), + response_byte_count); if (response_code == 200 || response_code == 221) /* http or ftp success.. */ { @@ -1851,7 +1923,11 @@ static void gotMetadataFromURL(tr_session* session, bool did_connect, bool did_t else { char result[1024]; - tr_snprintf(result, sizeof(result), "gotMetadataFromURL: http error %ld: %s", response_code, + tr_snprintf( + result, + sizeof(result), + "gotMetadataFromURL: http error %ld: %s", + response_code, tr_webGetResponseStr(response_code)); tr_idle_function_done(data->data, result); } @@ -1889,7 +1965,10 @@ static tr_file_index_t* fileListFromList(tr_variant* list, tr_file_index_t* setm return files; } -static char const* torrentAdd(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* torrentAdd( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -1909,8 +1988,7 @@ static char const* torrentAdd(tr_session* session, tr_variant* args_in, tr_varia char const* download_dir = NULL; - if (tr_variantDictFindStr(args_in, TR_KEY_download_dir, &download_dir, NULL) && - tr_sys_path_is_relative(download_dir)) + if (tr_variantDictFindStr(args_in, TR_KEY_download_dir, &download_dir, NULL) && tr_sys_path_is_relative(download_dir)) { return "download directory path is not absolute"; } @@ -2026,7 +2104,10 @@ static char const* torrentAdd(tr_session* session, tr_variant* args_in, tr_varia **** ***/ -static char const* sessionSet(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* sessionSet( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_out); @@ -2037,14 +2118,12 @@ static char const* sessionSet(tr_session* session, tr_variant* args_in, tr_varia char const* download_dir = NULL; char const* incomplete_dir = NULL; - if (tr_variantDictFindStr(args_in, TR_KEY_download_dir, &download_dir, NULL) && - tr_sys_path_is_relative(download_dir)) + if (tr_variantDictFindStr(args_in, TR_KEY_download_dir, &download_dir, NULL) && tr_sys_path_is_relative(download_dir)) { return "download directory path is not absolute"; } - if (tr_variantDictFindStr(args_in, TR_KEY_incomplete_dir, &incomplete_dir, NULL) && - tr_sys_path_is_relative(incomplete_dir)) + if (tr_variantDictFindStr(args_in, TR_KEY_incomplete_dir, &incomplete_dir, NULL) && tr_sys_path_is_relative(incomplete_dir)) { return "incomplete torrents directory path is not absolute"; } @@ -2290,7 +2369,10 @@ static char const* sessionSet(tr_session* session, tr_variant* args_in, tr_varia return NULL; } -static char const* sessionStats(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* sessionStats( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_in); @@ -2661,7 +2743,10 @@ static char const* freeSpace(tr_session* session, tr_variant* args_in, tr_varian **** ***/ -static char const* sessionClose(tr_session* session, tr_variant* args_in, tr_variant* args_out, +static char const* sessionClose( + tr_session* session, + tr_variant* args_in, + tr_variant* args_out, struct tr_rpc_idle_data* idle_data) { TR_UNUSED(args_in); @@ -2676,16 +2761,14 @@ static char const* sessionClose(tr_session* session, tr_variant* args_in, tr_var **** ***/ -typedef char const* (* handler)(tr_session*, tr_variant*, tr_variant*, struct tr_rpc_idle_data*); +typedef char const* (*handler)(tr_session*, tr_variant*, tr_variant*, struct tr_rpc_idle_data*); static struct method { char const* name; bool immediate; handler func; -} -methods[] = -{ +} methods[] = { { "port-test", false, portTest }, { "blocklist-update", false, blocklistUpdate }, { "free-space", true, freeSpace }, @@ -2707,7 +2790,7 @@ methods[] = { "queue-move-top", true, queueMoveTop }, { "queue-move-up", true, queueMoveUp }, { "queue-move-down", true, queueMoveDown }, - { "queue-move-bottom", true, queueMoveBottom } + { "queue-move-bottom", true, queueMoveBottom }, }; static void noop_response_callback(tr_session* session, tr_variant* response, void* user_data) @@ -2717,7 +2800,10 @@ static void noop_response_callback(tr_session* session, tr_variant* response, vo TR_UNUSED(user_data); } -void tr_rpc_request_exec_json(tr_session* session, tr_variant const* request, tr_rpc_response_func callback, +void tr_rpc_request_exec_json( + tr_session* session, + tr_variant const* request, + tr_rpc_response_func callback, void* callback_user_data) { char const* str; @@ -2858,8 +2944,12 @@ void tr_rpc_parse_list_str(tr_variant* setme, char const* str, size_t len) tr_free(values); } -void tr_rpc_request_exec_uri(tr_session* session, void const* request_uri, size_t request_uri_len, - tr_rpc_response_func callback, void* callback_user_data) +void tr_rpc_request_exec_uri( + tr_session* session, + void const* request_uri, + size_t request_uri_len, + tr_rpc_response_func callback, + void* callback_user_data) { char const* pch; tr_variant top; @@ -2887,7 +2977,9 @@ void tr_rpc_request_exec_uri(tr_session* session, void const* request_uri, size_ bool isArg = strcmp(key, "method") != 0 && strcmp(key, "tag") != 0; tr_variant* parent = isArg ? args : ⊤ - tr_rpc_parse_list_str(tr_variantDictAdd(parent, tr_quark_new(key, (size_t)(delim - pch))), delim + 1, + tr_rpc_parse_list_str( + tr_variantDictAdd(parent, tr_quark_new(key, (size_t)(delim - pch))), + delim + 1, next != NULL ? (size_t)(next - (delim + 1)) : strlen(delim + 1)); tr_free(key); } diff --git a/libtransmission/rpcimpl.h b/libtransmission/rpcimpl.h index 4368c8911..514c0f700 100644 --- a/libtransmission/rpcimpl.h +++ b/libtransmission/rpcimpl.h @@ -18,15 +18,22 @@ TR_BEGIN_DECLS **** RPC processing ***/ -typedef void (* tr_rpc_response_func)(tr_session* session, tr_variant* response, void* user_data); +typedef void (*tr_rpc_response_func)(tr_session* session, tr_variant* response, void* user_data); /* http://www.json.org/ */ -void tr_rpc_request_exec_json(tr_session* session, tr_variant const* request, tr_rpc_response_func callback, +void tr_rpc_request_exec_json( + tr_session* session, + tr_variant const* request, + tr_rpc_response_func callback, void* callback_user_data); /* see the RPC spec's "Request URI Notation" section */ -void tr_rpc_request_exec_uri(tr_session* session, void const* request_uri, size_t request_uri_len, - tr_rpc_response_func callback, void* callback_user_data); +void tr_rpc_request_exec_uri( + tr_session* session, + void const* request_uri, + size_t request_uri_len, + tr_rpc_response_func callback, + void* callback_user_data); void tr_rpc_parse_list_str(tr_variant* setme, char const* list_str, size_t list_str_len); diff --git a/libtransmission/session.c b/libtransmission/session.c index c07dfac52..b9739a59e 100644 --- a/libtransmission/session.c +++ b/libtransmission/session.c @@ -180,7 +180,12 @@ static void accept_incoming_peer(evutil_socket_t fd, short what, void* vsession) { char addrstr[TR_ADDRSTRLEN]; tr_address_and_port_to_string(addrstr, sizeof(addrstr), &clientAddr, clientPort); - tr_logAddDeep(__FILE__, __LINE__, NULL, "new incoming connection %" PRIdMAX " (%s)", (intmax_t)clientSocket, + tr_logAddDeep( + __FILE__, + __LINE__, + NULL, + "new incoming connection %" PRIdMAX " (%s)", + (intmax_t)clientSocket, addrstr); } @@ -986,8 +991,7 @@ static void sessionSetImpl(void* vdata) free_incoming_peer_port(session); - if (!tr_variantDictFindStr(settings, TR_KEY_bind_address_ipv4, &str, NULL) || - !tr_address_from_string(&b.addr, str) || + if (!tr_variantDictFindStr(settings, TR_KEY_bind_address_ipv4, &str, NULL) || !tr_address_from_string(&b.addr, str) || b.addr.type != TR_AF_INET) { b.addr = tr_inaddr_any; @@ -996,8 +1000,7 @@ static void sessionSetImpl(void* vdata) b.socket = TR_BAD_SOCKET; session->bind_ipv4 = tr_memdup(&b, sizeof(struct tr_bindinfo)); - if (!tr_variantDictFindStr(settings, TR_KEY_bind_address_ipv6, &str, NULL) || - !tr_address_from_string(&b.addr, str) || + if (!tr_variantDictFindStr(settings, TR_KEY_bind_address_ipv6, &str, NULL) || !tr_address_from_string(&b.addr, str) || b.addr.type != TR_AF_INET6) { b.addr = tr_in6addr_any; @@ -2064,7 +2067,10 @@ void tr_sessionClose(tr_session* session) time_t const deadline = time(NULL) + SHUTDOWN_MAX_SECONDS; - dbgmsg("shutting down transmission session %p... now is %zu, deadline is %zu", (void*)session, (size_t)time(NULL), + dbgmsg( + "shutting down transmission session %p... now is %zu, deadline is %zu", + (void*)session, + (size_t)time(NULL), (size_t)deadline); /* close the session */ @@ -2081,10 +2087,14 @@ void tr_sessionClose(tr_session* session) * for a bit while they tell the router & tracker * that we're closing now */ while ((session->shared != NULL || session->web != NULL || session->announcer != NULL || session->announcer_udp != NULL) && - !deadlineReached(deadline)) + !deadlineReached(deadline)) { - dbgmsg("waiting on port unmap (%p) or announcer (%p)... now %zu deadline %zu", (void*)session->shared, - (void*)session->announcer, (size_t)time(NULL), (size_t)deadline); + dbgmsg( + "waiting on port unmap (%p) or announcer (%p)... now %zu deadline %zu", + (void*)session->shared, + (void*)session->announcer, + (size_t)time(NULL), + (size_t)deadline); tr_wait_msec(50); } @@ -2161,7 +2171,8 @@ static void sessionLoadTorrents(void* vdata) tr_sys_path_info info; char const* dirname = tr_getTorrentDir(data->session); tr_sys_dir_t odir = (tr_sys_path_get_info(dirname, 0, &info, NULL) && info.type == TR_SYS_PATH_IS_DIRECTORY) ? - tr_sys_dir_open(dirname, NULL) : TR_BAD_SYS_DIR; + tr_sys_dir_open(dirname, NULL) : + TR_BAD_SYS_DIR; if (odir != TR_BAD_SYS_DIR) { @@ -2486,7 +2497,8 @@ static void loadBlocklists(tr_session* session) tr_blocklistFileFree(b); } - else if (tr_sys_path_get_info(path, 0, &path_info, NULL) && + else if ( + tr_sys_path_get_info(path, 0, &path_info, NULL) && path_info.last_modified_at >= binname_info.last_modified_at) /* update it */ { char* old; @@ -2673,7 +2685,8 @@ static void metainfoLookupInit(tr_session* session) tr_sys_path_info info; char const* dirname = tr_getTorrentDir(session); tr_sys_dir_t odir = (tr_sys_path_get_info(dirname, 0, &info, NULL) && info.type == TR_SYS_PATH_IS_DIRECTORY) ? - tr_sys_dir_open(dirname, NULL) : TR_BAD_SYS_DIR; + tr_sys_dir_open(dirname, NULL) : + TR_BAD_SYS_DIR; if (odir != TR_BAD_SYS_DIR) { @@ -3056,7 +3069,11 @@ void tr_sessionGetNextQueuedTorrents(tr_session* session, tr_direction direction } else if (num_wanted < num_candidates) { - tr_quickfindFirstK(candidates, num_candidates, sizeof(struct TorrentAndPosition), compareTorrentAndPositions, + tr_quickfindFirstK( + candidates, + num_candidates, + sizeof(struct TorrentAndPosition), + compareTorrentAndPositions, num_wanted); } diff --git a/libtransmission/session.h b/libtransmission/session.h index 32c8e6a9a..97636454d 100644 --- a/libtransmission/session.h +++ b/libtransmission/session.h @@ -28,16 +28,14 @@ typedef enum TR_NET_OK, TR_NET_ERROR, TR_NET_WAIT -} -tr_tristate_t; +} tr_tristate_t; typedef enum { TR_AUTO_SWITCH_UNUSED, TR_AUTO_SWITCH_ON, TR_AUTO_SWITCH_OFF, -} -tr_auto_switch_state_t; +} tr_auto_switch_state_t; enum { diff --git a/libtransmission/stats.c b/libtransmission/stats.c index 1e11ab17a..d0c720247 100644 --- a/libtransmission/stats.c +++ b/libtransmission/stats.c @@ -18,14 +18,13 @@ **** ***/ -struct tr_session_stats const TR_SESSION_STATS_INIT = -{ +struct tr_session_stats const TR_SESSION_STATS_INIT = { .ratio = 0.0F, .uploadedBytes = 0, .downloadedBytes = 0, .filesAdded = 0, .sessionCount = 0, - .secondsActive = 0 + .secondsActive = 0, }; /** @brief Opaque, per-session data structure for bandwidth use statistics */ diff --git a/libtransmission/subprocess-posix.c b/libtransmission/subprocess-posix.c index da41fc33f..7b8797bfb 100644 --- a/libtransmission/subprocess-posix.c +++ b/libtransmission/subprocess-posix.c @@ -32,8 +32,7 @@ static void handle_sigchld(int i) { /* FIXME: Only check for our own PIDs */ rc = waitpid(-1, NULL, WNOHANG); - } - while (rc > 0 || (rc == -1 && errno == EINTR)); + } while (rc > 0 || (rc == -1 && errno == EINTR)); /* FIXME: Call old handler, if any */ } @@ -95,8 +94,7 @@ static bool tr_spawn_async_in_parent(int pipe_fd, tr_error** error) do { count = read(pipe_fd, &child_errno, sizeof(child_errno)); - } - while (count == -1 && errno == EINTR); + } while (count == -1 && errno == EINTR); close(pipe_fd); diff --git a/libtransmission/subprocess-win32.c b/libtransmission/subprocess-win32.c index 709268bf0..15b32a08b 100644 --- a/libtransmission/subprocess-win32.c +++ b/libtransmission/subprocess-win32.c @@ -305,7 +305,10 @@ static void append_argument(char** arguments, char const* argument) static bool contains_batch_metachars(char const* text) { /* First part - chars explicitly documented by `cmd.exe /?` as "special" */ - return strpbrk(text, "&<>()@^|" "%!^\"") != NULL; + return strpbrk( + text, + "&<>()@^|" + "%!^\"") != NULL; } static enum tr_app_type get_app_type(char const* app) @@ -392,17 +395,25 @@ bool tr_spawn_async(char* const* cmd, char* const* env, char const* work_dir, tr wchar_t* current_dir = work_dir != NULL ? tr_win32_utf8_to_native(work_dir, -1) : NULL; - STARTUPINFOW si = - { + STARTUPINFOW si = { .cb = sizeof(si), .dwFlags = STARTF_USESHOWWINDOW, - .wShowWindow = SW_HIDE + .wShowWindow = SW_HIDE, }; PROCESS_INFORMATION pi; - bool const ret = CreateProcessW(NULL, cmd_line, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | - CREATE_NO_WINDOW | CREATE_DEFAULT_ERROR_MODE, env_block, current_dir, &si, &pi); + bool const ret = CreateProcessW( + NULL, + cmd_line, + NULL, + NULL, + FALSE, + NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW | CREATE_DEFAULT_ERROR_MODE, + env_block, + current_dir, + &si, + &pi); if (ret) { diff --git a/libtransmission/torrent.c b/libtransmission/torrent.c index 4252423f0..f10475bdd 100644 --- a/libtransmission/torrent.c +++ b/libtransmission/torrent.c @@ -154,8 +154,7 @@ bool tr_torrentIsPieceTransferAllowed(tr_torrent const* tor, tr_direction direct bool allowed = true; - if (tr_torrentUsesSpeedLimit(tor, direction) && - tr_torrentGetSpeedLimit_Bps(tor, direction) <= 0) + if (tr_torrentUsesSpeedLimit(tor, direction) && tr_torrentGetSpeedLimit_Bps(tor, direction) <= 0) { allowed = false; } @@ -200,8 +199,7 @@ static int peerIdTTL(tr_torrent const* tor) unsigned char const* tr_torrentGetPeerId(tr_torrent* tor) { - bool const needs_new_peer_id = - (*tor->peer_id == '\0') || // doesn't have one + bool const needs_new_peer_id = (*tor->peer_id == '\0') || // doesn't have one (!tr_torrentIsPrivate(tor) && (peerIdTTL(tor) <= 0)); // has one but it's expired if (needs_new_peer_id) @@ -874,8 +872,11 @@ static bool setLocalErrorIfFilesDisappeared(tr_torrent* tor) if (disappeared) { tr_deeplog_tor(tor, "%s", "[LAZY] uh oh, the files disappeared"); - tr_torrentSetLocalError(tor, "%s", _("No data found! Ensure your drives are connected or use \"Set Location\". " - "To re-download, remove the torrent and re-add it.")); + tr_torrentSetLocalError( + tor, + "%s", + _("No data found! Ensure your drives are connected or use \"Set Location\". " + "To re-download, remove the torrent and re-add it.")); } return disappeared; @@ -1030,7 +1031,11 @@ static void torrentInit(tr_torrent* tor, tr_ctor const* ctor) tr_sessionUnlock(session); } -static tr_parse_result torrentParseImpl(tr_ctor const* ctor, tr_info* setmeInfo, bool* setmeHasInfo, size_t* dictLength, +static tr_parse_result torrentParseImpl( + tr_ctor const* ctor, + tr_info* setmeInfo, + bool* setmeHasInfo, + size_t* dictLength, int* setme_duplicate_id) { bool doFree; @@ -2197,16 +2202,14 @@ static void torrentCallScript(tr_torrent const* tor, char const* script) char* const torrent_dir = tr_sys_path_native_separators(tr_strdup(tor->currentDir)); - char* const cmd[] = - { + char* const cmd[] = { tr_strdup(script), - NULL + NULL, }; char* labels = tr_strjoin((char const* const*)tr_ptrArrayBase(&tor->labels), tr_ptrArraySize(&tor->labels), ","); - char* const env[] = - { + char* const env[] = { tr_strdup_printf("TR_APP_VERSION=%s", SHORT_VERSION_STRING), tr_strdup_printf("TR_TIME_LOCALTIME=%s", ctime_str), tr_strdup_printf("TR_TORRENT_DIR=%s", torrent_dir), @@ -2214,7 +2217,7 @@ static void torrentCallScript(tr_torrent const* tor, char const* script) tr_strdup_printf("TR_TORRENT_ID=%d", tr_torrentId(tor)), tr_strdup_printf("TR_TORRENT_NAME=%s", tr_torrentName(tor)), tr_strdup_printf("TR_TORRENT_LABELS=%s", labels), - NULL + NULL, }; tr_logAddTorInfo(tor, "Calling script \"%s\"", script); @@ -2249,7 +2252,10 @@ void tr_torrentRecheckCompleteness(tr_torrent* tor) if (recentChange) { - tr_logAddTorInfo(tor, _("State changed from \"%1$s\" to \"%2$s\""), getCompletionString(tor->completeness), + tr_logAddTorInfo( + tor, + _("State changed from \"%1$s\" to \"%2$s\""), + getCompletionString(tor->completeness), getCompletionString(completeness)); } @@ -2340,7 +2346,10 @@ void tr_torrentInitFilePriority(tr_torrent* tor, tr_file_index_t fileIndex, tr_p } } -void tr_torrentSetFilePriorities(tr_torrent* tor, tr_file_index_t const* files, tr_file_index_t fileCount, +void tr_torrentSetFilePriorities( + tr_torrent* tor, + tr_file_index_t const* files, + tr_file_index_t fileCount, tr_priority_t priority) { TR_ASSERT(tr_isTorrent(tor)); @@ -2552,7 +2561,11 @@ uint16_t tr_torrentGetPeerLimit(tr_torrent const* tor) **** ***/ -void tr_torrentGetBlockLocation(tr_torrent const* tor, tr_block_index_t block, tr_piece_index_t* piece, uint32_t* offset, +void tr_torrentGetBlockLocation( + tr_torrent const* tor, + tr_block_index_t block, + tr_piece_index_t* piece, + uint32_t* offset, uint32_t* length) { uint64_t pos = block; @@ -2614,8 +2627,13 @@ bool tr_torrentReqIsValid(tr_torrent const* tor, tr_piece_index_t index, uint32_ if (err != 0) { - tr_logAddTorDbg(tor, "index %lu offset %lu length %lu err %d\n", (unsigned long)index, (unsigned long)offset, - (unsigned long)length, err); + tr_logAddTorDbg( + tor, + "index %lu offset %lu length %lu err %d\n", + (unsigned long)index, + (unsigned long)offset, + (unsigned long)length, + err); } return err == 0; @@ -2652,7 +2670,10 @@ void tr_torGetFileBlockRange(tr_torrent const* tor, tr_file_index_t const file, } } -void tr_torGetPieceBlockRange(tr_torrent const* tor, tr_piece_index_t const piece, tr_block_index_t* first, +void tr_torGetPieceBlockRange( + tr_torrent const* tor, + tr_piece_index_t const piece, + tr_block_index_t* first, tr_block_index_t* last) { uint64_t offset = tor->info.pieceSize; @@ -2732,8 +2753,7 @@ bool tr_torrentPieceNeedsCheck(tr_torrent const* tor, tr_piece_index_t p) for (tr_file_index_t i = f; i < inf->fileCount && pieceHasFile(p, &inf->files[i]); ++i) { - if (tr_cpFileIsComplete(&tor->completion, i) && - (tr_torrentGetFileMTime(tor, i) > inf->pieces[p].timeChecked)) + if (tr_cpFileIsComplete(&tor->completion, i) && (tr_torrentGetFileMTime(tor, i) > inf->pieces[p].timeChecked)) { return true; } @@ -2877,7 +2897,10 @@ bool tr_torrentSetAnnounceList(tr_torrent* tor, tr_tracker_info const* trackers_ **/ #define BACK_COMPAT_FUNC(oldname, newname) \ - void oldname(tr_torrent * tor, time_t t) { newname(tor, t); } + void oldname(tr_torrent* tor, time_t t) \ + { \ + newname(tor, t); \ + } BACK_COMPAT_FUNC(tr_torrentSetAddedDate, tr_torrentSetDateAdded) BACK_COMPAT_FUNC(tr_torrentSetActivityDate, tr_torrentSetDateActive) BACK_COMPAT_FUNC(tr_torrentSetDoneDate, tr_torrentSetDateDone) @@ -2946,11 +2969,10 @@ uint64_t tr_torrentGetBytesLeftToAllocate(tr_torrent const* tor) static bool isJunkFile(char const* base) { - static char const* files[] = - { + static char const* files[] = { ".DS_Store", "desktop.ini", - "Thumbs.db" + "Thumbs.db", }; for (size_t i = 0; i < TR_N_ELEMENTS(files); ++i) @@ -3307,7 +3329,11 @@ static void setLocation(void* vdata) tr_free(data); } -void tr_torrentSetLocation(tr_torrent* tor, char const* location, bool move_from_old_location, double volatile* setme_progress, +void tr_torrentSetLocation( + tr_torrent* tor, + char const* location, + bool move_from_old_location, + double volatile* setme_progress, int volatile* setme_state) { TR_ASSERT(tr_isTorrent(tor)); @@ -3344,7 +3370,7 @@ char const* tr_torrentPrimaryMimeType(tr_torrent const* tor) struct count* counts = tr_new0(struct count, inf->fileCount); size_t num_counts = 0; - for (tr_file const* it = inf->files, * end = it + inf->fileCount; it != end; ++it) + for (tr_file const *it = inf->files, *end = it + inf->fileCount; it != end; ++it) { char const* mime_type = tr_get_mime_type_for_filename(it->name); size_t i; @@ -3367,7 +3393,7 @@ char const* tr_torrentPrimaryMimeType(tr_torrent const* tor) uint64_t max_len = 0; char const* mime_type = NULL; - for (struct count const* it = counts, *end = it + num_counts; it != end; ++it) + for (struct count const *it = counts, *end = it + num_counts; it != end; ++it) { if ((max_len < it->length) && (it->mime_type != NULL)) { @@ -3441,9 +3467,7 @@ static void tr_torrentPieceCompleted(tr_torrent* tor, tr_piece_index_t pieceInde { tr_file const* file = &tor->info.files[i]; - if ((file->firstPiece <= pieceIndex) && - (pieceIndex <= file->lastPiece) && - tr_cpFileIsComplete(&tor->completion, i)) + if ((file->firstPiece <= pieceIndex) && (pieceIndex <= file->lastPiece) && tr_cpFileIsComplete(&tor->completion, i)) { tr_torrentFileCompleted(tor, i); } @@ -3496,7 +3520,11 @@ void tr_torrentGotBlock(tr_torrent* tor, tr_block_index_t block) **** ***/ -static void find_file_in_dir(char const* name, char const* search_dir, char const** base, char const** subpath, +static void find_file_in_dir( + char const* name, + char const* search_dir, + char const** base, + char const** subpath, tr_sys_path_info* file_info) { char* filename = tr_buildPath(search_dir, name, NULL); @@ -3691,17 +3719,13 @@ void tr_torrentSetQueuePosition(tr_torrent* tor, int pos) while ((walk = tr_torrentNext(tor->session, walk)) != NULL) { - if ((old_pos < pos) && - (old_pos <= walk->queuePosition) && - (walk->queuePosition <= pos)) + if ((old_pos < pos) && (old_pos <= walk->queuePosition) && (walk->queuePosition <= pos)) { walk->queuePosition--; walk->anyDate = now; } - if ((old_pos > pos) && - (pos <= walk->queuePosition) && - (walk->queuePosition < old_pos)) + if ((old_pos > pos) && (pos <= walk->queuePosition) && (walk->queuePosition < old_pos)) { walk->queuePosition++; walk->anyDate = now; @@ -3789,7 +3813,7 @@ static void torrentSetQueued(tr_torrent* tor, bool queued) } } -void tr_torrentSetQueueStartCallback(tr_torrent* torrent, void (* callback)(tr_torrent*, void*), void* user_data) +void tr_torrentSetQueueStartCallback(tr_torrent* torrent, void (*callback)(tr_torrent*, void*), void* user_data) { torrent->queue_started_callback = callback; torrent->queue_started_user_data = user_data; @@ -4033,7 +4057,11 @@ static void torrentRenamePath(void* vdata) tr_free(data); } -void tr_torrentRenamePath(tr_torrent* tor, char const* oldpath, char const* newname, tr_torrent_rename_done_func callback, +void tr_torrentRenamePath( + tr_torrent* tor, + char const* oldpath, + char const* newname, + tr_torrent_rename_done_func callback, void* callback_user_data) { struct rename_data* data; diff --git a/libtransmission/torrent.h b/libtransmission/torrent.h index b0ca582fc..bca6018d7 100644 --- a/libtransmission/torrent.h +++ b/libtransmission/torrent.h @@ -68,13 +68,23 @@ bool tr_torrentReqIsValid(tr_torrent const* tor, tr_piece_index_t index, uint32_ uint64_t tr_pieceOffset(tr_torrent const* tor, tr_piece_index_t index, uint32_t offset, uint32_t length); -void tr_torrentGetBlockLocation(tr_torrent const* tor, tr_block_index_t block, tr_piece_index_t* piece, uint32_t* offset, +void tr_torrentGetBlockLocation( + tr_torrent const* tor, + tr_block_index_t block, + tr_piece_index_t* piece, + uint32_t* offset, uint32_t* length); -void tr_torGetFileBlockRange(tr_torrent const* tor, tr_file_index_t const file, tr_block_index_t* first, +void tr_torGetFileBlockRange( + tr_torrent const* tor, + tr_file_index_t const file, + tr_block_index_t* first, tr_block_index_t* last); -void tr_torGetPieceBlockRange(tr_torrent const* tor, tr_piece_index_t const piece, tr_block_index_t* first, +void tr_torGetPieceBlockRange( + tr_torrent const* tor, + tr_piece_index_t const piece, + tr_block_index_t* first, tr_block_index_t* last); void tr_torrentInitFilePriority(tr_torrent* tor, tr_file_index_t fileIndex, tr_priority_t priority); @@ -105,8 +115,7 @@ typedef enum TR_VERIFY_NONE, TR_VERIFY_WAIT, TR_VERIFY_NOW -} -tr_verify_state; +} tr_verify_state; void tr_torrentSetVerifyState(tr_torrent* tor, tr_verify_state state); @@ -223,7 +232,7 @@ struct tr_torrent void* idle_limit_hit_func_user_data; void* queue_started_user_data; - void (* queue_started_callback)(tr_torrent*, void* queue_started_user_data); + void (*queue_started_callback)(tr_torrent*, void* queue_started_user_data); bool isRunning; bool isStopping; diff --git a/libtransmission/tr-dht.c b/libtransmission/tr-dht.c index ca5f5f01e..0d4876b67 100644 --- a/libtransmission/tr-dht.c +++ b/libtransmission/tr-dht.c @@ -731,8 +731,12 @@ static int tr_dhtAnnounce(tr_torrent* tor, int af, bool announce) if (rc >= 0) { - tr_logAddTorInfo(tor, "Starting %s DHT announce (%s, %d nodes)", af == AF_INET6 ? "IPv6" : "IPv4", - tr_dhtPrintableStatus(status), numnodes); + tr_logAddTorInfo( + tor, + "Starting %s DHT announce (%s, %d nodes)", + af == AF_INET6 ? "IPv6" : "IPv4", + tr_dhtPrintableStatus(status), + numnodes); if (af == AF_INET) { @@ -747,13 +751,22 @@ static int tr_dhtAnnounce(tr_torrent* tor, int af, bool announce) } else { - tr_logAddTorErr(tor, "%s DHT announce failed (%s, %d nodes): %s", af == AF_INET6 ? "IPv6" : "IPv4", - tr_dhtPrintableStatus(status), numnodes, tr_strerror(errno)); + tr_logAddTorErr( + tor, + "%s DHT announce failed (%s, %d nodes): %s", + af == AF_INET6 ? "IPv6" : "IPv4", + tr_dhtPrintableStatus(status), + numnodes, + tr_strerror(errno)); } } else { - tr_logAddTorDbg(tor, "%s DHT not ready (%s, %d nodes)", af == AF_INET6 ? "IPv6" : "IPv4", tr_dhtPrintableStatus(status), + tr_logAddTorDbg( + tor, + "%s DHT not ready (%s, %d nodes)", + af == AF_INET6 ? "IPv6" : "IPv4", + tr_dhtPrintableStatus(status), numnodes); } diff --git a/libtransmission/tr-getopt.c b/libtransmission/tr-getopt.c index eef99dbb3..6d7d3f127 100644 --- a/libtransmission/tr-getopt.c +++ b/libtransmission/tr-getopt.c @@ -69,10 +69,15 @@ static void getopts_usage_line(tr_option const* opt, int longWidth, int shortWid int const d_width = 80 - d_indent; char const* d = opt->description; - printf(" %s%-*s %s%-*s %-*s ", tr_str_is_empty(shortName) ? " " : "-", shortWidth, shortName, - tr_str_is_empty(longName) ? " " : "--", longWidth, longName, argWidth, arg); + printf( + " %s%-*s %s%-*s %-*s ", + tr_str_is_empty(shortName) ? " " : "-", + TR_ARG_TUPLE(shortWidth, shortName), + tr_str_is_empty(longName) ? " " : "--", + TR_ARG_TUPLE(longWidth, longName), + TR_ARG_TUPLE(argWidth, arg)); len = get_next_line_len(d, d_width); - printf("%*.*s\n", len, len, d); + printf("%*.*s\n", TR_ARG_TUPLE(len, len, d)); d += len; @@ -83,7 +88,7 @@ static void getopts_usage_line(tr_option const* opt, int longWidth, int shortWid while ((len = get_next_line_len(d, d_width)) != 0) { - printf("%*.*s%*.*s\n", d_indent, d_indent, "", len, len, d); + printf("%*.*s%*.*s\n", TR_ARG_TUPLE(d_indent, d_indent, ""), TR_ARG_TUPLE(len, len, d)); d += len; while (isspace(*d)) diff --git a/libtransmission/tr-getopt.h b/libtransmission/tr-getopt.h index d4325b2eb..736e5314e 100644 --- a/libtransmission/tr-getopt.h +++ b/libtransmission/tr-getopt.h @@ -28,8 +28,7 @@ typedef struct tr_option char const* shortName; /* short form */ bool has_arg; /* 0 for no argument, 1 for argument */ char const* argName; /* argument's description for tr_getopt_usage() */ -} -tr_option; +} tr_option; enum { diff --git a/libtransmission/tr-lpd.c b/libtransmission/tr-lpd.c index 93d73365f..ce692ca46 100644 --- a/libtransmission/tr-lpd.c +++ b/libtransmission/tr-lpd.c @@ -477,13 +477,13 @@ bool tr_lpdEnabled(tr_session const* ss) */ bool tr_lpdSendAnnounce(tr_torrent const* t) { - char const fmt[] = - "BT-SEARCH * HTTP/%u.%u" CRLF - "Host: %s:%u" CRLF - "Port: %u" CRLF - "Infohash: %s" CRLF - CRLF - CRLF; + char const fmt[] = // + "BT-SEARCH * HTTP/%u.%u" CRLF // + "Host: %s:%u" CRLF // + "Port: %u" CRLF // + "Infohash: %s" CRLF // + "" CRLF // + "" CRLF; char hashString[SIZEOF_HASH_STRING]; char query[lpd_maxDatagramLength + 1] = { 0 }; @@ -508,7 +508,12 @@ bool tr_lpdSendAnnounce(tr_torrent const* t) /* destination address info has already been set up in tr_lpdInit(), * so we refrain from preparing another sockaddr_in here */ - int res = sendto(lpd_socket2, (void const*)query, len, 0, (struct sockaddr const*)&lpd_mcastAddr, + int res = sendto( + lpd_socket2, + (void const*)query, + len, + 0, + (struct sockaddr const*)&lpd_mcastAddr, sizeof(lpd_mcastAddr)); if (res != len) @@ -672,7 +677,10 @@ static int tr_lpdAnnounceMore(time_t const now, int const interval) if (lpd_unsolicitedMsgCounter < 0) { - tr_logAddNamedInfo("LPD", "Dropped %d announces in the last interval (max. %d allowed)", -lpd_unsolicitedMsgCounter, + tr_logAddNamedInfo( + "LPD", + "Dropped %d announces in the last interval (max. %d allowed)", + -lpd_unsolicitedMsgCounter, maxAnnounceCap); } @@ -717,7 +725,12 @@ static void event_callback(evutil_socket_t s, short type, void* user_data) char foreignMsg[lpd_maxDatagramLength + 1]; /* process local announcement from foreign peer */ - int res = recvfrom(lpd_socket, (void*)foreignMsg, lpd_maxDatagramLength, 0, (struct sockaddr*)&foreignAddr, + int res = recvfrom( + lpd_socket, + (void*)foreignMsg, + lpd_maxDatagramLength, + 0, + (struct sockaddr*)&foreignAddr, (socklen_t*)&addrLen); /* besides, do we get flooded? then bail out! */ @@ -728,10 +741,9 @@ static void event_callback(evutil_socket_t s, short type, void* user_data) if (res > 0 && res <= lpd_maxDatagramLength) { - struct tr_pex foreignPeer = - { + struct tr_pex foreignPeer = { .port = 0, /* the peer-to-peer port is yet unknown */ - .flags = 0 + .flags = 0, }; /* be paranoid enough about zero terminating the foreign string */ diff --git a/libtransmission/tr-macros.h b/libtransmission/tr-macros.h index 39b10485e..43b47013d 100644 --- a/libtransmission/tr-macros.h +++ b/libtransmission/tr-macros.h @@ -35,18 +35,15 @@ #endif #ifdef __GNUC__ -#define TR_GNUC_CHECK_VERSION(major, minor) \ - (__GNUC__ > (major) || \ - (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor))) +#define TR_GNUC_CHECK_VERSION(major, minor) (__GNUC__ > (major) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor))) #else #define TR_GNUC_CHECK_VERSION(major, minor) 0 #endif #ifdef __UCLIBC__ #define TR_UCLIBC_CHECK_VERSION(major, minor, micro) \ - (__UCLIBC_MAJOR__ > (major) || \ - (__UCLIBC_MAJOR__ == (major) && __UCLIBC_MINOR__ > (minor)) || \ - (__UCLIBC_MAJOR__ == (major) && __UCLIBC_MINOR__ == (minor) && __UCLIBC_SUBLEVEL__ >= (micro))) + (__UCLIBC_MAJOR__ > (major) || (__UCLIBC_MAJOR__ == (major) && __UCLIBC_MINOR__ > (minor)) || \ + (__UCLIBC_MAJOR__ == (major) && __UCLIBC_MINOR__ == (minor) && __UCLIBC_SUBLEVEL__ >= (micro))) #else #define TR_UCLIBC_CHECK_VERSION(major, minor, micro) 0 #endif @@ -56,7 +53,11 @@ ***/ // http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ -#define TR_UNUSED(x) do { ((void)sizeof(x)); } while(0) +#define TR_UNUSED(x) \ + do \ + { \ + ((void)sizeof(x)); \ + } while (0) /*** **** @@ -139,7 +140,11 @@ #elif __has_feature(c_static_assert) || __has_extension(c_static_assert) || TR_GNUC_CHECK_VERSION(4, 6) #define TR_STATIC_ASSERT _Static_assert #else -#define TR_STATIC_ASSERT(x, msg) do { ((void)sizeof(x)); } while(0) +#define TR_STATIC_ASSERT(x, msg) \ + do \ + { \ + ((void)sizeof(x)); \ + } while (0) #endif /* Sometimes the system defines MAX/MIN, sometimes not. @@ -169,10 +174,15 @@ #define TR_BAD_SIZE ((size_t)-1) /* Guard C code in headers, while including them from C++ */ -#ifdef __cplusplus -#define TR_BEGIN_DECLS extern "C" { -#define TR_END_DECLS } +#ifdef __cplusplus +#define TR_BEGIN_DECLS \ + extern "C" \ + { +#define TR_END_DECLS } #else #define TR_BEGIN_DECLS #define TR_END_DECLS #endif + +// Mostly to enforce better formatting +#define TR_ARG_TUPLE(...) __VA_ARGS__ diff --git a/libtransmission/transmission.h b/libtransmission/transmission.h index 35a39a602..1196db2db 100644 --- a/libtransmission/transmission.h +++ b/libtransmission/transmission.h @@ -46,7 +46,7 @@ struct tr_variant; typedef int8_t tr_priority_t; -typedef int (* tr_voidptr_compare_func)(void const* lhs, void const* rhs); +typedef int (*tr_voidptr_compare_func)(void const* lhs, void const* rhs); #define TR_RPC_SESSION_ID_HEADER "X-Transmission-Session-Id" @@ -55,16 +55,14 @@ typedef enum TR_PREALLOCATE_NONE = 0, TR_PREALLOCATE_SPARSE = 1, TR_PREALLOCATE_FULL = 2 -} -tr_preallocation_mode; +} tr_preallocation_mode; typedef enum { TR_CLEAR_PREFERRED, TR_ENCRYPTION_PREFERRED, TR_ENCRYPTION_REQUIRED -} -tr_encryption_mode; +} tr_encryption_mode; /*** **** @@ -395,8 +393,7 @@ typedef enum TR_RPC_SESSION_CHANGED, TR_RPC_SESSION_QUEUE_POSITIONS_CHANGED, /* catch potentially multiple torrents being moved in the queue */ TR_RPC_SESSION_CLOSE -} -tr_rpc_callback_type; +} tr_rpc_callback_type; typedef enum { @@ -407,10 +404,12 @@ typedef enum * need to keep the torrent alive long enough to cleanly close * some resources in another thread. */ TR_RPC_NOREMOVE = (1 << 1) -} -tr_rpc_callback_status; +} tr_rpc_callback_status; -typedef tr_rpc_callback_status (* tr_rpc_func)(tr_session* session, tr_rpc_callback_type type, struct tr_torrent* tor_or_null, +typedef tr_rpc_callback_status (*tr_rpc_func)( // + tr_session* session, + tr_rpc_callback_type type, + struct tr_torrent* tor_or_null, void* user_data); /** @@ -437,8 +436,7 @@ typedef struct tr_session_stats uint64_t filesAdded; /* number of files added */ uint64_t sessionCount; /* program started N times */ uint64_t secondsActive; /* how long Transmisson's been running */ -} -tr_session_stats; +} tr_session_stats; /** @brief Get bandwidth use statistics for the current session */ void tr_sessionGetStats(tr_session const* session, tr_session_stats* setme); @@ -497,8 +495,7 @@ typedef enum TR_PORT_UNMAPPING, TR_PORT_MAPPING, TR_PORT_MAPPED -} -tr_port_forwarding; +} tr_port_forwarding; tr_port_forwarding tr_sessionGetPortForwarding(tr_session const* session); @@ -508,8 +505,7 @@ typedef enum TR_UP = 0, TR_PEER_TO_CLIENT = 1, TR_DOWN = 1 -} -tr_direction; +} tr_direction; /*** **** @@ -556,13 +552,12 @@ typedef enum TR_SCHED_WEEKDAY = (TR_SCHED_MON | TR_SCHED_TUES | TR_SCHED_WED | TR_SCHED_THURS | TR_SCHED_FRI), TR_SCHED_WEEKEND = (TR_SCHED_SUN | TR_SCHED_SAT), TR_SCHED_ALL = (TR_SCHED_WEEKDAY | TR_SCHED_WEEKEND) -} -tr_sched_day; +} tr_sched_day; void tr_sessionSetAltSpeedDay(tr_session*, tr_sched_day day); tr_sched_day tr_sessionGetAltSpeedDay(tr_session const*); -typedef void (* tr_altSpeedFunc)(tr_session*, bool active, bool userDriven, void*); +typedef void (*tr_altSpeedFunc)(tr_session*, bool active, bool userDriven, void*); void tr_sessionSetAltSpeedFunc(tr_session*, tr_altSpeedFunc, void*); @@ -689,7 +684,7 @@ bool tr_sessionGetQueueStalledEnabled(tr_session const*); **/ /** @brief Set a callback that is invoked when the queue starts a torrent */ -void tr_torrentSetQueueStartCallback(tr_torrent* torrent, void (* callback)(tr_torrent*, void*), void* user_data); +void tr_torrentSetQueueStartCallback(tr_torrent* torrent, void (*callback)(tr_torrent*, void*), void* user_data); /*** **** @@ -732,8 +727,7 @@ typedef enum TR_LOG_INFO = 2, TR_LOG_DEBUG = 3, TR_LOG_FIREHOSE = 4 -} -tr_log_level; +} tr_log_level; void tr_logSetLevel(tr_log_level); @@ -761,8 +755,7 @@ typedef struct tr_log_message /* linked list of messages */ struct tr_log_message* next; -} -tr_log_message; +} tr_log_message; tr_log_message* tr_logGetQueue(void); bool tr_logGetQueueEnabled(void); @@ -840,8 +833,7 @@ typedef enum { TR_FALLBACK, /* indicates the ctor value should be used only in case of missing resume settings */ TR_FORCE /* indicates the ctor value should be used regardless of what's in the resume settings */ -} -tr_ctorMode; +} tr_ctorMode; /** @brief Create a torrent constructor object used to instantiate a tr_torrent @param session_or_NULL the tr_session. @@ -932,8 +924,7 @@ typedef enum TR_PARSE_OK, TR_PARSE_ERR, TR_PARSE_DUPLICATE -} -tr_parse_result; +} tr_parse_result; /** * @brief Parses the specified metainfo @@ -985,7 +976,7 @@ tr_torrent* tr_torrentNew(tr_ctor const* ctor, int* setme_error, int* setme_dupl /** @addtogroup tr_torrent Torrents @{ */ -typedef bool (* tr_fileFunc)(char const* filename, struct tr_error** error); +typedef bool (*tr_fileFunc)(char const* filename, struct tr_error** error); /** @brief Removes our .torrent and .resume files for this torrent */ void tr_torrentRemove(tr_torrent* torrent, bool removeLocalData, tr_fileFunc removeFunc); @@ -996,7 +987,11 @@ void tr_torrentStart(tr_torrent* torrent); /** @brief Stop (pause) a torrent */ void tr_torrentStop(tr_torrent* torrent); -typedef void (* tr_torrent_rename_done_func)(tr_torrent* torrent, char const* oldpath, char const* newname, int error, +typedef void (*tr_torrent_rename_done_func)( // + tr_torrent* torrent, + char const* oldpath, + char const* newname, + int error, void* user_data); /** @@ -1040,7 +1035,11 @@ typedef void (* tr_torrent_rename_done_func)(tr_torrent* torrent, char const* ol * If the path exists on disk but can't be renamed, the error argument * will be the errno set by rename(). */ -void tr_torrentRenamePath(tr_torrent* tor, char const* oldpath, char const* newname, tr_torrent_rename_done_func callback, +void tr_torrentRenamePath( + tr_torrent* tor, + char const* oldpath, + char const* newname, + tr_torrent_rename_done_func callback, void* callback_data); enum @@ -1057,8 +1056,12 @@ enum * will be clobberred s.t. additional files being added will be saved * to the torrent's downloadDir. */ -void tr_torrentSetLocation(tr_torrent* torrent, char const* location, bool move_from_previous_location, - double volatile* setme_progress, int volatile* setme_state); +void tr_torrentSetLocation( + tr_torrent* torrent, + char const* location, + bool move_from_previous_location, + double volatile* setme_progress, + int volatile* setme_state); uint64_t tr_torrentGetBytesLeftToAllocate(tr_torrent const* torrent); @@ -1120,8 +1123,7 @@ typedef enum TR_RATIOLIMIT_SINGLE = 1, /* override the global settings, seeding regardless of ratio */ TR_RATIOLIMIT_UNLIMITED = 2 -} -tr_ratiolimit; +} tr_ratiolimit; void tr_torrentSetRatioMode(tr_torrent* tor, tr_ratiolimit mode); @@ -1145,8 +1147,7 @@ typedef enum TR_IDLELIMIT_SINGLE = 1, /* override the global settings, seeding regardless of activity */ TR_IDLELIMIT_UNLIMITED = 2 -} -tr_idlelimit; +} tr_idlelimit; void tr_torrentSetIdleMode(tr_torrent* tor, tr_idlelimit mode); @@ -1182,7 +1183,10 @@ enum * * @param priority must be one of TR_PRI_NORMAL, _HIGH, or _LOW */ -void tr_torrentSetFilePriorities(tr_torrent* torrent, tr_file_index_t const* files, tr_file_index_t fileCount, +void tr_torrentSetFilePriorities( + tr_torrent* torrent, + tr_file_index_t const* files, + tr_file_index_t fileCount, tr_priority_t priority); /** @@ -1237,8 +1241,7 @@ typedef struct tr_tracker_info char* announce; char* scrape; uint32_t id; /* unique identifier used to match to a tr_tracker_stat */ -} -tr_tracker_info; +} tr_tracker_info; /** * @brief Modify a torrent's tracker list. @@ -1264,19 +1267,21 @@ typedef enum TR_LEECH, /* doesn't have all the desired pieces */ TR_SEED, /* has the entire torrent */ TR_PARTIAL_SEED /* has the desired pieces, but not the entire torrent */ -} -tr_completeness; +} tr_completeness; /** * @param wasRunning whether or not the torrent was running when * it changed its completeness state */ -typedef void (* tr_torrent_completeness_func)(tr_torrent* torrent, tr_completeness completeness, bool wasRunning, +typedef void (*tr_torrent_completeness_func)( // + tr_torrent* torrent, + tr_completeness completeness, + bool wasRunning, void* user_data); -typedef void (* tr_torrent_ratio_limit_hit_func)(tr_torrent* torrent, void* user_data); +typedef void (*tr_torrent_ratio_limit_hit_func)(tr_torrent* torrent, void* user_data); -typedef void (* tr_torrent_idle_limit_hit_func)(tr_torrent* torrent, void* user_data); +typedef void (*tr_torrent_idle_limit_hit_func)(tr_torrent* torrent, void* user_data); /** * Register to be notified whenever a torrent's "completeness" @@ -1295,7 +1300,7 @@ void tr_torrentSetCompletenessCallback(tr_torrent* torrent, tr_torrent_completen void tr_torrentClearCompletenessCallback(tr_torrent* torrent); -typedef void (* tr_torrent_metadata_func)(tr_torrent* torrent, void* user_data); +typedef void (*tr_torrent_metadata_func)(tr_torrent* torrent, void* user_data); /** * Register to be notified whenever a torrent changes from * having incomplete metadata to having complete metadata. @@ -1391,8 +1396,7 @@ typedef struct tr_peer_stat /* how many requests we've made and are currently awaiting a response for */ int pendingReqsToPeer; -} -tr_peer_stat; +} tr_peer_stat; tr_peer_stat* tr_torrentPeers(tr_torrent const* torrent, int* peerCount); @@ -1415,8 +1419,7 @@ typedef enum TR_TRACKER_QUEUED = 2, /* we're (announcing,scraping) this torrent right now */ TR_TRACKER_ACTIVE = 3 -} -tr_tracker_state; +} tr_tracker_state; typedef struct { @@ -1509,8 +1512,7 @@ typedef struct /* used to match to a tr_tracker_info */ uint32_t id; -} -tr_tracker_stat; +} tr_tracker_stat; tr_tracker_stat* tr_torrentTrackers(tr_torrent const* torrent, int* setmeTrackerCount); @@ -1532,8 +1534,7 @@ typedef struct tr_file_stat { uint64_t bytesCompleted; float progress; -} -tr_file_stat; +} tr_file_stat; tr_file_stat* tr_torrentFiles(tr_torrent const* torrent, tr_file_index_t* fileCount); @@ -1560,7 +1561,7 @@ void tr_torrentAmountFinished(tr_torrent const* torrent, float* tab, int size); * being called during verification. * @param user_data the user-defined pointer from tr_torrentVerify() */ -typedef void (* tr_verify_done_func)(tr_torrent* torrent, bool aborted, void* user_data); +typedef void (*tr_verify_done_func)(tr_torrent* torrent, bool aborted, void* user_data); /** * Queue a torrent for verification. @@ -1586,8 +1587,7 @@ typedef struct tr_file tr_piece_index_t firstPiece; /* We need pieces [firstPiece... */ tr_piece_index_t lastPiece; /* ...lastPiece] to dl this file */ uint64_t offset; /* file begins at the torrent's nth byte */ -} -tr_file; +} tr_file; /** @brief a part of tr_info that represents a single piece of the torrent's content */ typedef struct tr_piece @@ -1596,8 +1596,7 @@ typedef struct tr_piece uint8_t hash[SHA_DIGEST_LENGTH]; /* pieces hash */ int8_t priority; /* TR_PRI_HIGH, _NORMAL, or _LOW */ bool dnd; /* "do not download" flag */ -} -tr_piece; +} tr_piece; /** @brief information about a torrent that comes from its metainfo file */ struct tr_info @@ -1664,8 +1663,7 @@ typedef enum TR_STATUS_DOWNLOAD = 4, /* Downloading */ TR_STATUS_SEED_WAIT = 5, /* Queued to seed */ TR_STATUS_SEED = 6 /* Seeding */ -} -tr_torrent_activity; +} tr_torrent_activity; enum { @@ -1689,8 +1687,7 @@ typedef enum TR_STAT_TRACKER_ERROR = 2, /* local trouble, such as disk full or permissions error */ TR_STAT_LOCAL_ERROR = 3 -} -tr_stat_errtype; +} tr_stat_errtype; /** @brief Used by tr_torrentStat() to tell clients about a torrent's state and statistics */ typedef struct tr_stat @@ -1863,8 +1860,7 @@ typedef struct tr_stat /** True if the torrent is running, but has been idle for long enough to be considered stalled. @see tr_sessionGetQueueStalledMinutes() */ bool isStalled; -} -tr_stat; +} tr_stat; /** Return a pointer to an tr_stat structure with updated information on the torrent. This is typically called by the GUI clients every diff --git a/libtransmission/trevent.c b/libtransmission/trevent.c index 3c69c2481..16a20e83e 100644 --- a/libtransmission/trevent.c +++ b/libtransmission/trevent.c @@ -157,12 +157,11 @@ typedef struct tr_event_handle tr_thread* thread; struct event_base* base; struct event* pipeEvent; -} -tr_event_handle; +} tr_event_handle; struct tr_run_data { - void (* func)(void*); + void (*func)(void*); void* user_data; }; @@ -182,8 +181,7 @@ static void readFromPipe(evutil_socket_t fd, short eventType, void* veh) do { ret = piperead(fd, &ch, 1); - } - while (!eh->die && ret == -1 && errno == EAGAIN); + } while (!eh->die && ret == -1 && errno == EAGAIN); dbgmsg("command is [%c], ret is %d, errno is %d", ch, ret, (int)errno); @@ -329,7 +327,7 @@ bool tr_amInEventThread(tr_session const* session) *** **/ -void tr_runInEventThread(tr_session* session, void (* func)(void*), void* user_data) +void tr_runInEventThread(tr_session* session, void (*func)(void*), void* user_data) { TR_ASSERT(tr_isSession(session)); TR_ASSERT(session->events != NULL); diff --git a/libtransmission/trevent.h b/libtransmission/trevent.h index 3f8464d02..584d269bf 100644 --- a/libtransmission/trevent.h +++ b/libtransmission/trevent.h @@ -22,6 +22,6 @@ void tr_eventClose(tr_session*); bool tr_amInEventThread(tr_session const*); -void tr_runInEventThread(tr_session*, void (* func)(void*), void* user_data); +void tr_runInEventThread(tr_session*, void (*func)(void*), void* user_data); TR_END_DECLS diff --git a/libtransmission/upnp.c b/libtransmission/upnp.c index ab2ebe002..58ef2bbea 100644 --- a/libtransmission/upnp.c +++ b/libtransmission/upnp.c @@ -36,8 +36,7 @@ typedef enum TR_UPNP_DISCOVER, TR_UPNP_MAP, TR_UPNP_UNMAP -} -tr_upnp_state; +} tr_upnp_state; struct tr_upnp { @@ -121,13 +120,35 @@ static int tr_upnpGetSpecificPortMappingEntry(tr_upnp* handle, char const* proto tr_snprintf(portStr, sizeof(portStr), "%d", handle->port); #if (MINIUPNPC_API_VERSION >= 10) /* adds remoteHost arg */ - err = UPNP_GetSpecificPortMappingEntry(handle->urls.controlURL, handle->data.first.servicetype, portStr, proto, - NULL /*remoteHost*/, intClient, intPort, NULL /*desc*/, NULL /*enabled*/, NULL /*duration*/); + err = UPNP_GetSpecificPortMappingEntry( + handle->urls.controlURL, + handle->data.first.servicetype, + portStr, + proto, + NULL /*remoteHost*/, + intClient, + intPort, + NULL /*desc*/, + NULL /*enabled*/, + NULL /*duration*/); #elif (MINIUPNPC_API_VERSION >= 8) /* adds desc, enabled and leaseDuration args */ - err = UPNP_GetSpecificPortMappingEntry(handle->urls.controlURL, handle->data.first.servicetype, portStr, proto, intClient, - intPort, NULL /*desc*/, NULL /*enabled*/, NULL /*duration*/); + err = UPNP_GetSpecificPortMappingEntry( + handle->urls.controlURL, + handle->data.first.servicetype, + portStr, + proto, + intClient, + intPort, + NULL /*desc*/, + NULL /*enabled*/, + NULL /*duration*/); #else - err = UPNP_GetSpecificPortMappingEntry(handle->urls.controlURL, handle->data.first.servicetype, portStr, proto, intClient, + err = UPNP_GetSpecificPortMappingEntry( + handle->urls.controlURL, + handle->data.first.servicetype, + portStr, + proto, + intClient, intPort); #endif @@ -144,16 +165,36 @@ static int tr_upnpAddPortMapping(tr_upnp const* handle, char const* proto, tr_po tr_snprintf(portStr, sizeof(portStr), "%d", (int)port); #if (MINIUPNPC_API_VERSION >= 8) - err = UPNP_AddPortMapping(handle->urls.controlURL, handle->data.first.servicetype, portStr, portStr, handle->lanaddr, desc, - proto, NULL, NULL); + err = UPNP_AddPortMapping( + handle->urls.controlURL, + handle->data.first.servicetype, + portStr, + portStr, + handle->lanaddr, + desc, + proto, + NULL, + NULL); #else - err = UPNP_AddPortMapping(handle->urls.controlURL, handle->data.first.servicetype, portStr, portStr, handle->lanaddr, desc, - proto, NULL); + err = UPNP_AddPortMapping( + handle->urls.controlURL, + handle->data.first.servicetype, + portStr, + portStr, + handle->lanaddr, + desc, + proto, + NULL); #endif if (err != 0) { - tr_logAddNamedDbg(getKey(), "%s Port forwarding failed with error %d (errno %d - %s)", proto, err, errno, + tr_logAddNamedDbg( + getKey(), + "%s Port forwarding failed with error %d (errno %d - %s)", + proto, + err, + errno, tr_strerror(errno)); } @@ -194,8 +235,8 @@ int tr_upnpPulse(tr_upnp* handle, tr_port port, bool isEnabled, bool doPortCheck errno = 0; - if (UPNP_GetValidIGD(devlist, &handle->urls, &handle->data, handle->lanaddr, - sizeof(handle->lanaddr)) == UPNP_IGD_VALID_CONNECTED) + if (UPNP_GetValidIGD(devlist, &handle->urls, &handle->data, handle->lanaddr, sizeof(handle->lanaddr)) == + UPNP_IGD_VALID_CONNECTED) { tr_logAddNamedInfo(getKey(), _("Found Internet Gateway Device \"%s\""), handle->urls.controlURL); tr_logAddNamedInfo(getKey(), _("Local Address is \"%s\""), handle->lanaddr); @@ -212,18 +253,14 @@ int tr_upnpPulse(tr_upnp* handle, tr_port port, bool isEnabled, bool doPortCheck freeUPNPDevlist(devlist); } - if ((handle->state == TR_UPNP_IDLE) && - (handle->isMapped) && - (!isEnabled || handle->port != port)) + if ((handle->state == TR_UPNP_IDLE) && (handle->isMapped) && (!isEnabled || handle->port != port)) { handle->state = TR_UPNP_UNMAP; } - if (isEnabled && - handle->isMapped && - doPortCheck && + if (isEnabled && handle->isMapped && doPortCheck && ((tr_upnpGetSpecificPortMappingEntry(handle, "TCP") != UPNPCOMMAND_SUCCESS) || - (tr_upnpGetSpecificPortMappingEntry(handle, "UDP") != UPNPCOMMAND_SUCCESS))) + (tr_upnpGetSpecificPortMappingEntry(handle, "UDP") != UPNPCOMMAND_SUCCESS))) { tr_logAddNamedInfo(getKey(), _("Port %d isn't forwarded"), handle->port); handle->isMapped = false; @@ -234,7 +271,10 @@ int tr_upnpPulse(tr_upnp* handle, tr_port port, bool isEnabled, bool doPortCheck tr_upnpDeletePortMapping(handle, "TCP", handle->port); tr_upnpDeletePortMapping(handle, "UDP", handle->port); - tr_logAddNamedInfo(getKey(), _("Stopping port forwarding through \"%s\", service \"%s\""), handle->urls.controlURL, + tr_logAddNamedInfo( + getKey(), + _("Stopping port forwarding through \"%s\", service \"%s\""), + handle->urls.controlURL, handle->data.first.servicetype); handle->isMapped = false; @@ -266,8 +306,13 @@ int tr_upnpPulse(tr_upnp* handle, tr_port port, bool isEnabled, bool doPortCheck handle->isMapped = err_tcp == 0 || err_udp == 0; } - tr_logAddNamedInfo(getKey(), _("Port forwarding through \"%s\", service \"%s\". (local address: %s:%d)"), - handle->urls.controlURL, handle->data.first.servicetype, handle->lanaddr, port); + tr_logAddNamedInfo( + getKey(), + _("Port forwarding through \"%s\", service \"%s\". (local address: %s:%d)"), + handle->urls.controlURL, + handle->data.first.servicetype, + handle->lanaddr, + port); if (handle->isMapped) { diff --git a/libtransmission/utils.c b/libtransmission/utils.c index bcb386c84..9ad21bbd0 100644 --- a/libtransmission/utils.c +++ b/libtransmission/utils.c @@ -834,21 +834,21 @@ void tr_hex_to_binary(void const* vinput, void* voutput, size_t byte_length) static bool isValidURLChars(char const* url, size_t url_len) { - static char const rfc2396_valid_chars[] = - "abcdefghijklmnopqrstuvwxyz" /* lowalpha */ - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* upalpha */ - "0123456789" /* digit */ - "-_.!~*'()" /* mark */ - ";/?:@&=+$," /* reserved */ - "<>#%<\"" /* delims */ - "{}|\\^[]`"; /* unwise */ + static char const rfc2396_valid_chars + [] = "abcdefghijklmnopqrstuvwxyz" /* lowalpha */ + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* upalpha */ + "0123456789" /* digit */ + "-_.!~*'()" /* mark */ + ";/?:@&=+$," /* reserved */ + "<>#%<\"" /* delims */ + "{}|\\^[]`"; /* unwise */ if (url == NULL) { return false; } - for (char const* c = url, * end = url + url_len; c < end && *c != '\0'; ++c) + for (char const *c = url, *end = url + url_len; c < end && *c != '\0'; ++c) { if (memchr(rfc2396_valid_chars, *c, sizeof(rfc2396_valid_chars) - 1) == NULL) { @@ -886,7 +886,7 @@ bool tr_urlIsValid(char const* url, size_t url_len) return isValidURLChars(url, url_len) && tr_urlParse(url, url_len, NULL, NULL, NULL, NULL) && (memcmp(url, "http://", 7) == 0 || memcmp(url, "https://", 8) == 0 || memcmp(url, "ftp://", 6) == 0 || - memcmp(url, "sftp://", 7) == 0); + memcmp(url, "sftp://", 7) == 0); } bool tr_addressIsIP(char const* str) @@ -920,14 +920,13 @@ static int get_port_for_scheme(char const* scheme, size_t scheme_len) int port; }; - static struct known_scheme const known_schemes[] = - { - { "udp", 80 }, - { "ftp", 21 }, - { "sftp", 22 }, - { "http", 80 }, - { "https", 443 }, - { NULL, 0 } + static struct known_scheme const known_schemes[] = { + { "udp", 80 }, // + { "ftp", 21 }, // + { "sftp", 22 }, // + { "http", 80 }, // + { "https", 443 }, // + { NULL, 0 }, // }; for (struct known_scheme const* s = known_schemes; s->name != NULL; ++s) @@ -1033,11 +1032,18 @@ void tr_removeElementFromArray(void* array, size_t index_to_remove, size_t sizeo { char* a = array; - memmove(a + sizeof_element * index_to_remove, a + sizeof_element * (index_to_remove + 1), + memmove( + a + sizeof_element * index_to_remove, + a + sizeof_element * (index_to_remove + 1), sizeof_element * (--nmemb - index_to_remove)); } -int tr_lowerBound(void const* key, void const* base, size_t nmemb, size_t size, tr_voidptr_compare_func compar, +int tr_lowerBound( + void const* key, + void const* base, + size_t nmemb, + size_t size, + tr_voidptr_compare_func compar, bool* exact_match) { size_t first = 0; @@ -1090,13 +1096,16 @@ int tr_lowerBound(void const* key, void const* base, size_t nmemb, size_t size, char __tmp = *__a; \ *__a++ = *__b; \ *__b++ = __tmp; \ - } \ - while (--__size > 0); \ + } while (--__size > 0); \ } \ - } \ - while (0) + } while (0) -static size_t quickfindPartition(char* base, size_t left, size_t right, size_t size, tr_voidptr_compare_func compar, +static size_t quickfindPartition( + char* base, + size_t left, + size_t right, + size_t size, + tr_voidptr_compare_func compar, size_t pivotIndex) { size_t storeIndex; @@ -1297,7 +1306,11 @@ char* tr_win32_native_to_utf8(wchar_t const* text, int text_size) return tr_win32_native_to_utf8_ex(text, text_size, 0, 0, NULL); } -char* tr_win32_native_to_utf8_ex(wchar_t const* text, int text_size, int extra_chars_before, int extra_chars_after, +char* tr_win32_native_to_utf8_ex( + wchar_t const* text, + int text_size, + int extra_chars_before, + int extra_chars_after, int* real_result_size) { char* ret = NULL; @@ -1343,7 +1356,11 @@ wchar_t* tr_win32_utf8_to_native(char const* text, int text_size) return tr_win32_utf8_to_native_ex(text, text_size, 0, 0, NULL); } -wchar_t* tr_win32_utf8_to_native_ex(char const* text, int text_size, int extra_chars_before, int extra_chars_after, +wchar_t* tr_win32_utf8_to_native_ex( + char const* text, + int text_size, + int extra_chars_before, + int extra_chars_after, int* real_result_size) { wchar_t* ret = NULL; @@ -1391,8 +1408,14 @@ char* tr_win32_format_message(uint32_t code) char* text = NULL; size_t text_size; - wide_size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, code, 0, (LPWSTR)&wide_text, 0, NULL); + wide_size = FormatMessageW( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + code, + 0, + (LPWSTR)&wide_text, + 0, + NULL); if (wide_size == 0) { @@ -1469,7 +1492,7 @@ void tr_win32_make_args_utf8(int* argc, char*** argv) LocalFree(my_wide_argv); } -int tr_main_win32(int argc, char** argv, int (* real_main)(int, char**)) +int tr_main_win32(int argc, char** argv, int (*real_main)(int, char**)) { tr_win32_make_args_utf8(&argc, &argv); SetConsoleCP(CP_UTF8); @@ -1665,7 +1688,7 @@ double tr_truncd(double x, int precision) { char* pt; char buf[128]; - tr_snprintf(buf, sizeof(buf), "%.*f", DBL_DIG, x); + tr_snprintf(buf, sizeof(buf), "%.*f", TR_ARG_TUPLE(DBL_DIG, x)); if ((pt = strstr(buf, localeconv()->decimal_point)) != NULL) { @@ -1791,8 +1814,7 @@ uint64_t tr_htonll(uint64_t x) { uint32_t lx[2]; uint64_t llx; - } - u; + } u; u.lx[0] = htonl(x >> 32); u.lx[1] = htonl(x & 0xFFFFFFFFULL); return u.llx; @@ -1813,8 +1835,7 @@ uint64_t tr_ntohll(uint64_t x) { uint32_t lx[2]; uint64_t llx; - } - u; + } u; u.llx = x; return ((uint64_t)ntohl(u.lx[0]) << 32) | (uint64_t)ntohl(u.lx[1]); @@ -1846,7 +1867,12 @@ enum TR_FMT_TB }; -static void formatter_init(struct formatter_units* units, size_t kilo, char const* kb, char const* mb, char const* gb, +static void formatter_init( + struct formatter_units* units, + size_t kilo, + char const* kb, + char const* mb, + char const* gb, char const* tb) { size_t value; @@ -1908,7 +1934,7 @@ static char* formatter_get_size_str(struct formatter_units const* u, char* buf, precision = 1; } - tr_snprintf(buf, buflen, "%.*f %s", precision, value, units); + tr_snprintf(buf, buflen, "%.*f %s", TR_ARG_TUPLE(precision, value), units); return buf; } @@ -2149,7 +2175,8 @@ char const* tr_get_mime_type_for_filename(char const* filename) *out = '\0'; - info = bsearch(lowercase_suffix, + info = bsearch( + lowercase_suffix, mime_type_suffixes, TR_N_ELEMENTS(mime_type_suffixes), sizeof(*mime_type_suffixes), diff --git a/libtransmission/utils.h b/libtransmission/utils.h index da2f0c8cb..1154bab6e 100644 --- a/libtransmission/utils.h +++ b/libtransmission/utils.h @@ -116,18 +116,25 @@ char* tr_utf8clean(char const* str, size_t len) TR_GNUC_MALLOC; #ifdef _WIN32 char* tr_win32_native_to_utf8(wchar_t const* text, int text_size); -char* tr_win32_native_to_utf8_ex(wchar_t const* text, int text_size, int extra_chars_before, int extra_chars_after, +char* tr_win32_native_to_utf8_ex( + wchar_t const* text, + int text_size, + int extra_chars_before, + int extra_chars_after, int* real_result_size); wchar_t* tr_win32_utf8_to_native(char const* text, int text_size); -wchar_t* tr_win32_utf8_to_native_ex(char const* text, int text_size, int extra_chars_before, int extra_chars_after, +wchar_t* tr_win32_utf8_to_native_ex( + char const* text, + int text_size, + int extra_chars_before, + int extra_chars_after, int* real_result_size); char* tr_win32_format_message(uint32_t code); void tr_win32_make_args_utf8(int* argc, char*** argv); -int tr_main_win32(int argc, char** argv, int (* real_main)(int, char**)); +int tr_main_win32(int argc, char** argv, int (*real_main)(int, char**)); -/* *INDENT-OFF* */ #define tr_main(...) \ main_impl(__VA_ARGS__); \ int main(int argc, char* argv[]) \ @@ -135,7 +142,6 @@ int tr_main_win32(int argc, char** argv, int (* real_main)(int, char**)); return tr_main_win32(argc, argv, &main_impl); \ } \ int main_impl(__VA_ARGS__) -/* *INDENT-ON* */ #else @@ -170,16 +176,11 @@ void tr_free_ptrv(void* const* p); */ void* tr_memdup(void const* src, size_t byteCount); -/* *INDENT-OFF* */ -#define tr_new(struct_type, n_structs) \ - ((struct_type*)tr_malloc(sizeof(struct_type) * (size_t)(n_structs))) +#define tr_new(struct_type, n_structs) ((struct_type*)tr_malloc(sizeof(struct_type) * (size_t)(n_structs))) -#define tr_new0(struct_type, n_structs) \ - ((struct_type*)tr_malloc0(sizeof(struct_type) * (size_t)(n_structs))) +#define tr_new0(struct_type, n_structs) ((struct_type*)tr_malloc0(sizeof(struct_type) * (size_t)(n_structs))) -#define tr_renew(struct_type, mem, n_structs) \ - ((struct_type*)tr_realloc((mem), sizeof(struct_type) * (size_t)(n_structs))) -/* *INDENT-ON* */ +#define tr_renew(struct_type, mem, n_structs) ((struct_type*)tr_realloc((mem), sizeof(struct_type) * (size_t)(n_structs))) /** * @brief make a newly-allocated copy of a substring @@ -209,7 +210,12 @@ static inline bool tr_str_is_empty(char const* value) char* evbuffer_free_to_str(struct evbuffer* buf, size_t* result_len); /** @brief similar to bsearch() but returns the index of the lower bound */ -int tr_lowerBound(void const* key, void const* base, size_t nmemb, size_t size, tr_voidptr_compare_func compar, +int tr_lowerBound( + void const* key, + void const* base, + size_t nmemb, + size_t size, + tr_voidptr_compare_func compar, bool* exact_match) TR_GNUC_HOT TR_GNUC_NONNULL(1, 5, 6); /** @brief moves the best k items to the first slots in the array. O(n) */ @@ -271,8 +277,8 @@ bool tr_urlIsValid(char const* url, size_t url_len); /** @brief parse a URL into its component parts @return True on success or false if an error occurred */ -bool tr_urlParse(char const* url, size_t url_len, char** setme_scheme, char** setme_host, int* setme_port, - char** setme_path) TR_GNUC_NONNULL(1); +bool tr_urlParse(char const* url, size_t url_len, char** setme_scheme, char** setme_host, int* setme_port, char** setme_path) + TR_GNUC_NONNULL(1); /** @brief return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1] @return TR_RATIO_NA, TR_RATIO_INF, or a number in [0..1] */ diff --git a/libtransmission/variant-benc.c b/libtransmission/variant-benc.c index f9192cfc3..020ca384f 100644 --- a/libtransmission/variant-benc.c +++ b/libtransmission/variant-benc.c @@ -88,7 +88,11 @@ int tr_bencParseInt(void const* vbuf, void const* vbufend, uint8_t const** setme * Note that there is no constant beginning delimiter, and no ending delimiter. * Example: 4:spam represents the string "spam" */ -int tr_bencParseStr(void const* vbuf, void const* vbufend, uint8_t const** setme_end, uint8_t const** setme_str, +int tr_bencParseStr( + void const* vbuf, + void const* vbufend, + uint8_t const** setme_end, + uint8_t const** setme_str, size_t* setme_strlen) { uint8_t const* const buf = (uint8_t const*)vbuf; @@ -390,15 +394,14 @@ static void saveContainerEndFunc(tr_variant const* val, void* evbuf) evbuffer_add(evbuf, "e", 1); } -static struct VariantWalkFuncs const walk_funcs = -{ - saveIntFunc, - saveBoolFunc, - saveRealFunc, - saveStringFunc, - saveDictBeginFunc, - saveListBeginFunc, - saveContainerEndFunc +static struct VariantWalkFuncs const walk_funcs = { + saveIntFunc, // + saveBoolFunc, // + saveRealFunc, // + saveStringFunc, // + saveDictBeginFunc, // + saveListBeginFunc, // + saveContainerEndFunc, // }; void tr_variantToBufBenc(tr_variant const* top, struct evbuffer* buf) diff --git a/libtransmission/variant-common.h b/libtransmission/variant-common.h index d0d8b8bd1..fa9e31d8b 100644 --- a/libtransmission/variant-common.h +++ b/libtransmission/variant-common.h @@ -16,7 +16,7 @@ TR_BEGIN_DECLS -typedef void (* VariantWalkFunc)(tr_variant const* val, void* user_data); +typedef void (*VariantWalkFunc)(tr_variant const* val, void* user_data); struct VariantWalkFuncs { @@ -44,7 +44,11 @@ int tr_jsonParse(char const* source, void const* vbuf, size_t len, tr_variant* s int tr_bencParseInt(void const* buf, void const* bufend, uint8_t const** setme_end, int64_t* setme_val); /** @brief Private function that's exposed here only for unit tests */ -int tr_bencParseStr(void const* buf, void const* bufend, uint8_t const** setme_end, uint8_t const** setme_str, +int tr_bencParseStr( + void const* buf, + void const* bufend, + uint8_t const** setme_end, + uint8_t const** setme_str, size_t* setme_strlen); int tr_variantParseBenc(void const* buf, void const* end, tr_variant* top, char const** setme_end); diff --git a/libtransmission/variant-json.c b/libtransmission/variant-json.c index ddaca77b4..b6e2aac2b 100644 --- a/libtransmission/variant-json.c +++ b/libtransmission/variant-json.c @@ -85,8 +85,12 @@ static void error_handler(jsonsl_t jsn, jsonsl_error_t error, struct jsonsl_stat if (data->source != NULL) { - tr_logAddError("JSON parse failed in %s at pos %zu: %s -- remaining text \"%.16s\"", data->source, jsn->pos, - jsonsl_strerror(error), buf); + tr_logAddError( + "JSON parse failed in %s at pos %zu: %s -- remaining text \"%.16s\"", + data->source, + jsn->pos, + jsonsl_strerror(error), + buf); } else { @@ -161,8 +165,7 @@ static bool decode_hex_string(char const* in, unsigned int* setme) { return false; } - } - while (++in != end); + } while (++in != end); *setme = val; return true; @@ -694,15 +697,14 @@ static void jsonContainerEndFunc(tr_variant const* val, void* vdata) jsonChildFunc(data); } -static struct VariantWalkFuncs const walk_funcs = -{ - jsonIntFunc, - jsonBoolFunc, - jsonRealFunc, - jsonStringFunc, - jsonDictBeginFunc, - jsonListBeginFunc, - jsonContainerEndFunc +static struct VariantWalkFuncs const walk_funcs = { + jsonIntFunc, // + jsonBoolFunc, // + jsonRealFunc, // + jsonStringFunc, // + jsonDictBeginFunc, // + jsonListBeginFunc, // + jsonContainerEndFunc, // }; void tr_variantToBufJson(tr_variant const* top, struct evbuffer* buf, bool lean) diff --git a/libtransmission/variant.c b/libtransmission/variant.c index cfd7dcefe..1f82f4cf1 100644 --- a/libtransmission/variant.c +++ b/libtransmission/variant.c @@ -129,12 +129,11 @@ void tr_variantInit(tr_variant* v, char type) **** ***/ -static struct tr_variant_string const STRING_INIT = -{ +static struct tr_variant_string const STRING_INIT = { .type = TR_STRING_TYPE_QUARK, .quark = TR_KEY_NONE, .len = 0, - .str.str = "" + .str.str = "", }; static void tr_variant_string_clear(struct tr_variant_string* str) @@ -357,17 +356,13 @@ bool tr_variantGetBool(tr_variant const* v, bool* setme) success = true; } - if ((!success) && - tr_variantIsInt(v) && - (v->val.i == 0 || v->val.i == 1)) + if ((!success) && tr_variantIsInt(v) && (v->val.i == 0 || v->val.i == 1)) { *setme = v->val.i != 0; success = true; } - if ((!success) && - tr_variantGetStr(v, &str, NULL) && - (strcmp(str, "true") == 0 || strcmp(str, "false") == 0)) + if ((!success) && tr_variantGetStr(v, &str, NULL) && (strcmp(str, "true") == 0 || strcmp(str, "false") == 0)) { *setme = strcmp(str, "true") == 0; success = true; @@ -957,15 +952,14 @@ static void freeContainerEndFunc(tr_variant const* v, void* user_data) tr_free(v->val.l.vals); } -static struct VariantWalkFuncs const freeWalkFuncs = -{ - freeDummyFunc, - freeDummyFunc, - freeDummyFunc, - freeStringFunc, - freeDummyFunc, - freeDummyFunc, - freeContainerEndFunc +static struct VariantWalkFuncs const freeWalkFuncs = { + freeDummyFunc, // + freeDummyFunc, // + freeDummyFunc, // + freeStringFunc, // + freeDummyFunc, // + freeDummyFunc, // + freeContainerEndFunc, // }; void tr_variantFree(tr_variant* v) @@ -1284,7 +1278,12 @@ bool tr_variantFromFile(tr_variant* setme, tr_variant_fmt fmt, char const* filen return ret; } -int tr_variantFromBuf(tr_variant* setme, tr_variant_fmt fmt, void const* buf, size_t buflen, char const* optional_source, +int tr_variantFromBuf( + tr_variant* setme, + tr_variant_fmt fmt, + void const* buf, + size_t buflen, + char const* optional_source, char const** setme_end) { int err; diff --git a/libtransmission/variant.h b/libtransmission/variant.h index 34f2f62f2..ed5a8cba9 100644 --- a/libtransmission/variant.h +++ b/libtransmission/variant.h @@ -36,8 +36,7 @@ typedef enum TR_STRING_TYPE_QUARK, TR_STRING_TYPE_HEAP, TR_STRING_TYPE_BUF -} -tr_string_type; +} tr_string_type; /* these are PRIVATE IMPLEMENTATION details that should not be touched. * I'll probably change them just to break your code! HA HA HA! @@ -51,8 +50,7 @@ struct tr_variant_string { char buf[16]; char const* str; - } - str; + } str; }; /* these are PRIVATE IMPLEMENTATION details that should not be touched. @@ -93,10 +91,8 @@ typedef struct tr_variant size_t count; struct tr_variant* vals; } l; - } - val; -} -tr_variant; + } val; +} tr_variant; void tr_variantFree(tr_variant*); @@ -109,8 +105,7 @@ typedef enum TR_VARIANT_FMT_BENC, TR_VARIANT_FMT_JSON, TR_VARIANT_FMT_JSON_LEAN /* saves bandwidth by omitting all whitespace. */ -} -tr_variant_fmt; +} tr_variant_fmt; int tr_variantToFile(tr_variant const* variant, tr_variant_fmt fmt, char const* filename); @@ -122,7 +117,12 @@ struct evbuffer* tr_variantToBuf(tr_variant const* variant, tr_variant_fmt fmt); bool tr_variantFromFile(tr_variant* setme, tr_variant_fmt fmt, char const* filename, struct tr_error** error); /* TR_VARIANT_FMT_JSON_LEAN and TR_VARIANT_FMT_JSON are equivalent here. */ -int tr_variantFromBuf(tr_variant* setme, tr_variant_fmt fmt, void const* buf, size_t buflen, char const* optional_source, +int tr_variantFromBuf( + tr_variant* setme, + tr_variant_fmt fmt, + void const* buf, + size_t buflen, + char const* optional_source, char const** setme_end); static inline int tr_variantFromBenc(tr_variant* setme, void const* buf, size_t buflen) @@ -130,13 +130,21 @@ static inline int tr_variantFromBenc(tr_variant* setme, void const* buf, size_t return tr_variantFromBuf(setme, TR_VARIANT_FMT_BENC, buf, buflen, NULL, NULL); } -static inline int tr_variantFromBencFull(tr_variant* setme, void const* buf, size_t buflen, char const* source, +static inline int tr_variantFromBencFull( + tr_variant* setme, + void const* buf, + size_t buflen, + char const* source, char const** setme_end) { return tr_variantFromBuf(setme, TR_VARIANT_FMT_BENC, buf, buflen, source, setme_end); } -static inline int tr_variantFromJsonFull(tr_variant* setme, void const* buf, size_t buflen, char const* source, +static inline int tr_variantFromJsonFull( + tr_variant* setme, + void const* buf, + size_t buflen, + char const* source, char const** setme_end) { return tr_variantFromBuf(setme, TR_VARIANT_FMT_JSON, buf, buflen, source, setme_end); diff --git a/libtransmission/verify.c b/libtransmission/verify.c index 630031a1e..2a1d94215 100644 --- a/libtransmission/verify.c +++ b/libtransmission/verify.c @@ -67,8 +67,8 @@ static bool verifyTorrent(tr_torrent* tor, bool* stopFlag) if (filePos == 0 && fd == TR_BAD_SYS_FILE && fileIndex != prevFileIndex) { char* filename = tr_torrentFindFile(tor, fileIndex); - fd = filename == NULL ? TR_BAD_SYS_FILE : tr_sys_file_open(filename, TR_SYS_FILE_READ | TR_SYS_FILE_SEQUENTIAL, 0, - NULL); + fd = filename == NULL ? TR_BAD_SYS_FILE : + tr_sys_file_open(filename, TR_SYS_FILE_READ | TR_SYS_FILE_SEQUENTIAL, 0, NULL); tr_free(filename); prevFileIndex = fileIndex; } @@ -156,8 +156,12 @@ static bool verifyTorrent(tr_torrent* tor, bool* stopFlag) /* stopwatch */ time_t const end = tr_time(); - tr_logAddTorDbg(tor, "Verification is done. It took %d seconds to verify %" PRIu64 " bytes (%" PRIu64 " bytes per second)", - (int)(end - begin), tor->info.totalSize, (uint64_t)(tor->info.totalSize / (1 + (end - begin)))); + tr_logAddTorDbg( + tor, + "Verification is done. It took %d seconds to verify %" PRIu64 " bytes (%" PRIu64 " bytes per second)", + (int)(end - begin), + tor->info.totalSize, + (uint64_t)(tor->info.totalSize / (1 + (end - begin)))); return changed; } diff --git a/libtransmission/watchdir-common.h b/libtransmission/watchdir-common.h index b1b8e2e8c..34c6dab81 100644 --- a/libtransmission/watchdir-common.h +++ b/libtransmission/watchdir-common.h @@ -16,9 +16,8 @@ struct tr_ptrArray; typedef struct tr_watchdir_backend { - void (* free_func)(struct tr_watchdir_backend*); -} -tr_watchdir_backend; + void (*free_func)(struct tr_watchdir_backend*); +} tr_watchdir_backend; #define BACKEND_DOWNCAST(b) ((tr_watchdir_backend*)(b)) diff --git a/libtransmission/watchdir-generic.c b/libtransmission/watchdir-generic.c index e5dc15baf..c6e5e350c 100644 --- a/libtransmission/watchdir-generic.c +++ b/libtransmission/watchdir-generic.c @@ -24,8 +24,9 @@ **** ***/ -#define log_error(...) (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \ - tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:generic", __VA_ARGS__)) +#define log_error(...) \ + (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \ + tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:generic", __VA_ARGS__)) /*** **** @@ -37,8 +38,7 @@ typedef struct tr_watchdir_generic struct event* event; tr_ptrArray dir_entries; -} -tr_watchdir_generic; +} tr_watchdir_generic; #define BACKEND_UPCAST(b) ((tr_watchdir_generic*)(b)) @@ -89,8 +89,9 @@ tr_watchdir_backend* tr_watchdir_generic_new(tr_watchdir_t handle) backend = tr_new0(tr_watchdir_generic, 1); backend->base.free_func = &tr_watchdir_generic_free; - if ((backend->event = event_new(tr_watchdir_get_event_base(handle), -1, EV_PERSIST, &tr_watchdir_generic_on_event, - handle)) == NULL) + if ((backend + ->event = event_new(tr_watchdir_get_event_base(handle), -1, EV_PERSIST, &tr_watchdir_generic_on_event, handle)) == + NULL) { log_error("Failed to create event: %s", tr_strerror(errno)); goto FAIL; diff --git a/libtransmission/watchdir-inotify.c b/libtransmission/watchdir-inotify.c index 579869510..e89221029 100644 --- a/libtransmission/watchdir-inotify.c +++ b/libtransmission/watchdir-inotify.c @@ -30,8 +30,9 @@ **** ***/ -#define log_error(...) (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \ - tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:inotify", __VA_ARGS__)) +#define log_error(...) \ + (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \ + tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:inotify", __VA_ARGS__)) /*** **** @@ -44,8 +45,7 @@ typedef struct tr_watchdir_inotify int infd; int inwd; struct bufferevent* event; -} -tr_watchdir_inotify; +} tr_watchdir_inotify; #define BACKEND_UPCAST(b) ((tr_watchdir_inotify*)(b)) @@ -188,8 +188,8 @@ tr_watchdir_backend* tr_watchdir_inotify_new(tr_watchdir_t handle) bufferevent_enable(backend->event, EV_READ); /* Perform an initial scan on the directory */ - if (event_base_once(tr_watchdir_get_event_base(handle), -1, EV_TIMEOUT, &tr_watchdir_inotify_on_first_scan, handle, - NULL) == -1) + if (event_base_once(tr_watchdir_get_event_base(handle), -1, EV_TIMEOUT, &tr_watchdir_inotify_on_first_scan, handle, NULL) == + -1) { log_error("Failed to perform initial scan: %s", tr_strerror(errno)); } diff --git a/libtransmission/watchdir-kqueue.c b/libtransmission/watchdir-kqueue.c index a4fe3b4a6..cdad8b6c2 100644 --- a/libtransmission/watchdir-kqueue.c +++ b/libtransmission/watchdir-kqueue.c @@ -35,8 +35,9 @@ **** ***/ -#define log_error(...) (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \ - tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:kqueue", __VA_ARGS__)) +#define log_error(...) \ + (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \ + tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:kqueue", __VA_ARGS__)) /*** **** @@ -50,8 +51,7 @@ typedef struct tr_watchdir_kqueue int dirfd; struct event* event; tr_ptrArray dir_entries; -} -tr_watchdir_kqueue; +} tr_watchdir_kqueue; #define BACKEND_UPCAST(b) ((tr_watchdir_kqueue*)(b)) @@ -147,8 +147,12 @@ tr_watchdir_backend* tr_watchdir_kqueue_new(tr_watchdir_t handle) } /* Create libevent task for event descriptor */ - if ((backend->event = event_new(tr_watchdir_get_event_base(handle), backend->kq, EV_READ | EV_ET | EV_PERSIST, - &tr_watchdir_kqueue_on_event, handle)) == NULL) + if ((backend->event = event_new( + tr_watchdir_get_event_base(handle), + backend->kq, + EV_READ | EV_ET | EV_PERSIST, + &tr_watchdir_kqueue_on_event, + handle)) == NULL) { log_error("Failed to create event: %s", tr_strerror(errno)); goto fail; diff --git a/libtransmission/watchdir-win32.c b/libtransmission/watchdir-win32.c index 93b8c69e8..73d4fc290 100644 --- a/libtransmission/watchdir-win32.c +++ b/libtransmission/watchdir-win32.c @@ -32,8 +32,9 @@ **** ***/ -#define log_error(...) (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \ - tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:win32", __VA_ARGS__)) +#define log_error(...) \ + (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \ + tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:win32", __VA_ARGS__)) /*** **** @@ -49,8 +50,7 @@ typedef struct tr_watchdir_win32 evutil_socket_t notify_pipe[2]; struct bufferevent* event; HANDLE thread; -} -tr_watchdir_win32; +} tr_watchdir_win32; #define BACKEND_UPCAST(b) ((tr_watchdir_win32*)(b)) @@ -60,10 +60,14 @@ tr_watchdir_win32; **** ***/ -static BOOL tr_get_overlapped_result_ex(HANDLE handle, LPOVERLAPPED overlapped, LPDWORD bytes_transferred, DWORD timeout, +static BOOL tr_get_overlapped_result_ex( + HANDLE handle, + LPOVERLAPPED overlapped, + LPDWORD bytes_transferred, + DWORD timeout, BOOL alertable) { - typedef BOOL (WINAPI* impl_t)(HANDLE, LPOVERLAPPED, LPDWORD, DWORD, BOOL); + typedef BOOL(WINAPI * impl_t)(HANDLE, LPOVERLAPPED, LPDWORD, DWORD, BOOL); static impl_t real_impl = NULL; static bool is_real_impl_valid = false; @@ -116,8 +120,15 @@ static unsigned int __stdcall tr_watchdir_win32_thread(void* context) send(backend->notify_pipe[1], (char const*)backend->buffer, bytes_transferred, 0); - if (!ReadDirectoryChangesW(backend->fd, backend->buffer, sizeof(backend->buffer), FALSE, WIN32_WATCH_MASK, NULL, - &backend->overlapped, NULL)) + if (!ReadDirectoryChangesW( + backend->fd, + backend->buffer, + sizeof(backend->buffer), + FALSE, + WIN32_WATCH_MASK, + NULL, + &backend->overlapped, + NULL)) { log_error("Failed to read directory changes"); return 0; @@ -270,8 +281,14 @@ tr_watchdir_backend* tr_watchdir_win32_new(tr_watchdir_t handle) goto fail; } - if ((backend->fd = CreateFileW(wide_path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, - OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL)) == INVALID_HANDLE_VALUE) + if ((backend->fd = CreateFileW( + wide_path, + FILE_LIST_DIRECTORY, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, + NULL)) == INVALID_HANDLE_VALUE) { log_error("Failed to open directory \"%s\"", path); goto fail; @@ -282,8 +299,15 @@ tr_watchdir_backend* tr_watchdir_win32_new(tr_watchdir_t handle) backend->overlapped.Pointer = handle; - if (!ReadDirectoryChangesW(backend->fd, backend->buffer, sizeof(backend->buffer), FALSE, WIN32_WATCH_MASK, NULL, - &backend->overlapped, NULL)) + if (!ReadDirectoryChangesW( + backend->fd, + backend->buffer, + sizeof(backend->buffer), + FALSE, + WIN32_WATCH_MASK, + NULL, + &backend->overlapped, + NULL)) { log_error("Failed to read directory changes"); goto fail; @@ -312,8 +336,8 @@ tr_watchdir_backend* tr_watchdir_win32_new(tr_watchdir_t handle) } /* Perform an initial scan on the directory */ - if (event_base_once(tr_watchdir_get_event_base(handle), -1, EV_TIMEOUT, &tr_watchdir_win32_on_first_scan, handle, - NULL) == -1) + if (event_base_once(tr_watchdir_get_event_base(handle), -1, EV_TIMEOUT, &tr_watchdir_win32_on_first_scan, handle, NULL) == + -1) { log_error("Failed to perform initial scan: %s", tr_strerror(errno)); } diff --git a/libtransmission/watchdir.c b/libtransmission/watchdir.c index b7b7ad35a..ff2599801 100644 --- a/libtransmission/watchdir.c +++ b/libtransmission/watchdir.c @@ -28,11 +28,11 @@ **** ***/ -#define log_debug(...) (!tr_logLevelIsActive(TR_LOG_DEBUG) ? (void)0 : \ - tr_logAddMessage(__FILE__, __LINE__, TR_LOG_DEBUG, "watchdir", __VA_ARGS__)) +#define log_debug(...) \ + (!tr_logLevelIsActive(TR_LOG_DEBUG) ? (void)0 : tr_logAddMessage(__FILE__, __LINE__, TR_LOG_DEBUG, "watchdir", __VA_ARGS__)) -#define log_error(...) (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \ - tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir", __VA_ARGS__)) +#define log_error(...) \ + (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir", __VA_ARGS__)) /*** **** @@ -120,8 +120,7 @@ typedef struct tr_watchdir_retry unsigned int counter; struct event* timer; struct timeval interval; -} -tr_watchdir_retry; +} tr_watchdir_retry; /* Non-static and mutable for unit tests */ unsigned int tr_watchdir_retry_limit = 3; @@ -129,7 +128,7 @@ struct timeval tr_watchdir_retry_start_interval = { .tv_sec = 1, .tv_usec = 0 }; struct timeval tr_watchdir_retry_max_interval = { .tv_sec = 10, .tv_usec = 0 }; #define tr_watchdir_retries_init(r) (void)0 -#define tr_watchdir_retries_destroy(r) tr_ptrArrayDestruct((r), (PtrArrayForeachFunc) & tr_watchdir_retry_free) +#define tr_watchdir_retries_destroy(r) tr_ptrArrayDestruct((r), (PtrArrayForeachFunc)&tr_watchdir_retry_free) #define tr_watchdir_retries_insert(r, v) tr_ptrArrayInsertSorted((r), (v), &compare_retry_names) #define tr_watchdir_retries_remove(r, v) tr_ptrArrayRemoveSortedPointer((r), (v), &compare_retry_names) #define tr_watchdir_retries_find(r, v) tr_ptrArrayFindSorted((r), (v), &compare_retry_names) @@ -222,8 +221,12 @@ static void tr_watchdir_retry_restart(tr_watchdir_retry* retry) **** ***/ -tr_watchdir_t tr_watchdir_new(char const* path, tr_watchdir_cb callback, void* callback_user_data, - struct event_base* event_base, bool force_generic) +tr_watchdir_t tr_watchdir_new( + char const* path, + tr_watchdir_cb callback, + void* callback_user_data, + struct event_base* event_base, + bool force_generic) { tr_watchdir_t handle; diff --git a/libtransmission/watchdir.h b/libtransmission/watchdir.h index 3a5703c79..af71de437 100644 --- a/libtransmission/watchdir.h +++ b/libtransmission/watchdir.h @@ -21,15 +21,18 @@ typedef enum TR_WATCHDIR_ACCEPT, TR_WATCHDIR_IGNORE, TR_WATCHDIR_RETRY -} -tr_watchdir_status; +} tr_watchdir_status; -typedef tr_watchdir_status (* tr_watchdir_cb)(tr_watchdir_t handle, char const* name, void* user_data); +typedef tr_watchdir_status (*tr_watchdir_cb)(tr_watchdir_t handle, char const* name, void* user_data); /* ... */ -tr_watchdir_t tr_watchdir_new(char const* path, tr_watchdir_cb callback, void* callback_user_data, - struct event_base* event_base, bool force_generic); +tr_watchdir_t tr_watchdir_new( + char const* path, + tr_watchdir_cb callback, + void* callback_user_data, + struct event_base* event_base, + bool force_generic); void tr_watchdir_free(tr_watchdir_t handle); diff --git a/libtransmission/web.c b/libtransmission/web.c index 6dbee276c..4ef55ef38 100644 --- a/libtransmission/web.c +++ b/libtransmission/web.c @@ -173,10 +173,9 @@ static CURLcode ssl_context_func(CURL* curl, void* ssl_ctx, void* user_data) return CURLE_OK; } - static LPCWSTR const sys_store_names[] = - { + static LPCWSTR const sys_store_names[] = { L"CA", - L"ROOT" + L"ROOT", }; for (size_t i = 0; i < TR_N_ELEMENTS(sys_store_names); ++i) @@ -325,8 +324,14 @@ static void task_finish_func(void* vtask) if (task->done_func != NULL) { - (*task->done_func)(task->session, task->did_connect, task->did_timeout, task->code, evbuffer_pullup(task->response, -1), - evbuffer_get_length(task->response), task->done_func_user_data); + (*task->done_func)( + task->session, + task->did_connect, + task->did_timeout, + task->code, + evbuffer_pullup(task->response, -1), + evbuffer_get_length(task->response), + task->done_func_user_data); } task_free(task); @@ -338,8 +343,14 @@ static void task_finish_func(void* vtask) static void tr_webThreadFunc(void* vsession); -static struct tr_web_task* tr_webRunImpl(tr_session* session, int torrentId, char const* url, char const* range, - char const* cookies, tr_web_done_func done_func, void* done_func_user_data, +static struct tr_web_task* tr_webRunImpl( + tr_session* session, + int torrentId, + char const* url, + char const* range, + char const* cookies, + tr_web_done_func done_func, + void* done_func_user_data, struct evbuffer* buffer) { struct tr_web_task* task = NULL; @@ -376,7 +387,11 @@ static struct tr_web_task* tr_webRunImpl(tr_session* session, int torrentId, cha return task; } -struct tr_web_task* tr_webRunWithCookies(tr_session* session, char const* url, char const* cookies, tr_web_done_func done_func, +struct tr_web_task* tr_webRunWithCookies( + tr_session* session, + char const* url, + char const* cookies, + tr_web_done_func done_func, void* done_func_user_data) { return tr_webRunImpl(session, -1, url, NULL, cookies, done_func, done_func_user_data, NULL); @@ -387,8 +402,13 @@ struct tr_web_task* tr_webRun(tr_session* session, char const* url, tr_web_done_ return tr_webRunWithCookies(session, url, NULL, done_func, done_func_user_data); } -struct tr_web_task* tr_webRunWebseed(tr_torrent* tor, char const* url, char const* range, tr_web_done_func done_func, - void* done_func_user_data, struct evbuffer* buffer) +struct tr_web_task* tr_webRunWebseed( + tr_torrent* tor, + char const* url, + char const* range, + tr_web_done_func done_func, + void* done_func_user_data, + struct evbuffer* buffer) { return tr_webRunImpl(tor->session, tr_torrentId(tor), url, range, NULL, done_func, done_func_user_data, buffer); } @@ -419,7 +439,9 @@ static void tr_webThreadFunc(void* vsession) if (web->curl_ssl_verify) { - tr_logAddNamedInfo("web", "will verify tracker certs using envvar CURL_CA_BUNDLE: %s", + tr_logAddNamedInfo( + "web", + "will verify tracker certs using envvar CURL_CA_BUNDLE: %s", web->curl_ca_bundle == NULL ? "none" : web->curl_ca_bundle); tr_logAddNamedInfo("web", "NB: this only works if you built against libcurl with openssl or gnutls, NOT nss"); tr_logAddNamedInfo("web", "NB: invalid certs will show up as 'Could not connect to tracker' like many other errors"); @@ -532,8 +554,7 @@ static void tr_webThreadFunc(void* vsession) do { mcode = curl_multi_perform(multi, &unused); - } - while (mcode == CURLM_CALL_MULTI_PERFORM); + } while (mcode == CURLM_CALL_MULTI_PERFORM); /* pump completed tasks from the multi */ while ((msg = curl_multi_info_read(multi, &unused)) != NULL) diff --git a/libtransmission/web.h b/libtransmission/web.h index 6cf6d9b5a..96303ef37 100644 --- a/libtransmission/web.h +++ b/libtransmission/web.h @@ -19,25 +19,39 @@ typedef enum { TR_WEB_CLOSE_WHEN_IDLE, TR_WEB_CLOSE_NOW -} -tr_web_close_mode; +} tr_web_close_mode; void tr_webClose(tr_session* session, tr_web_close_mode close_mode); -typedef void (* tr_web_done_func)(tr_session* session, bool did_connect_flag, bool timeout_flag, long response_code, - void const* response, size_t response_byte_count, void* user_data); +typedef void (*tr_web_done_func)( + tr_session* session, + bool did_connect_flag, + bool timeout_flag, + long response_code, + void const* response, + size_t response_byte_count, + void* user_data); char const* tr_webGetResponseStr(long response_code); struct tr_web_task* tr_webRun(tr_session* session, char const* url, tr_web_done_func done_func, void* done_func_user_data); -struct tr_web_task* tr_webRunWithCookies(tr_session* session, char const* url, char const* cookies, tr_web_done_func done_func, +struct tr_web_task* tr_webRunWithCookies( + tr_session* session, + char const* url, + char const* cookies, + tr_web_done_func done_func, void* done_func_user_data); struct evbuffer; -struct tr_web_task* tr_webRunWebseed(tr_torrent* tor, char const* url, char const* range, tr_web_done_func done_func, - void* done_func_user_data, struct evbuffer* buffer); +struct tr_web_task* tr_webRunWebseed( + tr_torrent* tor, + char const* url, + char const* range, + tr_web_done_func done_func, + void* done_func_user_data, + struct evbuffer* buffer); long tr_webGetTaskResponseCode(struct tr_web_task* task); diff --git a/libtransmission/webseed.c b/libtransmission/webseed.c index 779258472..8b14f755a 100644 --- a/libtransmission/webseed.c +++ b/libtransmission/webseed.c @@ -356,8 +356,14 @@ static void on_idle(tr_webseed* w) } } -static void web_response_func(tr_session* session, bool did_connect, bool did_timeout, long response_code, void const* response, - size_t response_byte_count, void* vtask) +static void web_response_func( + tr_session* session, + bool did_connect, + bool did_timeout, + long response_code, + void const* response, + size_t response_byte_count, + void* vtask) { TR_UNUSED(did_connect); TR_UNUSED(did_timeout); @@ -578,10 +584,9 @@ static void webseed_destruct(tr_peer* peer) tr_peerDestruct(&w->parent); } -static struct tr_peer_virtual_funcs const my_funcs = -{ +static struct tr_peer_virtual_funcs const my_funcs = { .destruct = webseed_destruct, - .is_transferring_pieces = webseed_is_transferring_pieces + .is_transferring_pieces = webseed_is_transferring_pieces, }; /*** diff --git a/macosx/AboutWindowController.h b/macosx/AboutWindowController.h index b264569b0..633c22d42 100644 --- a/macosx/AboutWindowController.h +++ b/macosx/AboutWindowController.h @@ -24,15 +24,18 @@ @interface AboutWindowController : NSWindowController { - IBOutlet NSTextView * fTextView, * fLicenseView; - IBOutlet NSTextField * fVersionField, * fCopyrightField; - IBOutlet NSButton * fLicenseButton, * fLicenseCloseButton; - IBOutlet NSPanel * fLicenseSheet; + IBOutlet NSTextView* fTextView; + IBOutlet NSTextView* fLicenseView; + IBOutlet NSTextField* fVersionField; + IBOutlet NSTextField* fCopyrightField; + IBOutlet NSButton* fLicenseButton; + IBOutlet NSButton* fLicenseCloseButton; + IBOutlet NSPanel* fLicenseSheet; } -@property (nonatomic, class, readonly) AboutWindowController * aboutController; +@property(nonatomic, class, readonly) AboutWindowController* aboutController; -- (IBAction) showLicense: (id) sender; -- (IBAction) hideLicense: (id) sender; +- (IBAction)showLicense:(id)sender; +- (IBAction)hideLicense:(id)sender; @end diff --git a/macosx/AboutWindowController.m b/macosx/AboutWindowController.m index 8f2af4ad6..51118a5bc 100644 --- a/macosx/AboutWindowController.m +++ b/macosx/AboutWindowController.m @@ -26,26 +26,30 @@ @implementation AboutWindowController -AboutWindowController * fAboutBoxInstance = nil; -+ (AboutWindowController *) aboutController +AboutWindowController* fAboutBoxInstance = nil; + ++ (AboutWindowController*)aboutController { if (!fAboutBoxInstance) - fAboutBoxInstance = [[self alloc] initWithWindowNibName: @"AboutWindow"]; + { + fAboutBoxInstance = [[self alloc] initWithWindowNibName:@"AboutWindow"]; + } return fAboutBoxInstance; } -- (void) awakeFromNib +- (void)awakeFromNib { fVersionField.stringValue = @(LONG_VERSION_STRING); - fCopyrightField.stringValue = [NSBundle.mainBundle localizedStringForKey: @"NSHumanReadableCopyright" - value: nil table: @"InfoPlist"]; + fCopyrightField.stringValue = [NSBundle.mainBundle localizedStringForKey:@"NSHumanReadableCopyright" value:nil + table:@"InfoPlist"]; - [fTextView.textStorage setAttributedString: [[NSAttributedString alloc] initWithPath: - [NSBundle.mainBundle pathForResource: @"Credits" ofType: @"rtf"] documentAttributes: nil]]; + [fTextView.textStorage setAttributedString:[[NSAttributedString alloc] initWithPath:[NSBundle.mainBundle pathForResource:@"Credits" + ofType:@"rtf"] + documentAttributes:nil]]; //size license button - const CGFloat oldButtonWidth = NSWidth(fLicenseButton.frame); + CGFloat const oldButtonWidth = NSWidth(fLicenseButton.frame); fLicenseButton.title = NSLocalizedString(@"License", "About window -> license button"); [fLicenseButton sizeToFit]; @@ -56,30 +60,31 @@ AboutWindowController * fAboutBoxInstance = nil; fLicenseButton.frame = buttonFrame; } -- (void) windowDidLoad +- (void)windowDidLoad { [self.window center]; } -- (void) windowWillClose: (id) sender +- (void)windowWillClose:(id)sender { fAboutBoxInstance = nil; } -- (IBAction) showLicense: (id) sender +- (IBAction)showLicense:(id)sender { - NSString * licenseText = [NSString stringWithContentsOfFile: [NSBundle.mainBundle pathForResource: @"COPYING" ofType: nil] - usedEncoding: nil error: NULL]; + NSString* licenseText = [NSString stringWithContentsOfFile:[NSBundle.mainBundle pathForResource:@"COPYING" ofType:nil] + usedEncoding:nil + error:NULL]; fLicenseView.string = licenseText; fLicenseCloseButton.title = NSLocalizedString(@"OK", "About window -> license close button"); - [self.window beginSheet: fLicenseSheet completionHandler:nil]; + [self.window beginSheet:fLicenseSheet completionHandler:nil]; } -- (IBAction) hideLicense: (id) sender +- (IBAction)hideLicense:(id)sender { - [fLicenseSheet orderOut: nil]; - [NSApp endSheet: fLicenseSheet]; + [fLicenseSheet orderOut:nil]; + [NSApp endSheet:fLicenseSheet]; } @end diff --git a/macosx/AddMagnetWindowController.h b/macosx/AddMagnetWindowController.h index 1fad103a3..c177633f4 100644 --- a/macosx/AddMagnetWindowController.h +++ b/macosx/AddMagnetWindowController.h @@ -29,38 +29,43 @@ @interface AddMagnetWindowController : NSWindowController { - IBOutlet NSImageView * fLocationImageView; - IBOutlet NSTextField * fNameField, * fLocationField; - IBOutlet NSButton * fStartCheck; - IBOutlet NSPopUpButton * fGroupPopUp, * fPriorityPopUp; + IBOutlet NSImageView* fLocationImageView; + IBOutlet NSTextField* fNameField; + IBOutlet NSTextField* fLocationField; + IBOutlet NSButton* fStartCheck; + IBOutlet NSPopUpButton* fGroupPopUp; + IBOutlet NSPopUpButton* fPriorityPopUp; //remove these when switching to auto layout - IBOutlet NSTextField * fMagnetLinkLabel; - IBOutlet NSTextField * fDownloadToLabel, * fGroupLabel, * fPriorityLabel; - IBOutlet NSButton * fChangeDestinationButton; - IBOutlet NSBox * fDownloadToBox; - IBOutlet NSButton * fAddButton, * fCancelButton; + IBOutlet NSTextField* fMagnetLinkLabel; + IBOutlet NSTextField* fDownloadToLabel; + IBOutlet NSTextField* fGroupLabel; + IBOutlet NSTextField* fPriorityLabel; + IBOutlet NSButton* fChangeDestinationButton; + IBOutlet NSBox* fDownloadToBox; + IBOutlet NSButton* fAddButton; + IBOutlet NSButton* fCancelButton; - Controller * fController; + Controller* fController; - Torrent * fTorrent; - NSString * fDestination; + Torrent* fTorrent; + NSString* fDestination; NSInteger fGroupValue; TorrentDeterminationType fGroupDeterminationType; } -- (instancetype) initWithTorrent: (Torrent *) torrent destination: (NSString *) path controller: (Controller *) controller; +- (instancetype)initWithTorrent:(Torrent*)torrent destination:(NSString*)path controller:(Controller*)controller; -@property (nonatomic, readonly) Torrent *torrent; +@property(nonatomic, readonly) Torrent* torrent; -- (void) setDestination: (id) sender; +- (void)setDestination:(id)sender; -- (void) add: (id) sender; -- (void) cancelAdd: (id) sender; +- (void)add:(id)sender; +- (void)cancelAdd:(id)sender; -- (void) changePriority: (id) sender; +- (void)changePriority:(id)sender; -- (void) updateGroupMenu: (NSNotification *) notification; +- (void)updateGroupMenu:(NSNotification*)notification; @end diff --git a/macosx/AddMagnetWindowController.m b/macosx/AddMagnetWindowController.m index 4951b2037..26dc1836f 100644 --- a/macosx/AddMagnetWindowController.m +++ b/macosx/AddMagnetWindowController.m @@ -33,20 +33,20 @@ @interface AddMagnetWindowController (Private) -- (void) confirmAdd; +- (void)confirmAdd; -- (void) setDestinationPath: (NSString *) destination determinationType: (TorrentDeterminationType) determinationType; +- (void)setDestinationPath:(NSString*)destination determinationType:(TorrentDeterminationType)determinationType; -- (void) setGroupsMenu; -- (void) changeGroupValue: (id) sender; +- (void)setGroupsMenu; +- (void)changeGroupValue:(id)sender; @end @implementation AddMagnetWindowController -- (instancetype) initWithTorrent: (Torrent *) torrent destination: (NSString *) path controller: (Controller *) controller +- (instancetype)initWithTorrent:(Torrent*)torrent destination:(NSString*)path controller:(Controller*)controller { - if ((self = [super initWithWindowNibName: @"AddMagnetWindow"])) + if ((self = [super initWithWindowNibName:@"AddMagnetWindow"])) { fTorrent = torrent; fDestination = path.stringByExpandingTildeInPath; @@ -59,61 +59,69 @@ return self; } -- (void) awakeFromNib +- (void)awakeFromNib { - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateGroupMenu:) - name: @"UpdateGroups" object: nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateGroupMenu:) name:@"UpdateGroups" object:nil]; - NSString * name = fTorrent.name; + NSString* name = fTorrent.name; self.window.title = name; fNameField.stringValue = name; fNameField.toolTip = name; [self setGroupsMenu]; - [fGroupPopUp selectItemWithTag: fGroupValue]; + [fGroupPopUp selectItemWithTag:fGroupValue]; NSInteger priorityIndex; switch (fTorrent.priority) { - case TR_PRI_HIGH: priorityIndex = POPUP_PRIORITY_HIGH; break; - case TR_PRI_NORMAL: priorityIndex = POPUP_PRIORITY_NORMAL; break; - case TR_PRI_LOW: priorityIndex = POPUP_PRIORITY_LOW; break; - default: - NSAssert1(NO, @"Unknown priority for adding torrent: %d", fTorrent.priority); - priorityIndex = POPUP_PRIORITY_NORMAL; + case TR_PRI_HIGH: + priorityIndex = POPUP_PRIORITY_HIGH; + break; + case TR_PRI_NORMAL: + priorityIndex = POPUP_PRIORITY_NORMAL; + break; + case TR_PRI_LOW: + priorityIndex = POPUP_PRIORITY_LOW; + break; + default: + NSAssert1(NO, @"Unknown priority for adding torrent: %d", fTorrent.priority); + priorityIndex = POPUP_PRIORITY_NORMAL; } - [fPriorityPopUp selectItemAtIndex: priorityIndex]; + [fPriorityPopUp selectItemAtIndex:priorityIndex]; - fStartCheck.state = [NSUserDefaults.standardUserDefaults boolForKey: @"AutoStartDownload"] ? NSOnState : NSOffState; + fStartCheck.state = [NSUserDefaults.standardUserDefaults boolForKey:@"AutoStartDownload"] ? NSOnState : NSOffState; if (fDestination) - [self setDestinationPath: fDestination determinationType: TorrentDeterminationAutomatic]; + { + [self setDestinationPath:fDestination determinationType:TorrentDeterminationAutomatic]; + } else { fLocationField.stringValue = @""; fLocationImageView.image = nil; } - #warning when 10.7-only, switch to auto layout +#warning when 10.7-only, switch to auto layout [fMagnetLinkLabel sizeToFit]; - const CGFloat downloadToLabelOldWidth = fDownloadToLabel.frame.size.width; + CGFloat const downloadToLabelOldWidth = fDownloadToLabel.frame.size.width; [fDownloadToLabel sizeToFit]; - const CGFloat changeDestOldWidth = fChangeDestinationButton.frame.size.width; + CGFloat const changeDestOldWidth = fChangeDestinationButton.frame.size.width; [fChangeDestinationButton sizeToFit]; NSRect changeDestFrame = fChangeDestinationButton.frame; changeDestFrame.origin.x -= changeDestFrame.size.width - changeDestOldWidth; fChangeDestinationButton.frame = changeDestFrame; NSRect downloadToBoxFrame = fDownloadToBox.frame; - const CGFloat downloadToBoxSizeDiff = (fDownloadToLabel.frame.size.width - downloadToLabelOldWidth) + (changeDestFrame.size.width - changeDestOldWidth); + CGFloat const downloadToBoxSizeDiff = (fDownloadToLabel.frame.size.width - downloadToLabelOldWidth) + + (changeDestFrame.size.width - changeDestOldWidth); downloadToBoxFrame.size.width -= downloadToBoxSizeDiff; downloadToBoxFrame.origin.x -= downloadToLabelOldWidth - fDownloadToLabel.frame.size.width; fDownloadToBox.frame = downloadToBoxFrame; NSRect groupPopUpFrame = fGroupPopUp.frame; NSRect priorityPopUpFrame = fPriorityPopUp.frame; - const CGFloat popUpOffset = groupPopUpFrame.origin.x - NSMaxX(fGroupLabel.frame); + CGFloat const popUpOffset = groupPopUpFrame.origin.x - NSMaxX(fGroupLabel.frame); [fGroupLabel sizeToFit]; [fPriorityLabel sizeToFit]; NSRect groupLabelFrame = fGroupLabel.frame; @@ -122,7 +130,7 @@ groupLabelFrame.origin.x = MIN(groupLabelFrame.origin.x, priorityLabelFrame.origin.x); priorityLabelFrame.origin.x = MIN(groupLabelFrame.origin.x, priorityLabelFrame.origin.x); //then align on the right - const CGFloat labelWidth = MAX(groupLabelFrame.size.width, priorityLabelFrame.size.width); + CGFloat const labelWidth = MAX(groupLabelFrame.size.width, priorityLabelFrame.size.width); groupLabelFrame.origin.x += labelWidth - groupLabelFrame.size.width; priorityLabelFrame.origin.x += labelWidth - priorityLabelFrame.size.width; groupPopUpFrame.origin.x = NSMaxX(groupLabelFrame) + popUpOffset; @@ -132,9 +140,9 @@ fPriorityLabel.frame = priorityLabelFrame; fPriorityPopUp.frame = priorityPopUpFrame; - const CGFloat minButtonWidth = 82.0; - const CGFloat oldAddButtonWidth = fAddButton.bounds.size.width; - const CGFloat oldCancelButtonWidth = fCancelButton.bounds.size.width; + CGFloat const minButtonWidth = 82.0; + CGFloat const oldAddButtonWidth = fAddButton.bounds.size.width; + CGFloat const oldCancelButtonWidth = fCancelButton.bounds.size.width; [fAddButton sizeToFit]; [fCancelButton sizeToFit]; NSRect addButtonFrame = fAddButton.frame; @@ -143,7 +151,7 @@ buttonWidth = MAX(buttonWidth, minButtonWidth); addButtonFrame.size.width = buttonWidth; cancelButtonFrame.size.width = buttonWidth; - const CGFloat addButtonWidthIncrease = buttonWidth - oldAddButtonWidth; + CGFloat const addButtonWidthIncrease = buttonWidth - oldAddButtonWidth; addButtonFrame.origin.x -= addButtonWidthIncrease; cancelButtonFrame.origin.x -= addButtonWidthIncrease + (buttonWidth - oldCancelButtonWidth); fAddButton.frame = addButtonFrame; @@ -152,26 +160,28 @@ [fStartCheck sizeToFit]; } -- (void) windowDidLoad +- (void)windowDidLoad { //if there is no destination, prompt for one right away if (!fDestination) - [self setDestination: nil]; + { + [self setDestination:nil]; + } } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; } -- (Torrent *) torrent +- (Torrent*)torrent { return fTorrent; } -- (void) setDestination: (id) sender +- (void)setDestination:(id)sender { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; panel.prompt = NSLocalizedString(@"Select", "Open torrent -> prompt"); panel.allowsMultipleSelection = NO; @@ -179,82 +189,99 @@ panel.canChooseDirectories = YES; panel.canCreateDirectories = YES; - panel.message = [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"", - "Add -> select destination folder"), fTorrent.name]; + panel.message = [NSString stringWithFormat:NSLocalizedString(@"Select the download folder for \"%@\"", "Add -> select destination folder"), + fTorrent.name]; - [panel beginSheetModalForWindow: self.window completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) - [self setDestinationPath: panel.URLs[0].path determinationType:TorrentDeterminationUserSpecified]; + { + [self setDestinationPath:panel.URLs[0].path determinationType:TorrentDeterminationUserSpecified]; + } else { if (!fDestination) - [self performSelectorOnMainThread: @selector(cancelAdd:) withObject: nil waitUntilDone: NO]; + { + [self performSelectorOnMainThread:@selector(cancelAdd:) withObject:nil waitUntilDone:NO]; + } } }]; } -- (void) add: (id) sender +- (void)add:(id)sender { - if ([fDestination.lastPathComponent isEqualToString: fTorrent.name] - && [NSUserDefaults.standardUserDefaults boolForKey: @"WarningFolderDataSameName"]) + if ([fDestination.lastPathComponent isEqualToString:fTorrent.name] && + [NSUserDefaults.standardUserDefaults boolForKey:@"WarningFolderDataSameName"]) { - NSAlert * alert = [[NSAlert alloc] init]; - alert.messageText = NSLocalizedString(@"The destination directory and root data directory have the same name.", - "Add torrent -> same name -> title"); - alert.informativeText = NSLocalizedString(@"If you are attempting to use already existing data," - " the root data directory should be inside the destination directory.", "Add torrent -> same name -> message"); + NSAlert* alert = [[NSAlert alloc] init]; + alert.messageText = NSLocalizedString(@"The destination directory and root data directory have the same name.", "Add torrent -> same name -> title"); + alert.informativeText = NSLocalizedString( + @"If you are attempting to use already existing data," + " the root data directory should be inside the destination directory.", + "Add torrent -> same name -> message"); alert.alertStyle = NSWarningAlertStyle; - [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Add torrent -> same name -> button")]; - [alert addButtonWithTitle: NSLocalizedString(@"Add", "Add torrent -> same name -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Cancel", "Add torrent -> same name -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Add", "Add torrent -> same name -> button")]; alert.showsSuppressionButton = YES; [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { if (alert.suppressionButton.state == NSOnState) - [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningFolderDataSameName"]; + { + [NSUserDefaults.standardUserDefaults setBool:NO forKey:@"WarningFolderDataSameName"]; + } if (returnCode == NSAlertSecondButtonReturn) - [self performSelectorOnMainThread: @selector(confirmAdd) withObject: nil waitUntilDone: NO]; + { + [self performSelectorOnMainThread:@selector(confirmAdd) withObject:nil waitUntilDone:NO]; + } }]; } else + { [self confirmAdd]; + } } -- (void) cancelAdd: (id) sender +- (void)cancelAdd:(id)sender { - [self.window performClose: sender]; + [self.window performClose:sender]; } //only called on cancel -- (BOOL) windowShouldClose: (id) window +- (BOOL)windowShouldClose:(id)window { - [fController askOpenMagnetConfirmed: self add: NO]; + [fController askOpenMagnetConfirmed:self add:NO]; return YES; } -- (void) changePriority: (id) sender +- (void)changePriority:(id)sender { tr_priority_t priority; switch ([sender indexOfSelectedItem]) { - case POPUP_PRIORITY_HIGH: priority = TR_PRI_HIGH; break; - case POPUP_PRIORITY_NORMAL: priority = TR_PRI_NORMAL; break; - case POPUP_PRIORITY_LOW: priority = TR_PRI_LOW; break; - default: - NSAssert1(NO, @"Unknown priority tag for adding torrent: %ld", [sender tag]); - priority = TR_PRI_NORMAL; + case POPUP_PRIORITY_HIGH: + priority = TR_PRI_HIGH; + break; + case POPUP_PRIORITY_NORMAL: + priority = TR_PRI_NORMAL; + break; + case POPUP_PRIORITY_LOW: + priority = TR_PRI_LOW; + break; + default: + NSAssert1(NO, @"Unknown priority tag for adding torrent: %ld", [sender tag]); + priority = TR_PRI_NORMAL; } fTorrent.priority = priority; } -- (void) updateGroupMenu: (NSNotification *) notification +- (void)updateGroupMenu:(NSNotification*)notification { [self setGroupsMenu]; - if (![fGroupPopUp selectItemWithTag: fGroupValue]) + if (![fGroupPopUp selectItemWithTag:fGroupValue]) { fGroupValue = -1; fGroupDeterminationType = TorrentDeterminationAutomatic; - [fGroupPopUp selectItemWithTag: fGroupValue]; + [fGroupPopUp selectItemWithTag:fGroupValue]; } } @@ -262,51 +289,58 @@ @implementation AddMagnetWindowController (Private) -- (void) confirmAdd +- (void)confirmAdd { - [fTorrent setGroupValue: fGroupValue determinationType: fGroupDeterminationType]; + [fTorrent setGroupValue:fGroupValue determinationType:fGroupDeterminationType]; if (fStartCheck.state == NSOnState) + { [fTorrent startTransfer]; + } [self close]; - [fController askOpenMagnetConfirmed: self add: YES]; + [fController askOpenMagnetConfirmed:self add:YES]; } -- (void) setDestinationPath: (NSString *) destination determinationType: (TorrentDeterminationType) determinationType +- (void)setDestinationPath:(NSString*)destination determinationType:(TorrentDeterminationType)determinationType { destination = destination.stringByExpandingTildeInPath; - if (!fDestination || ![fDestination isEqualToString: destination]) + if (!fDestination || ![fDestination isEqualToString:destination]) { fDestination = destination; - [fTorrent changeDownloadFolderBeforeUsing: fDestination determinationType: determinationType]; + [fTorrent changeDownloadFolderBeforeUsing:fDestination determinationType:determinationType]; } fLocationField.stringValue = fDestination.stringByAbbreviatingWithTildeInPath; fLocationField.toolTip = fDestination; - ExpandedPathToIconTransformer * iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; - fLocationImageView.image = [iconTransformer transformedValue: fDestination]; + ExpandedPathToIconTransformer* iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; + fLocationImageView.image = [iconTransformer transformedValue:fDestination]; } -- (void) setGroupsMenu +- (void)setGroupsMenu { - NSMenu * groupMenu = [GroupsController.groups groupMenuWithTarget: self action: @selector(changeGroupValue:) isSmall: NO]; + NSMenu* groupMenu = [GroupsController.groups groupMenuWithTarget:self action:@selector(changeGroupValue:) isSmall:NO]; fGroupPopUp.menu = groupMenu; } -- (void) changeGroupValue: (id) sender +- (void)changeGroupValue:(id)sender { NSInteger previousGroup = fGroupValue; fGroupValue = [sender tag]; fGroupDeterminationType = TorrentDeterminationUserSpecified; - if ([GroupsController.groups usesCustomDownloadLocationForIndex: fGroupValue]) - [self setDestinationPath: [GroupsController.groups customDownloadLocationForIndex: fGroupValue] determinationType: TorrentDeterminationAutomatic]; - else if ([fDestination isEqualToString: [GroupsController.groups customDownloadLocationForIndex: previousGroup]]) - [self setDestinationPath: [NSUserDefaults.standardUserDefaults stringForKey: @"DownloadFolder"] determinationType: TorrentDeterminationAutomatic]; - else; + if ([GroupsController.groups usesCustomDownloadLocationForIndex:fGroupValue]) + { + [self setDestinationPath:[GroupsController.groups customDownloadLocationForIndex:fGroupValue] + determinationType:TorrentDeterminationAutomatic]; + } + else if ([fDestination isEqualToString:[GroupsController.groups customDownloadLocationForIndex:previousGroup]]) + { + [self setDestinationPath:[NSUserDefaults.standardUserDefaults stringForKey:@"DownloadFolder"] + determinationType:TorrentDeterminationAutomatic]; + } } @end diff --git a/macosx/AddWindowController.h b/macosx/AddWindowController.h index 0f2f0a40a..10e9fcc4d 100644 --- a/macosx/AddWindowController.h +++ b/macosx/AddWindowController.h @@ -30,53 +30,67 @@ @interface AddWindowController : NSWindowController { - IBOutlet NSImageView * fIconView, * fLocationImageView; - IBOutlet NSTextField * fNameField, * fStatusField, * fLocationField; - IBOutlet NSButton * fStartCheck, * fDeleteCheck; - IBOutlet NSPopUpButton * fGroupPopUp, * fPriorityPopUp; - IBOutlet NSProgressIndicator * fVerifyIndicator; + IBOutlet NSImageView* fIconView; + IBOutlet NSImageView* fLocationImageView; + IBOutlet NSTextField* fNameField; + IBOutlet NSTextField* fStatusField; + IBOutlet NSTextField* fLocationField; + IBOutlet NSButton* fStartCheck; + IBOutlet NSButton* fDeleteCheck; + IBOutlet NSPopUpButton* fGroupPopUp; + IBOutlet NSPopUpButton* fPriorityPopUp; + IBOutlet NSProgressIndicator* fVerifyIndicator; - IBOutlet NSTextField * fFileFilterField; - IBOutlet NSButton * fCheckAllButton, *fUncheckAllButton; + IBOutlet NSTextField* fFileFilterField; + IBOutlet NSButton* fCheckAllButton; + IBOutlet NSButton* fUncheckAllButton; - IBOutlet FileOutlineController * fFileController; - IBOutlet NSScrollView * fFileScrollView; + IBOutlet FileOutlineController* fFileController; + IBOutlet NSScrollView* fFileScrollView; - Controller * fController; + Controller* fController; - Torrent * fTorrent; - NSString * fDestination, * fTorrentFile; + Torrent* fTorrent; + NSString* fDestination; + NSString* fTorrentFile; BOOL fLockDestination; - BOOL fDeleteTorrentEnableInitially, fCanToggleDelete; + BOOL fDeleteTorrentEnableInitially; + BOOL fCanToggleDelete; NSInteger fGroupValue; - NSTimer * fTimer; + NSTimer* fTimer; TorrentDeterminationType fGroupValueDetermination; } -- (instancetype) initWithTorrent: (Torrent *) torrent destination: (NSString *) path lockDestination: (BOOL) lockDestination - controller: (Controller *) controller torrentFile: (NSString *) torrentFile - deleteTorrentCheckEnableInitially: (BOOL) deleteTorrent canToggleDelete: (BOOL) canToggleDelete; //if canToggleDelete is NO, we will also not delete the file regardless of the delete check's state (this is so it can be disabled and checked for a downloaded torrent, where the file's already deleted) +// if canToggleDelete is NO, we will also not delete the file regardless of the delete check's state +// (this is so it can be disabled and checked for a downloaded torrent, where the file's already deleted) +- (instancetype)initWithTorrent:(Torrent*)torrent + destination:(NSString*)path + lockDestination:(BOOL)lockDestination + controller:(Controller*)controller + torrentFile:(NSString*)torrentFile + deleteTorrentCheckEnableInitially:(BOOL)deleteTorrent + canToggleDelete:(BOOL)canToggleDelete; -@property (nonatomic, readonly) Torrent *torrent; +@property(nonatomic, readonly) Torrent* torrent; -- (void) setDestination: (id) sender; +- (void)setDestination:(id)sender; -- (void) add: (id) sender; -- (void) cancelAdd: (id) sender; +- (void)add:(id)sender; +- (void)cancelAdd:(id)sender; -- (IBAction) setFileFilterText: (id) sender; -- (IBAction) checkAll: (id) sender; -- (IBAction) uncheckAll: (id) sender; +- (IBAction)setFileFilterText:(id)sender; +- (IBAction)checkAll:(id)sender; +- (IBAction)uncheckAll:(id)sender; -- (void) verifyLocalData: (id) sender; +- (void)verifyLocalData:(id)sender; -- (void) changePriority: (id) sender; +- (void)changePriority:(id)sender; -- (void) updateCheckButtons: (NSNotification *) notification; +- (void)updateCheckButtons:(NSNotification*)notification; -- (void) updateGroupMenu: (NSNotification *) notification; +- (void)updateGroupMenu:(NSNotification*)notification; @end diff --git a/macosx/AddWindowController.m b/macosx/AddWindowController.m index 4ab56a475..ceffe0abf 100644 --- a/macosx/AddWindowController.m +++ b/macosx/AddWindowController.m @@ -36,24 +36,28 @@ @interface AddWindowController (Private) -- (void) updateFiles; +- (void)updateFiles; -- (void) confirmAdd; +- (void)confirmAdd; -- (void) setDestinationPath: (NSString *) destination determinationType: (TorrentDeterminationType) determinationType; +- (void)setDestinationPath:(NSString*)destination determinationType:(TorrentDeterminationType)determinationType; -- (void) setGroupsMenu; -- (void) changeGroupValue: (id) sender; +- (void)setGroupsMenu; +- (void)changeGroupValue:(id)sender; @end @implementation AddWindowController -- (instancetype) initWithTorrent: (Torrent *) torrent destination: (NSString *) path lockDestination: (BOOL) lockDestination - controller: (Controller *) controller torrentFile: (NSString *) torrentFile - deleteTorrentCheckEnableInitially: (BOOL) deleteTorrent canToggleDelete: (BOOL) canToggleDelete +- (instancetype)initWithTorrent:(Torrent*)torrent + destination:(NSString*)path + lockDestination:(BOOL)lockDestination + controller:(Controller*)controller + torrentFile:(NSString*)torrentFile + deleteTorrentCheckEnableInitially:(BOOL)deleteTorrent + canToggleDelete:(BOOL)canToggleDelete { - if ((self = [super initWithWindowNibName: @"AddWindow"])) + if ((self = [super initWithWindowNibName:@"AddWindow"])) { fTorrent = torrent; fDestination = path.stringByExpandingTildeInPath; @@ -74,15 +78,16 @@ return self; } -- (void) awakeFromNib +- (void)awakeFromNib { - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateCheckButtons:) name: @"TorrentFileCheckChange" object: fTorrent]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateCheckButtons:) name:@"TorrentFileCheckChange" + object:fTorrent]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateGroupMenu:) name: @"UpdateGroups" object: nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateGroupMenu:) name:@"UpdateGroups" object:nil]; - [fFileController setTorrent: fTorrent]; + [fFileController setTorrent:fTorrent]; - NSString * name = fTorrent.name; + NSString* name = fTorrent.name; self.window.title = name; fNameField.stringValue = name; fNameField.toolTip = name; @@ -96,69 +101,82 @@ fUncheckAllButton.hidden = YES; NSRect scrollFrame = fFileScrollView.frame; - const CGFloat diff = NSMinY(fFileScrollView.frame) - NSMinY(fFileFilterField.frame); + CGFloat const diff = NSMinY(fFileScrollView.frame) - NSMinY(fFileFilterField.frame); scrollFrame.origin.y -= diff; scrollFrame.size.height += diff; fFileScrollView.frame = scrollFrame; } else - [self updateCheckButtons: nil]; + { + [self updateCheckButtons:nil]; + } [self setGroupsMenu]; - [fGroupPopUp selectItemWithTag: fGroupValue]; + [fGroupPopUp selectItemWithTag:fGroupValue]; NSInteger priorityIndex; switch (fTorrent.priority) { - case TR_PRI_HIGH: priorityIndex = POPUP_PRIORITY_HIGH; break; - case TR_PRI_NORMAL: priorityIndex = POPUP_PRIORITY_NORMAL; break; - case TR_PRI_LOW: priorityIndex = POPUP_PRIORITY_LOW; break; - default: - NSAssert1(NO, @"Unknown priority for adding torrent: %d", fTorrent.priority); - priorityIndex = POPUP_PRIORITY_NORMAL; + case TR_PRI_HIGH: + priorityIndex = POPUP_PRIORITY_HIGH; + break; + case TR_PRI_NORMAL: + priorityIndex = POPUP_PRIORITY_NORMAL; + break; + case TR_PRI_LOW: + priorityIndex = POPUP_PRIORITY_LOW; + break; + default: + NSAssert1(NO, @"Unknown priority for adding torrent: %d", fTorrent.priority); + priorityIndex = POPUP_PRIORITY_NORMAL; } - [fPriorityPopUp selectItemAtIndex: priorityIndex]; + [fPriorityPopUp selectItemAtIndex:priorityIndex]; - fStartCheck.state = [NSUserDefaults.standardUserDefaults boolForKey: @"AutoStartDownload"] ? NSOnState : NSOffState; + fStartCheck.state = [NSUserDefaults.standardUserDefaults boolForKey:@"AutoStartDownload"] ? NSOnState : NSOffState; fDeleteCheck.state = fDeleteTorrentEnableInitially ? NSOnState : NSOffState; fDeleteCheck.enabled = fCanToggleDelete; if (fDestination) - [self setDestinationPath: fDestination determinationType: (fLockDestination ? TorrentDeterminationUserSpecified : TorrentDeterminationAutomatic)]; + { + [self setDestinationPath:fDestination + determinationType:(fLockDestination ? TorrentDeterminationUserSpecified : TorrentDeterminationAutomatic)]; + } else { fLocationField.stringValue = @""; fLocationImageView.image = nil; } - fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_SECONDS target: self - selector: @selector(updateFiles) userInfo: nil repeats: YES]; + fTimer = [NSTimer scheduledTimerWithTimeInterval:UPDATE_SECONDS target:self selector:@selector(updateFiles) userInfo:nil + repeats:YES]; [self updateFiles]; } -- (void) windowDidLoad +- (void)windowDidLoad { //if there is no destination, prompt for one right away if (!fDestination) - [self setDestination: nil]; + { + [self setDestination:nil]; + } } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; [fTimer invalidate]; } -- (Torrent *) torrent +- (Torrent*)torrent { return fTorrent; } -- (void) setDestination: (id) sender +- (void)setDestination:(id)sender { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; panel.prompt = NSLocalizedString(@"Select", "Open torrent -> prompt"); panel.allowsMultipleSelection = NO; @@ -166,140 +184,160 @@ panel.canChooseDirectories = YES; panel.canCreateDirectories = YES; - panel.message = [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"", - "Add -> select destination folder"), fTorrent.name]; + panel.message = [NSString stringWithFormat:NSLocalizedString(@"Select the download folder for \"%@\"", "Add -> select destination folder"), + fTorrent.name]; - [panel beginSheetModalForWindow: self.window completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) { fLockDestination = YES; - [self setDestinationPath: panel.URLs[0].path determinationType: TorrentDeterminationUserSpecified]; + [self setDestinationPath:panel.URLs[0].path determinationType:TorrentDeterminationUserSpecified]; } else { if (!fDestination) - [self performSelectorOnMainThread: @selector(cancelAdd:) withObject: nil waitUntilDone: NO]; + { + [self performSelectorOnMainThread:@selector(cancelAdd:) withObject:nil waitUntilDone:NO]; + } } }]; } -- (void) add: (id) sender +- (void)add:(id)sender { - if ([fDestination.lastPathComponent isEqualToString: fTorrent.name] - && [NSUserDefaults.standardUserDefaults boolForKey: @"WarningFolderDataSameName"]) + if ([fDestination.lastPathComponent isEqualToString:fTorrent.name] && + [NSUserDefaults.standardUserDefaults boolForKey:@"WarningFolderDataSameName"]) { - NSAlert * alert = [[NSAlert alloc] init]; - alert.messageText = NSLocalizedString(@"The destination directory and root data directory have the same name.", - "Add torrent -> same name -> title"); - alert.informativeText = NSLocalizedString(@"If you are attempting to use already existing data," - " the root data directory should be inside the destination directory.", "Add torrent -> same name -> message"); + NSAlert* alert = [[NSAlert alloc] init]; + alert.messageText = NSLocalizedString(@"The destination directory and root data directory have the same name.", "Add torrent -> same name -> title"); + alert.informativeText = NSLocalizedString( + @"If you are attempting to use already existing data," + " the root data directory should be inside the destination directory.", + "Add torrent -> same name -> message"); alert.alertStyle = NSWarningAlertStyle; - [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Add torrent -> same name -> button")]; - [alert addButtonWithTitle: NSLocalizedString(@"Add", "Add torrent -> same name -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Cancel", "Add torrent -> same name -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Add", "Add torrent -> same name -> button")]; alert.showsSuppressionButton = YES; [alert beginSheetModalForWindow:[self window] completionHandler:^(NSModalResponse returnCode) { if (alert.suppressionButton.state == NSOnState) - [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningFolderDataSameName"]; + { + [NSUserDefaults.standardUserDefaults setBool:NO forKey:@"WarningFolderDataSameName"]; + } if (returnCode == NSAlertSecondButtonReturn) - [self performSelectorOnMainThread: @selector(confirmAdd) withObject: nil waitUntilDone: NO]; + { + [self performSelectorOnMainThread:@selector(confirmAdd) withObject:nil waitUntilDone:NO]; + } }]; } else + { [self confirmAdd]; + } } -- (void) cancelAdd: (id) sender +- (void)cancelAdd:(id)sender { - [self.window performClose: sender]; + [self.window performClose:sender]; } //only called on cancel -- (BOOL) windowShouldClose: (id) window +- (BOOL)windowShouldClose:(id)window { [fTimer invalidate]; fTimer = nil; - [fFileController setTorrent: nil]; //avoid a crash when window tries to update + [fFileController setTorrent:nil]; //avoid a crash when window tries to update - [fController askOpenConfirmed: self add: NO]; + [fController askOpenConfirmed:self add:NO]; return YES; } -- (void) setFileFilterText: (id) sender +- (void)setFileFilterText:(id)sender { - [fFileController setFilterText: [sender stringValue]]; + [fFileController setFilterText:[sender stringValue]]; } -- (IBAction) checkAll: (id) sender +- (IBAction)checkAll:(id)sender { [fFileController checkAll]; } -- (IBAction) uncheckAll: (id) sender +- (IBAction)uncheckAll:(id)sender { [fFileController uncheckAll]; } -- (void) verifyLocalData: (id) sender +- (void)verifyLocalData:(id)sender { [fTorrent resetCache]; [self updateFiles]; } -- (void) changePriority: (id) sender +- (void)changePriority:(id)sender { tr_priority_t priority; switch ([sender indexOfSelectedItem]) { - case POPUP_PRIORITY_HIGH: priority = TR_PRI_HIGH; break; - case POPUP_PRIORITY_NORMAL: priority = TR_PRI_NORMAL; break; - case POPUP_PRIORITY_LOW: priority = TR_PRI_LOW; break; - default: - NSAssert1(NO, @"Unknown priority tag for adding torrent: %ld", [sender tag]); - priority = TR_PRI_NORMAL; + case POPUP_PRIORITY_HIGH: + priority = TR_PRI_HIGH; + break; + case POPUP_PRIORITY_NORMAL: + priority = TR_PRI_NORMAL; + break; + case POPUP_PRIORITY_LOW: + priority = TR_PRI_LOW; + break; + default: + NSAssert1(NO, @"Unknown priority tag for adding torrent: %ld", [sender tag]); + priority = TR_PRI_NORMAL; } fTorrent.priority = priority; } -- (void) updateCheckButtons: (NSNotification *) notification +- (void)updateCheckButtons:(NSNotification*)notification { - NSString * statusString = [NSString stringForFileSize: fTorrent.size]; + NSString* statusString = [NSString stringForFileSize:fTorrent.size]; if (fTorrent.folder) { //check buttons //keep synced with identical code in InfoFileViewController.m - const NSInteger filesCheckState = [fTorrent checkForFiles: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTorrent.fileCount)]]; + NSInteger const filesCheckState = [fTorrent + checkForFiles:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fTorrent.fileCount)]]; fCheckAllButton.enabled = filesCheckState != NSOnState; //if anything is unchecked fUncheckAllButton.enabled = !fTorrent.allDownloaded; //if there are any checked files that aren't finished //status field - NSString * fileString; + NSString* fileString; NSInteger count = fTorrent.fileCount; if (count != 1) - fileString = [NSString stringWithFormat: NSLocalizedString(@"%@ files", "Add torrent -> info"), - [NSString formattedUInteger: count]]; + { + fileString = [NSString + stringWithFormat:NSLocalizedString(@"%@ files", "Add torrent -> info"), [NSString formattedUInteger:count]]; + } else + { fileString = NSLocalizedString(@"1 file", "Add torrent -> info"); + } - NSString * selectedString = [NSString stringWithFormat: NSLocalizedString(@"%@ selected", "Add torrent -> info"), - [NSString stringForFileSize: fTorrent.totalSizeSelected]]; + NSString* selectedString = [NSString stringWithFormat:NSLocalizedString(@"%@ selected", "Add torrent -> info"), + [NSString stringForFileSize:fTorrent.totalSizeSelected]]; - statusString = [NSString stringWithFormat: @"%@, %@ (%@)", fileString, statusString, selectedString]; + statusString = [NSString stringWithFormat:@"%@, %@ (%@)", fileString, statusString, selectedString]; } fStatusField.stringValue = statusString; } -- (void) updateGroupMenu: (NSNotification *) notification +- (void)updateGroupMenu:(NSNotification*)notification { [self setGroupsMenu]; - if (![fGroupPopUp selectItemWithTag: fGroupValue]) + if (![fGroupPopUp selectItemWithTag:fGroupValue]) { fGroupValue = -1; fGroupValueDetermination = TorrentDeterminationAutomatic; - [fGroupPopUp selectItemWithTag: fGroupValue]; + [fGroupPopUp selectItemWithTag:fGroupValue]; } } @@ -307,71 +345,80 @@ @implementation AddWindowController (Private) -- (void) updateFiles +- (void)updateFiles { [fTorrent update]; [fFileController refresh]; - [self updateCheckButtons: nil]; //call in case button state changed by checking + [self updateCheckButtons:nil]; //call in case button state changed by checking if (fTorrent.checking) { - const BOOL waiting = fTorrent.checkingWaiting; + BOOL const waiting = fTorrent.checkingWaiting; fVerifyIndicator.indeterminate = waiting; if (waiting) - [fVerifyIndicator startAnimation: self]; + { + [fVerifyIndicator startAnimation:self]; + } else + { fVerifyIndicator.doubleValue = fTorrent.checkingProgress; + } } - else { + else + { fVerifyIndicator.indeterminate = YES; //we want to hide when stopped, which only applies when indeterminate - [fVerifyIndicator stopAnimation: self]; + [fVerifyIndicator stopAnimation:self]; } } -- (void) confirmAdd +- (void)confirmAdd { [fTimer invalidate]; fTimer = nil; - [fTorrent setGroupValue: fGroupValue determinationType: fGroupValueDetermination]; + [fTorrent setGroupValue:fGroupValue determinationType:fGroupValueDetermination]; if (fTorrentFile && fCanToggleDelete && fDeleteCheck.state == NSOnState) - [Torrent trashFile: fTorrentFile error: nil]; + { + [Torrent trashFile:fTorrentFile error:nil]; + } if (fStartCheck.state == NSOnState) + { [fTorrent startTransfer]; + } - [fFileController setTorrent: nil]; //avoid a crash when window tries to update + [fFileController setTorrent:nil]; //avoid a crash when window tries to update [self close]; - [fController askOpenConfirmed: self add: YES]; + [fController askOpenConfirmed:self add:YES]; } -- (void) setDestinationPath: (NSString *) destination determinationType: (TorrentDeterminationType) determinationType +- (void)setDestinationPath:(NSString*)destination determinationType:(TorrentDeterminationType)determinationType { destination = destination.stringByExpandingTildeInPath; - if (!fDestination || ![fDestination isEqualToString: destination]) + if (!fDestination || ![fDestination isEqualToString:destination]) { fDestination = destination; - [fTorrent changeDownloadFolderBeforeUsing: fDestination determinationType: determinationType]; + [fTorrent changeDownloadFolderBeforeUsing:fDestination determinationType:determinationType]; } fLocationField.stringValue = fDestination.stringByAbbreviatingWithTildeInPath; fLocationField.toolTip = fDestination; - ExpandedPathToIconTransformer * iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; - fLocationImageView.image = [iconTransformer transformedValue: fDestination]; + ExpandedPathToIconTransformer* iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; + fLocationImageView.image = [iconTransformer transformedValue:fDestination]; } -- (void) setGroupsMenu +- (void)setGroupsMenu { - NSMenu * groupMenu = [GroupsController.groups groupMenuWithTarget: self action: @selector(changeGroupValue:) isSmall: NO]; + NSMenu* groupMenu = [GroupsController.groups groupMenuWithTarget:self action:@selector(changeGroupValue:) isSmall:NO]; fGroupPopUp.menu = groupMenu; } -- (void) changeGroupValue: (id) sender +- (void)changeGroupValue:(id)sender { NSInteger previousGroup = fGroupValue; fGroupValue = [sender tag]; @@ -379,11 +426,16 @@ if (!fLockDestination) { - if ([GroupsController.groups usesCustomDownloadLocationForIndex: fGroupValue]) - [self setDestinationPath: [GroupsController.groups customDownloadLocationForIndex: fGroupValue] determinationType: TorrentDeterminationAutomatic]; - else if ([fDestination isEqualToString: [GroupsController.groups customDownloadLocationForIndex: previousGroup]]) - [self setDestinationPath: [NSUserDefaults.standardUserDefaults stringForKey: @"DownloadFolder"] determinationType: TorrentDeterminationAutomatic]; - else; + if ([GroupsController.groups usesCustomDownloadLocationForIndex:fGroupValue]) + { + [self setDestinationPath:[GroupsController.groups customDownloadLocationForIndex:fGroupValue] + determinationType:TorrentDeterminationAutomatic]; + } + else if ([fDestination isEqualToString:[GroupsController.groups customDownloadLocationForIndex:previousGroup]]) + { + [self setDestinationPath:[NSUserDefaults.standardUserDefaults stringForKey:@"DownloadFolder"] + determinationType:TorrentDeterminationAutomatic]; + } } } diff --git a/macosx/BadgeView.h b/macosx/BadgeView.h index 960fc5926..93b964419 100644 --- a/macosx/BadgeView.h +++ b/macosx/BadgeView.h @@ -26,17 +26,18 @@ @interface BadgeView : NSView { - tr_session * fLib; + tr_session* fLib; - NSMutableDictionary * fAttributes; + NSMutableDictionary* fAttributes; - CGFloat fDownloadRate, fUploadRate; + CGFloat fDownloadRate; + CGFloat fUploadRate; BOOL fQuitting; } -- (instancetype) initWithLib: (tr_session *) lib; +- (instancetype)initWithLib:(tr_session*)lib; -- (BOOL) setRatesWithDownload: (CGFloat) downloadRate upload: (CGFloat) uploadRate; -- (void) setQuitting; +- (BOOL)setRatesWithDownload:(CGFloat)downloadRate upload:(CGFloat)uploadRate; +- (void)setQuitting; @end diff --git a/macosx/BadgeView.m b/macosx/BadgeView.m index effe469ad..7585b3c79 100644 --- a/macosx/BadgeView.m +++ b/macosx/BadgeView.m @@ -27,13 +27,13 @@ @interface BadgeView (Private) -- (void) badge: (NSImage *) badge string: (NSString *) string atHeight: (CGFloat) height adjustForQuit: (BOOL) quit; +- (void)badge:(NSImage*)badge string:(NSString*)string atHeight:(CGFloat)height adjustForQuit:(BOOL)quit; @end @implementation BadgeView -- (instancetype) initWithLib: (tr_session *) lib +- (instancetype)initWithLib:(tr_session*)lib { if ((self = [super init])) { @@ -46,66 +46,71 @@ return self; } - -- (BOOL) setRatesWithDownload: (CGFloat) downloadRate upload: (CGFloat) uploadRate +- (BOOL)setRatesWithDownload:(CGFloat)downloadRate upload:(CGFloat)uploadRate { //only needs update if the badges were displayed or are displayed now if (fDownloadRate == downloadRate && fUploadRate == uploadRate) + { return NO; + } fDownloadRate = downloadRate; fUploadRate = uploadRate; return YES; } -- (void) setQuitting +- (void)setQuitting { fQuitting = YES; } -- (void) drawRect: (NSRect) rect +- (void)drawRect:(NSRect)rect { - [NSApp.applicationIconImage drawInRect: rect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0]; + [NSApp.applicationIconImage drawInRect:rect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; if (fQuitting) { - NSImage * quitBadge = [NSImage imageNamed: @"QuitBadge"]; - [self badge: quitBadge string: NSLocalizedString(@"Quitting", "Dock Badger -> quit") - atHeight: (NSHeight(rect) - quitBadge.size.height) * 0.5 adjustForQuit: YES]; + NSImage* quitBadge = [NSImage imageNamed:@"QuitBadge"]; + [self badge:quitBadge string:NSLocalizedString(@"Quitting", "Dock Badger -> quit") + atHeight:(NSHeight(rect) - quitBadge.size.height) * 0.5 + adjustForQuit:YES]; return; } - const BOOL upload = fUploadRate >= 0.1, - download = fDownloadRate >= 0.1; + BOOL const upload = fUploadRate >= 0.1; + BOOL const download = fDownloadRate >= 0.1; CGFloat bottom = 0.0; if (upload) { - NSImage * uploadBadge = [NSImage imageNamed: @"UploadBadge"]; - [self badge: uploadBadge string: [NSString stringForSpeedAbbrev: fUploadRate] atHeight: bottom adjustForQuit: NO]; + NSImage* uploadBadge = [NSImage imageNamed:@"UploadBadge"]; + [self badge:uploadBadge string:[NSString stringForSpeedAbbrev:fUploadRate] atHeight:bottom adjustForQuit:NO]; if (download) + { bottom += uploadBadge.size.height + BETWEEN_PADDING; //download rate above upload rate + } } if (download) - [self badge: [NSImage imageNamed: @"DownloadBadge"] string: [NSString stringForSpeedAbbrev: fDownloadRate] - atHeight: bottom adjustForQuit: NO]; + { + [self badge:[NSImage imageNamed:@"DownloadBadge"] string:[NSString stringForSpeedAbbrev:fDownloadRate] atHeight:bottom + adjustForQuit:NO]; + } } @end @implementation BadgeView (Private) -- (void) badge: (NSImage *) badge string: (NSString *) string atHeight: (CGFloat) height adjustForQuit: (BOOL) quit +- (void)badge:(NSImage*)badge string:(NSString*)string atHeight:(CGFloat)height adjustForQuit:(BOOL)quit { if (!fAttributes) { - NSShadow * stringShadow = [[NSShadow alloc] init]; + NSShadow* stringShadow = [[NSShadow alloc] init]; stringShadow.shadowOffset = NSMakeSize(2.0, -2.0); stringShadow.shadowBlurRadius = 4.0; - fAttributes = [[NSMutableDictionary alloc] initWithCapacity: 3]; + fAttributes = [[NSMutableDictionary alloc] initWithCapacity:3]; fAttributes[NSForegroundColorAttributeName] = NSColor.whiteColor; fAttributes[NSShadowAttributeName] = stringShadow; - } NSRect badgeRect; @@ -113,15 +118,15 @@ badgeRect.origin.x = 0.0; badgeRect.origin.y = height; - [badge drawInRect: badgeRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0]; + [badge drawInRect:badgeRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; //make sure text fits on the badge CGFloat fontSize = 26.0; NSSize stringSize; do { - fAttributes[NSFontAttributeName] = [NSFont boldSystemFontOfSize: fontSize]; - stringSize = [string sizeWithAttributes: fAttributes]; + fAttributes[NSFontAttributeName] = [NSFont boldSystemFontOfSize:fontSize]; + stringSize = [string sizeWithAttributes:fAttributes]; fontSize -= 1.0; } while (NSWidth(badgeRect) < stringSize.width); @@ -131,7 +136,7 @@ stringRect.origin.y = NSMidY(badgeRect) - stringSize.height * 0.5 + (quit ? 2.0 : 1.0); //adjust for shadow, extra for quit stringRect.size = stringSize; - [string drawInRect: stringRect withAttributes: fAttributes]; + [string drawInRect:stringRect withAttributes:fAttributes]; } @end diff --git a/macosx/Badger.h b/macosx/Badger.h index 065e5ff28..a1438df70 100644 --- a/macosx/Badger.h +++ b/macosx/Badger.h @@ -28,17 +28,17 @@ @interface Badger : NSObject { - tr_session * fLib; + tr_session* fLib; - NSMutableSet * fHashes; + NSMutableSet* fHashes; } -- (instancetype) initWithLib: (tr_session *) lib; +- (instancetype)initWithLib:(tr_session*)lib; -- (void) updateBadgeWithDownload: (CGFloat) downloadRate upload: (CGFloat) uploadRate; -- (void) addCompletedTorrent: (Torrent *) torrent; -- (void) removeTorrent: (Torrent *) torrent; -- (void) clearCompleted; -- (void) setQuitting; +- (void)updateBadgeWithDownload:(CGFloat)downloadRate upload:(CGFloat)uploadRate; +- (void)addCompletedTorrent:(Torrent*)torrent; +- (void)removeTorrent:(Torrent*)torrent; +- (void)clearCompleted; +- (void)setQuitting; @end diff --git a/macosx/Badger.m b/macosx/Badger.m index e2f6b1459..63fa3c2a7 100644 --- a/macosx/Badger.m +++ b/macosx/Badger.m @@ -27,13 +27,13 @@ @implementation Badger -- (instancetype) initWithLib: (tr_session *) lib +- (instancetype)initWithLib:(tr_session*)lib { if ((self = [super init])) { fLib = lib; - BadgeView * view = [[BadgeView alloc] initWithLib: lib]; + BadgeView* view = [[BadgeView alloc] initWithLib:lib]; NSApp.dockTile.contentView = view; fHashes = [[NSMutableSet alloc] init]; @@ -42,40 +42,43 @@ return self; } - -- (void) updateBadgeWithDownload: (CGFloat) downloadRate upload: (CGFloat) uploadRate +- (void)updateBadgeWithDownload:(CGFloat)downloadRate upload:(CGFloat)uploadRate { - const CGFloat displayDlRate = [NSUserDefaults.standardUserDefaults boolForKey: @"BadgeDownloadRate"] - ? downloadRate : 0.0; - const CGFloat displayUlRate = [NSUserDefaults.standardUserDefaults boolForKey: @"BadgeUploadRate"] - ? uploadRate : 0.0; + CGFloat const displayDlRate = [NSUserDefaults.standardUserDefaults boolForKey:@"BadgeDownloadRate"] ? downloadRate : 0.0; + CGFloat const displayUlRate = [NSUserDefaults.standardUserDefaults boolForKey:@"BadgeUploadRate"] ? uploadRate : 0.0; //only update if the badged values change - if ([(BadgeView *)NSApp.dockTile.contentView setRatesWithDownload: displayDlRate upload: displayUlRate]) - [NSApp.dockTile display]; -} - -- (void) addCompletedTorrent: (Torrent *) torrent -{ - NSParameterAssert(torrent != nil); - - [fHashes addObject: torrent.hashString]; - NSApp.dockTile.badgeLabel = [NSString formattedUInteger: fHashes.count]; -} - -- (void) removeTorrent: (Torrent *) torrent -{ - if ([fHashes member: torrent.hashString]) + if ([(BadgeView*)NSApp.dockTile.contentView setRatesWithDownload:displayDlRate upload:displayUlRate]) { - [fHashes removeObject: torrent.hashString]; - if (fHashes.count > 0) - NSApp.dockTile.badgeLabel = [NSString formattedUInteger: fHashes.count]; - else - NSApp.dockTile.badgeLabel = @""; + [NSApp.dockTile display]; } } -- (void) clearCompleted +- (void)addCompletedTorrent:(Torrent*)torrent +{ + NSParameterAssert(torrent != nil); + + [fHashes addObject:torrent.hashString]; + NSApp.dockTile.badgeLabel = [NSString formattedUInteger:fHashes.count]; +} + +- (void)removeTorrent:(Torrent*)torrent +{ + if ([fHashes member:torrent.hashString]) + { + [fHashes removeObject:torrent.hashString]; + if (fHashes.count > 0) + { + NSApp.dockTile.badgeLabel = [NSString formattedUInteger:fHashes.count]; + } + else + { + NSApp.dockTile.badgeLabel = @""; + } + } +} + +- (void)clearCompleted { if (fHashes.count > 0) { @@ -84,10 +87,10 @@ } } -- (void) setQuitting +- (void)setQuitting { [self clearCompleted]; - [(BadgeView *)NSApp.dockTile.contentView setQuitting]; + [(BadgeView*)NSApp.dockTile.contentView setQuitting]; [NSApp.dockTile display]; } diff --git a/macosx/BlocklistDownloader.h b/macosx/BlocklistDownloader.h index d83944a45..24713ebe2 100644 --- a/macosx/BlocklistDownloader.h +++ b/macosx/BlocklistDownloader.h @@ -24,30 +24,30 @@ @class BlocklistDownloaderViewController; -typedef NS_ENUM(unsigned int, blocklistDownloadState) { +typedef NS_ENUM(unsigned int, blocklistDownloadState) { // BLOCKLIST_DL_START, BLOCKLIST_DL_DOWNLOADING, BLOCKLIST_DL_PROCESSING }; -@interface BlocklistDownloader : NSObject +@interface BlocklistDownloader : NSObject { - NSURLDownload * fDownload; + NSURLDownload* fDownload; - BlocklistDownloaderViewController * fViewController; + BlocklistDownloaderViewController* fViewController; - NSString * fDestination; + NSString* fDestination; NSUInteger fCurrentSize; long long fExpectedSize; blocklistDownloadState fState; } -+ (BlocklistDownloader *) downloader; //starts download if not already occuring -@property (nonatomic, class, readonly) BOOL isRunning; ++ (BlocklistDownloader*)downloader; //starts download if not already occuring +@property(nonatomic, class, readonly) BOOL isRunning; -- (void) setViewController: (BlocklistDownloaderViewController *) viewController; +- (void)setViewController:(BlocklistDownloaderViewController*)viewController; -- (void) cancelDownload; +- (void)cancelDownload; @end diff --git a/macosx/BlocklistDownloader.m b/macosx/BlocklistDownloader.m index cc076806a..2351e4de1 100644 --- a/macosx/BlocklistDownloader.m +++ b/macosx/BlocklistDownloader.m @@ -27,15 +27,16 @@ @interface BlocklistDownloader (Private) -- (void) startDownload; -- (void) decompressBlocklist; +- (void)startDownload; +- (void)decompressBlocklist; @end @implementation BlocklistDownloader -BlocklistDownloader * fBLDownloader = nil; -+ (BlocklistDownloader *) downloader +BlocklistDownloader* fBLDownloader = nil; + ++ (BlocklistDownloader*)downloader { if (!fBLDownloader) { @@ -46,33 +47,32 @@ BlocklistDownloader * fBLDownloader = nil; return fBLDownloader; } -+ (BOOL) isRunning ++ (BOOL)isRunning { return fBLDownloader != nil; } -- (void) setViewController: (BlocklistDownloaderViewController *) viewController +- (void)setViewController:(BlocklistDownloaderViewController*)viewController { fViewController = viewController; if (fViewController) { switch (fState) { - case BLOCKLIST_DL_START: - [fViewController setStatusStarting]; - break; - case BLOCKLIST_DL_DOWNLOADING: - [fViewController setStatusProgressForCurrentSize: fCurrentSize expectedSize: fExpectedSize]; - break; - case BLOCKLIST_DL_PROCESSING: - [fViewController setStatusProcessing]; - break; + case BLOCKLIST_DL_START: + [fViewController setStatusStarting]; + break; + case BLOCKLIST_DL_DOWNLOADING: + [fViewController setStatusProgressForCurrentSize:fCurrentSize expectedSize:fExpectedSize]; + break; + case BLOCKLIST_DL_PROCESSING: + [fViewController setStatusProcessing]; + break; } } } - -- (void) cancelDownload +- (void)cancelDownload { [fViewController setFinished]; @@ -84,43 +84,43 @@ BlocklistDownloader * fBLDownloader = nil; } //using the actual filename is the best bet -- (void) download: (NSURLDownload *) download decideDestinationWithSuggestedFilename: (NSString *) filename +- (void)download:(NSURLDownload*)download decideDestinationWithSuggestedFilename:(NSString*)filename { - [fDownload setDestination: [NSTemporaryDirectory() stringByAppendingPathComponent: filename] allowOverwrite: NO]; + [fDownload setDestination:[NSTemporaryDirectory() stringByAppendingPathComponent:filename] allowOverwrite:NO]; } -- (void) download: (NSURLDownload *) download didCreateDestination: (NSString *) path +- (void)download:(NSURLDownload*)download didCreateDestination:(NSString*)path { fDestination = path; } -- (void) download: (NSURLDownload *) download didReceiveResponse: (NSURLResponse *) response +- (void)download:(NSURLDownload*)download didReceiveResponse:(NSURLResponse*)response { fState = BLOCKLIST_DL_DOWNLOADING; fCurrentSize = 0; fExpectedSize = response.expectedContentLength; - [fViewController setStatusProgressForCurrentSize: fCurrentSize expectedSize: fExpectedSize]; + [fViewController setStatusProgressForCurrentSize:fCurrentSize expectedSize:fExpectedSize]; } -- (void) download: (NSURLDownload *) download didReceiveDataOfLength: (NSUInteger) length +- (void)download:(NSURLDownload*)download didReceiveDataOfLength:(NSUInteger)length { fCurrentSize += length; - [fViewController setStatusProgressForCurrentSize: fCurrentSize expectedSize: fExpectedSize]; + [fViewController setStatusProgressForCurrentSize:fCurrentSize expectedSize:fExpectedSize]; } -- (void) download: (NSURLDownload *) download didFailWithError: (NSError *) error +- (void)download:(NSURLDownload*)download didFailWithError:(NSError*)error { - [fViewController setFailed: error.localizedDescription]; + [fViewController setFailed:error.localizedDescription]; - [NSUserDefaults.standardUserDefaults setObject: [NSDate date] forKey: @"BlocklistNewLastUpdate"]; + [NSUserDefaults.standardUserDefaults setObject:[NSDate date] forKey:@"BlocklistNewLastUpdate"]; [BlocklistScheduler.scheduler updateSchedule]; fBLDownloader = nil; } -- (void) downloadDidFinish: (NSURLDownload *) download +- (void)downloadDidFinish:(NSURLDownload*)download { fState = BLOCKLIST_DL_PROCESSING; @@ -132,31 +132,34 @@ BlocklistDownloader * fBLDownloader = nil; [self decompressBlocklist]; dispatch_async(dispatch_get_main_queue(), ^{ - const int count = tr_blocklistSetContent(((Controller *)NSApp.delegate).sessionHandle, fDestination.UTF8String); + int const count = tr_blocklistSetContent(((Controller*)NSApp.delegate).sessionHandle, fDestination.UTF8String); //delete downloaded file - [NSFileManager.defaultManager removeItemAtPath: fDestination error: NULL]; + [NSFileManager.defaultManager removeItemAtPath:fDestination error:NULL]; if (count > 0) + { [fViewController setFinished]; + } else - [fViewController setFailed: NSLocalizedString(@"The specified blocklist file did not contain any valid rules.", - "blocklist fail message")]; + { + [fViewController setFailed:NSLocalizedString(@"The specified blocklist file did not contain any valid rules.", "blocklist fail message")]; + } //update last updated date for schedule - NSDate * date = [NSDate date]; - [NSUserDefaults.standardUserDefaults setObject: date forKey: @"BlocklistNewLastUpdate"]; - [NSUserDefaults.standardUserDefaults setObject: date forKey: @"BlocklistNewLastUpdateSuccess"]; + NSDate* date = [NSDate date]; + [NSUserDefaults.standardUserDefaults setObject:date forKey:@"BlocklistNewLastUpdate"]; + [NSUserDefaults.standardUserDefaults setObject:date forKey:@"BlocklistNewLastUpdateSuccess"]; [BlocklistScheduler.scheduler updateSchedule]; - [NSNotificationCenter.defaultCenter postNotificationName: @"BlocklistUpdated" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"BlocklistUpdated" object:nil]; fBLDownloader = nil; }); }); } -- (BOOL) download: (NSURLDownload *) download shouldDecodeSourceDataOfMIMEType: (NSString *) encodingType +- (BOOL)download:(NSURLDownload*)download shouldDecodeSourceDataOfMIMEType:(NSString*)encodingType { return YES; } @@ -165,41 +168,47 @@ BlocklistDownloader * fBLDownloader = nil; @implementation BlocklistDownloader (Private) -- (void) startDownload +- (void)startDownload { fState = BLOCKLIST_DL_START; [BlocklistScheduler.scheduler cancelSchedule]; - NSString * urlString = [NSUserDefaults.standardUserDefaults stringForKey: @"BlocklistURL"]; + NSString* urlString = [NSUserDefaults.standardUserDefaults stringForKey:@"BlocklistURL"]; if (!urlString) + { urlString = @""; - else if (![urlString isEqualToString: @""] && [urlString rangeOfString: @"://"].location == NSNotFound) - urlString = [@"http://" stringByAppendingString: urlString]; + } + else if (![urlString isEqualToString:@""] && [urlString rangeOfString:@"://"].location == NSNotFound) + { + urlString = [@"http://" stringByAppendingString:urlString]; + } - NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: urlString]]; + NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]; - fDownload = [[NSURLDownload alloc] initWithRequest: request delegate: self]; + fDownload = [[NSURLDownload alloc] initWithRequest:request delegate:self]; } //.gz, .tar.gz, .tgz, and .bgz will be decompressed by NSURLDownload for us. However, we have to do .zip files manually. -- (void) decompressBlocklist +- (void)decompressBlocklist { - if ([fDestination.pathExtension.lowercaseString isEqualToString: @"zip"]) { + if ([fDestination.pathExtension.lowercaseString isEqualToString:@"zip"]) + { BOOL success = NO; - NSString * workingDirectory = fDestination.stringByDeletingLastPathComponent; + NSString* workingDirectory = fDestination.stringByDeletingLastPathComponent; //First, perform the actual unzipping - NSTask * unzip = [[NSTask alloc] init]; + NSTask* unzip = [[NSTask alloc] init]; unzip.launchPath = @"/usr/bin/unzip"; unzip.currentDirectoryPath = workingDirectory; unzip.arguments = @[ - @"-o", /* overwrite */ - @"-q", /* quiet! */ - fDestination, /* source zip file */ - @"-d", workingDirectory /*destination*/ - ]; + @"-o", /* overwrite */ + @"-q", /* quiet! */ + fDestination, /* source zip file */ + @"-d", + workingDirectory /*destination*/ + ]; @try { @@ -207,43 +216,48 @@ BlocklistDownloader * fBLDownloader = nil; [unzip waitUntilExit]; if (unzip.terminationStatus == 0) + { success = YES; + } } - @catch(id exc) + @catch (id exc) { success = NO; } - if (success) { + if (success) + { //Now find out what file we actually extracted; don't just assume it matches the zipfile's name - NSTask *zipinfo; + NSTask* zipinfo; zipinfo = [[NSTask alloc] init]; zipinfo.launchPath = @"/usr/bin/zipinfo"; zipinfo.arguments = @[ - @"-1", /* just the filename */ - fDestination /* source zip file */ - ]; + @"-1", /* just the filename */ + fDestination /* source zip file */ + ]; zipinfo.standardOutput = [NSPipe pipe]; @try { - NSFileHandle * zipinfoOutput = [zipinfo.standardOutput fileHandleForReading]; + NSFileHandle* zipinfoOutput = [zipinfo.standardOutput fileHandleForReading]; [zipinfo launch]; [zipinfo waitUntilExit]; - NSString * actualFilename = [[NSString alloc] initWithData: [zipinfoOutput readDataToEndOfFile] - encoding: NSUTF8StringEncoding]; - actualFilename = [actualFilename stringByTrimmingCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; - NSString * newBlocklistPath = [workingDirectory stringByAppendingPathComponent: actualFilename]; + NSString* actualFilename = [[NSString alloc] initWithData:[zipinfoOutput readDataToEndOfFile] + encoding:NSUTF8StringEncoding]; + actualFilename = [actualFilename stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; + NSString* newBlocklistPath = [workingDirectory stringByAppendingPathComponent:actualFilename]; //Finally, delete the ZIP file; we're done with it, and we'll return the unzipped blocklist - [NSFileManager.defaultManager removeItemAtPath: fDestination error: NULL]; + [NSFileManager.defaultManager removeItemAtPath:fDestination error:NULL]; fDestination = newBlocklistPath; } - @catch(id exc) {} + @catch (id exc) + { + } } } } diff --git a/macosx/BlocklistDownloaderViewController.h b/macosx/BlocklistDownloaderViewController.h index 40e9567a3..96898c44e 100644 --- a/macosx/BlocklistDownloaderViewController.h +++ b/macosx/BlocklistDownloaderViewController.h @@ -28,23 +28,23 @@ @interface BlocklistDownloaderViewController : NSObject { - PrefsController * fPrefsController; + PrefsController* fPrefsController; - IBOutlet NSWindow * fStatusWindow; - IBOutlet NSProgressIndicator * fProgressBar; - IBOutlet NSTextField * fTextField; - IBOutlet NSButton * fButton; + IBOutlet NSWindow* fStatusWindow; + IBOutlet NSProgressIndicator* fProgressBar; + IBOutlet NSTextField* fTextField; + IBOutlet NSButton* fButton; } -+ (void) downloadWithPrefsController: (PrefsController *) prefsController; ++ (void)downloadWithPrefsController:(PrefsController*)prefsController; -- (void) cancelDownload: (id) sender; +- (void)cancelDownload:(id)sender; -- (void) setStatusStarting; -- (void) setStatusProgressForCurrentSize: (NSUInteger) currentSize expectedSize: (long long) expectedSize; -- (void) setStatusProcessing; +- (void)setStatusStarting; +- (void)setStatusProgressForCurrentSize:(NSUInteger)currentSize expectedSize:(long long)expectedSize; +- (void)setStatusProcessing; -- (void) setFinished; -- (void) setFailed: (NSString *) error; +- (void)setFinished; +- (void)setFailed:(NSString*)error; @end diff --git a/macosx/BlocklistDownloaderViewController.m b/macosx/BlocklistDownloaderViewController.m index 533ff38a9..11b8a8392 100644 --- a/macosx/BlocklistDownloaderViewController.m +++ b/macosx/BlocklistDownloaderViewController.m @@ -27,28 +27,28 @@ @interface BlocklistDownloaderViewController (Private) -- (instancetype) initWithPrefsController: (PrefsController *) prefsController; -- (void) startDownload; +- (instancetype)initWithPrefsController:(PrefsController*)prefsController; +- (void)startDownload; @end @implementation BlocklistDownloaderViewController -BlocklistDownloaderViewController * fBLViewController = nil; -+ (void) downloadWithPrefsController: (PrefsController *) prefsController +BlocklistDownloaderViewController* fBLViewController = nil; ++ (void)downloadWithPrefsController:(PrefsController*)prefsController { if (!fBLViewController) { - fBLViewController = [[BlocklistDownloaderViewController alloc] initWithPrefsController: prefsController]; + fBLViewController = [[BlocklistDownloaderViewController alloc] initWithPrefsController:prefsController]; [fBLViewController startDownload]; } } -- (void) awakeFromNib +- (void)awakeFromNib { fButton.title = NSLocalizedString(@"Cancel", "Blocklist -> cancel button"); - const CGFloat oldWidth = NSWidth(fButton.frame); + CGFloat const oldWidth = NSWidth(fButton.frame); [fButton sizeToFit]; NSRect buttonFrame = fButton.frame; buttonFrame.size.width += 12.0; //sizeToFit sizes a bit too small @@ -56,69 +56,71 @@ BlocklistDownloaderViewController * fBLViewController = nil; fButton.frame = buttonFrame; fProgressBar.usesThreadedAnimation = YES; - [fProgressBar startAnimation: self]; + [fProgressBar startAnimation:self]; } -- (void) cancelDownload: (id) sender +- (void)cancelDownload:(id)sender { [[BlocklistDownloader downloader] cancelDownload]; } -- (void) setStatusStarting +- (void)setStatusStarting { fTextField.stringValue = [NSLocalizedString(@"Connecting to site", "Blocklist -> message") stringByAppendingEllipsis]; fProgressBar.indeterminate = YES; } -- (void) setStatusProgressForCurrentSize: (NSUInteger) currentSize expectedSize: (long long) expectedSize +- (void)setStatusProgressForCurrentSize:(NSUInteger)currentSize expectedSize:(long long)expectedSize { - NSString * string = NSLocalizedString(@"Downloading blocklist", "Blocklist -> message"); + NSString* string = NSLocalizedString(@"Downloading blocklist", "Blocklist -> message"); if (expectedSize != NSURLResponseUnknownLength) { fProgressBar.indeterminate = NO; - NSString * substring = [NSString stringForFilePartialSize: currentSize fullSize: expectedSize]; - string = [string stringByAppendingFormat: @" (%@)", substring]; + NSString* substring = [NSString stringForFilePartialSize:currentSize fullSize:expectedSize]; + string = [string stringByAppendingFormat:@" (%@)", substring]; fProgressBar.doubleValue = (double)currentSize / expectedSize; } else - string = [string stringByAppendingFormat: @" (%@)", [NSString stringForFileSize: currentSize]]; + { + string = [string stringByAppendingFormat:@" (%@)", [NSString stringForFileSize:currentSize]]; + } fTextField.stringValue = string; } -- (void) setStatusProcessing +- (void)setStatusProcessing { //change to indeterminate while processing fProgressBar.indeterminate = YES; - [fProgressBar startAnimation: self]; + [fProgressBar startAnimation:self]; fTextField.stringValue = [NSLocalizedString(@"Processing blocklist", "Blocklist -> message") stringByAppendingEllipsis]; fButton.enabled = NO; } -- (void) setFinished +- (void)setFinished { - [NSApp endSheet: fStatusWindow]; - [fStatusWindow orderOut: self]; + [NSApp endSheet:fStatusWindow]; + [fStatusWindow orderOut:self]; fBLViewController = nil; } -- (void) setFailed: (NSString *) error +- (void)setFailed:(NSString*)error { - [NSApp endSheet: fStatusWindow]; - [fStatusWindow orderOut: self]; + [NSApp endSheet:fStatusWindow]; + [fStatusWindow orderOut:self]; - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Blocklist -> button")]; + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Blocklist -> button")]; alert.messageText = NSLocalizedString(@"Download of the blocklist failed.", "Blocklist -> message"); alert.alertStyle = NSWarningAlertStyle; alert.informativeText = error; [alert beginSheetModalForWindow:fPrefsController.window completionHandler:^(NSModalResponse returnCode) { - [alert.window orderOut: self]; + [alert.window orderOut:self]; fBLViewController = nil; }]; @@ -128,7 +130,7 @@ BlocklistDownloaderViewController * fBLViewController = nil; @implementation BlocklistDownloaderViewController (Private) -- (instancetype) initWithPrefsController: (PrefsController *) prefsController +- (instancetype)initWithPrefsController:(PrefsController*)prefsController { if ((self = [super init])) { @@ -138,15 +140,15 @@ BlocklistDownloaderViewController * fBLViewController = nil; return self; } -- (void) startDownload +- (void)startDownload { //load window and show as sheet - [NSBundle.mainBundle loadNibNamed: @"BlocklistStatusWindow" owner: self topLevelObjects: NULL]; + [NSBundle.mainBundle loadNibNamed:@"BlocklistStatusWindow" owner:self topLevelObjects:NULL]; - BlocklistDownloader * downloader = [BlocklistDownloader downloader]; - [downloader setViewController: self]; //do before showing the sheet to ensure it doesn't slide out with placeholder text + BlocklistDownloader* downloader = [BlocklistDownloader downloader]; + [downloader setViewController:self]; //do before showing the sheet to ensure it doesn't slide out with placeholder text - [fPrefsController.window beginSheet: fStatusWindow completionHandler:nil]; + [fPrefsController.window beginSheet:fStatusWindow completionHandler:nil]; } @end diff --git a/macosx/BlocklistScheduler.h b/macosx/BlocklistScheduler.h index 6da02617b..a1fc6aaf8 100644 --- a/macosx/BlocklistScheduler.h +++ b/macosx/BlocklistScheduler.h @@ -24,12 +24,12 @@ @interface BlocklistScheduler : NSObject { - NSTimer * fTimer; + NSTimer* fTimer; } -@property (nonatomic, class, readonly) BlocklistScheduler * scheduler; +@property(nonatomic, class, readonly) BlocklistScheduler* scheduler; -- (void) updateSchedule; -- (void) cancelSchedule; +- (void)updateSchedule; +- (void)cancelSchedule; @end diff --git a/macosx/BlocklistScheduler.m b/macosx/BlocklistScheduler.m index fa03066c0..2878a87f7 100644 --- a/macosx/BlocklistScheduler.m +++ b/macosx/BlocklistScheduler.m @@ -31,52 +31,59 @@ @interface BlocklistScheduler (Private) -- (void) runUpdater; +- (void)runUpdater; @end @implementation BlocklistScheduler -BlocklistScheduler * fScheduler = nil; -+ (BlocklistScheduler *) scheduler +BlocklistScheduler* fScheduler = nil; + ++ (BlocklistScheduler*)scheduler { if (!fScheduler) + { fScheduler = [[BlocklistScheduler alloc] init]; + } return fScheduler; } -- (void) updateSchedule +- (void)updateSchedule { if (BlocklistDownloader.isRunning) return; [self cancelSchedule]; - NSString * blocklistURL; - if (![NSUserDefaults.standardUserDefaults boolForKey: @"BlocklistNew"] - || !((blocklistURL = [NSUserDefaults.standardUserDefaults stringForKey: @"BlocklistURL"]) && - ![blocklistURL isEqualToString: @""]) - || ![NSUserDefaults.standardUserDefaults boolForKey: @"BlocklistAutoUpdate"]) + NSString* blocklistURL; + if (![NSUserDefaults.standardUserDefaults boolForKey:@"BlocklistNew"] || + !((blocklistURL = [NSUserDefaults.standardUserDefaults stringForKey:@"BlocklistURL"]) && ![blocklistURL isEqualToString:@""]) || + ![NSUserDefaults.standardUserDefaults boolForKey:@"BlocklistAutoUpdate"]) + { return; + } - NSDate * lastUpdateDate = [NSUserDefaults.standardUserDefaults objectForKey: @"BlocklistNewLastUpdate"]; + NSDate* lastUpdateDate = [NSUserDefaults.standardUserDefaults objectForKey:@"BlocklistNewLastUpdate"]; if (lastUpdateDate) - lastUpdateDate = [lastUpdateDate dateByAddingTimeInterval: FULL_WAIT]; - NSDate * closeDate = [NSDate dateWithTimeIntervalSinceNow: SMALL_DELAY]; + { + lastUpdateDate = [lastUpdateDate dateByAddingTimeInterval:FULL_WAIT]; + } + NSDate* closeDate = [NSDate dateWithTimeIntervalSinceNow:SMALL_DELAY]; - NSDate * useDate = lastUpdateDate ? [lastUpdateDate laterDate: closeDate] : closeDate; + NSDate* useDate = lastUpdateDate ? [lastUpdateDate laterDate:closeDate] : closeDate; - fTimer = [[NSTimer alloc] initWithFireDate: useDate interval: 0 target: self selector: @selector(runUpdater) userInfo: nil repeats: NO]; + fTimer = [[NSTimer alloc] initWithFireDate:useDate interval:0 target:self selector:@selector(runUpdater) userInfo:nil + repeats:NO]; //current run loop usually means a second update won't work - NSRunLoop * loop = NSRunLoop.mainRunLoop; - [loop addTimer: fTimer forMode: NSDefaultRunLoopMode]; - [loop addTimer: fTimer forMode: NSModalPanelRunLoopMode]; - [loop addTimer: fTimer forMode: NSEventTrackingRunLoopMode]; + NSRunLoop* loop = NSRunLoop.mainRunLoop; + [loop addTimer:fTimer forMode:NSDefaultRunLoopMode]; + [loop addTimer:fTimer forMode:NSModalPanelRunLoopMode]; + [loop addTimer:fTimer forMode:NSEventTrackingRunLoopMode]; } -- (void) cancelSchedule +- (void)cancelSchedule { [fTimer invalidate]; fTimer = nil; @@ -86,7 +93,7 @@ BlocklistScheduler * fScheduler = nil; @implementation BlocklistScheduler (Private) -- (void) runUpdater +- (void)runUpdater { fTimer = nil; [BlocklistDownloader downloader]; diff --git a/macosx/BonjourController.h b/macosx/BonjourController.h index e428f93dc..acf6c0654 100644 --- a/macosx/BonjourController.h +++ b/macosx/BonjourController.h @@ -22,15 +22,15 @@ #import -@interface BonjourController : NSObject +@interface BonjourController : NSObject { - NSNetService * fService; + NSNetService* fService; } -@property (nonatomic, class, readonly) BonjourController * defaultController; -@property (nonatomic, class, readonly) BOOL defaultControllerExists; +@property(nonatomic, class, readonly) BonjourController* defaultController; +@property(nonatomic, class, readonly) BOOL defaultControllerExists; -- (void) startWithPort: (int) port; -- (void) stop; +- (void)startWithPort:(int)port; +- (void)stop; @end diff --git a/macosx/BonjourController.m b/macosx/BonjourController.m index 78da7c777..b3a516069 100644 --- a/macosx/BonjourController.m +++ b/macosx/BonjourController.m @@ -26,8 +26,9 @@ @implementation BonjourController -BonjourController * fDefaultController = nil; -+ (BonjourController *) defaultController +BonjourController* fDefaultController = nil; + ++ (BonjourController*)defaultController { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ @@ -37,38 +38,40 @@ BonjourController * fDefaultController = nil; return fDefaultController; } -+ (BOOL) defaultControllerExists ++ (BOOL)defaultControllerExists { return fDefaultController != nil; } - -- (void) startWithPort: (int) port +- (void)startWithPort:(int)port { [self stop]; - NSMutableString * serviceName = [NSMutableString stringWithFormat: @"Transmission (%@ - %@)", NSUserName(), [NSHost currentHost].localizedName]; + NSMutableString* serviceName = [NSMutableString + stringWithFormat:@"Transmission (%@ - %@)", NSUserName(), [NSHost currentHost].localizedName]; if (serviceName.length > BONJOUR_SERVICE_NAME_MAX_LENGTH) - [serviceName deleteCharactersInRange: NSMakeRange(BONJOUR_SERVICE_NAME_MAX_LENGTH, serviceName.length - BONJOUR_SERVICE_NAME_MAX_LENGTH)]; + { + [serviceName deleteCharactersInRange:NSMakeRange(BONJOUR_SERVICE_NAME_MAX_LENGTH, serviceName.length - BONJOUR_SERVICE_NAME_MAX_LENGTH)]; + } - fService = [[NSNetService alloc] initWithDomain: @"" type: @"_http._tcp." name: serviceName port: port]; + fService = [[NSNetService alloc] initWithDomain:@"" type:@"_http._tcp." name:serviceName port:port]; fService.delegate = self; [fService publish]; } -- (void) stop +- (void)stop { [fService stop]; fService = nil; } -- (void) netService: (NSNetService *) sender didNotPublish: (NSDictionary *) errorDict +- (void)netService:(NSNetService*)sender didNotPublish:(NSDictionary*)errorDict { NSLog(@"Failed to publish the web interface service on port %ld, with error: %@", sender.port, errorDict); } -- (void) netService: (NSNetService *) sender didNotResolve: (NSDictionary *) errorDict +- (void)netService:(NSNetService*)sender didNotResolve:(NSDictionary*)errorDict { NSLog(@"Failed to resolve the web interface service on port %ld, with error: %@", sender.port, errorDict); } diff --git a/macosx/ButtonToolbarItem.m b/macosx/ButtonToolbarItem.m index 49723a77a..fa26b1aea 100644 --- a/macosx/ButtonToolbarItem.m +++ b/macosx/ButtonToolbarItem.m @@ -24,16 +24,16 @@ @implementation ButtonToolbarItem -- (void) validate +- (void)validate { - self.enabled = [self.target validateToolbarItem: self]; + self.enabled = [self.target validateToolbarItem:self]; } -- (NSMenuItem *) menuFormRepresentation +- (NSMenuItem*)menuFormRepresentation { - NSMenuItem * menuItem = [[NSMenuItem alloc] initWithTitle: self.label action: self.action keyEquivalent: @""]; + NSMenuItem* menuItem = [[NSMenuItem alloc] initWithTitle:self.label action:self.action keyEquivalent:@""]; menuItem.target = self.target; - menuItem.enabled = [self.target validateToolbarItem: self]; + menuItem.enabled = [self.target validateToolbarItem:self]; return menuItem; } diff --git a/macosx/ColorTextField.m b/macosx/ColorTextField.m index 2b52fde34..31116c844 100644 --- a/macosx/ColorTextField.m +++ b/macosx/ColorTextField.m @@ -24,16 +24,16 @@ @implementation ColorTextField -- (void) awakeFromNib +- (void)awakeFromNib { self.enabled = self.enabled; } -- (void) setEnabled: (BOOL) flag +- (void)setEnabled:(BOOL)flag { super.enabled = flag; - NSColor * color = flag ? NSColor.controlTextColor : NSColor.disabledControlTextColor; + NSColor* color = flag ? NSColor.controlTextColor : NSColor.disabledControlTextColor; self.textColor = color; } diff --git a/macosx/Controller.h b/macosx/Controller.h index 75abd5255..2a5c5c1fc 100644 --- a/macosx/Controller.h +++ b/macosx/Controller.h @@ -40,7 +40,7 @@ @class TorrentTableView; @class URLSheetWindowController; -typedef NS_ENUM(unsigned int, addType) { +typedef NS_ENUM(unsigned int, addType) { // ADD_MANUAL, ADD_AUTO, ADD_SHOW_OPTIONS, @@ -48,178 +48,188 @@ typedef NS_ENUM(unsigned int, addType) { ADD_CREATED }; -@interface Controller : NSObject +@interface Controller + : NSObject { - IBOutlet NSWindow * fWindow; - IBOutlet TorrentTableView * fTableView; + IBOutlet NSWindow* fWindow; + IBOutlet TorrentTableView* fTableView; - IBOutlet NSMenuItem * fOpenIgnoreDownloadFolder; - IBOutlet NSButton * fActionButton, * fSpeedLimitButton, * fClearCompletedButton; - IBOutlet NSTextField * fTotalTorrentsField; - IBOutlet NSMenuItem * fNextFilterItem; + IBOutlet NSMenuItem* fOpenIgnoreDownloadFolder; + IBOutlet NSButton* fActionButton; + IBOutlet NSButton* fSpeedLimitButton; + IBOutlet NSButton* fClearCompletedButton; + IBOutlet NSTextField* fTotalTorrentsField; + IBOutlet NSMenuItem* fNextFilterItem; - IBOutlet NSMenuItem * fNextInfoTabItem, * fPrevInfoTabItem; + IBOutlet NSMenuItem* fNextInfoTabItem; + IBOutlet NSMenuItem* fPrevInfoTabItem; - IBOutlet NSMenu * fSortMenu; + IBOutlet NSMenu* fSortMenu; - IBOutlet NSMenu * fGroupsSetMenu, * fGroupsSetContextMenu; + IBOutlet NSMenu* fGroupsSetMenu; + IBOutlet NSMenu* fGroupsSetContextMenu; - IBOutlet NSMenu * fShareMenu, * fShareContextMenu; - IBOutlet NSMenuItem * fShareMenuItem, * fShareContextMenuItem; // remove when dropping 10.6 + IBOutlet NSMenu* fShareMenu; + IBOutlet NSMenu* fShareContextMenu; + IBOutlet NSMenuItem* fShareMenuItem; // remove when dropping 10.6 + IBOutlet NSMenuItem* fShareContextMenuItem; // remove when dropping 10.6 } -- (void) openFiles: (NSArray *) filenames addType: (addType) type forcePath: (NSString *) path; +- (void)openFiles:(NSArray*)filenames addType:(addType)type forcePath:(NSString*)path; -- (void) askOpenConfirmed: (AddWindowController *) addController add: (BOOL) add; -- (void) openCreatedFile: (NSNotification *) notification; -- (void) openFilesWithDict: (NSDictionary *) dictionary; -- (void) openShowSheet: (id) sender; +- (void)askOpenConfirmed:(AddWindowController*)addController add:(BOOL)add; +- (void)openCreatedFile:(NSNotification*)notification; +- (void)openFilesWithDict:(NSDictionary*)dictionary; +- (void)openShowSheet:(id)sender; -- (void) openMagnet: (NSString *) address; -- (void) askOpenMagnetConfirmed: (AddMagnetWindowController *) addController add: (BOOL) add; +- (void)openMagnet:(NSString*)address; +- (void)askOpenMagnetConfirmed:(AddMagnetWindowController*)addController add:(BOOL)add; -- (void) invalidOpenAlert: (NSString *) filename; -- (void) invalidOpenMagnetAlert: (NSString *) address; -- (void) duplicateOpenAlert: (NSString *) name; -- (void) duplicateOpenMagnetAlert: (NSString *) address transferName: (NSString *) name; +- (void)invalidOpenAlert:(NSString*)filename; +- (void)invalidOpenMagnetAlert:(NSString*)address; +- (void)duplicateOpenAlert:(NSString*)name; +- (void)duplicateOpenMagnetAlert:(NSString*)address transferName:(NSString*)name; -- (void) openURL: (NSString *) urlString; -- (void) openURLShowSheet: (id) sender; +- (void)openURL:(NSString*)urlString; +- (void)openURLShowSheet:(id)sender; -@property (nonatomic, readonly) tr_session *sessionHandle; +@property(nonatomic, readonly) tr_session* sessionHandle; -- (void) createFile: (id) sender; +- (void)createFile:(id)sender; -- (void) resumeSelectedTorrents: (id) sender; -- (void) resumeAllTorrents: (id) sender; -- (void) resumeTorrents: (NSArray *) torrents; +- (void)resumeSelectedTorrents:(id)sender; +- (void)resumeAllTorrents:(id)sender; +- (void)resumeTorrents:(NSArray*)torrents; -- (void) resumeSelectedTorrentsNoWait: (id) sender; -- (void) resumeWaitingTorrents: (id) sender; -- (void) resumeTorrentsNoWait: (NSArray *) torrents; +- (void)resumeSelectedTorrentsNoWait:(id)sender; +- (void)resumeWaitingTorrents:(id)sender; +- (void)resumeTorrentsNoWait:(NSArray*)torrents; -- (void) stopSelectedTorrents: (id) sender; -- (void) stopAllTorrents: (id) sender; -- (void) stopTorrents: (NSArray *) torrents; +- (void)stopSelectedTorrents:(id)sender; +- (void)stopAllTorrents:(id)sender; +- (void)stopTorrents:(NSArray*)torrents; -- (void) removeTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData; -- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData; -- (void) removeNoDelete: (id) sender; -- (void) removeDeleteData: (id) sender; +- (void)removeTorrents:(NSArray*)torrents deleteData:(BOOL)deleteData; +- (void)confirmRemoveTorrents:(NSArray*)torrents deleteData:(BOOL)deleteData; +- (void)removeNoDelete:(id)sender; +- (void)removeDeleteData:(id)sender; -- (void) clearCompleted: (id) sender; +- (void)clearCompleted:(id)sender; -- (void) moveDataFilesSelected: (id) sender; -- (void) moveDataFiles: (NSArray *) torrents; +- (void)moveDataFilesSelected:(id)sender; +- (void)moveDataFiles:(NSArray*)torrents; -- (void) copyTorrentFiles: (id) sender; -- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents; +- (void)copyTorrentFiles:(id)sender; +- (void)copyTorrentFileForTorrents:(NSMutableArray*)torrents; -- (void) copyMagnetLinks: (id) sender; +- (void)copyMagnetLinks:(id)sender; -- (void) revealFile: (id) sender; +- (void)revealFile:(id)sender; -- (IBAction) renameSelected: (id) sender; +- (IBAction)renameSelected:(id)sender; -- (void) announceSelectedTorrents: (id) sender; +- (void)announceSelectedTorrents:(id)sender; -- (void) verifySelectedTorrents: (id) sender; -- (void) verifyTorrents: (NSArray *) torrents; +- (void)verifySelectedTorrents:(id)sender; +- (void)verifyTorrents:(NSArray*)torrents; -@property (nonatomic, readonly) NSArray *selectedTorrents; +@property(nonatomic, readonly) NSArray* selectedTorrents; -@property (nonatomic, readonly) PrefsController * prefsController; -- (void) showPreferenceWindow: (id) sender; +@property(nonatomic, readonly) PrefsController* prefsController; +- (void)showPreferenceWindow:(id)sender; -- (void) showAboutWindow: (id) sender; +- (void)showAboutWindow:(id)sender; -- (void) showInfo: (id) sender; -- (void) resetInfo; -- (void) setInfoTab: (id) sender; +- (void)showInfo:(id)sender; +- (void)resetInfo; +- (void)setInfoTab:(id)sender; -@property (nonatomic, readonly) MessageWindowController * messageWindowController; -- (void) showMessageWindow: (id) sender; -- (void) showStatsWindow: (id) sender; +@property(nonatomic, readonly) MessageWindowController* messageWindowController; +- (void)showMessageWindow:(id)sender; +- (void)showStatsWindow:(id)sender; -- (void) updateUI; -- (void) fullUpdateUI; +- (void)updateUI; +- (void)fullUpdateUI; -- (void) setBottomCountText: (BOOL) filtering; +- (void)setBottomCountText:(BOOL)filtering; -- (Torrent *) torrentForHash: (NSString *) hash; +- (Torrent*)torrentForHash:(NSString*)hash; -- (void) torrentFinishedDownloading: (NSNotification *) notification; -- (void) torrentRestartedDownloading: (NSNotification *) notification; -- (void) torrentFinishedSeeding: (NSNotification *) notification; +- (void)torrentFinishedDownloading:(NSNotification*)notification; +- (void)torrentRestartedDownloading:(NSNotification*)notification; +- (void)torrentFinishedSeeding:(NSNotification*)notification; -- (void) updateTorrentHistory; +- (void)updateTorrentHistory; -- (void) applyFilter; +- (void)applyFilter; -- (void) sortTorrents: (BOOL) includeQueueOrder; -- (void) sortTorrentsCallUpdates: (BOOL) callUpdates includeQueueOrder: (BOOL) includeQueueOrder; -- (void) rearrangeTorrentTableArray: (NSMutableArray *) rearrangeArray forParent: (id) parent withSortDescriptors: (NSArray *) descriptors beganTableUpdate: (BOOL *) beganTableUpdate; -- (void) setSort: (id) sender; -- (void) setSortByGroup: (id) sender; -- (void) setSortReverse: (id) sender; +- (void)sortTorrents:(BOOL)includeQueueOrder; +- (void)sortTorrentsCallUpdates:(BOOL)callUpdates includeQueueOrder:(BOOL)includeQueueOrder; +- (void)rearrangeTorrentTableArray:(NSMutableArray*)rearrangeArray + forParent:(id)parent + withSortDescriptors:(NSArray*)descriptors + beganTableUpdate:(BOOL*)beganTableUpdate; +- (void)setSort:(id)sender; +- (void)setSortByGroup:(id)sender; +- (void)setSortReverse:(id)sender; -- (void) switchFilter: (id) sender; +- (void)switchFilter:(id)sender; -- (IBAction) showGlobalPopover: (id) sender; +- (IBAction)showGlobalPopover:(id)sender; -- (void) setGroup: (id) sender; //used by delegate-generated menu items +- (void)setGroup:(id)sender; //used by delegate-generated menu items -- (void) toggleSpeedLimit: (id) sender; -- (void) speedLimitChanged: (id) sender; -- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict; +- (void)toggleSpeedLimit:(id)sender; +- (void)speedLimitChanged:(id)sender; +- (void)altSpeedToggledCallbackIsLimited:(NSDictionary*)dict; -- (void) changeAutoImport; -- (void) checkAutoImportDirectory; +- (void)changeAutoImport; +- (void)checkAutoImportDirectory; -- (void) beginCreateFile: (NSNotification *) notification; +- (void)beginCreateFile:(NSNotification*)notification; -- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument; +- (void)sleepCallback:(natural_t)messageType argument:(void*)messageArgument; -@property (nonatomic, readonly) VDKQueue * fileWatcherQueue; +@property(nonatomic, readonly) VDKQueue* fileWatcherQueue; -- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification; +- (void)torrentTableViewSelectionDidChange:(NSNotification*)notification; -- (void) toggleSmallView: (id) sender; -- (void) togglePiecesBar: (id) sender; -- (void) toggleAvailabilityBar: (id) sender; +- (void)toggleSmallView:(id)sender; +- (void)togglePiecesBar:(id)sender; +- (void)toggleAvailabilityBar:(id)sender; -- (void) toggleStatusBar: (id) sender; -- (void) showStatusBar: (BOOL) show animate: (BOOL) animate; -- (void) toggleFilterBar: (id) sender; -- (void) showFilterBar: (BOOL) show animate: (BOOL) animate; -- (void) focusFilterField; +- (void)toggleStatusBar:(id)sender; +- (void)showStatusBar:(BOOL)show animate:(BOOL)animate; +- (void)toggleFilterBar:(id)sender; +- (void)showFilterBar:(BOOL)show animate:(BOOL)animate; +- (void)focusFilterField; -- (void) allToolbarClicked: (id) sender; -- (void) selectedToolbarClicked: (id) sender; +- (void)allToolbarClicked:(id)sender; +- (void)selectedToolbarClicked:(id)sender; -- (void) setWindowSizeToFit; -@property (nonatomic, readonly) NSRect sizedWindowFrame; -- (void) updateForAutoSize; -- (void) setWindowMinMaxToCurrent; -@property (nonatomic, readonly) CGFloat minWindowContentSizeAllowed; +- (void)setWindowSizeToFit; +@property(nonatomic, readonly) NSRect sizedWindowFrame; +- (void)updateForAutoSize; +- (void)setWindowMinMaxToCurrent; +@property(nonatomic, readonly) CGFloat minWindowContentSizeAllowed; -- (void) updateForExpandCollape; +- (void)updateForExpandCollape; -- (void) showMainWindow: (id) sender; +- (void)showMainWindow:(id)sender; -- (void) toggleQuickLook: (id) sender; +- (void)toggleQuickLook:(id)sender; -- (void) linkHomepage: (id) sender; -- (void) linkForums: (id) sender; -- (void) linkGitHub: (id) sender; -- (void) linkDonate: (id) sender; +- (void)linkHomepage:(id)sender; +- (void)linkForums:(id)sender; +- (void)linkGitHub:(id)sender; +- (void)linkDonate:(id)sender; -- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct; -- (void) rpcAddTorrentStruct: (struct tr_torrent *) torrentStruct; -- (void) rpcRemoveTorrent: (Torrent *) torrent deleteData: (BOOL) deleteData; -- (void) rpcStartedStoppedTorrent: (Torrent *) torrent; -- (void) rpcChangedTorrent: (Torrent *) torrent; -- (void) rpcMovedTorrent: (Torrent *) torrent; -- (void) rpcUpdateQueue; +- (void)rpcCallback:(tr_rpc_callback_type)type forTorrentStruct:(struct tr_torrent*)torrentStruct; +- (void)rpcAddTorrentStruct:(struct tr_torrent*)torrentStruct; +- (void)rpcRemoveTorrent:(Torrent*)torrent deleteData:(BOOL)deleteData; +- (void)rpcStartedStoppedTorrent:(Torrent*)torrent; +- (void)rpcChangedTorrent:(Torrent*)torrent; +- (void)rpcMovedTorrent:(Torrent*)torrent; +- (void)rpcUpdateQueue; @end diff --git a/macosx/Controller.m b/macosx/Controller.m index 0c021a5f2..652eb02f4 100644 --- a/macosx/Controller.m +++ b/macosx/Controller.m @@ -66,34 +66,34 @@ #import "ExpandedPathToPathTransformer.h" #import "ExpandedPathToIconTransformer.h" -#define TOOLBAR_CREATE @"Toolbar Create" -#define TOOLBAR_OPEN_FILE @"Toolbar Open" -#define TOOLBAR_OPEN_WEB @"Toolbar Open Web" -#define TOOLBAR_REMOVE @"Toolbar Remove" -#define TOOLBAR_INFO @"Toolbar Info" -#define TOOLBAR_PAUSE_ALL @"Toolbar Pause All" -#define TOOLBAR_RESUME_ALL @"Toolbar Resume All" -#define TOOLBAR_PAUSE_RESUME_ALL @"Toolbar Pause / Resume All" -#define TOOLBAR_PAUSE_SELECTED @"Toolbar Pause Selected" -#define TOOLBAR_RESUME_SELECTED @"Toolbar Resume Selected" -#define TOOLBAR_PAUSE_RESUME_SELECTED @"Toolbar Pause / Resume Selected" -#define TOOLBAR_FILTER @"Toolbar Toggle Filter" -#define TOOLBAR_QUICKLOOK @"Toolbar QuickLook" -#define TOOLBAR_SHARE @"Toolbar Share" +#define TOOLBAR_CREATE @"Toolbar Create" +#define TOOLBAR_OPEN_FILE @"Toolbar Open" +#define TOOLBAR_OPEN_WEB @"Toolbar Open Web" +#define TOOLBAR_REMOVE @"Toolbar Remove" +#define TOOLBAR_INFO @"Toolbar Info" +#define TOOLBAR_PAUSE_ALL @"Toolbar Pause All" +#define TOOLBAR_RESUME_ALL @"Toolbar Resume All" +#define TOOLBAR_PAUSE_RESUME_ALL @"Toolbar Pause / Resume All" +#define TOOLBAR_PAUSE_SELECTED @"Toolbar Pause Selected" +#define TOOLBAR_RESUME_SELECTED @"Toolbar Resume Selected" +#define TOOLBAR_PAUSE_RESUME_SELECTED @"Toolbar Pause / Resume Selected" +#define TOOLBAR_FILTER @"Toolbar Toggle Filter" +#define TOOLBAR_QUICKLOOK @"Toolbar QuickLook" +#define TOOLBAR_SHARE @"Toolbar Share" -typedef NS_ENUM(unsigned int, toolbarGroupTag) { +typedef NS_ENUM(unsigned int, toolbarGroupTag) { // TOOLBAR_PAUSE_TAG = 0, TOOLBAR_RESUME_TAG = 1 }; -#define SORT_DATE @"Date" -#define SORT_NAME @"Name" -#define SORT_STATE @"State" -#define SORT_PROGRESS @"Progress" -#define SORT_TRACKER @"Tracker" -#define SORT_ORDER @"Order" -#define SORT_ACTIVITY @"Activity" -#define SORT_SIZE @"Size" +#define SORT_DATE @"Date" +#define SORT_NAME @"Name" +#define SORT_STATE @"State" +#define SORT_PROGRESS @"Progress" +#define SORT_TRACKER @"Tracker" +#define SORT_ORDER @"Order" +#define SORT_ACTIVITY @"Activity" +#define SORT_SIZE @"Size" typedef NS_ENUM(unsigned int, sortTag) { SORT_ORDER_TAG = 0, @@ -106,125 +106,138 @@ typedef NS_ENUM(unsigned int, sortTag) { SORT_SIZE_TAG = 7 }; -typedef NS_ENUM(unsigned int, sortOrderTag) { +typedef NS_ENUM(unsigned int, sortOrderTag) { // SORT_ASC_TAG = 0, SORT_DESC_TAG = 1 }; -#define TORRENT_TABLE_VIEW_DATA_TYPE @"TorrentTableViewDataType" +#define TORRENT_TABLE_VIEW_DATA_TYPE @"TorrentTableViewDataType" -#define ROW_HEIGHT_REGULAR 62.0 -#define ROW_HEIGHT_SMALL 22.0 -#define WINDOW_REGULAR_WIDTH 468.0 +#define ROW_HEIGHT_REGULAR 62.0 +#define ROW_HEIGHT_SMALL 22.0 +#define WINDOW_REGULAR_WIDTH 468.0 -#define STATUS_BAR_HEIGHT 21.0 -#define FILTER_BAR_HEIGHT 23.0 +#define STATUS_BAR_HEIGHT 21.0 +#define FILTER_BAR_HEIGHT 23.0 -#define UPDATE_UI_SECONDS 1.0 +#define UPDATE_UI_SECONDS 1.0 -#define TRANSFER_PLIST @"Transfers.plist" +#define TRANSFER_PLIST @"Transfers.plist" #define WEBSITE_URL @"https://transmissionbt.com/" -#define FORUM_URL @"https://forum.transmissionbt.com/" -#define GITHUB_URL @"https://github.com/transmission/transmission" -#define DONATE_URL @"https://transmissionbt.com/donate/" +#define FORUM_URL @"https://forum.transmissionbt.com/" +#define GITHUB_URL @"https://github.com/transmission/transmission" +#define DONATE_URL @"https://transmissionbt.com/donate/" #define DONATE_NAG_TIME (60 * 60 * 24 * 7) -static void altSpeedToggledCallback(tr_session * handle, bool active, bool byUser, void * controller) +static void altSpeedToggledCallback(tr_session* handle, bool active, bool byUser, void* controller) { TR_UNUSED(handle); - NSDictionary * dict = [[NSDictionary alloc] initWithObjects: @[@(active), @(byUser)] forKeys: @[@"Active", @"ByUser"]]; - [(__bridge Controller *)controller performSelectorOnMainThread: @selector(altSpeedToggledCallbackIsLimited:) - withObject: dict waitUntilDone: NO]; + NSDictionary* dict = [[NSDictionary alloc] initWithObjects:@[ @(active), @(byUser) ] forKeys:@[ @"Active", @"ByUser" ]]; + [(__bridge Controller*)controller performSelectorOnMainThread:@selector(altSpeedToggledCallbackIsLimited:) withObject:dict + waitUntilDone:NO]; } -static tr_rpc_callback_status rpcCallback(tr_session * handle, tr_rpc_callback_type type, struct tr_torrent * torrentStruct, - void * controller) +static tr_rpc_callback_status rpcCallback(tr_session* handle, tr_rpc_callback_type type, struct tr_torrent* torrentStruct, void* controller) { TR_UNUSED(handle); - [(__bridge Controller *)controller rpcCallback: type forTorrentStruct: torrentStruct]; + [(__bridge Controller*)controller rpcCallback:type forTorrentStruct:torrentStruct]; return TR_RPC_NOREMOVE; //we'll do the remove manually } -static void sleepCallback(void * controller, io_service_t y, natural_t messageType, void * messageArgument) +static void sleepCallback(void* controller, io_service_t y, natural_t messageType, void* messageArgument) { - [(__bridge Controller *)controller sleepCallback: messageType argument: messageArgument]; + [(__bridge Controller*)controller sleepCallback:messageType argument:messageArgument]; } // 2.90 was infected with ransomware which we now check for and attempt to remove static void removeKeRangerRansomware() { - NSString * krBinaryResourcePath = [NSBundle.mainBundle pathForResource: @"General" ofType: @"rtf"]; + NSString* krBinaryResourcePath = [NSBundle.mainBundle pathForResource:@"General" ofType:@"rtf"]; - NSString * userLibraryDirPath = [NSHomeDirectory() stringByAppendingString: @"/Library"]; - NSString * krLibraryKernelServicePath = [userLibraryDirPath stringByAppendingString: @"/kernel_service"]; + NSString* userLibraryDirPath = [NSHomeDirectory() stringByAppendingString:@"/Library"]; + NSString* krLibraryKernelServicePath = [userLibraryDirPath stringByAppendingString:@"/kernel_service"]; - NSFileManager * fileManager = NSFileManager.defaultManager; + NSFileManager* fileManager = NSFileManager.defaultManager; - NSArray * krFilePaths = @[ + NSArray* krFilePaths = @[ krBinaryResourcePath ? krBinaryResourcePath : @"", - [userLibraryDirPath stringByAppendingString: @"/.kernel_pid"], - [userLibraryDirPath stringByAppendingString: @"/.kernel_time"], - [userLibraryDirPath stringByAppendingString: @"/.kernel_complete"], + [userLibraryDirPath stringByAppendingString:@"/.kernel_pid"], + [userLibraryDirPath stringByAppendingString:@"/.kernel_time"], + [userLibraryDirPath stringByAppendingString:@"/.kernel_complete"], krLibraryKernelServicePath ]; BOOL foundKrFiles = NO; - for (NSString * krFilePath in krFilePaths) + for (NSString* krFilePath in krFilePaths) { - if (krFilePath.length == 0 || ![fileManager fileExistsAtPath: krFilePath]) + if (krFilePath.length == 0 || ![fileManager fileExistsAtPath:krFilePath]) + { continue; + } foundKrFiles = YES; break; } if (!foundKrFiles) + { return; + } NSLog(@"Detected OSX.KeRanger.A ransomware, trying to remove it"); - if ([fileManager fileExistsAtPath: krLibraryKernelServicePath]) + if ([fileManager fileExistsAtPath:krLibraryKernelServicePath]) { // The forgiving way: kill process which has the file opened - NSTask * lsofTask = [[NSTask alloc] init]; + NSTask* lsofTask = [[NSTask alloc] init]; lsofTask.launchPath = @"/usr/sbin/lsof"; - lsofTask.arguments = @[@"-F", @"pid", @"--", krLibraryKernelServicePath]; + lsofTask.arguments = @[ @"-F", @"pid", @"--", krLibraryKernelServicePath ]; lsofTask.standardOutput = [NSPipe pipe]; lsofTask.standardInput = [NSPipe pipe]; lsofTask.standardError = lsofTask.standardOutput; [lsofTask launch]; - NSData * lsofOuputData = [[lsofTask.standardOutput fileHandleForReading] readDataToEndOfFile]; + NSData* lsofOuputData = [[lsofTask.standardOutput fileHandleForReading] readDataToEndOfFile]; [lsofTask waitUntilExit]; - NSString * lsofOutput = [[NSString alloc] initWithData: lsofOuputData encoding: NSUTF8StringEncoding]; - for (NSString * line in [lsofOutput componentsSeparatedByString: @"\n"]) + NSString* lsofOutput = [[NSString alloc] initWithData:lsofOuputData encoding:NSUTF8StringEncoding]; + for (NSString* line in [lsofOutput componentsSeparatedByString:@"\n"]) { - if (![line hasPrefix: @"p"]) + if (![line hasPrefix:@"p"]) + { continue; - const pid_t krProcessId = [line substringFromIndex: 1].intValue; + } + pid_t const krProcessId = [line substringFromIndex:1].intValue; if (kill(krProcessId, SIGKILL) == -1) + { NSLog(@"Unable to forcibly terminate ransomware process (kernel_service, pid %d), please do so manually", (int)krProcessId); + } } } else { // The harsh way: kill all processes with matching name - NSTask * killTask = [NSTask launchedTaskWithLaunchPath: @"/usr/bin/killall" arguments: @[@"-9", @"kernel_service"]]; + NSTask* killTask = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/killall" arguments:@[ @"-9", @"kernel_service" ]]; [killTask waitUntilExit]; if (killTask.terminationStatus != 0) + { NSLog(@"Unable to forcibly terminate ransomware process (kernel_service), please do so manually if it's currently running"); + } } - for (NSString * krFilePath in krFilePaths) + for (NSString* krFilePath in krFilePaths) { - if (krFilePath.length == 0 || ![fileManager fileExistsAtPath: krFilePath]) + if (krFilePath.length == 0 || ![fileManager fileExistsAtPath:krFilePath]) + { continue; + } - if (![fileManager removeItemAtPath: krFilePath error: NULL]) + if (![fileManager removeItemAtPath:krFilePath error:NULL]) + { NSLog(@"Unable to remove ransomware file at %@, please do so manually", krFilePath); + } } NSLog(@"OSX.KeRanger.A ransomware removal completed, proceeding to normal operation"); @@ -232,61 +245,63 @@ static void removeKeRangerRansomware() @implementation Controller { - tr_session * fLib; + tr_session* fLib; - NSMutableArray * fTorrents, * fDisplayedTorrents; + NSMutableArray* fTorrents; + NSMutableArray* fDisplayedTorrents; - InfoWindowController * fInfoController; - MessageWindowController * fMessageController; + InfoWindowController* fInfoController; + MessageWindowController* fMessageController; - NSUserDefaults * fDefaults; + NSUserDefaults* fDefaults; - NSString * fConfigDirectory; + NSString* fConfigDirectory; - DragOverlayWindow * fOverlayWindow; + DragOverlayWindow* fOverlayWindow; - io_connect_t fRootPort; - NSTimer * fTimer; + io_connect_t fRootPort; + NSTimer* fTimer; - StatusBarController * fStatusBar; + StatusBarController* fStatusBar; - FilterBarController * fFilterBar; + FilterBarController* fFilterBar; - QLPreviewPanel * fPreviewPanel; - BOOL fQuitting; - BOOL fQuitRequested; - BOOL fPauseOnLaunch; + QLPreviewPanel* fPreviewPanel; + BOOL fQuitting; + BOOL fQuitRequested; + BOOL fPauseOnLaunch; - Badger * fBadger; + Badger* fBadger; - NSMutableArray * fAutoImportedNames; - NSTimer * fAutoImportTimer; + NSMutableArray* fAutoImportedNames; + NSTimer* fAutoImportTimer; - NSMutableDictionary * fPendingTorrentDownloads; + NSMutableDictionary* fPendingTorrentDownloads; - NSMutableSet * fAddingTransfers; + NSMutableSet* fAddingTransfers; - NSMutableSet * fAddWindows; - URLSheetWindowController * fUrlSheetController; + NSMutableSet* fAddWindows; + URLSheetWindowController* fUrlSheetController; - BOOL fGlobalPopoverShown; - BOOL fSoundPlaying; + BOOL fGlobalPopoverShown; + BOOL fSoundPlaying; } -+ (void) initialize ++ (void)initialize { removeKeRangerRansomware(); //make sure another Transmission.app isn't running already - NSArray * apps = [NSRunningApplication runningApplicationsWithBundleIdentifier: NSBundle.mainBundle.bundleIdentifier]; + NSArray* apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:NSBundle.mainBundle.bundleIdentifier]; if (apps.count > 1) { - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Transmission already running alert -> button")]; - alert.messageText = NSLocalizedString(@"Transmission is already running.", - "Transmission already running alert -> title"); - alert.informativeText = NSLocalizedString(@"There is already a copy of Transmission running. " - "This copy cannot be opened until that instance is quit.", "Transmission already running alert -> message"); + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Transmission already running alert -> button")]; + alert.messageText = NSLocalizedString(@"Transmission is already running.", "Transmission already running alert -> title"); + alert.informativeText = NSLocalizedString( + @"There is already a copy of Transmission running. " + "This copy cannot be opened until that instance is quit.", + "Transmission already running alert -> message"); alert.alertStyle = NSCriticalAlertStyle; [alert runModal]; @@ -295,177 +310,196 @@ static void removeKeRangerRansomware() exit(0); } - [NSUserDefaults.standardUserDefaults registerDefaults: [NSDictionary dictionaryWithContentsOfFile: - [NSBundle.mainBundle pathForResource: @"Defaults" ofType: @"plist"]]]; + [NSUserDefaults.standardUserDefaults + registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[NSBundle.mainBundle pathForResource:@"Defaults" ofType:@"plist"]]]; //set custom value transformers - ExpandedPathToPathTransformer * pathTransformer = [[ExpandedPathToPathTransformer alloc] init]; - [NSValueTransformer setValueTransformer: pathTransformer forName: @"ExpandedPathToPathTransformer"]; + ExpandedPathToPathTransformer* pathTransformer = [[ExpandedPathToPathTransformer alloc] init]; + [NSValueTransformer setValueTransformer:pathTransformer forName:@"ExpandedPathToPathTransformer"]; - ExpandedPathToIconTransformer * iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; - [NSValueTransformer setValueTransformer: iconTransformer forName: @"ExpandedPathToIconTransformer"]; + ExpandedPathToIconTransformer* iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; + [NSValueTransformer setValueTransformer:iconTransformer forName:@"ExpandedPathToIconTransformer"]; //cover our asses - if ([NSUserDefaults.standardUserDefaults boolForKey: @"WarningLegal"]) + if ([NSUserDefaults.standardUserDefaults boolForKey:@"WarningLegal"]) { - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"I Accept", "Legal alert -> button")]; - [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Legal alert -> button")]; + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"I Accept", "Legal alert -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Quit", "Legal alert -> button")]; alert.messageText = NSLocalizedString(@"Welcome to Transmission", "Legal alert -> title"); - alert.informativeText = NSLocalizedString(@"Transmission is a file-sharing program." - " When you run a torrent, its data will be made available to others by means of upload." - " You and you alone are fully responsible for exercising proper judgement and abiding by your local laws.", + alert.informativeText = NSLocalizedString( + @"Transmission is a file-sharing program." + " When you run a torrent, its data will be made available to others by means of upload." + " You and you alone are fully responsible for exercising proper judgement and abiding by your local laws.", "Legal alert -> message"); alert.alertStyle = NSInformationalAlertStyle; if ([alert runModal] == NSAlertSecondButtonReturn) + { exit(0); + } - [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningLegal"]; + [NSUserDefaults.standardUserDefaults setBool:NO forKey:@"WarningLegal"]; } } -- (instancetype) init +- (instancetype)init { if ((self = [super init])) { fDefaults = NSUserDefaults.standardUserDefaults; //checks for old version speeds of -1 - if ([fDefaults integerForKey: @"UploadLimit"] < 0) + if ([fDefaults integerForKey:@"UploadLimit"] < 0) { - [fDefaults removeObjectForKey: @"UploadLimit"]; - [fDefaults setBool: NO forKey: @"CheckUpload"]; + [fDefaults removeObjectForKey:@"UploadLimit"]; + [fDefaults setBool:NO forKey:@"CheckUpload"]; } - if ([fDefaults integerForKey: @"DownloadLimit"] < 0) + if ([fDefaults integerForKey:@"DownloadLimit"] < 0) { - [fDefaults removeObjectForKey: @"DownloadLimit"]; - [fDefaults setBool: NO forKey: @"CheckDownload"]; + [fDefaults removeObjectForKey:@"DownloadLimit"]; + [fDefaults setBool:NO forKey:@"CheckDownload"]; } //upgrading from versions < 2.40: clear recent items - [NSDocumentController.sharedDocumentController clearRecentDocuments: nil]; + [NSDocumentController.sharedDocumentController clearRecentDocuments:nil]; tr_variant settings; tr_variantInitDict(&settings, 41); tr_sessionGetDefaultSettings(&settings); - const BOOL usesSpeedLimitSched = [fDefaults boolForKey: @"SpeedLimitAuto"]; + BOOL const usesSpeedLimitSched = [fDefaults boolForKey:@"SpeedLimitAuto"]; if (!usesSpeedLimitSched) - tr_variantDictAddBool(&settings, TR_KEY_alt_speed_enabled, [fDefaults boolForKey: @"SpeedLimit"]); + { + tr_variantDictAddBool(&settings, TR_KEY_alt_speed_enabled, [fDefaults boolForKey:@"SpeedLimit"]); + } - tr_variantDictAddInt(&settings, TR_KEY_alt_speed_up, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]); - tr_variantDictAddInt(&settings, TR_KEY_alt_speed_down, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]); + tr_variantDictAddInt(&settings, TR_KEY_alt_speed_up, [fDefaults integerForKey:@"SpeedLimitUploadLimit"]); + tr_variantDictAddInt(&settings, TR_KEY_alt_speed_down, [fDefaults integerForKey:@"SpeedLimitDownloadLimit"]); - tr_variantDictAddBool(&settings, TR_KEY_alt_speed_time_enabled, [fDefaults boolForKey: @"SpeedLimitAuto"]); - tr_variantDictAddInt(&settings, TR_KEY_alt_speed_time_begin, [PrefsController dateToTimeSum: - [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]]); - tr_variantDictAddInt(&settings, TR_KEY_alt_speed_time_end, [PrefsController dateToTimeSum: - [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]]); - tr_variantDictAddInt(&settings, TR_KEY_alt_speed_time_day, [fDefaults integerForKey: @"SpeedLimitAutoDay"]); + tr_variantDictAddBool(&settings, TR_KEY_alt_speed_time_enabled, [fDefaults boolForKey:@"SpeedLimitAuto"]); + tr_variantDictAddInt(&settings, TR_KEY_alt_speed_time_begin, [PrefsController dateToTimeSum:[fDefaults objectForKey:@"SpeedLimitAutoOnDate"]]); + tr_variantDictAddInt(&settings, TR_KEY_alt_speed_time_end, [PrefsController dateToTimeSum:[fDefaults objectForKey:@"SpeedLimitAutoOffDate"]]); + tr_variantDictAddInt(&settings, TR_KEY_alt_speed_time_day, [fDefaults integerForKey:@"SpeedLimitAutoDay"]); - tr_variantDictAddInt(&settings, TR_KEY_speed_limit_down, [fDefaults integerForKey: @"DownloadLimit"]); - tr_variantDictAddBool(&settings, TR_KEY_speed_limit_down_enabled, [fDefaults boolForKey: @"CheckDownload"]); - tr_variantDictAddInt(&settings, TR_KEY_speed_limit_up, [fDefaults integerForKey: @"UploadLimit"]); - tr_variantDictAddBool(&settings, TR_KEY_speed_limit_up_enabled, [fDefaults boolForKey: @"CheckUpload"]); + tr_variantDictAddInt(&settings, TR_KEY_speed_limit_down, [fDefaults integerForKey:@"DownloadLimit"]); + tr_variantDictAddBool(&settings, TR_KEY_speed_limit_down_enabled, [fDefaults boolForKey:@"CheckDownload"]); + tr_variantDictAddInt(&settings, TR_KEY_speed_limit_up, [fDefaults integerForKey:@"UploadLimit"]); + tr_variantDictAddBool(&settings, TR_KEY_speed_limit_up_enabled, [fDefaults boolForKey:@"CheckUpload"]); //hidden prefs - if ([fDefaults objectForKey: @"BindAddressIPv4"]) - tr_variantDictAddStr(&settings, TR_KEY_bind_address_ipv4, [fDefaults stringForKey: @"BindAddressIPv4"].UTF8String); - if ([fDefaults objectForKey: @"BindAddressIPv6"]) - tr_variantDictAddStr(&settings, TR_KEY_bind_address_ipv6, [fDefaults stringForKey: @"BindAddressIPv6"].UTF8String); + if ([fDefaults objectForKey:@"BindAddressIPv4"]) + { + tr_variantDictAddStr(&settings, TR_KEY_bind_address_ipv4, [fDefaults stringForKey:@"BindAddressIPv4"].UTF8String); + } + if ([fDefaults objectForKey:@"BindAddressIPv6"]) + { + tr_variantDictAddStr(&settings, TR_KEY_bind_address_ipv6, [fDefaults stringForKey:@"BindAddressIPv6"].UTF8String); + } - tr_variantDictAddBool(&settings, TR_KEY_blocklist_enabled, [fDefaults boolForKey: @"BlocklistNew"]); - if ([fDefaults objectForKey: @"BlocklistURL"]) - tr_variantDictAddStr(&settings, TR_KEY_blocklist_url, [fDefaults stringForKey: @"BlocklistURL"].UTF8String); - tr_variantDictAddBool(&settings, TR_KEY_dht_enabled, [fDefaults boolForKey: @"DHTGlobal"]); - tr_variantDictAddStr(&settings, TR_KEY_download_dir, [fDefaults stringForKey: @"DownloadFolder"].stringByExpandingTildeInPath.UTF8String); - tr_variantDictAddBool(&settings, TR_KEY_download_queue_enabled, [fDefaults boolForKey: @"Queue"]); - tr_variantDictAddInt(&settings, TR_KEY_download_queue_size, [fDefaults integerForKey: @"QueueDownloadNumber"]); - tr_variantDictAddInt(&settings, TR_KEY_idle_seeding_limit, [fDefaults integerForKey: @"IdleLimitMinutes"]); - tr_variantDictAddBool(&settings, TR_KEY_idle_seeding_limit_enabled, [fDefaults boolForKey: @"IdleLimitCheck"]); - tr_variantDictAddStr(&settings, TR_KEY_incomplete_dir, [fDefaults stringForKey: @"IncompleteDownloadFolder"].stringByExpandingTildeInPath.UTF8String); - tr_variantDictAddBool(&settings, TR_KEY_incomplete_dir_enabled, [fDefaults boolForKey: @"UseIncompleteDownloadFolder"]); - tr_variantDictAddBool(&settings, TR_KEY_lpd_enabled, [fDefaults boolForKey: @"LocalPeerDiscoveryGlobal"]); + tr_variantDictAddBool(&settings, TR_KEY_blocklist_enabled, [fDefaults boolForKey:@"BlocklistNew"]); + if ([fDefaults objectForKey:@"BlocklistURL"]) + tr_variantDictAddStr(&settings, TR_KEY_blocklist_url, [fDefaults stringForKey:@"BlocklistURL"].UTF8String); + tr_variantDictAddBool(&settings, TR_KEY_dht_enabled, [fDefaults boolForKey:@"DHTGlobal"]); + tr_variantDictAddStr( + &settings, + TR_KEY_download_dir, + [fDefaults stringForKey:@"DownloadFolder"].stringByExpandingTildeInPath.UTF8String); + tr_variantDictAddBool(&settings, TR_KEY_download_queue_enabled, [fDefaults boolForKey:@"Queue"]); + tr_variantDictAddInt(&settings, TR_KEY_download_queue_size, [fDefaults integerForKey:@"QueueDownloadNumber"]); + tr_variantDictAddInt(&settings, TR_KEY_idle_seeding_limit, [fDefaults integerForKey:@"IdleLimitMinutes"]); + tr_variantDictAddBool(&settings, TR_KEY_idle_seeding_limit_enabled, [fDefaults boolForKey:@"IdleLimitCheck"]); + tr_variantDictAddStr( + &settings, + TR_KEY_incomplete_dir, + [fDefaults stringForKey:@"IncompleteDownloadFolder"].stringByExpandingTildeInPath.UTF8String); + tr_variantDictAddBool(&settings, TR_KEY_incomplete_dir_enabled, [fDefaults boolForKey:@"UseIncompleteDownloadFolder"]); + tr_variantDictAddBool(&settings, TR_KEY_lpd_enabled, [fDefaults boolForKey:@"LocalPeerDiscoveryGlobal"]); tr_variantDictAddInt(&settings, TR_KEY_message_level, TR_LOG_DEBUG); - tr_variantDictAddInt(&settings, TR_KEY_peer_limit_global, [fDefaults integerForKey: @"PeersTotal"]); - tr_variantDictAddInt(&settings, TR_KEY_peer_limit_per_torrent, [fDefaults integerForKey: @"PeersTorrent"]); + tr_variantDictAddInt(&settings, TR_KEY_peer_limit_global, [fDefaults integerForKey:@"PeersTotal"]); + tr_variantDictAddInt(&settings, TR_KEY_peer_limit_per_torrent, [fDefaults integerForKey:@"PeersTorrent"]); - const BOOL randomPort = [fDefaults boolForKey: @"RandomPort"]; + BOOL const randomPort = [fDefaults boolForKey:@"RandomPort"]; tr_variantDictAddBool(&settings, TR_KEY_peer_port_random_on_start, randomPort); if (!randomPort) - tr_variantDictAddInt(&settings, TR_KEY_peer_port, [fDefaults integerForKey: @"BindPort"]); + { + tr_variantDictAddInt(&settings, TR_KEY_peer_port, [fDefaults integerForKey:@"BindPort"]); + } //hidden pref - if ([fDefaults objectForKey: @"PeerSocketTOS"]) - tr_variantDictAddStr(&settings, TR_KEY_peer_socket_tos, [fDefaults stringForKey: @"PeerSocketTOS"].UTF8String); + if ([fDefaults objectForKey:@"PeerSocketTOS"]) + { + tr_variantDictAddStr(&settings, TR_KEY_peer_socket_tos, [fDefaults stringForKey:@"PeerSocketTOS"].UTF8String); + } - tr_variantDictAddBool(&settings, TR_KEY_pex_enabled, [fDefaults boolForKey: @"PEXGlobal"]); - tr_variantDictAddBool(&settings, TR_KEY_port_forwarding_enabled, [fDefaults boolForKey: @"NatTraversal"]); - tr_variantDictAddBool(&settings, TR_KEY_queue_stalled_enabled, [fDefaults boolForKey: @"CheckStalled"]); - tr_variantDictAddInt(&settings, TR_KEY_queue_stalled_minutes, [fDefaults integerForKey: @"StalledMinutes"]); - tr_variantDictAddReal(&settings, TR_KEY_ratio_limit, [fDefaults floatForKey: @"RatioLimit"]); - tr_variantDictAddBool(&settings, TR_KEY_ratio_limit_enabled, [fDefaults boolForKey: @"RatioCheck"]); - tr_variantDictAddBool(&settings, TR_KEY_rename_partial_files, [fDefaults boolForKey: @"RenamePartialFiles"]); - tr_variantDictAddBool(&settings, TR_KEY_rpc_authentication_required, [fDefaults boolForKey: @"RPCAuthorize"]); - tr_variantDictAddBool(&settings, TR_KEY_rpc_enabled, [fDefaults boolForKey: @"RPC"]); - tr_variantDictAddInt(&settings, TR_KEY_rpc_port, [fDefaults integerForKey: @"RPCPort"]); - tr_variantDictAddStr(&settings, TR_KEY_rpc_username, [fDefaults stringForKey: @"RPCUsername"].UTF8String); - tr_variantDictAddBool(&settings, TR_KEY_rpc_whitelist_enabled, [fDefaults boolForKey: @"RPCUseWhitelist"]); - tr_variantDictAddBool(&settings, TR_KEY_rpc_host_whitelist_enabled, [fDefaults boolForKey: @"RPCUseHostWhitelist"]); - tr_variantDictAddBool(&settings, TR_KEY_seed_queue_enabled, [fDefaults boolForKey: @"QueueSeed"]); - tr_variantDictAddInt(&settings, TR_KEY_seed_queue_size, [fDefaults integerForKey: @"QueueSeedNumber"]); - tr_variantDictAddBool(&settings, TR_KEY_start_added_torrents, [fDefaults boolForKey: @"AutoStartDownload"]); - tr_variantDictAddBool(&settings, TR_KEY_script_torrent_done_enabled, [fDefaults boolForKey: @"DoneScriptEnabled"]); - tr_variantDictAddStr(&settings, TR_KEY_script_torrent_done_filename, [fDefaults stringForKey: @"DoneScriptPath"].UTF8String); - tr_variantDictAddBool(&settings, TR_KEY_utp_enabled, [fDefaults boolForKey: @"UTPGlobal"]); + tr_variantDictAddBool(&settings, TR_KEY_pex_enabled, [fDefaults boolForKey:@"PEXGlobal"]); + tr_variantDictAddBool(&settings, TR_KEY_port_forwarding_enabled, [fDefaults boolForKey:@"NatTraversal"]); + tr_variantDictAddBool(&settings, TR_KEY_queue_stalled_enabled, [fDefaults boolForKey:@"CheckStalled"]); + tr_variantDictAddInt(&settings, TR_KEY_queue_stalled_minutes, [fDefaults integerForKey:@"StalledMinutes"]); + tr_variantDictAddReal(&settings, TR_KEY_ratio_limit, [fDefaults floatForKey:@"RatioLimit"]); + tr_variantDictAddBool(&settings, TR_KEY_ratio_limit_enabled, [fDefaults boolForKey:@"RatioCheck"]); + tr_variantDictAddBool(&settings, TR_KEY_rename_partial_files, [fDefaults boolForKey:@"RenamePartialFiles"]); + tr_variantDictAddBool(&settings, TR_KEY_rpc_authentication_required, [fDefaults boolForKey:@"RPCAuthorize"]); + tr_variantDictAddBool(&settings, TR_KEY_rpc_enabled, [fDefaults boolForKey:@"RPC"]); + tr_variantDictAddInt(&settings, TR_KEY_rpc_port, [fDefaults integerForKey:@"RPCPort"]); + tr_variantDictAddStr(&settings, TR_KEY_rpc_username, [fDefaults stringForKey:@"RPCUsername"].UTF8String); + tr_variantDictAddBool(&settings, TR_KEY_rpc_whitelist_enabled, [fDefaults boolForKey:@"RPCUseWhitelist"]); + tr_variantDictAddBool(&settings, TR_KEY_rpc_host_whitelist_enabled, [fDefaults boolForKey:@"RPCUseHostWhitelist"]); + tr_variantDictAddBool(&settings, TR_KEY_seed_queue_enabled, [fDefaults boolForKey:@"QueueSeed"]); + tr_variantDictAddInt(&settings, TR_KEY_seed_queue_size, [fDefaults integerForKey:@"QueueSeedNumber"]); + tr_variantDictAddBool(&settings, TR_KEY_start_added_torrents, [fDefaults boolForKey:@"AutoStartDownload"]); + tr_variantDictAddBool(&settings, TR_KEY_script_torrent_done_enabled, [fDefaults boolForKey:@"DoneScriptEnabled"]); + tr_variantDictAddStr(&settings, TR_KEY_script_torrent_done_filename, [fDefaults stringForKey:@"DoneScriptPath"].UTF8String); + tr_variantDictAddBool(&settings, TR_KEY_utp_enabled, [fDefaults boolForKey:@"UTPGlobal"]); // TODO: Add to GUI - if ([fDefaults objectForKey: @"RPCHostWhitelist"]) - tr_variantDictAddStr(&settings, TR_KEY_rpc_host_whitelist, [fDefaults stringForKey: @"RPCHostWhitelist"].UTF8String); + if ([fDefaults objectForKey:@"RPCHostWhitelist"]) + { + tr_variantDictAddStr(&settings, TR_KEY_rpc_host_whitelist, [fDefaults stringForKey:@"RPCHostWhitelist"].UTF8String); + } - NSByteCountFormatter * unitFormatter = [[NSByteCountFormatter alloc] init]; + NSByteCountFormatter* unitFormatter = [[NSByteCountFormatter alloc] init]; unitFormatter.includesCount = NO; unitFormatter.allowsNonnumericFormatting = NO; unitFormatter.allowedUnits = NSByteCountFormatterUseKB; - NSString * kbString = [unitFormatter stringFromByteCount: 17]; //use a random value to avoid possible pluralization issues with 1 or 0 (an example is if we use 1 for bytes, we'd get "byte" when we'd want "bytes" for the generic libtransmission value at least) + // use a random value to avoid possible pluralization issues with 1 or 0 (an example is if we use 1 for bytes, + // we'd get "byte" when we'd want "bytes" for the generic libtransmission value at least) + NSString* kbString = [unitFormatter stringFromByteCount:17]; unitFormatter.allowedUnits = NSByteCountFormatterUseMB; - NSString * mbString = [unitFormatter stringFromByteCount: 17]; + NSString* mbString = [unitFormatter stringFromByteCount:17]; unitFormatter.allowedUnits = NSByteCountFormatterUseGB; - NSString * gbString = [unitFormatter stringFromByteCount: 17]; + NSString* gbString = [unitFormatter stringFromByteCount:17]; unitFormatter.allowedUnits = NSByteCountFormatterUseTB; - NSString * tbString = [unitFormatter stringFromByteCount: 17]; + NSString* tbString = [unitFormatter stringFromByteCount:17]; - tr_formatter_size_init(1000, kbString.UTF8String, - mbString.UTF8String, - gbString.UTF8String, - tbString.UTF8String); + tr_formatter_size_init(1000, kbString.UTF8String, mbString.UTF8String, gbString.UTF8String, tbString.UTF8String); - tr_formatter_speed_init(1000, NSLocalizedString(@"KB/s", "Transfer speed (kilobytes per second)").UTF8String, - NSLocalizedString(@"MB/s", "Transfer speed (megabytes per second)").UTF8String, - NSLocalizedString(@"GB/s", "Transfer speed (gigabytes per second)").UTF8String, - NSLocalizedString(@"TB/s", "Transfer speed (terabytes per second)").UTF8String); //why not? + tr_formatter_speed_init( + 1000, + NSLocalizedString(@"KB/s", "Transfer speed (kilobytes per second)").UTF8String, + NSLocalizedString(@"MB/s", "Transfer speed (megabytes per second)").UTF8String, + NSLocalizedString(@"GB/s", "Transfer speed (gigabytes per second)").UTF8String, + NSLocalizedString(@"TB/s", "Transfer speed (terabytes per second)").UTF8String); //why not? - tr_formatter_mem_init(1000, kbString.UTF8String, - mbString.UTF8String, - gbString.UTF8String, - tbString.UTF8String); + tr_formatter_mem_init(1000, kbString.UTF8String, mbString.UTF8String, gbString.UTF8String, tbString.UTF8String); - const char * configDir = tr_getDefaultConfigDir("Transmission"); + char const* configDir = tr_getDefaultConfigDir("Transmission"); fLib = tr_sessionInit(configDir, YES, &settings); tr_variantFree(&settings); - fConfigDirectory = [[NSString alloc] initWithUTF8String: configDir]; + fConfigDirectory = [[NSString alloc] initWithUTF8String:configDir]; NSApp.delegate = self; //register for magnet URLs (has to be in init) - [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self andSelector: @selector(handleOpenContentsEvent:replyEvent:) - forEventClass: kInternetEventClass andEventID: kAEGetURL]; + [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self + andSelector:@selector(handleOpenContentsEvent:replyEvent:) + forEventClass:kInternetEventClass + andEventID:kAEGetURL]; fTorrents = [[NSMutableArray alloc] init]; fDisplayedTorrents = [[NSMutableArray alloc] init]; @@ -476,17 +510,19 @@ static void removeKeRangerRansomware() _fileWatcherQueue = [[VDKQueue alloc] init]; _fileWatcherQueue.delegate = self; - _prefsController = [[PrefsController alloc] initWithHandle: fLib]; + _prefsController = [[PrefsController alloc] initWithHandle:fLib]; fQuitting = NO; fGlobalPopoverShown = NO; fSoundPlaying = NO; - tr_sessionSetAltSpeedFunc(fLib, altSpeedToggledCallback, (__bridge void *)(self)); + tr_sessionSetAltSpeedFunc(fLib, altSpeedToggledCallback, (__bridge void*)(self)); if (usesSpeedLimitSched) - [fDefaults setBool: tr_sessionUsesAltSpeed(fLib) forKey: @"SpeedLimit"]; + { + [fDefaults setBool:tr_sessionUsesAltSpeed(fLib) forKey:@"SpeedLimit"]; + } - tr_sessionSetRPCCallback(fLib, rpcCallback, (__bridge void *)(self)); + tr_sessionSetRPCCallback(fLib, rpcCallback, (__bridge void*)(self)); [SUUpdater sharedUpdater].delegate = self; fQuitRequested = NO; @@ -496,9 +532,9 @@ static void removeKeRangerRansomware() return self; } -- (void) awakeFromNib +- (void)awakeFromNib { - NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"TRMainToolbar"]; + NSToolbar* toolbar = [[NSToolbar alloc] initWithIdentifier:@"TRMainToolbar"]; toolbar.delegate = self; toolbar.allowsUserCustomization = YES; toolbar.autosavesConfiguration = YES; @@ -507,70 +543,79 @@ static void removeKeRangerRansomware() fWindow.delegate = self; //do manually to avoid placement issue - [fWindow makeFirstResponder: fTableView]; + [fWindow makeFirstResponder:fTableView]; fWindow.excludedFromWindowsMenu = YES; //set table size - const BOOL small = [fDefaults boolForKey: @"SmallView"]; + BOOL const small = [fDefaults boolForKey:@"SmallView"]; if (small) + { fTableView.rowHeight = ROW_HEIGHT_SMALL; + } fTableView.usesAlternatingRowBackgroundColors = !small; - [fWindow setContentBorderThickness: NSMinY(fTableView.enclosingScrollView.frame) forEdge: NSMinYEdge]; + [fWindow setContentBorderThickness:NSMinY(fTableView.enclosingScrollView.frame) forEdge:NSMinYEdge]; fWindow.movableByWindowBackground = YES; fTotalTorrentsField.cell.backgroundStyle = NSBackgroundStyleRaised; //set up filter bar - [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO]; + [self showFilterBar:[fDefaults boolForKey:@"FilterBar"] animate:NO]; //set up status bar - [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO]; + [self showStatusBar:[fDefaults boolForKey:@"StatusBar"] animate:NO]; - fActionButton.toolTip = NSLocalizedString(@"Shortcuts for changing global settings.", - "Main window -> 1st bottom left button (action) tooltip"); - fSpeedLimitButton.toolTip = NSLocalizedString(@"Speed Limit overrides the total bandwidth limits with its own limits.", + fActionButton.toolTip = NSLocalizedString(@"Shortcuts for changing global settings.", "Main window -> 1st bottom left button (action) tooltip"); + fSpeedLimitButton.toolTip = NSLocalizedString( + @"Speed Limit overrides the total bandwidth limits with its own limits.", "Main window -> 2nd bottom left button (turtle) tooltip"); - - if (@available(macOS 11.0, *)) { - fActionButton.image = [NSImage imageWithSystemSymbolName: @"gearshape.fill" accessibilityDescription: nil]; - fSpeedLimitButton.image = [NSImage imageWithSystemSymbolName: @"tortoise.fill" accessibilityDescription: nil]; + + if (@available(macOS 11.0, *)) + { + fActionButton.image = [NSImage imageWithSystemSymbolName:@"gearshape.fill" accessibilityDescription:nil]; + fSpeedLimitButton.image = [NSImage imageWithSystemSymbolName:@"tortoise.fill" accessibilityDescription:nil]; } - fClearCompletedButton.toolTip = NSLocalizedString(@"Remove all transfers that have completed seeding.", + fClearCompletedButton.toolTip = NSLocalizedString( + @"Remove all transfers that have completed seeding.", "Main window -> 3rd bottom left button (remove all) tooltip"); - [fTableView registerForDraggedTypes: @[TORRENT_TABLE_VIEW_DATA_TYPE]]; - [fWindow registerForDraggedTypes: @[NSFilenamesPboardType, NSURLPboardType]]; + [fTableView registerForDraggedTypes:@[ TORRENT_TABLE_VIEW_DATA_TYPE ]]; + [fWindow registerForDraggedTypes:@[ NSFilenamesPboardType, NSURLPboardType ]]; //sort the sort menu items (localization is from strings file) - NSMutableArray * sortMenuItems = [NSMutableArray arrayWithCapacity: 7]; + NSMutableArray* sortMenuItems = [NSMutableArray arrayWithCapacity:7]; NSUInteger sortMenuIndex = 0; BOOL foundSortItem = NO; - for (NSMenuItem * item in fSortMenu.itemArray) + for (NSMenuItem* item in fSortMenu.itemArray) { //assume all sort items are together and the Queue Order item is first if (item.action == @selector(setSort:) && item.tag != SORT_ORDER_TAG) { - [sortMenuItems addObject: item]; - [fSortMenu removeItemAtIndex: sortMenuIndex]; + [sortMenuItems addObject:item]; + [fSortMenu removeItemAtIndex:sortMenuIndex]; foundSortItem = YES; } else { if (foundSortItem) + { break; + } ++sortMenuIndex; } } - [sortMenuItems sortUsingDescriptors: @[[NSSortDescriptor sortDescriptorWithKey: @"title" ascending: YES selector: @selector(localizedCompare:)]]]; + [sortMenuItems sortUsingDescriptors:@[ [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES + selector:@selector(localizedCompare:)] ]]; - for (NSMenuItem * item in sortMenuItems) - [fSortMenu insertItem: item atIndex: sortMenuIndex++]; + for (NSMenuItem* item in sortMenuItems) + { + [fSortMenu insertItem:item atIndex:sortMenuIndex++]; + } //you would think this would be called later in this method from updateUI, but it's not reached in awakeFromNib //this must be called after showStatusBar: - [fStatusBar updateWithDownload: 0.0 upload: 0.0]; + [fStatusBar updateWithDownload:0.0 upload:0.0]; //this should also be after the rest of the setup [self updateForAutoSize]; @@ -578,218 +623,244 @@ static void removeKeRangerRansomware() //register for sleep notifications IONotificationPortRef notify; io_object_t iterator; - if ((fRootPort = IORegisterForSystemPower((__bridge void *)(self), & notify, sleepCallback, &iterator))) + if ((fRootPort = IORegisterForSystemPower((__bridge void*)(self), ¬ify, sleepCallback, &iterator))) + { CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes); + } else + { NSLog(@"Could not IORegisterForSystemPower"); + } //load previous transfers - NSString * historyFile = [fConfigDirectory stringByAppendingPathComponent: TRANSFER_PLIST]; - NSArray * history = [NSArray arrayWithContentsOfFile: historyFile]; + NSString* historyFile = [fConfigDirectory stringByAppendingPathComponent:TRANSFER_PLIST]; + NSArray* history = [NSArray arrayWithContentsOfFile:historyFile]; if (!history) { //old version saved transfer info in prefs file - if ((history = [fDefaults arrayForKey: @"History"])) - [fDefaults removeObjectForKey: @"History"]; + if ((history = [fDefaults arrayForKey:@"History"])) + { + [fDefaults removeObjectForKey:@"History"]; + } } if (history) { - NSMutableArray * waitToStartTorrents = [NSMutableArray arrayWithCapacity: ((history.count > 0 && !fPauseOnLaunch) ? history.count-1 : 0)]; //theoretical max without doing a lot of work + // theoretical max without doing a lot of work + NSMutableArray* waitToStartTorrents = [NSMutableArray + arrayWithCapacity:((history.count > 0 && !fPauseOnLaunch) ? history.count - 1 : 0)]; - for (NSDictionary * historyItem in history) + for (NSDictionary* historyItem in history) { - Torrent * torrent; - if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib forcePause: fPauseOnLaunch])) + Torrent* torrent; + if ((torrent = [[Torrent alloc] initWithHistory:historyItem lib:fLib forcePause:fPauseOnLaunch])) { - [fTorrents addObject: torrent]; + [fTorrents addObject:torrent]; - NSNumber * waitToStart; + NSNumber* waitToStart; if (!fPauseOnLaunch && (waitToStart = historyItem[@"WaitToStart"]) && waitToStart.boolValue) - [waitToStartTorrents addObject: torrent]; + { + [waitToStartTorrents addObject:torrent]; + } } } //now that all are loaded, let's set those in the queue to waiting - for (Torrent * torrent in waitToStartTorrents) + for (Torrent* torrent in waitToStartTorrents) + { [torrent startTransfer]; + } } - fBadger = [[Badger alloc] initWithLib: fLib]; + fBadger = [[Badger alloc] initWithLib:fLib]; NSUserNotificationCenter.defaultUserNotificationCenter.delegate = self; //observe notifications - NSNotificationCenter * nc = NSNotificationCenter.defaultCenter; + NSNotificationCenter* nc = NSNotificationCenter.defaultCenter; - [nc addObserver: self selector: @selector(updateUI) - name: @"UpdateUI" object: nil]; + [nc addObserver:self selector:@selector(updateUI) name:@"UpdateUI" object:nil]; - [nc addObserver: self selector: @selector(torrentFinishedDownloading:) - name: @"TorrentFinishedDownloading" object: nil]; + [nc addObserver:self selector:@selector(torrentFinishedDownloading:) name:@"TorrentFinishedDownloading" object:nil]; - [nc addObserver: self selector: @selector(torrentRestartedDownloading:) - name: @"TorrentRestartedDownloading" object: nil]; + [nc addObserver:self selector:@selector(torrentRestartedDownloading:) name:@"TorrentRestartedDownloading" object:nil]; - [nc addObserver: self selector: @selector(torrentFinishedSeeding:) - name: @"TorrentFinishedSeeding" object: nil]; + [nc addObserver:self selector:@selector(torrentFinishedSeeding:) name:@"TorrentFinishedSeeding" object:nil]; - [nc addObserver: self selector: @selector(applyFilter) - name: kTorrentDidChangeGroupNotification object: nil]; + [nc addObserver:self selector:@selector(applyFilter) name:kTorrentDidChangeGroupNotification object:nil]; //avoids need of setting delegate - [nc addObserver: self selector: @selector(torrentTableViewSelectionDidChange:) - name: NSOutlineViewSelectionDidChangeNotification object: fTableView]; + [nc addObserver:self selector:@selector(torrentTableViewSelectionDidChange:) + name:NSOutlineViewSelectionDidChangeNotification + object:fTableView]; - [nc addObserver: self selector: @selector(changeAutoImport) - name: @"AutoImportSettingChange" object: nil]; + [nc addObserver:self selector:@selector(changeAutoImport) name:@"AutoImportSettingChange" object:nil]; - [nc addObserver: self selector: @selector(updateForAutoSize) - name: @"AutoSizeSettingChange" object: nil]; + [nc addObserver:self selector:@selector(updateForAutoSize) name:@"AutoSizeSettingChange" object:nil]; - [nc addObserver: self selector: @selector(updateForExpandCollape) - name: @"OutlineExpandCollapse" object: nil]; + [nc addObserver:self selector:@selector(updateForExpandCollape) name:@"OutlineExpandCollapse" object:nil]; - [nc addObserver: fWindow selector: @selector(makeKeyWindow) - name: @"MakeWindowKey" object: nil]; + [nc addObserver:fWindow selector:@selector(makeKeyWindow) name:@"MakeWindowKey" object:nil]; - #warning rename - [nc addObserver: self selector: @selector(fullUpdateUI) - name: @"UpdateQueue" object: nil]; +#warning rename + [nc addObserver:self selector:@selector(fullUpdateUI) name:@"UpdateQueue" object:nil]; - [nc addObserver: self selector: @selector(applyFilter) - name: @"ApplyFilter" object: nil]; + [nc addObserver:self selector:@selector(applyFilter) name:@"ApplyFilter" object:nil]; //open newly created torrent file - [nc addObserver: self selector: @selector(beginCreateFile:) - name: @"BeginCreateTorrentFile" object: nil]; + [nc addObserver:self selector:@selector(beginCreateFile:) name:@"BeginCreateTorrentFile" object:nil]; //open newly created torrent file - [nc addObserver: self selector: @selector(openCreatedFile:) - name: @"OpenCreatedTorrentFile" object: nil]; + [nc addObserver:self selector:@selector(openCreatedFile:) name:@"OpenCreatedTorrentFile" object:nil]; - [nc addObserver: self selector: @selector(applyFilter) - name: @"UpdateGroups" object: nil]; + [nc addObserver:self selector:@selector(applyFilter) name:@"UpdateGroups" object:nil]; //timer to update the interface every second [self updateUI]; - fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_UI_SECONDS target: self - selector: @selector(updateUI) userInfo: nil repeats: YES]; - [NSRunLoop.currentRunLoop addTimer: fTimer forMode: NSModalPanelRunLoopMode]; - [NSRunLoop.currentRunLoop addTimer: fTimer forMode: NSEventTrackingRunLoopMode]; + fTimer = [NSTimer scheduledTimerWithTimeInterval:UPDATE_UI_SECONDS target:self selector:@selector(updateUI) userInfo:nil + repeats:YES]; + [NSRunLoop.currentRunLoop addTimer:fTimer forMode:NSModalPanelRunLoopMode]; + [NSRunLoop.currentRunLoop addTimer:fTimer forMode:NSEventTrackingRunLoopMode]; [self applyFilter]; - [fWindow makeKeyAndOrderFront: nil]; + [fWindow makeKeyAndOrderFront:nil]; - if ([fDefaults boolForKey: @"InfoVisible"]) - [self showInfo: nil]; + if ([fDefaults boolForKey:@"InfoVisible"]) + { + [self showInfo:nil]; + } } -- (void) applicationDidFinishLaunching: (NSNotification *) notification +- (void)applicationDidFinishLaunching:(NSNotification*)notification { NSApp.servicesProvider = self; //register for dock icon drags (has to be in applicationDidFinishLaunching: to work) - [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self andSelector: @selector(handleOpenContentsEvent:replyEvent:) - forEventClass: kCoreEventClass andEventID: kAEOpenContents]; + [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(handleOpenContentsEvent:replyEvent:) + forEventClass:kCoreEventClass + andEventID:kAEOpenContents]; //if we were opened from a user notification, do the corresponding action - NSUserNotification * launchNotification = notification.userInfo[NSApplicationLaunchUserNotificationKey]; + NSUserNotification* launchNotification = notification.userInfo[NSApplicationLaunchUserNotificationKey]; if (launchNotification) - [self userNotificationCenter: nil didActivateNotification: launchNotification]; + { + [self userNotificationCenter:nil didActivateNotification:launchNotification]; + } //auto importing [self checkAutoImportDirectory]; //registering the Web UI to Bonjour - if ([fDefaults boolForKey: @"RPC"] && [fDefaults boolForKey: @"RPCWebDiscovery"]) - [BonjourController.defaultController startWithPort: [fDefaults integerForKey: @"RPCPort"]]; + if ([fDefaults boolForKey:@"RPC"] && [fDefaults boolForKey:@"RPCWebDiscovery"]) + { + [BonjourController.defaultController startWithPort:[fDefaults integerForKey:@"RPCPort"]]; + } //shamelessly ask for donations - if ([fDefaults boolForKey: @"WarningDonate"]) + if ([fDefaults boolForKey:@"WarningDonate"]) { tr_session_stats stats; tr_sessionGetCumulativeStats(fLib, &stats); - const BOOL firstLaunch = stats.sessionCount <= 1; + BOOL const firstLaunch = stats.sessionCount <= 1; - NSDate * lastDonateDate = [fDefaults objectForKey: @"DonateAskDate"]; - const BOOL timePassed = !lastDonateDate || (-1 * lastDonateDate.timeIntervalSinceNow) >= DONATE_NAG_TIME; + NSDate* lastDonateDate = [fDefaults objectForKey:@"DonateAskDate"]; + BOOL const timePassed = !lastDonateDate || (-1 * lastDonateDate.timeIntervalSinceNow) >= DONATE_NAG_TIME; if (!firstLaunch && timePassed) { - [fDefaults setObject: [NSDate date] forKey: @"DonateAskDate"]; + [fDefaults setObject:[NSDate date] forKey:@"DonateAskDate"]; - NSAlert * alert = [[NSAlert alloc] init]; + NSAlert* alert = [[NSAlert alloc] init]; alert.messageText = NSLocalizedString(@"Support open-source indie software", "Donation beg -> title"); - NSString * donateMessage = [NSString stringWithFormat: @"%@\n\n%@", - NSLocalizedString(@"Transmission is a full-featured torrent application." - " A lot of time and effort have gone into development, coding, and refinement." - " If you enjoy using it, please consider showing your love with a donation.", "Donation beg -> message"), - NSLocalizedString(@"Donate or not, there will be no difference to your torrenting experience.", "Donation beg -> message")]; + NSString* donateMessage = [NSString + stringWithFormat:@"%@\n\n%@", + NSLocalizedString( + @"Transmission is a full-featured torrent application." + " A lot of time and effort have gone into development, coding, and refinement." + " If you enjoy using it, please consider showing your love with a donation.", + "Donation beg -> message"), + NSLocalizedString(@"Donate or not, there will be no difference to your torrenting experience.", "Donation beg -> message")]; alert.informativeText = donateMessage; alert.alertStyle = NSInformationalAlertStyle; - [alert addButtonWithTitle: [NSLocalizedString(@"Donate", "Donation beg -> button") stringByAppendingEllipsis]]; - NSButton * noDonateButton = [alert addButtonWithTitle: NSLocalizedString(@"Nope", "Donation beg -> button")]; + [alert addButtonWithTitle:[NSLocalizedString(@"Donate", "Donation beg -> button") stringByAppendingEllipsis]]; + NSButton* noDonateButton = [alert addButtonWithTitle:NSLocalizedString(@"Nope", "Donation beg -> button")]; noDonateButton.keyEquivalent = @"\e"; //escape key - const BOOL allowNeverAgain = lastDonateDate != nil; //hide the "don't show again" check the first time - give them time to try the app + // hide the "don't show again" check the first time - give them time to try the app + BOOL const allowNeverAgain = lastDonateDate != nil; alert.showsSuppressionButton = allowNeverAgain; if (allowNeverAgain) + { alert.suppressionButton.title = NSLocalizedString(@"Don't bug me about this ever again.", "Donation beg -> button"); + } - const NSInteger donateResult = [alert runModal]; + NSInteger const donateResult = [alert runModal]; if (donateResult == NSAlertFirstButtonReturn) - [self linkDonate: self]; + { + [self linkDonate:self]; + } if (allowNeverAgain) - [fDefaults setBool: (alert.suppressionButton.state != NSOnState) forKey: @"WarningDonate"]; + { + [fDefaults setBool:(alert.suppressionButton.state != NSOnState) forKey:@"WarningDonate"]; + } } } } -- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows +- (BOOL)applicationShouldHandleReopen:(NSApplication*)app hasVisibleWindows:(BOOL)visibleWindows { - NSWindow * mainWindow = NSApp.mainWindow; + NSWindow* mainWindow = NSApp.mainWindow; if (!mainWindow || !mainWindow.visible) - [fWindow makeKeyAndOrderFront: nil]; + { + [fWindow makeKeyAndOrderFront:nil]; + } return NO; } -- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender +- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender { - if (!fQuitRequested && [fDefaults boolForKey: @"CheckQuit"]) + if (!fQuitRequested && [fDefaults boolForKey:@"CheckQuit"]) { NSInteger active = 0, downloading = 0; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { if (torrent.active && !torrent.stalled) { active++; if (!torrent.allDownloaded) + { downloading++; + } } + } - if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0) + if ([fDefaults boolForKey:@"CheckQuitDownloading"] ? downloading > 0 : active > 0) { - NSAlert *alert = [[NSAlert alloc] init]; + NSAlert* alert = [[NSAlert alloc] init]; alert.alertStyle = NSAlertStyleInformational; alert.messageText = NSLocalizedString(@"Are you sure you want to quit?", "Confirm Quit panel -> title"); - alert.informativeText = active == 1 - ? NSLocalizedString(@"There is an active transfer that will be paused on quit." - " The transfer will automatically resume on the next launch.", "Confirm Quit panel -> message") - : [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers that will be paused on quit." - " The transfers will automatically resume on the next launch.", "Confirm Quit panel -> message"), active]; + alert.informativeText = active == 1 ? + NSLocalizedString( + @"There is an active transfer that will be paused on quit." + " The transfer will automatically resume on the next launch.", + "Confirm Quit panel -> message") : + [NSString stringWithFormat:NSLocalizedString( + @"There are %d active transfers that will be paused on quit." + " The transfers will automatically resume on the next launch.", + "Confirm Quit panel -> message"), + active]; [alert addButtonWithTitle:NSLocalizedString(@"Quit", "Confirm Quit panel -> button")]; [alert addButtonWithTitle:NSLocalizedString(@"Cancel", "Confirm Quit panel -> button")]; - - [alert beginSheetModalForWindow:fWindow - completionHandler:^(NSModalResponse returnCode) { - [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertFirstButtonReturn]; - }]; + + [alert beginSheetModalForWindow:fWindow completionHandler:^(NSModalResponse returnCode) { + [NSApp replyToApplicationShouldTerminate:returnCode == NSAlertFirstButtonReturn]; + }]; return NSTerminateLater; } } @@ -797,27 +868,33 @@ static void removeKeRangerRansomware() return NSTerminateNow; } -- (void) applicationWillTerminate: (NSNotification *) notification +- (void)applicationWillTerminate:(NSNotification*)notification { fQuitting = YES; //stop the Bonjour service if (BonjourController.defaultControllerExists) + { [BonjourController.defaultController stop]; + } //stop blocklist download if (BlocklistDownloader.isRunning) + { [[BlocklistDownloader downloader] cancelDownload]; + } //stop timers and notification checking - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; [fTimer invalidate]; if (fAutoImportTimer) { if (fAutoImportTimer.valid) + { [fAutoImportTimer invalidate]; + } } [fBadger setQuitting]; @@ -825,166 +902,185 @@ static void removeKeRangerRansomware() //remove all torrent downloads if (fPendingTorrentDownloads) { - for (NSDictionary * downloadDict in fPendingTorrentDownloads) + for (NSDictionary* downloadDict in fPendingTorrentDownloads) { - NSURLDownload * download = downloadDict[@"Download"]; + NSURLDownload* download = downloadDict[@"Download"]; [download cancel]; } } //remember window states and close all windows - [fDefaults setBool: fInfoController.window.visible forKey: @"InfoVisible"]; + [fDefaults setBool:fInfoController.window.visible forKey:@"InfoVisible"]; if ([QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible) + { [[QLPreviewPanel sharedPreviewPanel] updateController]; + } - for (NSWindow * window in NSApp.windows) + for (NSWindow* window in NSApp.windows) + { [window close]; + } - [self showStatusBar: NO animate: NO]; - [self showFilterBar: NO animate: NO]; + [self showStatusBar:NO animate:NO]; + [self showFilterBar:NO animate:NO]; //save history [self updateTorrentHistory]; [fTableView saveCollapsedGroups]; - + _fileWatcherQueue = nil; //complete cleanup tr_sessionClose(fLib); } -- (tr_session *) sessionHandle +- (tr_session*)sessionHandle { return fLib; } -- (void) handleOpenContentsEvent: (NSAppleEventDescriptor *) event replyEvent: (NSAppleEventDescriptor *) replyEvent +- (void)handleOpenContentsEvent:(NSAppleEventDescriptor*)event replyEvent:(NSAppleEventDescriptor*)replyEvent { - NSString * urlString = nil; + NSString* urlString = nil; - NSAppleEventDescriptor * directObject = [event paramDescriptorForKeyword: keyDirectObject]; + NSAppleEventDescriptor* directObject = [event paramDescriptorForKeyword:keyDirectObject]; if (directObject.descriptorType == typeAEList) { for (NSInteger i = 1; i <= directObject.numberOfItems; i++) - if ((urlString = [directObject descriptorAtIndex: i].stringValue)) + { + if ((urlString = [directObject descriptorAtIndex:i].stringValue)) + { break; + } + } } else + { urlString = directObject.stringValue; + } if (urlString) - [self openURL: urlString]; + { + [self openURL:urlString]; + } } -- (void) download: (NSURLDownload *) download decideDestinationWithSuggestedFilename: (NSString *) suggestedName +- (void)download:(NSURLDownload*)download decideDestinationWithSuggestedFilename:(NSString*)suggestedName { - if ([suggestedName.pathExtension caseInsensitiveCompare: @"torrent"] != NSOrderedSame) + if ([suggestedName.pathExtension caseInsensitiveCompare:@"torrent"] != NSOrderedSame) { [download cancel]; - [fPendingTorrentDownloads removeObjectForKey: download.request.URL]; + [fPendingTorrentDownloads removeObjectForKey:download.request.URL]; if (fPendingTorrentDownloads.count == 0) { fPendingTorrentDownloads = nil; } - NSString * message = [NSString stringWithFormat: NSLocalizedString(@"It appears that the file \"%@\" from %@ is not a torrent file.", - "Download not a torrent -> message"), suggestedName, - [download.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]; + NSString* message = [NSString + stringWithFormat:NSLocalizedString(@"It appears that the file \"%@\" from %@ is not a torrent file.", "Download not a torrent -> message"), + suggestedName, + [download.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Download not a torrent -> button")]; + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Download not a torrent -> button")]; alert.messageText = NSLocalizedString(@"Torrent download failed", "Download not a torrent -> title"); alert.informativeText = message; [alert runModal]; } else - [download setDestination: [NSTemporaryDirectory() stringByAppendingPathComponent: suggestedName.lastPathComponent] - allowOverwrite: NO]; + { + [download setDestination:[NSTemporaryDirectory() stringByAppendingPathComponent:suggestedName.lastPathComponent] + allowOverwrite:NO]; + } } --(void) download: (NSURLDownload *) download didCreateDestination: (NSString *) path +- (void)download:(NSURLDownload*)download didCreateDestination:(NSString*)path { - NSMutableDictionary * dict = fPendingTorrentDownloads[download.request.URL]; + NSMutableDictionary* dict = fPendingTorrentDownloads[download.request.URL]; dict[@"Path"] = path; } -- (void) download: (NSURLDownload *) download didFailWithError: (NSError *) error +- (void)download:(NSURLDownload*)download didFailWithError:(NSError*)error { - NSString * message = [NSString stringWithFormat: NSLocalizedString(@"The torrent could not be downloaded from %@: %@.", - "Torrent download failed -> message"), - [download.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding], - error.localizedDescription]; + NSString* message = [NSString + stringWithFormat:NSLocalizedString(@"The torrent could not be downloaded from %@: %@.", "Torrent download failed -> message"), + [download.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding], + error.localizedDescription]; - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent download failed -> button")]; + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Torrent download failed -> button")]; alert.messageText = NSLocalizedString(@"Torrent download failed", "Torrent download error -> title"); alert.informativeText = message; [alert runModal]; - [fPendingTorrentDownloads removeObjectForKey: download.request.URL]; + [fPendingTorrentDownloads removeObjectForKey:download.request.URL]; if (fPendingTorrentDownloads.count == 0) { fPendingTorrentDownloads = nil; } } -- (void) downloadDidFinish: (NSURLDownload *) download +- (void)downloadDidFinish:(NSURLDownload*)download { - NSString * path = fPendingTorrentDownloads[download.request.URL][@"Path"]; + NSString* path = fPendingTorrentDownloads[download.request.URL][@"Path"]; - [self openFiles: @[path] addType: ADD_URL forcePath: nil]; + [self openFiles:@[ path ] addType:ADD_URL forcePath:nil]; //delete the torrent file after opening - [NSFileManager.defaultManager removeItemAtPath: path error: NULL]; + [NSFileManager.defaultManager removeItemAtPath:path error:NULL]; - [fPendingTorrentDownloads removeObjectForKey: download.request.URL]; + [fPendingTorrentDownloads removeObjectForKey:download.request.URL]; if (fPendingTorrentDownloads.count == 0) { fPendingTorrentDownloads = nil; } } -- (void) application: (NSApplication *) app openFiles: (NSArray *) filenames +- (void)application:(NSApplication*)app openFiles:(NSArray*)filenames { - [self openFiles: filenames addType: ADD_MANUAL forcePath: nil]; + [self openFiles:filenames addType:ADD_MANUAL forcePath:nil]; } -- (void) openFiles: (NSArray *) filenames addType: (addType) type forcePath: (NSString *) path +- (void)openFiles:(NSArray*)filenames addType:(addType)type forcePath:(NSString*)path { BOOL deleteTorrentFile, canToggleDelete = NO; switch (type) { - case ADD_CREATED: - deleteTorrentFile = NO; - break; - case ADD_URL: - deleteTorrentFile = YES; - break; - default: - deleteTorrentFile = [fDefaults boolForKey: @"DeleteOriginalTorrent"]; - canToggleDelete = YES; + case ADD_CREATED: + deleteTorrentFile = NO; + break; + case ADD_URL: + deleteTorrentFile = YES; + break; + default: + deleteTorrentFile = [fDefaults boolForKey:@"DeleteOriginalTorrent"]; + canToggleDelete = YES; } - for (NSString * torrentPath in filenames) + for (NSString* torrentPath in filenames) { //ensure torrent doesn't already exist - tr_ctor * ctor = tr_ctorNew(fLib); + tr_ctor* ctor = tr_ctorNew(fLib); tr_ctorSetMetainfoFromFile(ctor, torrentPath.UTF8String); tr_info info; - const tr_parse_result result = tr_torrentParse(ctor, &info); + tr_parse_result const result = tr_torrentParse(ctor, &info); tr_ctorFree(ctor); if (result != TR_PARSE_OK) { if (result == TR_PARSE_DUPLICATE) - [self duplicateOpenAlert: @(info.name)]; + { + [self duplicateOpenAlert:@(info.name)]; + } else if (result == TR_PARSE_ERR) { if (type != ADD_AUTO) - [self invalidOpenAlert: torrentPath.lastPathComponent]; + { + [self invalidOpenAlert:torrentPath.lastPathComponent]; + } } else NSAssert2(NO, @"Unknown error code (%d) when attempting to open \"%@\"", result, torrentPath); @@ -994,338 +1090,405 @@ static void removeKeRangerRansomware() } //determine download location - NSString * location; + NSString* location; BOOL lockDestination = NO; //don't override the location with a group location if it has a hardcoded path if (path) { location = path.stringByExpandingTildeInPath; lockDestination = YES; } - else if ([fDefaults boolForKey: @"DownloadLocationConstant"]) - location = [fDefaults stringForKey: @"DownloadFolder"].stringByExpandingTildeInPath; + else if ([fDefaults boolForKey:@"DownloadLocationConstant"]) + { + location = [fDefaults stringForKey:@"DownloadFolder"].stringByExpandingTildeInPath; + } else if (type != ADD_URL) + { location = torrentPath.stringByDeletingLastPathComponent; + } else + { location = nil; + } //determine to show the options window - const BOOL showWindow = type == ADD_SHOW_OPTIONS || ([fDefaults boolForKey: @"DownloadAsk"] - && (info.isFolder || ![fDefaults boolForKey: @"DownloadAskMulti"]) - && (type != ADD_AUTO || ![fDefaults boolForKey: @"DownloadAskManual"])); + BOOL const showWindow = type == ADD_SHOW_OPTIONS || + ([fDefaults boolForKey:@"DownloadAsk"] && (info.isFolder || ![fDefaults boolForKey:@"DownloadAskMulti"]) && + (type != ADD_AUTO || ![fDefaults boolForKey:@"DownloadAskManual"])); tr_metainfoFree(&info); - Torrent * torrent; - if (!(torrent = [[Torrent alloc] initWithPath: torrentPath location: location - deleteTorrentFile: showWindow ? NO : deleteTorrentFile lib: fLib])) + Torrent* torrent; + if (!(torrent = [[Torrent alloc] initWithPath:torrentPath location:location + deleteTorrentFile:showWindow ? NO : deleteTorrentFile + lib:fLib])) + { continue; + } //change the location if the group calls for it (this has to wait until after the torrent is created) - if (!lockDestination && [GroupsController.groups usesCustomDownloadLocationForIndex: torrent.groupValue]) + if (!lockDestination && [GroupsController.groups usesCustomDownloadLocationForIndex:torrent.groupValue]) { - location = [GroupsController.groups customDownloadLocationForIndex: torrent.groupValue]; - [torrent changeDownloadFolderBeforeUsing: location determinationType: TorrentDeterminationAutomatic]; + location = [GroupsController.groups customDownloadLocationForIndex:torrent.groupValue]; + [torrent changeDownloadFolderBeforeUsing:location determinationType:TorrentDeterminationAutomatic]; } //verify the data right away if it was newly created if (type == ADD_CREATED) + { [torrent resetCache]; + } //show the add window or add directly if (showWindow || !location) { - AddWindowController * addController = [[AddWindowController alloc] initWithTorrent: torrent destination: location - lockDestination: lockDestination controller: self torrentFile: torrentPath - deleteTorrentCheckEnableInitially: deleteTorrentFile canToggleDelete: canToggleDelete]; - [addController showWindow: self]; + AddWindowController* addController = [[AddWindowController alloc] initWithTorrent:torrent destination:location + lockDestination:lockDestination + controller:self + torrentFile:torrentPath + deleteTorrentCheckEnableInitially:deleteTorrentFile + canToggleDelete:canToggleDelete]; + [addController showWindow:self]; if (!fAddWindows) + { fAddWindows = [[NSMutableSet alloc] init]; - [fAddWindows addObject: addController]; + } + [fAddWindows addObject:addController]; } else { - if ([fDefaults boolForKey: @"AutoStartDownload"]) + if ([fDefaults boolForKey:@"AutoStartDownload"]) + { [torrent startTransfer]; + } [torrent update]; - [fTorrents addObject: torrent]; + [fTorrents addObject:torrent]; if (!fAddingTransfers) + { fAddingTransfers = [[NSMutableSet alloc] init]; - [fAddingTransfers addObject: torrent]; + } + [fAddingTransfers addObject:torrent]; } } [self fullUpdateUI]; } -- (void) askOpenConfirmed: (AddWindowController *) addController add: (BOOL) add +- (void)askOpenConfirmed:(AddWindowController*)addController add:(BOOL)add { - Torrent * torrent = addController.torrent; + Torrent* torrent = addController.torrent; if (add) { torrent.queuePosition = fTorrents.count; [torrent update]; - [fTorrents addObject: torrent]; + [fTorrents addObject:torrent]; if (!fAddingTransfers) + { fAddingTransfers = [[NSMutableSet alloc] init]; - [fAddingTransfers addObject: torrent]; + } + [fAddingTransfers addObject:torrent]; [self fullUpdateUI]; } else { - [torrent closeRemoveTorrent: NO]; + [torrent closeRemoveTorrent:NO]; } - [fAddWindows removeObject: addController]; + [fAddWindows removeObject:addController]; if (fAddWindows.count == 0) { fAddWindows = nil; } } -- (void) openMagnet: (NSString *) address +- (void)openMagnet:(NSString*)address { - tr_torrent * duplicateTorrent; + tr_torrent* duplicateTorrent; if ((duplicateTorrent = tr_torrentFindFromMagnetLink(fLib, address.UTF8String))) { - const tr_info * info = tr_torrentInfo(duplicateTorrent); - NSString * name = (info != NULL && info->name != NULL) ? @(info->name) : nil; - [self duplicateOpenMagnetAlert: address transferName: name]; + tr_info const* info = tr_torrentInfo(duplicateTorrent); + NSString* name = (info != NULL && info->name != NULL) ? @(info->name) : nil; + [self duplicateOpenMagnetAlert:address transferName:name]; return; } //determine download location - NSString * location = nil; - if ([fDefaults boolForKey: @"DownloadLocationConstant"]) - location = [fDefaults stringForKey: @"DownloadFolder"].stringByExpandingTildeInPath; - - Torrent * torrent; - if (!(torrent = [[Torrent alloc] initWithMagnetAddress: address location: location lib: fLib])) + NSString* location = nil; + if ([fDefaults boolForKey:@"DownloadLocationConstant"]) { - [self invalidOpenMagnetAlert: address]; + location = [fDefaults stringForKey:@"DownloadFolder"].stringByExpandingTildeInPath; + } + + Torrent* torrent; + if (!(torrent = [[Torrent alloc] initWithMagnetAddress:address location:location lib:fLib])) + { + [self invalidOpenMagnetAlert:address]; return; } //change the location if the group calls for it (this has to wait until after the torrent is created) - if ([GroupsController.groups usesCustomDownloadLocationForIndex: torrent.groupValue]) + if ([GroupsController.groups usesCustomDownloadLocationForIndex:torrent.groupValue]) { - location = [GroupsController.groups customDownloadLocationForIndex: torrent.groupValue]; - [torrent changeDownloadFolderBeforeUsing: location determinationType: TorrentDeterminationAutomatic]; + location = [GroupsController.groups customDownloadLocationForIndex:torrent.groupValue]; + [torrent changeDownloadFolderBeforeUsing:location determinationType:TorrentDeterminationAutomatic]; } - if ([fDefaults boolForKey: @"MagnetOpenAsk"] || !location) + if ([fDefaults boolForKey:@"MagnetOpenAsk"] || !location) { - AddMagnetWindowController * addController = [[AddMagnetWindowController alloc] initWithTorrent: torrent destination: location - controller: self]; - [addController showWindow: self]; + AddMagnetWindowController* addController = [[AddMagnetWindowController alloc] initWithTorrent:torrent destination:location + controller:self]; + [addController showWindow:self]; if (!fAddWindows) + { fAddWindows = [[NSMutableSet alloc] init]; - [fAddWindows addObject: addController]; + } + [fAddWindows addObject:addController]; } else { - if ([fDefaults boolForKey: @"AutoStartDownload"]) + if ([fDefaults boolForKey:@"AutoStartDownload"]) + { [torrent startTransfer]; + } [torrent update]; - [fTorrents addObject: torrent]; + [fTorrents addObject:torrent]; if (!fAddingTransfers) + { fAddingTransfers = [[NSMutableSet alloc] init]; - [fAddingTransfers addObject: torrent]; + } + [fAddingTransfers addObject:torrent]; } [self fullUpdateUI]; } -- (void) askOpenMagnetConfirmed: (AddMagnetWindowController *) addController add: (BOOL) add +- (void)askOpenMagnetConfirmed:(AddMagnetWindowController*)addController add:(BOOL)add { - Torrent * torrent = addController.torrent; + Torrent* torrent = addController.torrent; if (add) { torrent.queuePosition = fTorrents.count; [torrent update]; - [fTorrents addObject: torrent]; + [fTorrents addObject:torrent]; if (!fAddingTransfers) + { fAddingTransfers = [[NSMutableSet alloc] init]; - [fAddingTransfers addObject: torrent]; + } + [fAddingTransfers addObject:torrent]; [self fullUpdateUI]; } else { - [torrent closeRemoveTorrent: NO]; + [torrent closeRemoveTorrent:NO]; } - [fAddWindows removeObject: addController]; + [fAddWindows removeObject:addController]; if (fAddWindows.count == 0) { fAddWindows = nil; } } -- (void) openCreatedFile: (NSNotification *) notification +- (void)openCreatedFile:(NSNotification*)notification { - NSDictionary * dict = notification.userInfo; - [self openFiles: @[dict[@"File"]] addType: ADD_CREATED forcePath: dict[@"Path"]]; + NSDictionary* dict = notification.userInfo; + [self openFiles:@[ dict[@"File"] ] addType:ADD_CREATED forcePath:dict[@"Path"]]; } -- (void) openFilesWithDict: (NSDictionary *) dictionary +- (void)openFilesWithDict:(NSDictionary*)dictionary { - [self openFiles: dictionary[@"Filenames"] addType: [dictionary[@"AddType"] intValue] forcePath: nil]; + [self openFiles:dictionary[@"Filenames"] addType:[dictionary[@"AddType"] intValue] forcePath:nil]; } //called on by applescript -- (void) open: (NSArray *) files +- (void)open:(NSArray*)files { - NSDictionary * dict = [[NSDictionary alloc] initWithObjects: @[files, @(ADD_MANUAL)] forKeys: @[@"Filenames", @"AddType"]]; - [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dict waitUntilDone: NO]; + NSDictionary* dict = [[NSDictionary alloc] initWithObjects:@[ files, @(ADD_MANUAL) ] forKeys:@[ @"Filenames", @"AddType" ]]; + [self performSelectorOnMainThread:@selector(openFilesWithDict:) withObject:dict waitUntilDone:NO]; } -- (void) openShowSheet: (id) sender +- (void)openShowSheet:(id)sender { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; panel.allowsMultipleSelection = YES; panel.canChooseFiles = YES; panel.canChooseDirectories = NO; - panel.allowedFileTypes = @[@"org.bittorrent.torrent", @"torrent"]; + panel.allowedFileTypes = @[ @"org.bittorrent.torrent", @"torrent" ]; - [panel beginSheetModalForWindow: fWindow completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:fWindow completionHandler:^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) { - NSMutableArray * filenames = [NSMutableArray arrayWithCapacity: panel.URLs.count]; - for (NSURL * url in panel.URLs) - [filenames addObject: url.path]; + NSMutableArray* filenames = [NSMutableArray arrayWithCapacity:panel.URLs.count]; + for (NSURL* url in panel.URLs) + { + [filenames addObject:url.path]; + } - NSDictionary * dictionary = [[NSDictionary alloc] initWithObjects: @[filenames, sender == fOpenIgnoreDownloadFolder ? @(ADD_SHOW_OPTIONS) : @(ADD_MANUAL)] - forKeys: @[@"Filenames", @"AddType"]]; - [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO]; + NSDictionary* dictionary = [[NSDictionary alloc] + initWithObjects:@[ filenames, sender == fOpenIgnoreDownloadFolder ? @(ADD_SHOW_OPTIONS) : @(ADD_MANUAL) ] + forKeys:@[ @"Filenames", @"AddType" ]]; + [self performSelectorOnMainThread:@selector(openFilesWithDict:) withObject:dictionary waitUntilDone:NO]; } }]; } -- (void) invalidOpenAlert: (NSString *) filename +- (void)invalidOpenAlert:(NSString*)filename { - if (![fDefaults boolForKey: @"WarningInvalidOpen"]) + if (![fDefaults boolForKey:@"WarningInvalidOpen"]) + { return; + } + + NSAlert* alert = [[NSAlert alloc] init]; + alert.messageText = [NSString + stringWithFormat:NSLocalizedString(@"\"%@\" is not a valid torrent file.", "Open invalid alert -> title"), filename]; + alert.informativeText = NSLocalizedString(@"The torrent file cannot be opened because it contains invalid data.", "Open invalid alert -> message"); - NSAlert * alert = [[NSAlert alloc] init]; - alert.messageText = [NSString stringWithFormat: NSLocalizedString(@"\"%@\" is not a valid torrent file.", - "Open invalid alert -> title"), filename]; - alert.informativeText = NSLocalizedString(@"The torrent file cannot be opened because it contains invalid data.", - "Open invalid alert -> message"); - alert.alertStyle = NSWarningAlertStyle; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open invalid alert -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Open invalid alert -> button")]; [alert runModal]; if (alert.suppressionButton.state == NSOnState) - [fDefaults setBool: NO forKey: @"WarningInvalidOpen"]; + { + [fDefaults setBool:NO forKey:@"WarningInvalidOpen"]; + } } -- (void) invalidOpenMagnetAlert: (NSString *) address +- (void)invalidOpenMagnetAlert:(NSString*)address { - if (![fDefaults boolForKey: @"WarningInvalidOpen"]) + if (![fDefaults boolForKey:@"WarningInvalidOpen"]) + { return; + } - NSAlert * alert = [[NSAlert alloc] init]; + NSAlert* alert = [[NSAlert alloc] init]; alert.messageText = NSLocalizedString(@"Adding magnetized transfer failed.", "Magnet link failed -> title"); - alert.informativeText = [NSString stringWithFormat: NSLocalizedString(@"There was an error when adding the magnet link \"%@\"." - " The transfer will not occur.", "Magnet link failed -> message"), address]; + alert.informativeText = [NSString stringWithFormat:NSLocalizedString( + @"There was an error when adding the magnet link \"%@\"." + " The transfer will not occur.", + "Magnet link failed -> message"), + address]; alert.alertStyle = NSWarningAlertStyle; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Magnet link failed -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Magnet link failed -> button")]; [alert runModal]; if (alert.suppressionButton.state == NSOnState) - [fDefaults setBool: NO forKey: @"WarningInvalidOpen"]; + { + [fDefaults setBool:NO forKey:@"WarningInvalidOpen"]; + } } -- (void) duplicateOpenAlert: (NSString *) name +- (void)duplicateOpenAlert:(NSString*)name { - if (![fDefaults boolForKey: @"WarningDuplicate"]) + if (![fDefaults boolForKey:@"WarningDuplicate"]) + { return; + } - NSAlert * alert = [[NSAlert alloc] init]; - alert.messageText = [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.", - "Open duplicate alert -> title"), name]; - alert.informativeText = NSLocalizedString(@"The transfer cannot be added because it is a duplicate of an already existing transfer.", + NSAlert* alert = [[NSAlert alloc] init]; + alert.messageText = [NSString + stringWithFormat:NSLocalizedString(@"A transfer of \"%@\" already exists.", "Open duplicate alert -> title"), name]; + alert.informativeText = NSLocalizedString( + @"The transfer cannot be added because it is a duplicate of an already existing transfer.", "Open duplicate alert -> message"); - + alert.alertStyle = NSWarningAlertStyle; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open duplicate alert -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Open duplicate alert -> button")]; alert.showsSuppressionButton = YES; [alert runModal]; if (alert.suppressionButton.state) - [fDefaults setBool: NO forKey: @"WarningDuplicate"]; + { + [fDefaults setBool:NO forKey:@"WarningDuplicate"]; + } } -- (void) duplicateOpenMagnetAlert: (NSString *) address transferName: (NSString *) name +- (void)duplicateOpenMagnetAlert:(NSString*)address transferName:(NSString*)name { - if (![fDefaults boolForKey: @"WarningDuplicate"]) + if (![fDefaults boolForKey:@"WarningDuplicate"]) + { return; + } - NSAlert * alert = [[NSAlert alloc] init]; + NSAlert* alert = [[NSAlert alloc] init]; if (name) - alert.messageText = [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.", - "Open duplicate magnet alert -> title"), name]; - else - alert.messageText = NSLocalizedString(@"Magnet link is a duplicate of an existing transfer.", - "Open duplicate magnet alert -> title"); - alert.informativeText = [NSString stringWithFormat: - NSLocalizedString(@"The magnet link \"%@\" cannot be added because it is a duplicate of an already existing transfer.", - "Open duplicate magnet alert -> message"), address]; - alert.alertStyle = NSWarningAlertStyle; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open duplicate magnet alert -> button")]; - alert.showsSuppressionButton = YES; - - [alert runModal]; - if (alert.suppressionButton.state) - [fDefaults setBool: NO forKey: @"WarningDuplicate"]; -} - -- (void) openURL: (NSString *) urlString -{ - if ([urlString rangeOfString: @"magnet:" options: (NSAnchoredSearch | NSCaseInsensitiveSearch)].location != NSNotFound) - [self openMagnet: urlString]; + { + alert.messageText = [NSString + stringWithFormat:NSLocalizedString(@"A transfer of \"%@\" already exists.", "Open duplicate magnet alert -> title"), name]; + } else { - if ([urlString rangeOfString: @"://"].location == NSNotFound) + alert.messageText = NSLocalizedString(@"Magnet link is a duplicate of an existing transfer.", "Open duplicate magnet alert -> title"); + } + alert.informativeText = [NSString + stringWithFormat:NSLocalizedString( + @"The magnet link \"%@\" cannot be added because it is a duplicate of an already existing transfer.", + "Open duplicate magnet alert -> message"), + address]; + alert.alertStyle = NSWarningAlertStyle; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Open duplicate magnet alert -> button")]; + alert.showsSuppressionButton = YES; + + [alert runModal]; + if (alert.suppressionButton.state) + { + [fDefaults setBool:NO forKey:@"WarningDuplicate"]; + } +} + +- (void)openURL:(NSString*)urlString +{ + if ([urlString rangeOfString:@"magnet:" options:(NSAnchoredSearch | NSCaseInsensitiveSearch)].location != NSNotFound) + { + [self openMagnet:urlString]; + } + else + { + if ([urlString rangeOfString:@"://"].location == NSNotFound) { - if ([urlString rangeOfString: @"."].location == NSNotFound) + if ([urlString rangeOfString:@"."].location == NSNotFound) { NSInteger beforeCom; - if ((beforeCom = [urlString rangeOfString: @"/"].location) != NSNotFound) - urlString = [NSString stringWithFormat: @"http://www.%@.com/%@", - [urlString substringToIndex: beforeCom], - [urlString substringFromIndex: beforeCom + 1]]; + if ((beforeCom = [urlString rangeOfString:@"/"].location) != NSNotFound) + { + urlString = [NSString stringWithFormat:@"http://www.%@.com/%@", + [urlString substringToIndex:beforeCom], + [urlString substringFromIndex:beforeCom + 1]]; + } else - urlString = [NSString stringWithFormat: @"http://www.%@.com/", urlString]; + { + urlString = [NSString stringWithFormat:@"http://www.%@.com/", urlString]; + } } else - urlString = [@"http://" stringByAppendingString: urlString]; + { + urlString = [@"http://" stringByAppendingString:urlString]; + } } - - NSURL * url = [NSURL URLWithString: urlString]; + + NSURL* url = [NSURL URLWithString:urlString]; if (url == nil) { NSLog(@"Detected non-URL string \"%@\". Ignoring.", urlString); return; } - NSURLRequest * request = [NSURLRequest requestWithURL: url - cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval: 60]; + NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData + timeoutInterval:60]; if (fPendingTorrentDownloads[request.URL]) { @@ -1333,27 +1496,29 @@ static void removeKeRangerRansomware() return; } - NSURLDownload * download = [[NSURLDownload alloc] initWithRequest: request delegate: self]; + NSURLDownload* download = [[NSURLDownload alloc] initWithRequest:request delegate:self]; if (!fPendingTorrentDownloads) + { fPendingTorrentDownloads = [[NSMutableDictionary alloc] init]; - NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithObject: download forKey: @"Download"]; + } + NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithObject:download forKey:@"Download"]; fPendingTorrentDownloads[request.URL] = dict; } } -- (void) openURLShowSheet: (id) sender +- (void)openURLShowSheet:(id)sender { if (!fUrlSheetController) { - fUrlSheetController = [[URLSheetWindowController alloc] initWithController: self]; + fUrlSheetController = [[URLSheetWindowController alloc] initWithController:self]; - [fWindow beginSheet: fUrlSheetController.window completionHandler:^(NSModalResponse returnCode) { + [fWindow beginSheet:fUrlSheetController.window completionHandler:^(NSModalResponse returnCode) { if (returnCode == 1) { - NSString * urlString = [fUrlSheetController urlString]; + NSString* urlString = [fUrlSheetController urlString]; dispatch_async(dispatch_get_main_queue(), ^{ - [self openURL: urlString]; + [self openURL:urlString]; }); } fUrlSheetController = nil; @@ -1361,184 +1526,232 @@ static void removeKeRangerRansomware() } } -- (void) createFile: (id) sender +- (void)createFile:(id)sender { - [CreatorWindowController createTorrentFile: fLib]; + [CreatorWindowController createTorrentFile:fLib]; } -- (void) resumeSelectedTorrents: (id) sender +- (void)resumeSelectedTorrents:(id)sender { - [self resumeTorrents: fTableView.selectedTorrents]; + [self resumeTorrents:fTableView.selectedTorrents]; } -- (void) resumeAllTorrents: (id) sender +- (void)resumeAllTorrents:(id)sender { - NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: fTorrents.count]; + NSMutableArray* torrents = [NSMutableArray arrayWithCapacity:fTorrents.count]; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { if (!torrent.finishedSeeding) - [torrents addObject: torrent]; + { + [torrents addObject:torrent]; + } + } - [self resumeTorrents: torrents]; + [self resumeTorrents:torrents]; } -- (void) resumeTorrents: (NSArray *) torrents +- (void)resumeTorrents:(NSArray*)torrents { - for (Torrent * torrent in torrents) + for (Torrent* torrent in torrents) + { [torrent startTransfer]; + } [self fullUpdateUI]; } -- (void) resumeSelectedTorrentsNoWait: (id) sender +- (void)resumeSelectedTorrentsNoWait:(id)sender { - [self resumeTorrentsNoWait: fTableView.selectedTorrents]; + [self resumeTorrentsNoWait:fTableView.selectedTorrents]; } -- (void) resumeWaitingTorrents: (id) sender +- (void)resumeWaitingTorrents:(id)sender { - NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: fTorrents.count]; + NSMutableArray* torrents = [NSMutableArray arrayWithCapacity:fTorrents.count]; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { if (torrent.waitingToStart) - [torrents addObject: torrent]; + { + [torrents addObject:torrent]; + } + } - [self resumeTorrentsNoWait: torrents]; + [self resumeTorrentsNoWait:torrents]; } -- (void) resumeTorrentsNoWait: (NSArray *) torrents +- (void)resumeTorrentsNoWait:(NSArray*)torrents { //iterate through instead of all at once to ensure no conflicts - for (Torrent * torrent in torrents) + for (Torrent* torrent in torrents) + { [torrent startTransferNoQueue]; + } [self fullUpdateUI]; } -- (void) stopSelectedTorrents: (id) sender +- (void)stopSelectedTorrents:(id)sender { - [self stopTorrents: fTableView.selectedTorrents]; + [self stopTorrents:fTableView.selectedTorrents]; } -- (void) stopAllTorrents: (id) sender +- (void)stopAllTorrents:(id)sender { - [self stopTorrents: fTorrents]; + [self stopTorrents:fTorrents]; } -- (void) stopTorrents: (NSArray *) torrents +- (void)stopTorrents:(NSArray*)torrents { //don't want any of these starting then stopping - for (Torrent * torrent in torrents) - if (torrent.waitingToStart) - [torrent stopTransfer]; + for (Torrent* torrent in torrents) + { + if (torrent.waitingToStart) + { + [torrent stopTransfer]; + } + } - for (Torrent * torrent in torrents) + for (Torrent* torrent in torrents) + { [torrent stopTransfer]; + } [self fullUpdateUI]; } -- (void) removeTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData +- (void)removeTorrents:(NSArray*)torrents deleteData:(BOOL)deleteData { - if ([fDefaults boolForKey: @"CheckRemove"]) + if ([fDefaults boolForKey:@"CheckRemove"]) { NSUInteger active = 0, downloading = 0; - for (Torrent * torrent in torrents) + for (Torrent* torrent in torrents) + { if (torrent.active) { ++active; if (!torrent.seeding) + { ++downloading; + } } + } - if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0) + if ([fDefaults boolForKey:@"CheckRemoveDownloading"] ? downloading > 0 : active > 0) { - NSString * title, * message; + NSString *title, *message; - const NSUInteger selected = torrents.count; + NSUInteger const selected = torrents.count; if (selected == 1) { - NSString * torrentName = ((Torrent *)torrents[0]).name; + NSString* torrentName = ((Torrent*)torrents[0]).name; if (deleteData) - title = [NSString stringWithFormat: - NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list" - " and trash the data file?", "Removal confirm panel -> title"), torrentName]; + { + title = [NSString stringWithFormat:NSLocalizedString( + @"Are you sure you want to remove \"%@\" from the transfer list" + " and trash the data file?", + "Removal confirm panel -> title"), + torrentName]; + } else - title = [NSString stringWithFormat: - NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?", - "Removal confirm panel -> title"), torrentName]; + { + title = [NSString + stringWithFormat:NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?", "Removal confirm panel -> title"), + torrentName]; + } - message = NSLocalizedString(@"This transfer is active." - " Once removed, continuing the transfer will require the torrent file or magnet link.", - "Removal confirm panel -> message"); + message = NSLocalizedString( + @"This transfer is active." + " Once removed, continuing the transfer will require the torrent file or magnet link.", + "Removal confirm panel -> message"); } else { if (deleteData) - title = [NSString stringWithFormat: - NSLocalizedString(@"Are you sure you want to remove %@ transfers from the transfer list" - " and trash the data files?", "Removal confirm panel -> title"), [NSString formattedUInteger: selected]]; + { + title = [NSString stringWithFormat:NSLocalizedString( + @"Are you sure you want to remove %@ transfers from the transfer list" + " and trash the data files?", + "Removal confirm panel -> title"), + [NSString formattedUInteger:selected]]; + } else - title = [NSString stringWithFormat: - NSLocalizedString(@"Are you sure you want to remove %@ transfers from the transfer list?", - "Removal confirm panel -> title"), [NSString formattedUInteger: selected]]; + { + title = [NSString stringWithFormat:NSLocalizedString( + @"Are you sure you want to remove %@ transfers from the transfer list?", + "Removal confirm panel -> title"), + [NSString formattedUInteger:selected]]; + } if (selected == active) - message = [NSString stringWithFormat: NSLocalizedString(@"There are %@ active transfers.", - "Removal confirm panel -> message part 1"), [NSString formattedUInteger: active]]; + { + message = [NSString stringWithFormat:NSLocalizedString(@"There are %@ active transfers.", "Removal confirm panel -> message part 1"), + [NSString formattedUInteger:active]]; + } else - message = [NSString stringWithFormat: NSLocalizedString(@"There are %@ transfers (%@ active).", - "Removal confirm panel -> message part 1"), [NSString formattedUInteger: selected], [NSString formattedUInteger: active]]; - message = [message stringByAppendingFormat: @" %@", - NSLocalizedString(@"Once removed, continuing the transfers will require the torrent files or magnet links.", - "Removal confirm panel -> message part 2")]; + { + message = [NSString stringWithFormat:NSLocalizedString(@"There are %@ transfers (%@ active).", "Removal confirm panel -> message part 1"), + [NSString formattedUInteger:selected], + [NSString formattedUInteger:active]]; + } + message = [message stringByAppendingFormat:@" %@", + NSLocalizedString( + @"Once removed, continuing the transfers will require the torrent files or magnet links.", + "Removal confirm panel -> message part 2")]; } - NSAlert *alert = [[NSAlert alloc] init]; + NSAlert* alert = [[NSAlert alloc] init]; alert.alertStyle = NSAlertStyleInformational; alert.messageText = title; alert.informativeText = message; [alert addButtonWithTitle:NSLocalizedString(@"Remove", "Removal confirm panel -> button")]; [alert addButtonWithTitle:NSLocalizedString(@"Cancel", "Removal confirm panel -> button")]; - [alert beginSheetModalForWindow:fWindow - completionHandler:^(NSModalResponse returnCode) { - if (returnCode == NSAlertFirstButtonReturn) { - [self confirmRemoveTorrents: torrents deleteData: deleteData]; - } - }]; + [alert beginSheetModalForWindow:fWindow completionHandler:^(NSModalResponse returnCode) { + if (returnCode == NSAlertFirstButtonReturn) + { + [self confirmRemoveTorrents:torrents deleteData:deleteData]; + } + }]; return; } } - [self confirmRemoveTorrents: torrents deleteData: deleteData]; + [self confirmRemoveTorrents:torrents deleteData:deleteData]; } -- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData +- (void)confirmRemoveTorrents:(NSArray*)torrents deleteData:(BOOL)deleteData { //miscellaneous - for (Torrent * torrent in torrents) + for (Torrent* torrent in torrents) { //don't want any of these starting then stopping if (torrent.waitingToStart) + { [torrent stopTransfer]; + } //let's expand all groups that have removed items - they either don't exist anymore, are already expanded, or are collapsed (rpc) - [fTableView removeCollapsedGroup: torrent.groupValue]; + [fTableView removeCollapsedGroup:torrent.groupValue]; //we can't assume the window is active - RPC removal, for example - [fBadger removeTorrent: torrent]; + [fBadger removeTorrent:torrent]; } //#5106 - don't try to remove torrents that have already been removed (fix for a bug, but better safe than crash anyway) - NSIndexSet * indexesToRemove = [torrents indexesOfObjectsWithOptions: NSEnumerationConcurrent passingTest: ^BOOL(Torrent * torrent, NSUInteger idx, BOOL * stop) { - return [fTorrents indexOfObjectIdenticalTo: torrent] != NSNotFound; - }]; + NSIndexSet* indexesToRemove = [torrents indexesOfObjectsWithOptions:NSEnumerationConcurrent + passingTest:^BOOL(Torrent* torrent, NSUInteger idx, BOOL* stop) { + return [fTorrents indexOfObjectIdenticalTo:torrent] != NSNotFound; + }]; if (torrents.count != indexesToRemove.count) { - NSLog(@"trying to remove %ld transfers, but %ld have already been removed", torrents.count, torrents.count - indexesToRemove.count); - torrents = [torrents objectsAtIndexes: indexesToRemove]; + NSLog( + @"trying to remove %ld transfers, but %ld have already been removed", + torrents.count, + torrents.count - indexesToRemove.count); + torrents = [torrents objectsAtIndexes:indexesToRemove]; if (indexesToRemove.count == 0) { @@ -1547,15 +1760,16 @@ static void removeKeRangerRansomware() } } - [fTorrents removeObjectsInArray: torrents]; + [fTorrents removeObjectsInArray:torrents]; //set up helpers to remove from the table __block BOOL beganUpdate = NO; - void (^doTableRemoval)(NSMutableArray *, id) = ^(NSMutableArray * displayedTorrents, id parent) { - NSIndexSet * indexes = [displayedTorrents indexesOfObjectsWithOptions: NSEnumerationConcurrent passingTest: ^(id obj, NSUInteger idx, BOOL * stop) { - return [torrents containsObject: obj]; - }]; + void (^doTableRemoval)(NSMutableArray*, id) = ^(NSMutableArray* displayedTorrents, id parent) { + NSIndexSet* indexes = [displayedTorrents indexesOfObjectsWithOptions:NSEnumerationConcurrent + passingTest:^(id obj, NSUInteger idx, BOOL* stop) { + return [torrents containsObject:obj]; + }]; if (indexes.count > 0) { @@ -1565,30 +1779,36 @@ static void removeKeRangerRansomware() //we can't closeRemoveTorrent: until it's no longer in the GUI at all NSAnimationContext.currentContext.completionHandler = ^{ - for (Torrent * torrent in torrents) - [torrent closeRemoveTorrent: deleteData]; + for (Torrent* torrent in torrents) + { + [torrent closeRemoveTorrent:deleteData]; + } }; [fTableView beginUpdates]; beganUpdate = YES; } - [fTableView removeItemsAtIndexes: indexes inParent: parent withAnimation: NSTableViewAnimationSlideLeft]; + [fTableView removeItemsAtIndexes:indexes inParent:parent withAnimation:NSTableViewAnimationSlideLeft]; - [displayedTorrents removeObjectsAtIndexes: indexes]; + [displayedTorrents removeObjectsAtIndexes:indexes]; } }; //if not removed from the displayed torrents here, fullUpdateUI might cause a crash if (fDisplayedTorrents.count > 0) { - if ([fDisplayedTorrents[0] isKindOfClass: [TorrentGroup class]]) + if ([fDisplayedTorrents[0] isKindOfClass:[TorrentGroup class]]) { - for (TorrentGroup * group in fDisplayedTorrents) + for (TorrentGroup* group in fDisplayedTorrents) + { doTableRemoval(group.torrents, group); + } } else + { doTableRemoval(fDisplayedTorrents, nil); + } if (beganUpdate) { @@ -1600,79 +1820,94 @@ static void removeKeRangerRansomware() if (!beganUpdate) { //do here if we're not doing it at the end of the animation - for (Torrent * torrent in torrents) - [torrent closeRemoveTorrent: deleteData]; + for (Torrent* torrent in torrents) + { + [torrent closeRemoveTorrent:deleteData]; + } } [self fullUpdateUI]; } -- (void) removeNoDelete: (id) sender +- (void)removeNoDelete:(id)sender { - [self removeTorrents: fTableView.selectedTorrents deleteData: NO]; + [self removeTorrents:fTableView.selectedTorrents deleteData:NO]; } -- (void) removeDeleteData: (id) sender +- (void)removeDeleteData:(id)sender { - [self removeTorrents: fTableView.selectedTorrents deleteData: YES]; + [self removeTorrents:fTableView.selectedTorrents deleteData:YES]; } -- (void) clearCompleted: (id) sender +- (void)clearCompleted:(id)sender { - NSMutableArray * torrents = [NSMutableArray array]; + NSMutableArray* torrents = [NSMutableArray array]; - for (Torrent * torrent in fTorrents) - if (torrent.finishedSeeding) - [torrents addObject: torrent]; - - if ([fDefaults boolForKey: @"WarningRemoveCompleted"]) + for (Torrent* torrent in fTorrents) { - NSString * message, * info; + if (torrent.finishedSeeding) + { + [torrents addObject:torrent]; + } + } + + if ([fDefaults boolForKey:@"WarningRemoveCompleted"]) + { + NSString *message, *info; if (torrents.count == 1) { - NSString * torrentName = ((Torrent *)torrents[0]).name; - message = [NSString stringWithFormat: NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?", - "Remove completed confirm panel -> title"), torrentName]; + NSString* torrentName = ((Torrent*)torrents[0]).name; + message = [NSString + stringWithFormat:NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?", "Remove completed confirm panel -> title"), + torrentName]; - info = NSLocalizedString(@"Once removed, continuing the transfer will require the torrent file or magnet link.", - "Remove completed confirm panel -> message"); + info = NSLocalizedString( + @"Once removed, continuing the transfer will require the torrent file or magnet link.", + "Remove completed confirm panel -> message"); } else { - message = [NSString stringWithFormat: NSLocalizedString(@"Are you sure you want to remove %@ completed transfers from the transfer list?", - "Remove completed confirm panel -> title"), [NSString formattedUInteger: torrents.count]]; + message = [NSString stringWithFormat:NSLocalizedString( + @"Are you sure you want to remove %@ completed transfers from the transfer list?", + "Remove completed confirm panel -> title"), + [NSString formattedUInteger:torrents.count]]; - info = NSLocalizedString(@"Once removed, continuing the transfers will require the torrent files or magnet links.", - "Remove completed confirm panel -> message"); + info = NSLocalizedString( + @"Once removed, continuing the transfers will require the torrent files or magnet links.", + "Remove completed confirm panel -> message"); } - NSAlert * alert = [[NSAlert alloc] init]; + NSAlert* alert = [[NSAlert alloc] init]; alert.messageText = message; alert.informativeText = info; alert.alertStyle = NSWarningAlertStyle; - [alert addButtonWithTitle: NSLocalizedString(@"Remove", "Remove completed confirm panel -> button")]; - [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Remove completed confirm panel -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Remove", "Remove completed confirm panel -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Cancel", "Remove completed confirm panel -> button")]; alert.showsSuppressionButton = YES; - const NSInteger returnCode = [alert runModal]; + NSInteger const returnCode = [alert runModal]; if (alert.suppressionButton.state) - [fDefaults setBool: NO forKey: @"WarningRemoveCompleted"]; + { + [fDefaults setBool:NO forKey:@"WarningRemoveCompleted"]; + } if (returnCode != NSAlertFirstButtonReturn) + { return; + } } - [self confirmRemoveTorrents: torrents deleteData: NO]; + [self confirmRemoveTorrents:torrents deleteData:NO]; } -- (void) moveDataFilesSelected: (id) sender +- (void)moveDataFilesSelected:(id)sender { - [self moveDataFiles: fTableView.selectedTorrents]; + [self moveDataFiles:fTableView.selectedTorrents]; } -- (void) moveDataFiles: (NSArray *) torrents +- (void)moveDataFiles:(NSArray*)torrents { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; panel.prompt = NSLocalizedString(@"Select", "Move torrent -> prompt"); panel.allowsMultipleSelection = NO; panel.canChooseFiles = NO; @@ -1681,220 +1916,257 @@ static void removeKeRangerRansomware() NSInteger count = torrents.count; if (count == 1) - panel.message = [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".", - "Move torrent -> select destination folder"), ((Torrent *)torrents[0]).name]; + { + panel.message = [NSString + stringWithFormat:NSLocalizedString(@"Select the new folder for \"%@\".", "Move torrent -> select destination folder"), + ((Torrent*)torrents[0]).name]; + } else - panel.message = [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.", - "Move torrent -> select destination folder"), count]; + { + panel.message = [NSString + stringWithFormat:NSLocalizedString(@"Select the new folder for %d data files.", "Move torrent -> select destination folder"), count]; + } - [panel beginSheetModalForWindow: fWindow completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:fWindow completionHandler:^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) { - for (Torrent * torrent in torrents) - [torrent moveTorrentDataFileTo: panel.URLs[0].path]; + for (Torrent* torrent in torrents) + { + [torrent moveTorrentDataFileTo:panel.URLs[0].path]; + } } }]; } -- (void) copyTorrentFiles: (id) sender +- (void)copyTorrentFiles:(id)sender { - [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: fTableView.selectedTorrents]]; + [self copyTorrentFileForTorrents:[[NSMutableArray alloc] initWithArray:fTableView.selectedTorrents]]; } -- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents +- (void)copyTorrentFileForTorrents:(NSMutableArray*)torrents { if (torrents.count == 0) { return; } - Torrent * torrent = torrents[0]; + Torrent* torrent = torrents[0]; - if (!torrent.magnet && [NSFileManager.defaultManager fileExistsAtPath: torrent.torrentLocation]) + if (!torrent.magnet && [NSFileManager.defaultManager fileExistsAtPath:torrent.torrentLocation]) { - NSSavePanel * panel = [NSSavePanel savePanel]; - panel.allowedFileTypes = @[@"org.bittorrent.torrent", @"torrent"]; + NSSavePanel* panel = [NSSavePanel savePanel]; + panel.allowedFileTypes = @[ @"org.bittorrent.torrent", @"torrent" ]; panel.extensionHidden = NO; panel.nameFieldStringValue = torrent.name; - [panel beginSheetModalForWindow: fWindow completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:fWindow completionHandler:^(NSInteger result) { //copy torrent to new location with name of data file if (result == NSFileHandlingPanelOKButton) - [torrent copyTorrentFileTo: panel.URL.path]; + { + [torrent copyTorrentFileTo:panel.URL.path]; + } - [torrents removeObjectAtIndex: 0]; - [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO]; + [torrents removeObjectAtIndex:0]; + [self performSelectorOnMainThread:@selector(copyTorrentFileForTorrents:) withObject:torrents waitUntilDone:NO]; }]; } else { if (!torrent.magnet) { - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")]; - alert.messageText = [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created", - "Torrent file copy alert -> title"), torrent.name]; - alert.informativeText = [NSString stringWithFormat: - NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"), - torrent.torrentLocation]; + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Torrent file copy alert -> button")]; + alert.messageText = [NSString + stringWithFormat:NSLocalizedString(@"Copy of \"%@\" Cannot Be Created", "Torrent file copy alert -> title"), + torrent.name]; + alert.informativeText = [NSString + stringWithFormat:NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"), + torrent.torrentLocation]; alert.alertStyle = NSWarningAlertStyle; [alert runModal]; } - [torrents removeObjectAtIndex: 0]; - [self copyTorrentFileForTorrents: torrents]; + [torrents removeObjectAtIndex:0]; + [self copyTorrentFileForTorrents:torrents]; } } -- (void) copyMagnetLinks: (id) sender +- (void)copyMagnetLinks:(id)sender { - NSArray * torrents = fTableView.selectedTorrents; + NSArray* torrents = fTableView.selectedTorrents; if (torrents.count <= 0) + { return; + } - NSMutableArray * links = [NSMutableArray arrayWithCapacity: torrents.count]; - for (Torrent * torrent in torrents) - [links addObject: torrent.magnetLink]; + NSMutableArray* links = [NSMutableArray arrayWithCapacity:torrents.count]; + for (Torrent* torrent in torrents) + { + [links addObject:torrent.magnetLink]; + } - NSString * text = [links componentsJoinedByString: @"\n"]; + NSString* text = [links componentsJoinedByString:@"\n"]; - NSPasteboard * pb = NSPasteboard.generalPasteboard; + NSPasteboard* pb = NSPasteboard.generalPasteboard; [pb clearContents]; - [pb writeObjects: @[text]]; + [pb writeObjects:@[ text ]]; } -- (void) revealFile: (id) sender +- (void)revealFile:(id)sender { - NSArray * selected = fTableView.selectedTorrents; - NSMutableArray * paths = [NSMutableArray arrayWithCapacity: selected.count]; - for (Torrent * torrent in selected) + NSArray* selected = fTableView.selectedTorrents; + NSMutableArray* paths = [NSMutableArray arrayWithCapacity:selected.count]; + for (Torrent* torrent in selected) { - NSString * location = torrent.dataLocation; + NSString* location = torrent.dataLocation; if (location) - [paths addObject: [NSURL fileURLWithPath: location]]; + { + [paths addObject:[NSURL fileURLWithPath:location]]; + } } if (paths.count > 0) - [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs: paths]; + { + [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs:paths]; + } } -- (IBAction) renameSelected: (id) sender +- (IBAction)renameSelected:(id)sender { - NSArray * selected = fTableView.selectedTorrents; + NSArray* selected = fTableView.selectedTorrents; NSAssert(selected.count == 1, @"1 transfer needs to be selected to rename, but %ld are selected", selected.count); - Torrent * torrent = selected[0]; + Torrent* torrent = selected[0]; - [FileRenameSheetController presentSheetForTorrent:torrent modalForWindow: fWindow completionHandler: ^(BOOL didRename) { + [FileRenameSheetController presentSheetForTorrent:torrent modalForWindow:fWindow completionHandler:^(BOOL didRename) { if (didRename) { dispatch_async(dispatch_get_main_queue(), ^{ [self fullUpdateUI]; - [NSNotificationCenter.defaultCenter postNotificationName: @"ResetInspector" object: self userInfo: @{ @"Torrent" : torrent }]; + [NSNotificationCenter.defaultCenter postNotificationName:@"ResetInspector" object:self + userInfo:@{ @"Torrent" : torrent }]; }); } }]; } -- (void) announceSelectedTorrents: (id) sender +- (void)announceSelectedTorrents:(id)sender { - for (Torrent * torrent in fTableView.selectedTorrents) + for (Torrent* torrent in fTableView.selectedTorrents) { if (torrent.canManualAnnounce) + { [torrent manualAnnounce]; + } } } -- (void) verifySelectedTorrents: (id) sender +- (void)verifySelectedTorrents:(id)sender { - [self verifyTorrents: fTableView.selectedTorrents]; + [self verifyTorrents:fTableView.selectedTorrents]; } -- (void) verifyTorrents: (NSArray *) torrents +- (void)verifyTorrents:(NSArray*)torrents { - for (Torrent * torrent in torrents) + for (Torrent* torrent in torrents) + { [torrent resetCache]; + } [self applyFilter]; } -- (NSArray *)selectedTorrents +- (NSArray*)selectedTorrents { return fTableView.selectedTorrents; } -- (void) showPreferenceWindow: (id) sender +- (void)showPreferenceWindow:(id)sender { - NSWindow * window = _prefsController.window; + NSWindow* window = _prefsController.window; if (!window.visible) + { [window center]; + } - [window makeKeyAndOrderFront: nil]; + [window makeKeyAndOrderFront:nil]; } -- (void) showAboutWindow: (id) sender +- (void)showAboutWindow:(id)sender { - [AboutWindowController.aboutController showWindow: nil]; + [AboutWindowController.aboutController showWindow:nil]; } -- (void) showInfo: (id) sender +- (void)showInfo:(id)sender { if (fInfoController.window.visible) + { [fInfoController close]; + } else { [fInfoController updateInfoStats]; - [fInfoController.window orderFront: nil]; + [fInfoController.window orderFront:nil]; if (fInfoController.canQuickLook && [QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible) + { [[QLPreviewPanel sharedPreviewPanel] reloadData]; + } } [fWindow.toolbar validateVisibleItems]; } -- (void) resetInfo +- (void)resetInfo { - [fInfoController setInfoForTorrents: fTableView.selectedTorrents]; + [fInfoController setInfoForTorrents:fTableView.selectedTorrents]; if ([QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible) + { [[QLPreviewPanel sharedPreviewPanel] reloadData]; + } } -- (void) setInfoTab: (id) sender +- (void)setInfoTab:(id)sender { if (sender == fNextInfoTabItem) + { [fInfoController setNextTab]; + } else + { [fInfoController setPreviousTab]; + } } -- (MessageWindowController *) messageWindowController +- (MessageWindowController*)messageWindowController { if (!fMessageController) + { fMessageController = [[MessageWindowController alloc] init]; + } return fMessageController; } -- (void) showMessageWindow: (id) sender +- (void)showMessageWindow:(id)sender { - [self.messageWindowController showWindow: nil]; + [self.messageWindowController showWindow:nil]; } -- (void) showStatsWindow: (id) sender +- (void)showStatsWindow:(id)sender { - [StatsWindowController.statsWindow showWindow: nil]; + [StatsWindowController.statsWindow showWindow:nil]; } -- (void) updateUI +- (void)updateUI { CGFloat dlRate = 0.0, ulRate = 0.0; BOOL anyCompleted = NO; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) { [torrent update]; @@ -1909,24 +2181,26 @@ static void removeKeRangerRansomware() { if (fWindow.visible) { - [self sortTorrents: NO]; + [self sortTorrents:NO]; - [fStatusBar updateWithDownload: dlRate upload: ulRate]; + [fStatusBar updateWithDownload:dlRate upload:ulRate]; fClearCompletedButton.hidden = !anyCompleted; } //update non-constant parts of info window if (fInfoController.window.visible) + { [fInfoController updateInfoStats]; + } } //badge dock - [fBadger updateBadgeWithDownload: dlRate upload: ulRate]; + [fBadger updateBadgeWithDownload:dlRate upload:ulRate]; } #warning can this be removed or refined? -- (void) fullUpdateUI +- (void)fullUpdateUI { [self updateUI]; [self applyFilter]; @@ -1934,98 +2208,113 @@ static void removeKeRangerRansomware() [self updateTorrentHistory]; } -- (void) setBottomCountText: (BOOL) filtering +- (void)setBottomCountText:(BOOL)filtering { - NSString * totalTorrentsString; + NSString* totalTorrentsString; NSUInteger totalCount = fTorrents.count; if (totalCount != 1) - totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ transfers", "Status bar transfer count"), - [NSString formattedUInteger: totalCount]]; + { + totalTorrentsString = [NSString stringWithFormat:NSLocalizedString(@"%@ transfers", "Status bar transfer count"), + [NSString formattedUInteger:totalCount]]; + } else + { totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count"); + } if (filtering) { NSUInteger count = fTableView.numberOfRows; //have to factor in collapsed rows - if (count > 0 && ![fDisplayedTorrents[0] isKindOfClass: [Torrent class]]) + if (count > 0 && ![fDisplayedTorrents[0] isKindOfClass:[Torrent class]]) + { count -= fDisplayedTorrents.count; + } - totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Status bar transfer count"), - [NSString formattedUInteger: count], totalTorrentsString]; + totalTorrentsString = [NSString stringWithFormat:NSLocalizedString(@"%@ of %@", "Status bar transfer count"), + [NSString formattedUInteger:count], + totalTorrentsString]; } fTotalTorrentsField.stringValue = totalTorrentsString; } -- (BOOL) userNotificationCenter: (NSUserNotificationCenter *) center shouldPresentNotification:(NSUserNotification *) notification +- (BOOL)userNotificationCenter:(NSUserNotificationCenter*)center shouldPresentNotification:(NSUserNotification*)notification { return YES; } -- (void) userNotificationCenter: (NSUserNotificationCenter *) center didActivateNotification: (NSUserNotification *) notification +- (void)userNotificationCenter:(NSUserNotificationCenter*)center didActivateNotification:(NSUserNotification*)notification { if (!notification.userInfo) + { return; + } if (notification.activationType == NSUserNotificationActivationTypeActionButtonClicked) //reveal { - Torrent * torrent = [self torrentForHash: notification.userInfo[@"Hash"]]; - NSString * location = torrent.dataLocation; + Torrent* torrent = [self torrentForHash:notification.userInfo[@"Hash"]]; + NSString* location = torrent.dataLocation; if (!location) + { location = notification.userInfo[@"Location"]; + } if (location) - [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs: @[[NSURL fileURLWithPath: location]]]; + { + [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs:@[ [NSURL fileURLWithPath:location] ]]; + } } else if (notification.activationType == NSUserNotificationActivationTypeContentsClicked) { - Torrent * torrent = [self torrentForHash: notification.userInfo[@"Hash"]]; + Torrent* torrent = [self torrentForHash:notification.userInfo[@"Hash"]]; if (torrent) { //select in the table - first see if it's already shown - NSInteger row = [fTableView rowForItem: torrent]; + NSInteger row = [fTableView rowForItem:torrent]; if (row == -1) { //if it's not shown, see if it's in a collapsed row - if ([fDefaults boolForKey: @"SortByGroup"]) + if ([fDefaults boolForKey:@"SortByGroup"]) { - __block TorrentGroup * parent = nil; - [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(TorrentGroup * group, NSUInteger idx, BOOL *stop) { - if ([group.torrents containsObject: torrent]) - { - parent = group; - *stop = YES; - } - }]; + __block TorrentGroup* parent = nil; + [fDisplayedTorrents enumerateObjectsWithOptions:NSEnumerationConcurrent + usingBlock:^(TorrentGroup* group, NSUInteger idx, BOOL* stop) { + if ([group.torrents containsObject:torrent]) + { + parent = group; + *stop = YES; + } + }]; if (parent) { - [[fTableView animator] expandItem: parent]; - row = [fTableView rowForItem: torrent]; + [[fTableView animator] expandItem:parent]; + row = [fTableView rowForItem:torrent]; } } if (row == -1) { //not found - must be filtering - NSAssert([fDefaults boolForKey: @"FilterBar"], @"expected the filter to be enabled"); - [fFilterBar reset: YES]; + NSAssert([fDefaults boolForKey:@"FilterBar"], @"expected the filter to be enabled"); + [fFilterBar reset:YES]; - row = [fTableView rowForItem: torrent]; + row = [fTableView rowForItem:torrent]; //if it's not shown, it has to be in a collapsed row...again - if ([fDefaults boolForKey: @"SortByGroup"]) + if ([fDefaults boolForKey:@"SortByGroup"]) { - __block TorrentGroup * parent = nil; - [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(TorrentGroup * group, NSUInteger idx, BOOL *stop) { - if ([group.torrents containsObject: torrent]) - { - parent = group; - *stop = YES; - } - }]; + __block TorrentGroup* parent = nil; + [fDisplayedTorrents enumerateObjectsWithOptions:NSEnumerationConcurrent + usingBlock:^(TorrentGroup* group, NSUInteger idx, BOOL* stop) { + if ([group.torrents containsObject:torrent]) + { + parent = group; + *stop = YES; + } + }]; if (parent) { - [[fTableView animator] expandItem: parent]; - row = [fTableView rowForItem: torrent]; + [[fTableView animator] expandItem:parent]; + row = [fTableView rowForItem:torrent]; } } } @@ -2033,19 +2322,19 @@ static void removeKeRangerRansomware() NSAssert1(row != -1, @"expected a row to be found for torrent %@", torrent); - [self showMainWindow: nil]; - [fTableView selectAndScrollToRow: row]; + [self showMainWindow:nil]; + [fTableView selectAndScrollToRow:row]; } } } -- (Torrent *) torrentForHash: (NSString *) hash +- (Torrent*)torrentForHash:(NSString*)hash { NSParameterAssert(hash != nil); - __block Torrent * torrent = nil; - [fTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id obj, NSUInteger idx, BOOL * stop) { - if ([((Torrent *)obj).hashString isEqualToString: hash]) + __block Torrent* torrent = nil; + [fTorrents enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL* stop) { + if ([((Torrent*)obj).hashString isEqualToString:hash]) { torrent = obj; *stop = YES; @@ -2054,16 +2343,16 @@ static void removeKeRangerRansomware() return torrent; } -- (void) torrentFinishedDownloading: (NSNotification *) notification +- (void)torrentFinishedDownloading:(NSNotification*)notification { - Torrent * torrent = notification.object; + Torrent* torrent = notification.object; if ([notification.userInfo[@"WasRunning"] boolValue]) { - if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"]) + if (!fSoundPlaying && [fDefaults boolForKey:@"PlayDownloadSound"]) { - NSSound * sound; - if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]])) + NSSound* sound; + if ((sound = [NSSound soundNamed:[fDefaults stringForKey:@"DownloadSound"]])) { sound.delegate = self; fSoundPlaying = YES; @@ -2071,47 +2360,51 @@ static void removeKeRangerRansomware() } } - NSString * location = torrent.dataLocation; + NSString* location = torrent.dataLocation; - NSString * notificationTitle = NSLocalizedString(@"Download Complete", "notification title"); - NSUserNotification * notification = [[NSUserNotification alloc] init]; + NSString* notificationTitle = NSLocalizedString(@"Download Complete", "notification title"); + NSUserNotification* notification = [[NSUserNotification alloc] init]; notification.title = notificationTitle; notification.informativeText = torrent.name; notification.hasActionButton = YES; notification.actionButtonTitle = NSLocalizedString(@"Show", "notification button"); - NSMutableDictionary * userInfo = [NSMutableDictionary dictionaryWithObject: torrent.hashString forKey: @"Hash"]; + NSMutableDictionary* userInfo = [NSMutableDictionary dictionaryWithObject:torrent.hashString forKey:@"Hash"]; if (location) + { userInfo[@"Location"] = location; + } notification.userInfo = userInfo; - [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification: notification]; + [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification:notification]; if (!fWindow.mainWindow) - [fBadger addCompletedTorrent: torrent]; + { + [fBadger addCompletedTorrent:torrent]; + } //bounce download stack - [NSDistributedNotificationCenter.defaultCenter postNotificationName: @"com.apple.DownloadFileFinished" - object: torrent.dataLocation]; + [NSDistributedNotificationCenter.defaultCenter postNotificationName:@"com.apple.DownloadFileFinished" + object:torrent.dataLocation]; } [self fullUpdateUI]; } -- (void) torrentRestartedDownloading: (NSNotification *) notification +- (void)torrentRestartedDownloading:(NSNotification*)notification { [self fullUpdateUI]; } -- (void) torrentFinishedSeeding: (NSNotification *) notification +- (void)torrentFinishedSeeding:(NSNotification*)notification { - Torrent * torrent = notification.object; + Torrent* torrent = notification.object; - if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"]) + if (!fSoundPlaying && [fDefaults boolForKey:@"PlaySeedingSound"]) { - NSSound * sound; - if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]])) + NSSound* sound; + if ((sound = [NSSound soundNamed:[fDefaults stringForKey:@"SeedingSound"]])) { sound.delegate = self; fSoundPlaying = YES; @@ -2119,34 +2412,40 @@ static void removeKeRangerRansomware() } } - NSString * location = torrent.dataLocation; + NSString* location = torrent.dataLocation; - NSString * notificationTitle = NSLocalizedString(@"Seeding Complete", "notification title"); - NSUserNotification * userNotification = [[NSUserNotification alloc] init]; + NSString* notificationTitle = NSLocalizedString(@"Seeding Complete", "notification title"); + NSUserNotification* userNotification = [[NSUserNotification alloc] init]; userNotification.title = notificationTitle; userNotification.informativeText = torrent.name; userNotification.hasActionButton = YES; userNotification.actionButtonTitle = NSLocalizedString(@"Show", "notification button"); - NSMutableDictionary * userInfo = [NSMutableDictionary dictionaryWithObject: torrent.hashString forKey: @"Hash"]; + NSMutableDictionary* userInfo = [NSMutableDictionary dictionaryWithObject:torrent.hashString forKey:@"Hash"]; if (location) + { userInfo[@"Location"] = location; + } userNotification.userInfo = userInfo; - [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification: userNotification]; + [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification:userNotification]; //removing from the list calls fullUpdateUI if (torrent.removeWhenFinishSeeding) - [self confirmRemoveTorrents: @[ torrent ] deleteData: NO]; + { + [self confirmRemoveTorrents:@[ torrent ] deleteData:NO]; + } else { if (!fWindow.mainWindow) - [fBadger addCompletedTorrent: torrent]; + { + [fBadger addCompletedTorrent:torrent]; + } [self fullUpdateUI]; - if ([fTableView.selectedTorrents containsObject: torrent]) + if ([fTableView.selectedTorrents containsObject:torrent]) { [fInfoController updateInfoStats]; [fInfoController updateOptions]; @@ -2154,26 +2453,2268 @@ static void removeKeRangerRansomware() } } -- (void) updateTorrentHistory +- (void)updateTorrentHistory { - NSMutableArray * history = [NSMutableArray arrayWithCapacity: fTorrents.count]; + NSMutableArray* history = [NSMutableArray arrayWithCapacity:fTorrents.count]; - for (Torrent * torrent in fTorrents) - [history addObject: torrent.history]; + for (Torrent* torrent in fTorrents) + { + [history addObject:torrent.history]; + } - NSString * historyFile = [fConfigDirectory stringByAppendingPathComponent: TRANSFER_PLIST]; - [history writeToFile: historyFile atomically: YES]; + NSString* historyFile = [fConfigDirectory stringByAppendingPathComponent:TRANSFER_PLIST]; + [history writeToFile:historyFile atomically:YES]; } -- (void) setSort: (id) sender +- (void)setSort:(id)sender { - NSString * sortType; - NSMenuItem *senderMenuItem = sender; + NSString* sortType; + NSMenuItem* senderMenuItem = sender; switch (senderMenuItem.tag) { + case SORT_ORDER_TAG: + sortType = SORT_ORDER; + [fDefaults setBool:NO forKey:@"SortReverse"]; + break; + case SORT_DATE_TAG: + sortType = SORT_DATE; + break; + case SORT_NAME_TAG: + sortType = SORT_NAME; + break; + case SORT_PROGRESS_TAG: + sortType = SORT_PROGRESS; + break; + case SORT_STATE_TAG: + sortType = SORT_STATE; + break; + case SORT_TRACKER_TAG: + sortType = SORT_TRACKER; + break; + case SORT_ACTIVITY_TAG: + sortType = SORT_ACTIVITY; + break; + case SORT_SIZE_TAG: + sortType = SORT_SIZE; + break; + default: + NSAssert1(NO, @"Unknown sort tag received: %ld", senderMenuItem.tag); + return; + } + + [fDefaults setObject:sortType forKey:@"Sort"]; + + [self sortTorrents:YES]; +} + +- (void)setSortByGroup:(id)sender +{ + BOOL sortByGroup = ![fDefaults boolForKey:@"SortByGroup"]; + [fDefaults setBool:sortByGroup forKey:@"SortByGroup"]; + + [self applyFilter]; +} + +- (void)setSortReverse:(id)sender +{ + BOOL const setReverse = ((NSMenuItem*)sender).tag == SORT_DESC_TAG; + if (setReverse != [fDefaults boolForKey:@"SortReverse"]) + { + [fDefaults setBool:setReverse forKey:@"SortReverse"]; + [self sortTorrents:NO]; + } +} + +- (void)sortTorrents:(BOOL)includeQueueOrder +{ + //actually sort + [self sortTorrentsCallUpdates:YES includeQueueOrder:includeQueueOrder]; + fTableView.needsDisplay = YES; +} + +- (void)sortTorrentsCallUpdates:(BOOL)callUpdates includeQueueOrder:(BOOL)includeQueueOrder +{ + BOOL const asc = ![fDefaults boolForKey:@"SortReverse"]; + + NSArray* descriptors; + NSSortDescriptor* nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:asc + selector:@selector(localizedStandardCompare:)]; + + NSString* sortType = [fDefaults stringForKey:@"Sort"]; + if ([sortType isEqualToString:SORT_STATE]) + { + NSSortDescriptor* stateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"stateSortKey" ascending:!asc]; + NSSortDescriptor* progressDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"progress" ascending:!asc]; + NSSortDescriptor* ratioDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"ratio" ascending:!asc]; + + descriptors = @[ stateDescriptor, progressDescriptor, ratioDescriptor, nameDescriptor ]; + } + else if ([sortType isEqualToString:SORT_PROGRESS]) + { + NSSortDescriptor* progressDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"progress" ascending:asc]; + NSSortDescriptor* ratioProgressDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"progressStopRatio" ascending:asc]; + NSSortDescriptor* ratioDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"ratio" ascending:asc]; + + descriptors = @[ progressDescriptor, ratioProgressDescriptor, ratioDescriptor, nameDescriptor ]; + } + else if ([sortType isEqualToString:SORT_TRACKER]) + { + NSSortDescriptor* trackerDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"trackerSortKey" ascending:asc + selector:@selector(localizedCaseInsensitiveCompare:)]; + + descriptors = @[ trackerDescriptor, nameDescriptor ]; + } + else if ([sortType isEqualToString:SORT_ACTIVITY]) + { + NSSortDescriptor* rateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"totalRate" ascending:!asc]; + NSSortDescriptor* activityDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"dateActivityOrAdd" ascending:!asc]; + + descriptors = @[ rateDescriptor, activityDescriptor, nameDescriptor ]; + } + else if ([sortType isEqualToString:SORT_DATE]) + { + NSSortDescriptor* dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"dateAdded" ascending:asc]; + + descriptors = @[ dateDescriptor, nameDescriptor ]; + } + else if ([sortType isEqualToString:SORT_SIZE]) + { + NSSortDescriptor* sizeDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"size" ascending:asc]; + + descriptors = @[ sizeDescriptor, nameDescriptor ]; + } + else if ([sortType isEqualToString:SORT_NAME]) + { + descriptors = @[ nameDescriptor ]; + } + else + { + NSAssert1([sortType isEqualToString:SORT_ORDER], @"Unknown sort type received: %@", sortType); + + if (!includeQueueOrder) + { + return; + } + + NSSortDescriptor* orderDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"queuePosition" ascending:asc]; + + descriptors = @[ orderDescriptor ]; + } + + BOOL beganTableUpdate = !callUpdates; + + //actually sort + if ([fDefaults boolForKey:@"SortByGroup"]) + { + for (TorrentGroup* group in fDisplayedTorrents) + { + [self rearrangeTorrentTableArray:group.torrents forParent:group withSortDescriptors:descriptors + beganTableUpdate:&beganTableUpdate]; + } + } + else + { + [self rearrangeTorrentTableArray:fDisplayedTorrents forParent:nil withSortDescriptors:descriptors + beganTableUpdate:&beganTableUpdate]; + } + + if (beganTableUpdate && callUpdates) + { + [fTableView endUpdates]; + } +} + +#warning redo so that we search a copy once again (best explained by changing sorting from ascending to descending) +- (void)rearrangeTorrentTableArray:(NSMutableArray*)rearrangeArray + forParent:parent + withSortDescriptors:(NSArray*)descriptors + beganTableUpdate:(BOOL*)beganTableUpdate +{ + for (NSUInteger currentIndex = 1; currentIndex < rearrangeArray.count; ++currentIndex) + { + //manually do the sorting in-place + NSUInteger const insertIndex = [rearrangeArray indexOfObject:rearrangeArray[currentIndex] + inSortedRange:NSMakeRange(0, currentIndex) + options:(NSBinarySearchingInsertionIndex | NSBinarySearchingLastEqual) + usingComparator:^NSComparisonResult(id obj1, id obj2) { + for (NSSortDescriptor* descriptor in descriptors) + { + NSComparisonResult const result = [descriptor compareObject:obj1 + toObject:obj2]; + if (result != NSOrderedSame) + { + return result; + } + } + + return NSOrderedSame; + }]; + + if (insertIndex != currentIndex) + { + if (!*beganTableUpdate) + { + *beganTableUpdate = YES; + [fTableView beginUpdates]; + } + + [rearrangeArray moveObjectAtIndex:currentIndex toIndex:insertIndex]; + [fTableView moveItemAtIndex:currentIndex inParent:parent toIndex:insertIndex inParent:parent]; + } + } + + NSAssert2( + [rearrangeArray isEqualToArray:[rearrangeArray sortedArrayUsingDescriptors:descriptors]], + @"Torrent rearranging didn't work! %@ %@", + rearrangeArray, + [rearrangeArray sortedArrayUsingDescriptors:descriptors]); +} + +- (void)applyFilter +{ + __block int32_t active = 0, downloading = 0, seeding = 0, paused = 0; + NSString* filterType = [fDefaults stringForKey:@"Filter"]; + BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES; + if ([filterType isEqualToString:FILTER_ACTIVE]) + { + filterActive = YES; + } + else if ([filterType isEqualToString:FILTER_DOWNLOAD]) + { + filterDownload = YES; + } + else if ([filterType isEqualToString:FILTER_SEED]) + { + filterSeed = YES; + } + else if ([filterType isEqualToString:FILTER_PAUSE]) + { + filterPause = YES; + } + else + { + filterStatus = NO; + } + + NSInteger const groupFilterValue = [fDefaults integerForKey:@"FilterGroup"]; + BOOL const filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG; + + NSArray* searchStrings = fFilterBar.searchStrings; + if (searchStrings && searchStrings.count == 0) + { + searchStrings = nil; + } + BOOL const filterTracker = searchStrings && [[fDefaults stringForKey:@"FilterSearchType"] isEqualToString:FILTER_TYPE_TRACKER]; + + //filter & get counts of each type + NSIndexSet* indexesOfNonFilteredTorrents = [fTorrents + indexesOfObjectsWithOptions:NSEnumerationConcurrent passingTest:^BOOL(Torrent* torrent, NSUInteger idx, BOOL* stop) { + //check status + if (torrent.active && !torrent.checkingWaiting) + { + BOOL const isActive = !torrent.stalled; + if (isActive) + { + OSAtomicIncrement32(&active); + } + + if (torrent.seeding) + { + OSAtomicIncrement32(&seeding); + if (filterStatus && !((filterActive && isActive) || filterSeed)) + { + return NO; + } + } + else + { + OSAtomicIncrement32(&downloading); + if (filterStatus && !((filterActive && isActive) || filterDownload)) + { + return NO; + } + } + } + else + { + OSAtomicIncrement32(&paused); + if (filterStatus && !filterPause) + { + return NO; + } + } + + //checkGroup + if (filterGroup) + if (torrent.groupValue != groupFilterValue) + { + return NO; + } + + //check text field + if (searchStrings) + { + __block BOOL removeTextField = NO; + if (filterTracker) + { + NSArray* trackers = torrent.allTrackersFlat; + + //to count, we need each string in at least 1 tracker + [searchStrings enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id searchString, NSUInteger idx, BOOL* stop) { + __block BOOL found = NO; + [trackers enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id tracker, NSUInteger idx, BOOL* stopTracker) { + if ([tracker rangeOfString:searchString options:(NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)] + .location != NSNotFound) + { + found = YES; + *stopTracker = YES; + } + }]; + if (!found) + { + removeTextField = YES; + *stop = YES; + } + }]; + } + else + { + [searchStrings enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id searchString, NSUInteger idx, BOOL* stop) { + if ([torrent.name rangeOfString:searchString options:(NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)] + .location == NSNotFound) + { + removeTextField = YES; + *stop = YES; + } + }]; + } + + if (removeTextField) + { + return NO; + } + } + + return YES; + }]; + + NSArray* allTorrents = [fTorrents objectsAtIndexes:indexesOfNonFilteredTorrents]; + + //set button tooltips + if (fFilterBar) + { + [fFilterBar setCountAll:fTorrents.count active:active downloading:downloading seeding:seeding paused:paused]; + } + + //if either the previous or current lists are blank, set its value to the other + BOOL const groupRows = allTorrents.count > 0 ? + [fDefaults boolForKey:@"SortByGroup"] : + (fDisplayedTorrents.count > 0 && [fDisplayedTorrents[0] isKindOfClass:[TorrentGroup class]]); + BOOL const wasGroupRows = fDisplayedTorrents.count > 0 ? [fDisplayedTorrents[0] isKindOfClass:[TorrentGroup class]] : groupRows; + +#warning could probably be merged with later code somehow + //clear display cache for not-shown torrents + if (fDisplayedTorrents.count > 0) + { + //for each torrent, removes the previous piece info if it's not in allTorrents, and keeps track of which torrents we already found in allTorrents + void (^removePreviousFinishedPieces)(id, NSUInteger, BOOL*) = ^(Torrent* torrent, NSUInteger idx, BOOL* stop) { + //we used to keep track of which torrents we already found in allTorrents, but it wasn't safe fo concurrent enumeration + if (![allTorrents containsObject:torrent]) + { + torrent.previousFinishedPieces = nil; + } + }; + + if (wasGroupRows) + { + [fDisplayedTorrents enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL* stop) { + [((TorrentGroup*)obj).torrents enumerateObjectsWithOptions:NSEnumerationConcurrent + usingBlock:removePreviousFinishedPieces]; + }]; + } + else + { + [fDisplayedTorrents enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:removePreviousFinishedPieces]; + } + } + + BOOL beganUpdates = NO; + + //don't animate torrents when first launching + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSAnimationContext.currentContext.duration = 0; + }); + [NSAnimationContext beginGrouping]; + + //add/remove torrents (and rearrange for groups), one by one + if (!groupRows && !wasGroupRows) + { + NSMutableIndexSet* addIndexes = [NSMutableIndexSet indexSet]; + NSMutableIndexSet* removePreviousIndexes = [NSMutableIndexSet + indexSetWithIndexesInRange:NSMakeRange(0, fDisplayedTorrents.count)]; + + //for each of the torrents to add, find if it already exists (and keep track of those we've already added & those we need to remove) + [allTorrents enumerateObjectsWithOptions:0 usingBlock:^(id objAll, NSUInteger previousIndex, BOOL* stop) { + NSUInteger const currentIndex = [fDisplayedTorrents indexOfObjectAtIndexes:removePreviousIndexes + options:NSEnumerationConcurrent + passingTest:^(id objDisplay, NSUInteger idx, BOOL* stop) { + return (BOOL)(objAll == objDisplay); + }]; + if (currentIndex == NSNotFound) + { + [addIndexes addIndex:previousIndex]; + } + else + { + [removePreviousIndexes removeIndex:currentIndex]; + } + }]; + + if (addIndexes.count > 0 || removePreviousIndexes.count > 0) + { + beganUpdates = YES; + [fTableView beginUpdates]; + + //remove torrents we didn't find + if (removePreviousIndexes.count > 0) + { + [fDisplayedTorrents removeObjectsAtIndexes:removePreviousIndexes]; + [fTableView removeItemsAtIndexes:removePreviousIndexes inParent:nil withAnimation:NSTableViewAnimationSlideDown]; + } + + //add new torrents + if (addIndexes.count > 0) + { + //slide new torrents in differently + if (fAddingTransfers) + { + NSIndexSet* newAddIndexes = [allTorrents indexesOfObjectsAtIndexes:addIndexes options:NSEnumerationConcurrent + passingTest:^BOOL(id obj, NSUInteger idx, BOOL* stop) { + return [fAddingTransfers containsObject:obj]; + }]; + + [addIndexes removeIndexes:newAddIndexes]; + + [fDisplayedTorrents addObjectsFromArray:[allTorrents objectsAtIndexes:newAddIndexes]]; + [fTableView + insertItemsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange( + fDisplayedTorrents.count - newAddIndexes.count, + newAddIndexes.count)] + inParent:nil + withAnimation:NSTableViewAnimationSlideLeft]; + } + + [fDisplayedTorrents addObjectsFromArray:[allTorrents objectsAtIndexes:addIndexes]]; + [fTableView + insertItemsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange( + fDisplayedTorrents.count - addIndexes.count, + addIndexes.count)] + inParent:nil + withAnimation:NSTableViewAnimationSlideDown]; + } + } + } + else if (groupRows && wasGroupRows) + { + NSAssert(groupRows && wasGroupRows, @"Should have had group rows and should remain with group rows"); + +#warning don't always do? + beganUpdates = YES; + [fTableView beginUpdates]; + + NSMutableIndexSet* unusedAllTorrentsIndexes = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(0, allTorrents.count)]; + + NSMutableDictionary* groupsByIndex = [NSMutableDictionary dictionaryWithCapacity:fDisplayedTorrents.count]; + for (TorrentGroup* group in fDisplayedTorrents) + { + groupsByIndex[@(group.groupIndex)] = group; + } + + NSUInteger const originalGroupCount = fDisplayedTorrents.count; + for (NSUInteger index = 0; index < originalGroupCount; ++index) + { + TorrentGroup* group = fDisplayedTorrents[index]; + + NSMutableIndexSet* removeIndexes = [NSMutableIndexSet indexSet]; + + //needs to be a signed integer + for (NSUInteger indexInGroup = 0; indexInGroup < group.torrents.count; ++indexInGroup) + { + Torrent* torrent = group.torrents[indexInGroup]; + NSUInteger const allIndex = [allTorrents indexOfObjectAtIndexes:unusedAllTorrentsIndexes options:NSEnumerationConcurrent + passingTest:^(id obj, NSUInteger idx, BOOL* stop) { + return (BOOL)(obj == torrent); + }]; + if (allIndex == NSNotFound) + { + [removeIndexes addIndex:indexInGroup]; + } + else + { + BOOL markTorrentAsUsed = YES; + + NSInteger const groupValue = torrent.groupValue; + if (groupValue != group.groupIndex) + { + TorrentGroup* newGroup = groupsByIndex[@(groupValue)]; + if (!newGroup) + { + newGroup = [[TorrentGroup alloc] initWithGroup:groupValue]; + groupsByIndex[@(groupValue)] = newGroup; + [fDisplayedTorrents addObject:newGroup]; + + [fTableView insertItemsAtIndexes:[NSIndexSet indexSetWithIndex:fDisplayedTorrents.count - 1] inParent:nil + withAnimation:NSTableViewAnimationEffectFade]; + [fTableView isGroupCollapsed:groupValue] ? [fTableView collapseItem:newGroup] : + [fTableView expandItem:newGroup]; + } + else //if we haven't processed the other group yet, we have to make sure we don't flag it for removal the next time + { + //ugggh, but shouldn't happen too often + if ([fDisplayedTorrents indexOfObject:newGroup + inRange:NSMakeRange(index + 1, originalGroupCount - (index + 1))] != NSNotFound) + { + markTorrentAsUsed = NO; + } + } + + [group.torrents removeObjectAtIndex:indexInGroup]; + [newGroup.torrents addObject:torrent]; + + [fTableView moveItemAtIndex:indexInGroup inParent:group toIndex:newGroup.torrents.count - 1 + inParent:newGroup]; + + --indexInGroup; + } + + if (markTorrentAsUsed) + { + [unusedAllTorrentsIndexes removeIndex:allIndex]; + } + } + } + + if (removeIndexes.count > 0) + { + [group.torrents removeObjectsAtIndexes:removeIndexes]; + [fTableView removeItemsAtIndexes:removeIndexes inParent:group withAnimation:NSTableViewAnimationEffectFade]; + } + } + + //add remaining new torrents + for (Torrent* torrent in [allTorrents objectsAtIndexes:unusedAllTorrentsIndexes]) + { + NSInteger const groupValue = torrent.groupValue; + TorrentGroup* group = groupsByIndex[@(groupValue)]; + if (!group) + { + group = [[TorrentGroup alloc] initWithGroup:groupValue]; + groupsByIndex[@(groupValue)] = group; + [fDisplayedTorrents addObject:group]; + + [fTableView insertItemsAtIndexes:[NSIndexSet indexSetWithIndex:fDisplayedTorrents.count - 1] inParent:nil + withAnimation:NSTableViewAnimationEffectFade]; + [fTableView isGroupCollapsed:groupValue] ? [fTableView collapseItem:group] : [fTableView expandItem:group]; + } + + [group.torrents addObject:torrent]; + + BOOL const newTorrent = fAddingTransfers && [fAddingTransfers containsObject:torrent]; + [fTableView insertItemsAtIndexes:[NSIndexSet indexSetWithIndex:group.torrents.count - 1] inParent:group + withAnimation:newTorrent ? NSTableViewAnimationSlideLeft : NSTableViewAnimationSlideDown]; + } + + //remove empty groups + NSIndexSet* removeGroupIndexes = [fDisplayedTorrents + indexesOfObjectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, originalGroupCount)] + options:NSEnumerationConcurrent passingTest:^BOOL(id obj, NSUInteger idx, BOOL* stop) { + return ((TorrentGroup*)obj).torrents.count == 0; + }]; + + if (removeGroupIndexes.count > 0) + { + [fDisplayedTorrents removeObjectsAtIndexes:removeGroupIndexes]; + [fTableView removeItemsAtIndexes:removeGroupIndexes inParent:nil withAnimation:NSTableViewAnimationEffectFade]; + } + + //now that all groups are there, sort them - don't insert on the fly in case groups were reordered in prefs + NSSortDescriptor* groupDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"groupOrderValue" ascending:YES]; + [self rearrangeTorrentTableArray:fDisplayedTorrents forParent:nil withSortDescriptors:@[ groupDescriptor ] + beganTableUpdate:&beganUpdates]; + } + else + { + NSAssert(groupRows != wasGroupRows, @"Trying toggling group-torrent reordering when we weren't expecting to."); + + //set all groups as expanded + [fTableView removeAllCollapsedGroups]; + +//since we're not doing this the right way (boo buggy animation), we need to remember selected values +#warning when Lion-only and using views instead of cells, this likely won't be needed + NSArray* selectedValues = fTableView.selectedValues; + + beganUpdates = YES; + [fTableView beginUpdates]; + + [fTableView removeItemsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fDisplayedTorrents.count)] + inParent:nil + withAnimation:NSTableViewAnimationSlideDown]; + + if (groupRows) + { + //a map for quickly finding groups + NSMutableDictionary* groupsByIndex = [NSMutableDictionary dictionaryWithCapacity:GroupsController.groups.numberOfGroups]; + for (Torrent* torrent in allTorrents) + { + NSInteger const groupValue = torrent.groupValue; + TorrentGroup* group = groupsByIndex[@(groupValue)]; + if (!group) + { + group = [[TorrentGroup alloc] initWithGroup:groupValue]; + groupsByIndex[@(groupValue)] = group; + } + + [group.torrents addObject:torrent]; + } + + [fDisplayedTorrents setArray:groupsByIndex.allValues]; + + //we need the groups to be sorted, and we can do it without moving items in the table, too! + NSSortDescriptor* groupDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"groupOrderValue" ascending:YES]; + [fDisplayedTorrents sortUsingDescriptors:@[ groupDescriptor ]]; + } + else + [fDisplayedTorrents setArray:allTorrents]; + + [fTableView insertItemsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fDisplayedTorrents.count)] + inParent:nil + withAnimation:NSTableViewAnimationEffectFade]; + + if (groupRows) + { + //actually expand group rows + for (TorrentGroup* group in fDisplayedTorrents) + [fTableView expandItem:group]; + } + + if (selectedValues) + { + [fTableView selectValues:selectedValues]; + } + } + + //sort the torrents (won't sort the groups, though) + [self sortTorrentsCallUpdates:!beganUpdates includeQueueOrder:YES]; + + if (beganUpdates) + { + [fTableView endUpdates]; + } + fTableView.needsDisplay = YES; + + [NSAnimationContext endGrouping]; + + [self resetInfo]; //if group is already selected, but the torrents in it change + + [self setBottomCountText:groupRows || filterStatus || filterGroup || searchStrings]; + + [self setWindowSizeToFit]; + + if (fAddingTransfers) + { + fAddingTransfers = nil; + } +} + +- (void)switchFilter:(id)sender +{ + [fFilterBar switchFilter:sender == fNextFilterItem]; +} + +- (IBAction)showGlobalPopover:(id)sender +{ + if (fGlobalPopoverShown) + { + return; + } + + NSPopover* popover = [[NSPopover alloc] init]; + popover.behavior = NSPopoverBehaviorTransient; + GlobalOptionsPopoverViewController* viewController = [[GlobalOptionsPopoverViewController alloc] initWithHandle:fLib]; + popover.contentViewController = viewController; + popover.delegate = self; + + NSView* senderView = sender; + [popover showRelativeToRect:senderView.frame ofView:senderView preferredEdge:NSMaxYEdge]; +} + +//don't show multiple popovers when clicking the gear button repeatedly +- (void)popoverWillShow:(NSNotification*)notification +{ + fGlobalPopoverShown = YES; +} + +- (void)popoverWillClose:(NSNotification*)notification +{ + fGlobalPopoverShown = NO; +} + +- (void)menuNeedsUpdate:(NSMenu*)menu +{ + if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu) + { + for (NSInteger i = menu.numberOfItems - 1; i >= 0; i--) + { + [menu removeItemAtIndex:i]; + } + + NSMenu* groupMenu = [GroupsController.groups groupMenuWithTarget:self action:@selector(setGroup:) isSmall:NO]; + + NSInteger const groupMenuCount = groupMenu.numberOfItems; + for (NSInteger i = 0; i < groupMenuCount; i++) + { + NSMenuItem* item = [groupMenu itemAtIndex:0]; + [groupMenu removeItemAtIndex:0]; + [menu addItem:item]; + } + } + else if (menu == fShareMenu || menu == fShareContextMenu) + { + [menu removeAllItems]; + + for (NSMenuItem* item in ShareTorrentFileHelper.sharedHelper.menuItems) + { + [menu addItem:item]; + } + } +} + +- (void)setGroup:(id)sender +{ + for (Torrent* torrent in fTableView.selectedTorrents) + { + [fTableView removeCollapsedGroup:torrent.groupValue]; //remove old collapsed group + + [torrent setGroupValue:((NSMenuItem*)sender).tag determinationType:TorrentDeterminationUserSpecified]; + } + + [self applyFilter]; + [self updateUI]; + [self updateTorrentHistory]; +} + +- (void)toggleSpeedLimit:(id)sender +{ + [fDefaults setBool:![fDefaults boolForKey:@"SpeedLimit"] forKey:@"SpeedLimit"]; + [self speedLimitChanged:sender]; +} + +- (void)speedLimitChanged:(id)sender +{ + tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey:@"SpeedLimit"]); + [fStatusBar updateSpeedFieldsToolTips]; +} + +- (void)altSpeedToggledCallbackIsLimited:(NSDictionary*)dict +{ + BOOL const isLimited = [dict[@"Active"] boolValue]; + + [fDefaults setBool:isLimited forKey:@"SpeedLimit"]; + [fStatusBar updateSpeedFieldsToolTips]; + + if (![dict[@"ByUser"] boolValue]) + { + NSUserNotification* notification = [[NSUserNotification alloc] init]; + notification.title = isLimited ? NSLocalizedString(@"Speed Limit Auto Enabled", "notification title") : + NSLocalizedString(@"Speed Limit Auto Disabled", "notification title"); + notification.informativeText = NSLocalizedString(@"Bandwidth settings changed", "notification description"); + notification.hasActionButton = NO; + + [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification:notification]; + } +} + +- (void)sound:(NSSound*)sound didFinishPlaying:(BOOL)finishedPlaying +{ + fSoundPlaying = NO; +} + +- (void)VDKQueue:(VDKQueue*)queue receivedNotification:(NSString*)notification forPath:(NSString*)fpath +{ + //don't assume that just because we're watching for write notification, we'll only receive write notifications + + if (![fDefaults boolForKey:@"AutoImport"] || ![fDefaults stringForKey:@"AutoImportDirectory"]) + { + return; + } + + if (fAutoImportTimer.valid) + { + [fAutoImportTimer invalidate]; + } + + //check again in 10 seconds in case torrent file wasn't complete + fAutoImportTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(checkAutoImportDirectory) + userInfo:nil + repeats:NO]; + + [self checkAutoImportDirectory]; +} + +- (void)changeAutoImport +{ + if (fAutoImportTimer.valid) + { + [fAutoImportTimer invalidate]; + } + fAutoImportTimer = nil; + + fAutoImportedNames = nil; + + [self checkAutoImportDirectory]; +} + +- (void)checkAutoImportDirectory +{ + NSString* path; + if (![fDefaults boolForKey:@"AutoImport"] || !(path = [fDefaults stringForKey:@"AutoImportDirectory"])) + { + return; + } + + path = path.stringByExpandingTildeInPath; + + NSArray* importedNames; + if (!(importedNames = [NSFileManager.defaultManager contentsOfDirectoryAtPath:path error:NULL])) + { + return; + } + + //only check files that have not been checked yet + NSMutableArray* newNames = [importedNames mutableCopy]; + + if (fAutoImportedNames) + { + [newNames removeObjectsInArray:fAutoImportedNames]; + } + else + { + fAutoImportedNames = [[NSMutableArray alloc] init]; + } + [fAutoImportedNames setArray:importedNames]; + + for (NSString* file in newNames) + { + if ([file hasPrefix:@"."]) + { + continue; + } + + NSString* fullFile = [path stringByAppendingPathComponent:file]; + + if (!([[NSWorkspace.sharedWorkspace typeOfFile:fullFile error:NULL] isEqualToString:@"org.bittorrent.torrent"] || + [fullFile.pathExtension caseInsensitiveCompare:@"torrent"] == NSOrderedSame)) + { + continue; + } + + tr_ctor* ctor = tr_ctorNew(fLib); + tr_ctorSetMetainfoFromFile(ctor, fullFile.UTF8String); + + switch (tr_torrentParse(ctor, NULL)) + { + case TR_PARSE_OK: + { + [self openFiles:@[ fullFile ] addType:ADD_AUTO forcePath:nil]; + + NSString* notificationTitle = NSLocalizedString(@"Torrent File Auto Added", "notification title"); + NSUserNotification* notification = [[NSUserNotification alloc] init]; + notification.title = notificationTitle; + notification.informativeText = file; + + notification.hasActionButton = NO; + + [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification:notification]; + break; + } + case TR_PARSE_ERR: + [fAutoImportedNames removeObject:file]; + break; + + case TR_PARSE_DUPLICATE: //let's ignore this (but silence a warning) + break; + } + + tr_ctorFree(ctor); + } +} + +- (void)beginCreateFile:(NSNotification*)notification +{ + if (![fDefaults boolForKey:@"AutoImport"]) + { + return; + } + + NSString *location = ((NSURL*)notification.object).path, *path = [fDefaults stringForKey:@"AutoImportDirectory"]; + + if (location && path && [location.stringByDeletingLastPathComponent.stringByExpandingTildeInPath isEqualToString:path.stringByExpandingTildeInPath]) + { + [fAutoImportedNames addObject:location.lastPathComponent]; + } +} + +- (NSInteger)outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item +{ + if (item) + { + return ((TorrentGroup*)item).torrents.count; + } + else + { + return fDisplayedTorrents.count; + } +} + +- (id)outlineView:(NSOutlineView*)outlineView child:(NSInteger)index ofItem:(id)item +{ + if (item) + { + return ((TorrentGroup*)item).torrents[index]; + } + else + { + return fDisplayedTorrents[index]; + } +} + +- (BOOL)outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item +{ + return ![item isKindOfClass:[Torrent class]]; +} + +- (id)outlineView:(NSOutlineView*)outlineView objectValueForTableColumn:(NSTableColumn*)tableColumn byItem:(id)item +{ + if ([item isKindOfClass:[Torrent class]]) + { + if (tableColumn) + { + return nil; + } + return ((Torrent*)item).hashString; + } + else + { + NSString* ident = tableColumn.identifier; + TorrentGroup* group = (TorrentGroup*)item; + if ([ident isEqualToString:@"Group"]) + { + NSInteger groupIndex = group.groupIndex; + return groupIndex != -1 ? [GroupsController.groups nameForIndex:groupIndex] : NSLocalizedString(@"No Group", "Group table row"); + } + else if ([ident isEqualToString:@"Color"]) + { + NSInteger groupIndex = group.groupIndex; + return [GroupsController.groups imageForIndex:groupIndex]; + } + else if ([ident isEqualToString:@"DL Image"]) + { + return [NSImage imageNamed:@"DownArrowGroupTemplate"]; + } + else if ([ident isEqualToString:@"UL Image"]) + { + return [NSImage imageNamed:[fDefaults boolForKey:@"DisplayGroupRowRatio"] ? @"YingYangGroupTemplate" : @"UpArrowGroupTemplate"]; + } + else + { + if ([fDefaults boolForKey:@"DisplayGroupRowRatio"]) + { + return [NSString stringForRatio:group.ratio]; + } + else + { + CGFloat rate = [ident isEqualToString:@"UL"] ? group.uploadRate : group.downloadRate; + return [NSString stringForSpeed:rate]; + } + } + } +} + +- (BOOL)outlineView:(NSOutlineView*)outlineView writeItems:(NSArray*)items toPasteboard:(NSPasteboard*)pasteboard +{ + //only allow reordering of rows if sorting by order + if ([fDefaults boolForKey:@"SortByGroup"] || [[fDefaults stringForKey:@"Sort"] isEqualToString:SORT_ORDER]) + { + NSMutableIndexSet* indexSet = [NSMutableIndexSet indexSet]; + for (id torrent in items) + { + if (![torrent isKindOfClass:[Torrent class]]) + { + return NO; + } + + [indexSet addIndex:[fTableView rowForItem:torrent]]; + } + + [pasteboard declareTypes:@[ TORRENT_TABLE_VIEW_DATA_TYPE ] owner:self]; + [pasteboard setData:[NSKeyedArchiver archivedDataWithRootObject:indexSet] forType:TORRENT_TABLE_VIEW_DATA_TYPE]; + return YES; + } + return NO; +} + +- (NSDragOperation)outlineView:(NSOutlineView*)outlineView + validateDrop:(id)info + proposedItem:(id)item + proposedChildIndex:(NSInteger)index +{ + NSPasteboard* pasteboard = info.draggingPasteboard; + if ([pasteboard.types containsObject:TORRENT_TABLE_VIEW_DATA_TYPE]) + { + if ([fDefaults boolForKey:@"SortByGroup"]) + { + if (!item) + { + return NSDragOperationNone; + } + + if ([[fDefaults stringForKey:@"Sort"] isEqualToString:SORT_ORDER]) + { + if ([item isKindOfClass:[Torrent class]]) + { + TorrentGroup* group = [fTableView parentForItem:item]; + index = [group.torrents indexOfObject:item] + 1; + item = group; + } + } + else + { + if ([item isKindOfClass:[Torrent class]]) + { + item = [fTableView parentForItem:item]; + } + index = NSOutlineViewDropOnItemIndex; + } + } + else + { + if (index == NSOutlineViewDropOnItemIndex) + { + return NSDragOperationNone; + } + + if (item) + { + index = [fTableView rowForItem:item] + 1; + item = nil; + } + } + + [fTableView setDropItem:item dropChildIndex:index]; + return NSDragOperationGeneric; + } + + return NSDragOperationNone; +} + +- (BOOL)outlineView:(NSOutlineView*)outlineView acceptDrop:(id)info item:(id)item childIndex:(NSInteger)newRow +{ + NSPasteboard* pasteboard = info.draggingPasteboard; + if ([pasteboard.types containsObject:TORRENT_TABLE_VIEW_DATA_TYPE]) + { + NSIndexSet* indexes = [NSKeyedUnarchiver unarchiveObjectWithData:[pasteboard dataForType:TORRENT_TABLE_VIEW_DATA_TYPE]]; + + //get the torrents to move + NSMutableArray* movingTorrents = [NSMutableArray arrayWithCapacity:indexes.count]; + for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex:i]) + { + Torrent* torrent = [fTableView itemAtRow:i]; + [movingTorrents addObject:torrent]; + } + + //change groups + if (item) + { + TorrentGroup* group = (TorrentGroup*)item; + NSInteger const groupIndex = group.groupIndex; + + for (Torrent* torrent in movingTorrents) + { + [torrent setGroupValue:groupIndex determinationType:TorrentDeterminationUserSpecified]; + } + } + + //reorder queue order + if (newRow != NSOutlineViewDropOnItemIndex) + { + TorrentGroup* group = (TorrentGroup*)item; + //find torrent to place under + NSArray* groupTorrents = group ? group.torrents : fDisplayedTorrents; + Torrent* topTorrent = nil; + for (NSInteger i = newRow - 1; i >= 0; i--) + { + Torrent* tempTorrent = groupTorrents[i]; + if (![movingTorrents containsObject:tempTorrent]) + { + topTorrent = tempTorrent; + break; + } + } + + //remove objects to reinsert + [fTorrents removeObjectsInArray:movingTorrents]; + + //insert objects at new location + NSUInteger const insertIndex = topTorrent ? [fTorrents indexOfObject:topTorrent] + 1 : 0; + NSIndexSet* insertIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(insertIndex, movingTorrents.count)]; + [fTorrents insertObjects:movingTorrents atIndexes:insertIndexes]; + + //we need to make sure the queue order is updated in the Torrent object before we sort - safest to just reset all queue positions + NSUInteger i = 0; + for (Torrent* torrent in fTorrents) + { + torrent.queuePosition = i++; + [torrent update]; + } + + //do the drag animation here so that the dragged torrents are the ones that are animated as moving, and not the torrents around them + [fTableView beginUpdates]; + + NSUInteger insertDisplayIndex = topTorrent ? [groupTorrents indexOfObject:topTorrent] + 1 : 0; + + for (Torrent* torrent in movingTorrents) + { + TorrentGroup* oldParent = item ? [fTableView parentForItem:torrent] : nil; + NSMutableArray* oldTorrents = oldParent ? oldParent.torrents : fDisplayedTorrents; + NSUInteger const oldIndex = [oldTorrents indexOfObject:torrent]; + + if (item == oldParent) + { + if (oldIndex < insertDisplayIndex) + { + --insertDisplayIndex; + } + [oldTorrents moveObjectAtIndex:oldIndex toIndex:insertDisplayIndex]; + } + else + { + NSAssert(item && oldParent, @"Expected to be dragging between group rows"); + + NSMutableArray* newTorrents = ((TorrentGroup*)item).torrents; + [newTorrents insertObject:torrent atIndex:insertDisplayIndex]; + [oldTorrents removeObjectAtIndex:oldIndex]; + } + + [fTableView moveItemAtIndex:oldIndex inParent:oldParent toIndex:insertDisplayIndex inParent:item]; + + ++insertDisplayIndex; + } + + [fTableView endUpdates]; + } + + [self applyFilter]; + } + + return YES; +} + +- (void)torrentTableViewSelectionDidChange:(NSNotification*)notification +{ + [self resetInfo]; + [fWindow.toolbar validateVisibleItems]; +} + +- (NSDragOperation)draggingEntered:(id)info +{ + NSPasteboard* pasteboard = info.draggingPasteboard; + if ([pasteboard.types containsObject:NSFilenamesPboardType]) + { + //check if any torrent files can be added + BOOL torrent = NO; + NSArray* files = [pasteboard propertyListForType:NSFilenamesPboardType]; + for (NSString* file in files) + { + if ([[NSWorkspace.sharedWorkspace typeOfFile:file error:NULL] isEqualToString:@"org.bittorrent.torrent"] || + [file.pathExtension caseInsensitiveCompare:@"torrent"] == NSOrderedSame) + { + torrent = YES; + tr_ctor* ctor = tr_ctorNew(fLib); + tr_ctorSetMetainfoFromFile(ctor, file.UTF8String); + if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK) + { + if (!fOverlayWindow) + { + fOverlayWindow = [[DragOverlayWindow alloc] initWithLib:fLib forWindow:fWindow]; + } + [fOverlayWindow setTorrents:files]; + + return NSDragOperationCopy; + } + tr_ctorFree(ctor); + } + } + + //create a torrent file if a single file + if (!torrent && files.count == 1) + { + if (!fOverlayWindow) + { + fOverlayWindow = [[DragOverlayWindow alloc] initWithLib:fLib forWindow:fWindow]; + } + [fOverlayWindow setFile:[files[0] lastPathComponent]]; + + return NSDragOperationCopy; + } + } + else if ([pasteboard.types containsObject:NSURLPboardType]) + { + if (!fOverlayWindow) + { + fOverlayWindow = [[DragOverlayWindow alloc] initWithLib:fLib forWindow:fWindow]; + } + [fOverlayWindow setURL:[NSURL URLFromPasteboard:pasteboard].relativeString]; + + return NSDragOperationCopy; + } + + return NSDragOperationNone; +} + +- (void)draggingExited:(id)info +{ + if (fOverlayWindow) + { + [fOverlayWindow fadeOut]; + } +} + +- (BOOL)performDragOperation:(id)info +{ + if (fOverlayWindow) + { + [fOverlayWindow fadeOut]; + } + + NSPasteboard* pasteboard = info.draggingPasteboard; + if ([pasteboard.types containsObject:NSFilenamesPboardType]) + { + BOOL torrent = NO, accept = YES; + + //create an array of files that can be opened + NSArray* files = [pasteboard propertyListForType:NSFilenamesPboardType]; + NSMutableArray* filesToOpen = [NSMutableArray arrayWithCapacity:files.count]; + for (NSString* file in files) + { + if ([[NSWorkspace.sharedWorkspace typeOfFile:file error:NULL] isEqualToString:@"org.bittorrent.torrent"] || + [file.pathExtension caseInsensitiveCompare:@"torrent"] == NSOrderedSame) + { + torrent = YES; + tr_ctor* ctor = tr_ctorNew(fLib); + tr_ctorSetMetainfoFromFile(ctor, file.UTF8String); + if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK) + { + [filesToOpen addObject:file]; + } + tr_ctorFree(ctor); + } + } + + if (filesToOpen.count > 0) + { + [self application:NSApp openFiles:filesToOpen]; + } + else + { + if (!torrent && files.count == 1) + { + [CreatorWindowController createTorrentFile:fLib forFile:[NSURL fileURLWithPath:files[0]]]; + } + else + { + accept = NO; + } + } + + return accept; + } + else if ([pasteboard.types containsObject:NSURLPboardType]) + { + NSURL* url; + if ((url = [NSURL URLFromPasteboard:pasteboard])) + { + [self openURL:url.absoluteString]; + return YES; + } + } + + return NO; +} + +- (void)toggleSmallView:(id)sender +{ + BOOL makeSmall = ![fDefaults boolForKey:@"SmallView"]; + [fDefaults setBool:makeSmall forKey:@"SmallView"]; + + fTableView.usesAlternatingRowBackgroundColors = !makeSmall; + + fTableView.rowHeight = makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR; + + [fTableView beginUpdates]; + [fTableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fTableView.numberOfRows)]]; + [fTableView endUpdates]; + + //resize for larger min height if not set to auto size + if (![fDefaults boolForKey:@"AutoSize"]) + { + NSSize const contentSize = fWindow.contentView.frame.size; + + NSSize contentMinSize = fWindow.contentMinSize; + contentMinSize.height = self.minWindowContentSizeAllowed; + fWindow.contentMinSize = contentMinSize; + + //make sure the window already isn't too small + if (!makeSmall && contentSize.height < contentMinSize.height) + { + NSRect frame = fWindow.frame; + CGFloat heightChange = contentMinSize.height - contentSize.height; + frame.size.height += heightChange; + frame.origin.y -= heightChange; + + [fWindow setFrame:frame display:YES]; + } + } + else + { + [self setWindowSizeToFit]; + } +} + +- (void)togglePiecesBar:(id)sender +{ + [fDefaults setBool:![fDefaults boolForKey:@"PiecesBar"] forKey:@"PiecesBar"]; + [fTableView togglePiecesBar]; +} + +- (void)toggleAvailabilityBar:(id)sender +{ + [fDefaults setBool:![fDefaults boolForKey:@"DisplayProgressBarAvailable"] forKey:@"DisplayProgressBarAvailable"]; + [fTableView display]; +} + +- (NSRect)windowFrameByAddingHeight:(CGFloat)height checkLimits:(BOOL)check +{ + NSScrollView* scrollView = fTableView.enclosingScrollView; + + //convert pixels to points + NSRect windowFrame = fWindow.frame; + NSSize windowSize = [scrollView convertSize:windowFrame.size fromView:nil]; + windowSize.height += height; + + if (check) + { + //we can't call minSize, since it might be set to the current size (auto size) + CGFloat const minHeight = self.minWindowContentSizeAllowed + (NSHeight(fWindow.frame) - NSHeight(fWindow.contentView.frame)); //contentView to window + + if (windowSize.height <= minHeight) + { + windowSize.height = minHeight; + } + else + { + NSScreen* screen = fWindow.screen; + if (screen) + { + NSSize maxSize = [scrollView convertSize:screen.visibleFrame.size fromView:nil]; + if (!fStatusBar) + { + maxSize.height -= STATUS_BAR_HEIGHT; + } + if (!fFilterBar) + { + maxSize.height -= FILTER_BAR_HEIGHT; + } + if (windowSize.height > maxSize.height) + { + windowSize.height = maxSize.height; + } + } + } + } + + //convert points to pixels + windowSize = [scrollView convertSize:windowSize toView:nil]; + + windowFrame.origin.y -= (windowSize.height - windowFrame.size.height); + windowFrame.size.height = windowSize.height; + return windowFrame; +} + +- (void)toggleStatusBar:(id)sender +{ + BOOL const show = fStatusBar == nil; + [self showStatusBar:show animate:YES]; + [fDefaults setBool:show forKey:@"StatusBar"]; +} + +//doesn't save shown state +- (void)showStatusBar:(BOOL)show animate:(BOOL)animate +{ + BOOL const prevShown = fStatusBar != nil; + if (show == prevShown) + { + return; + } + + if (show) + { + fStatusBar = [[StatusBarController alloc] initWithLib:fLib]; + + NSView* contentView = fWindow.contentView; + NSSize const windowSize = [contentView convertSize:fWindow.frame.size fromView:nil]; + + NSRect statusBarFrame = fStatusBar.view.frame; + statusBarFrame.size.width = windowSize.width; + fStatusBar.view.frame = statusBarFrame; + + [contentView addSubview:fStatusBar.view]; + [fStatusBar.view setFrameOrigin:NSMakePoint(0.0, NSMaxY(contentView.frame))]; + } + + CGFloat heightChange = fStatusBar.view.frame.size.height; + if (!show) + { + heightChange *= -1; + } + + //allow bar to show even if not enough room + if (show && ![fDefaults boolForKey:@"AutoSize"]) + { + NSRect frame = [self windowFrameByAddingHeight:heightChange checkLimits:NO]; + + NSScreen* screen = fWindow.screen; + if (screen) + { + CGFloat change = screen.visibleFrame.size.height - frame.size.height; + if (change < 0.0) + { + frame = fWindow.frame; + frame.size.height += change; + frame.origin.y -= change; + [fWindow setFrame:frame display:NO animate:NO]; + } + } + } + + [self updateUI]; + + NSScrollView* scrollView = fTableView.enclosingScrollView; + + //set views to not autoresize + NSUInteger const statsMask = fStatusBar.view.autoresizingMask; + fStatusBar.view.autoresizingMask = NSViewNotSizable; + NSUInteger filterMask; + if (fFilterBar) + { + filterMask = fFilterBar.view.autoresizingMask; + fFilterBar.view.autoresizingMask = NSViewNotSizable; + } + NSUInteger const scrollMask = scrollView.autoresizingMask; + scrollView.autoresizingMask = NSViewNotSizable; + + NSRect frame = [self windowFrameByAddingHeight:heightChange checkLimits:NO]; + [fWindow setFrame:frame display:YES animate:animate]; + + //re-enable autoresize + fStatusBar.view.autoresizingMask = statsMask; + if (fFilterBar) + { + fFilterBar.view.autoresizingMask = filterMask; + } + scrollView.autoresizingMask = scrollMask; + + if (!show) + { + [fStatusBar.view removeFromSuperviewWithoutNeedingDisplay]; + fStatusBar = nil; + } + + if ([fDefaults boolForKey:@"AutoSize"]) + { + [self setWindowMinMaxToCurrent]; + } + else + { + //change min size + NSSize minSize = fWindow.contentMinSize; + minSize.height += heightChange; + fWindow.contentMinSize = minSize; + } +} + +- (void)toggleFilterBar:(id)sender +{ + BOOL const show = fFilterBar == nil; + + //disable filtering when hiding (have to do before showFilterBar:animate:) + if (!show) + { + [fFilterBar reset:NO]; + } + + [self showFilterBar:show animate:YES]; + [fDefaults setBool:show forKey:@"FilterBar"]; + [fWindow.toolbar validateVisibleItems]; + + [self applyFilter]; //do even if showing to ensure tooltips are updated +} + +//doesn't save shown state +- (void)showFilterBar:(BOOL)show animate:(BOOL)animate +{ + BOOL const prevShown = fFilterBar != nil; + if (show == prevShown) + { + return; + } + + if (show) + { + fFilterBar = [[FilterBarController alloc] init]; + + NSView* contentView = fWindow.contentView; + NSSize const windowSize = [contentView convertSize:fWindow.frame.size fromView:nil]; + + NSRect filterBarFrame = fFilterBar.view.frame; + filterBarFrame.size.width = windowSize.width; + fFilterBar.view.frame = filterBarFrame; + + if (fStatusBar) + { + [contentView addSubview:fFilterBar.view positioned:NSWindowBelow relativeTo:fStatusBar.view]; + } + else + { + [contentView addSubview:fFilterBar.view]; + } + CGFloat const originY = fStatusBar ? NSMinY(fStatusBar.view.frame) : NSMaxY(contentView.frame); + [fFilterBar.view setFrameOrigin:NSMakePoint(0.0, originY)]; + } + else + { + [fWindow makeFirstResponder:fTableView]; + } + + CGFloat heightChange = NSHeight(fFilterBar.view.frame); + if (!show) + { + heightChange *= -1; + } + + //allow bar to show even if not enough room + if (show && ![fDefaults boolForKey:@"AutoSize"]) + { + NSRect frame = [self windowFrameByAddingHeight:heightChange checkLimits:NO]; + + NSScreen* screen = fWindow.screen; + if (screen) + { + CGFloat change = screen.visibleFrame.size.height - frame.size.height; + if (change < 0.0) + { + frame = fWindow.frame; + frame.size.height += change; + frame.origin.y -= change; + [fWindow setFrame:frame display:NO animate:NO]; + } + } + } + + NSScrollView* scrollView = fTableView.enclosingScrollView; + + //set views to not autoresize + NSUInteger const filterMask = fFilterBar.view.autoresizingMask; + NSUInteger const scrollMask = scrollView.autoresizingMask; + fFilterBar.view.autoresizingMask = NSViewNotSizable; + scrollView.autoresizingMask = NSViewNotSizable; + + NSRect const frame = [self windowFrameByAddingHeight:heightChange checkLimits:NO]; + [fWindow setFrame:frame display:YES animate:animate]; + + //re-enable autoresize + fFilterBar.view.autoresizingMask = filterMask; + scrollView.autoresizingMask = scrollMask; + + if (!show) + { + [fFilterBar.view removeFromSuperviewWithoutNeedingDisplay]; + fFilterBar = nil; + } + + if ([fDefaults boolForKey:@"AutoSize"]) + { + [self setWindowMinMaxToCurrent]; + } + else + { + //change min size + NSSize minSize = fWindow.contentMinSize; + minSize.height += heightChange; + fWindow.contentMinSize = minSize; + } +} + +- (void)focusFilterField +{ + if (!fFilterBar) + { + [self toggleFilterBar:self]; + } + [fFilterBar focusSearchField]; +} + +- (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel +{ + return !fQuitting; +} + +- (void)beginPreviewPanelControl:(QLPreviewPanel*)panel +{ + fPreviewPanel = panel; + fPreviewPanel.delegate = self; + fPreviewPanel.dataSource = self; +} + +- (void)endPreviewPanelControl:(QLPreviewPanel*)panel +{ + fPreviewPanel = nil; +} + +- (NSArray*)quickLookableTorrents +{ + NSArray* selectedTorrents = fTableView.selectedTorrents; + NSMutableArray* qlArray = [NSMutableArray arrayWithCapacity:selectedTorrents.count]; + + for (Torrent* torrent in selectedTorrents) + { + if ((torrent.folder || torrent.complete) && torrent.dataLocation) + { + [qlArray addObject:torrent]; + } + } + + return qlArray; +} + +- (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel*)panel +{ + if (fInfoController.canQuickLook) + { + return fInfoController.quickLookURLs.count; + } + else + { + return [self quickLookableTorrents].count; + } +} + +- (id)previewPanel:(QLPreviewPanel*)panel previewItemAtIndex:(NSInteger)index +{ + if (fInfoController.canQuickLook) + { + return fInfoController.quickLookURLs[index]; + } + else + { + return [self quickLookableTorrents][index]; + } +} + +- (BOOL)previewPanel:(QLPreviewPanel*)panel handleEvent:(NSEvent*)event +{ + /*if ([event type] == NSKeyDown) + { + [super keyDown: event]; + return YES; + }*/ + + return NO; +} + +- (NSRect)previewPanel:(QLPreviewPanel*)panel sourceFrameOnScreenForPreviewItem:(id)item +{ + if (fInfoController.canQuickLook) + { + return [fInfoController quickLookSourceFrameForPreviewItem:item]; + } + else + { + if (!fWindow.visible) + { + return NSZeroRect; + } + + NSInteger const row = [fTableView rowForItem:item]; + if (row == -1) + { + return NSZeroRect; + } + + NSRect frame = [fTableView iconRectForRow:row]; + + if (!NSIntersectsRect(fTableView.visibleRect, frame)) + { + return NSZeroRect; + } + + frame.origin = [fTableView convertPoint:frame.origin toView:nil]; + frame = [fWindow convertRectToScreen:frame]; + frame.origin.y -= frame.size.height; + return frame; + } +} + +- (void)showToolbarShare:(id)sender +{ + NSParameterAssert([sender isKindOfClass:[NSButton class]]); + NSButton* senderButton = sender; + + NSSharingServicePicker* picker = [[NSSharingServicePicker alloc] initWithItems:ShareTorrentFileHelper.sharedHelper.shareTorrentURLs]; + picker.delegate = self; + + [picker showRelativeToRect:senderButton.bounds ofView:senderButton preferredEdge:NSMinYEdge]; +} + +- (id)sharingServicePicker:(NSSharingServicePicker*)sharingServicePicker + delegateForSharingService:(NSSharingService*)sharingService +{ + return self; +} + +- (NSWindow*)sharingService:(NSSharingService*)sharingService + sourceWindowForShareItems:(NSArray*)items + sharingContentScope:(NSSharingContentScope*)sharingContentScope +{ + return fWindow; +} + +- (ButtonToolbarItem*)standardToolbarButtonWithIdentifier:(NSString*)ident +{ + return [self toolbarButtonWithIdentifier:ident forToolbarButtonClass:[ButtonToolbarItem class]]; +} + +- (id)toolbarButtonWithIdentifier:(NSString*)ident forToolbarButtonClass:(Class)class +{ + ButtonToolbarItem* item = [[class alloc] initWithItemIdentifier:ident]; + + NSButton* button = [[NSButton alloc] init]; + button.bezelStyle = NSTexturedRoundedBezelStyle; + button.stringValue = @""; + + item.view = button; + + if (@available(macOS 11.0, *)) + { + // not needed + } + else + { + NSSize const buttonSize = NSMakeSize(36.0, 25.0); + item.minSize = buttonSize; + item.maxSize = buttonSize; + } + + return item; +} + +- (NSToolbarItem*)toolbar:(NSToolbar*)toolbar itemForItemIdentifier:(NSString*)ident willBeInsertedIntoToolbar:(BOOL)flag +{ + if ([ident isEqualToString:TOOLBAR_CREATE]) + { + ButtonToolbarItem* item = [self standardToolbarButtonWithIdentifier:ident]; + + item.label = NSLocalizedString(@"Create", "Create toolbar item -> label"); + item.paletteLabel = NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label"); + item.toolTip = NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip"); + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"doc.badge.plus" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:@"ToolbarCreateTemplate"]; + } + item.target = self; + item.action = @selector(createFile:); + item.autovalidates = NO; + + return item; + } + else if ([ident isEqualToString:TOOLBAR_OPEN_FILE]) + { + ButtonToolbarItem* item = [self standardToolbarButtonWithIdentifier:ident]; + + item.label = NSLocalizedString(@"Open", "Open toolbar item -> label"); + item.paletteLabel = NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label"); + item.toolTip = NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip"); + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"folder" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:@"ToolbarOpenTemplate"]; + } + item.target = self; + item.action = @selector(openShowSheet:); + item.autovalidates = NO; + + return item; + } + else if ([ident isEqualToString:TOOLBAR_OPEN_WEB]) + { + ButtonToolbarItem* item = [self standardToolbarButtonWithIdentifier:ident]; + + item.label = NSLocalizedString(@"Open Address", "Open address toolbar item -> label"); + item.paletteLabel = NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label"); + item.toolTip = NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip"); + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"globe" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:@"ToolbarOpenWebTemplate"]; + } + item.target = self; + item.action = @selector(openURLShowSheet:); + item.autovalidates = NO; + + return item; + } + else if ([ident isEqualToString:TOOLBAR_REMOVE]) + { + ButtonToolbarItem* item = [self standardToolbarButtonWithIdentifier:ident]; + + item.label = NSLocalizedString(@"Remove", "Remove toolbar item -> label"); + item.paletteLabel = NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label"); + item.toolTip = NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip"); + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"nosign" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:@"ToolbarRemoveTemplate"]; + } + item.target = self; + item.action = @selector(removeNoDelete:); + item.visibilityPriority = NSToolbarItemVisibilityPriorityHigh; + + return item; + } + else if ([ident isEqualToString:TOOLBAR_INFO]) + { + ButtonToolbarItem* item = [self standardToolbarButtonWithIdentifier:ident]; + ((NSButtonCell*)((NSButton*)item.view).cell).showsStateBy = NSContentsCellMask; //blue when enabled + + item.label = NSLocalizedString(@"Inspector", "Inspector toolbar item -> label"); + item.paletteLabel = NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label"); + item.toolTip = NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip"); + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"info.circle" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:@"ToolbarInfoTemplate"]; + } + item.target = self; + item.action = @selector(showInfo:); + + return item; + } + else if ([ident isEqualToString:TOOLBAR_PAUSE_RESUME_ALL]) + { + GroupToolbarItem* groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier:ident]; + + NSSegmentedControl* segmentedControl = [[NSSegmentedControl alloc] initWithFrame:NSZeroRect]; + segmentedControl.cell = [[ToolbarSegmentedCell alloc] init]; + groupItem.view = segmentedControl; + NSSegmentedCell* segmentedCell = (NSSegmentedCell*)segmentedControl.cell; + segmentedControl.segmentStyle = NSSegmentStyleSeparated; + + segmentedControl.segmentCount = 2; + segmentedCell.trackingMode = NSSegmentSwitchTrackingMomentary; + + if (@available(macOS 11.0, *)) + { + // not needed + } + else + { + NSSize const groupSize = NSMakeSize(72.0, 25.0); + groupItem.minSize = groupSize; + groupItem.maxSize = groupSize; + } + + groupItem.label = NSLocalizedString(@"Apply All", "All toolbar item -> label"); + groupItem.paletteLabel = NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label"); + groupItem.target = self; + groupItem.action = @selector(allToolbarClicked:); + + [groupItem setIdentifiers:@[ TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL ]]; + + [segmentedCell setTag:TOOLBAR_PAUSE_TAG forSegment:TOOLBAR_PAUSE_TAG]; + if (@available(macOS 11.0, *)) + { + [segmentedControl setImage:[[NSImage imageWithSystemSymbolName:@"pause.circle.fill" accessibilityDescription:nil] + imageWithSymbolConfiguration:[NSImageSymbolConfiguration configurationWithScale:NSImageSymbolScaleLarge]] + forSegment:TOOLBAR_PAUSE_TAG]; + } + else + { + [segmentedControl setImage:[NSImage imageNamed:@"ToolbarPauseAllTemplate"] forSegment:TOOLBAR_PAUSE_TAG]; + } + [segmentedCell setToolTip:NSLocalizedString(@"Pause all transfers", "All toolbar item -> tooltip") + forSegment:TOOLBAR_PAUSE_TAG]; + + [segmentedCell setTag:TOOLBAR_RESUME_TAG forSegment:TOOLBAR_RESUME_TAG]; + [segmentedControl setImage:[NSImage imageNamed:@"ToolbarResumeAllTemplate"] forSegment:TOOLBAR_RESUME_TAG]; + if (@available(macOS 11.0, *)) + { + [segmentedControl + setImage:[[NSImage imageWithSystemSymbolName:@"arrow.clockwise.circle.fill" accessibilityDescription:nil] + imageWithSymbolConfiguration:[NSImageSymbolConfiguration configurationWithScale:NSImageSymbolScaleLarge]] + forSegment:TOOLBAR_RESUME_TAG]; + } + else + { + [segmentedControl setImage:[NSImage imageNamed:@"ToolbarResumeAllTemplate"] forSegment:TOOLBAR_RESUME_TAG]; + } + [segmentedCell setToolTip:NSLocalizedString(@"Resume all transfers", "All toolbar item -> tooltip") + forSegment:TOOLBAR_RESUME_TAG]; + + [groupItem createMenu:@[ + NSLocalizedString(@"Pause All", "All toolbar item -> label"), + NSLocalizedString(@"Resume All", "All toolbar item -> label") + ]]; + + groupItem.visibilityPriority = NSToolbarItemVisibilityPriorityHigh; + + return groupItem; + } + else if ([ident isEqualToString:TOOLBAR_PAUSE_RESUME_SELECTED]) + { + GroupToolbarItem* groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier:ident]; + + NSSegmentedControl* segmentedControl = [[NSSegmentedControl alloc] initWithFrame:NSZeroRect]; + segmentedControl.cell = [[ToolbarSegmentedCell alloc] init]; + groupItem.view = segmentedControl; + NSSegmentedCell* segmentedCell = (NSSegmentedCell*)segmentedControl.cell; + + segmentedControl.segmentCount = 2; + segmentedCell.trackingMode = NSSegmentSwitchTrackingMomentary; + + if (@available(macOS 11.0, *)) + { + // not needed + } + else + { + NSSize const groupSize = NSMakeSize(72.0, 25.0); + groupItem.minSize = groupSize; + groupItem.maxSize = groupSize; + } + + groupItem.label = NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label"); + groupItem.paletteLabel = NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label"); + groupItem.target = self; + groupItem.action = @selector(selectedToolbarClicked:); + + [groupItem setIdentifiers:@[ TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED ]]; + + [segmentedCell setTag:TOOLBAR_PAUSE_TAG forSegment:TOOLBAR_PAUSE_TAG]; + if (@available(macOS 11.0, *)) + { + [segmentedControl setImage:[[NSImage imageWithSystemSymbolName:@"pause" accessibilityDescription:nil] + imageWithSymbolConfiguration:[NSImageSymbolConfiguration configurationWithScale:NSImageSymbolScaleLarge]] + forSegment:TOOLBAR_PAUSE_TAG]; + } + else + { + [segmentedControl setImage:[NSImage imageNamed:@"ToolbarPauseSelectedTemplate"] forSegment:TOOLBAR_PAUSE_TAG]; + } + [segmentedCell setToolTip:NSLocalizedString(@"Pause selected transfers", "Selected toolbar item -> tooltip") + forSegment:TOOLBAR_PAUSE_TAG]; + + [segmentedCell setTag:TOOLBAR_RESUME_TAG forSegment:TOOLBAR_RESUME_TAG]; + if (@available(macOS 11.0, *)) + { + [segmentedControl setImage:[NSImage imageWithSystemSymbolName:@"arrow.clockwise" accessibilityDescription:nil] + forSegment:TOOLBAR_RESUME_TAG]; + } + else + { + [segmentedControl setImage:[NSImage imageNamed:@"ToolbarResumeSelectedTemplate"] forSegment:TOOLBAR_RESUME_TAG]; + } + [segmentedCell setToolTip:NSLocalizedString(@"Resume selected transfers", "Selected toolbar item -> tooltip") + forSegment:TOOLBAR_RESUME_TAG]; + + [groupItem createMenu:@[ + NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"), + NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label") + ]]; + + groupItem.visibilityPriority = NSToolbarItemVisibilityPriorityHigh; + + return groupItem; + } + else if ([ident isEqualToString:TOOLBAR_FILTER]) + { + ButtonToolbarItem* item = [self standardToolbarButtonWithIdentifier:ident]; + ((NSButtonCell*)((NSButton*)item.view).cell).showsStateBy = NSContentsCellMask; //blue when enabled + + item.label = NSLocalizedString(@"Filter", "Filter toolbar item -> label"); + item.paletteLabel = NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label"); + item.toolTip = NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip"); + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"magnifyingglass" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:@"ToolbarFilterTemplate"]; + } + item.target = self; + item.action = @selector(toggleFilterBar:); + + return item; + } + else if ([ident isEqualToString:TOOLBAR_QUICKLOOK]) + { + ButtonToolbarItem* item = [self standardToolbarButtonWithIdentifier:ident]; + ((NSButtonCell*)((NSButton*)item.view).cell).showsStateBy = NSContentsCellMask; //blue when enabled + + item.label = NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label"); + item.paletteLabel = NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label"); + item.toolTip = NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip"); + item.image = [NSImage imageNamed:NSImageNameQuickLookTemplate]; + item.target = self; + item.action = @selector(toggleQuickLook:); + item.visibilityPriority = NSToolbarItemVisibilityPriorityLow; + + return item; + } + else if ([ident isEqualToString:TOOLBAR_SHARE]) + { + ShareToolbarItem* item = [self toolbarButtonWithIdentifier:ident forToolbarButtonClass:[ShareToolbarItem class]]; + + item.label = NSLocalizedString(@"Share", "Share toolbar item -> label"); + item.paletteLabel = NSLocalizedString(@"Share", "Share toolbar item -> palette label"); + item.toolTip = NSLocalizedString(@"Share torrent file", "Share toolbar item -> tooltip"); + item.image = [NSImage imageNamed:NSImageNameShareTemplate]; + item.visibilityPriority = NSToolbarItemVisibilityPriorityLow; + + NSButton* itemButton = (NSButton*)item.view; + itemButton.target = self; + itemButton.action = @selector(showToolbarShare:); + [itemButton sendActionOn:NSLeftMouseDownMask]; + + return item; + } + else + { + return nil; + } +} + +- (void)allToolbarClicked:(id)sender +{ + NSInteger tagValue = [sender isKindOfClass:[NSSegmentedControl class]] ? + [(NSSegmentedCell*)[sender cell] tagForSegment:[sender selectedSegment]] : + ((NSControl*)sender).tag; + switch (tagValue) + { + case TOOLBAR_PAUSE_TAG: + [self stopAllTorrents:sender]; + break; + case TOOLBAR_RESUME_TAG: + [self resumeAllTorrents:sender]; + break; + } +} + +- (void)selectedToolbarClicked:(id)sender +{ + NSInteger tagValue = [sender isKindOfClass:[NSSegmentedControl class]] ? + [(NSSegmentedCell*)[sender cell] tagForSegment:[sender selectedSegment]] : + ((NSControl*)sender).tag; + switch (tagValue) + { + case TOOLBAR_PAUSE_TAG: + [self stopSelectedTorrents:sender]; + break; + case TOOLBAR_RESUME_TAG: + [self resumeSelectedTorrents:sender]; + break; + } +} + +- (NSArray*)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar +{ + return @[ + TOOLBAR_CREATE, + TOOLBAR_OPEN_FILE, + TOOLBAR_OPEN_WEB, + TOOLBAR_REMOVE, + TOOLBAR_PAUSE_RESUME_SELECTED, + TOOLBAR_PAUSE_RESUME_ALL, + TOOLBAR_SHARE, + TOOLBAR_QUICKLOOK, + TOOLBAR_FILTER, + TOOLBAR_INFO, + NSToolbarSpaceItemIdentifier, + NSToolbarFlexibleSpaceItemIdentifier + ]; +} + +- (NSArray*)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar +{ + return @[ + TOOLBAR_CREATE, + TOOLBAR_OPEN_FILE, + TOOLBAR_REMOVE, + NSToolbarSpaceItemIdentifier, + TOOLBAR_PAUSE_RESUME_ALL, + NSToolbarFlexibleSpaceItemIdentifier, + TOOLBAR_SHARE, + TOOLBAR_QUICKLOOK, + TOOLBAR_FILTER, + TOOLBAR_INFO + ]; +} + +- (BOOL)validateToolbarItem:(NSToolbarItem*)toolbarItem +{ + NSString* ident = toolbarItem.itemIdentifier; + + //enable remove item + if ([ident isEqualToString:TOOLBAR_REMOVE]) + { + return fTableView.numberOfSelectedRows > 0; + } + + //enable pause all item + if ([ident isEqualToString:TOOLBAR_PAUSE_ALL]) + { + for (Torrent* torrent in fTorrents) + { + if (torrent.active || torrent.waitingToStart) + { + return YES; + } + } + return NO; + } + + //enable resume all item + if ([ident isEqualToString:TOOLBAR_RESUME_ALL]) + { + for (Torrent* torrent in fTorrents) + { + if (!torrent.active && !torrent.waitingToStart && !torrent.finishedSeeding) + { + return YES; + } + } + return NO; + } + + //enable pause item + if ([ident isEqualToString:TOOLBAR_PAUSE_SELECTED]) + { + for (Torrent* torrent in fTableView.selectedTorrents) + { + if (torrent.active || torrent.waitingToStart) + { + return YES; + } + } + return NO; + } + + //enable resume item + if ([ident isEqualToString:TOOLBAR_RESUME_SELECTED]) + { + for (Torrent* torrent in fTableView.selectedTorrents) + { + if (!torrent.active && !torrent.waitingToStart) + { + return YES; + } + } + return NO; + } + + //set info item + if ([ident isEqualToString:TOOLBAR_INFO]) + { + ((NSButton*)toolbarItem.view).state = fInfoController.window.visible; + return YES; + } + + //set filter item + if ([ident isEqualToString:TOOLBAR_FILTER]) + { + ((NSButton*)toolbarItem.view).state = fFilterBar != nil; + return YES; + } + + //set quick look item + if ([ident isEqualToString:TOOLBAR_QUICKLOOK]) + { + ((NSButton*)toolbarItem.view).state = [QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible; + return YES; + } + + //enable share item + if ([ident isEqualToString:TOOLBAR_SHARE]) + { + return fTableView.numberOfSelectedRows > 0; + } + + return YES; +} + +- (BOOL)validateMenuItem:(NSMenuItem*)menuItem +{ + SEL action = menuItem.action; + + if (action == @selector(toggleSpeedLimit:)) + { + menuItem.state = [fDefaults boolForKey:@"SpeedLimit"] ? NSOnState : NSOffState; + return YES; + } + + //only enable some items if it is in a context menu or the window is useable + BOOL canUseTable = fWindow.keyWindow || menuItem.menu.supermenu != NSApp.mainMenu; + + //enable open items + if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:)) + { + return fWindow.attachedSheet == nil; + } + + //enable sort options + if (action == @selector(setSort:)) + { + NSString* sortType; + switch (menuItem.tag) + { case SORT_ORDER_TAG: sortType = SORT_ORDER; - [fDefaults setBool: NO forKey: @"SortReverse"]; break; case SORT_DATE_TAG: sortType = SORT_DATE; @@ -2197,1924 +4738,11 @@ static void removeKeRangerRansomware() sortType = SORT_SIZE; break; default: - NSAssert1(NO, @"Unknown sort tag received: %ld", senderMenuItem.tag); - return; - } - - [fDefaults setObject: sortType forKey: @"Sort"]; - - [self sortTorrents: YES]; -} - -- (void) setSortByGroup: (id) sender -{ - BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"]; - [fDefaults setBool: sortByGroup forKey: @"SortByGroup"]; - - [self applyFilter]; -} - -- (void) setSortReverse: (id) sender -{ - const BOOL setReverse = ((NSMenuItem *)sender).tag == SORT_DESC_TAG; - if (setReverse != [fDefaults boolForKey: @"SortReverse"]) - { - [fDefaults setBool: setReverse forKey: @"SortReverse"]; - [self sortTorrents: NO]; - } -} - -- (void) sortTorrents: (BOOL) includeQueueOrder -{ - //actually sort - [self sortTorrentsCallUpdates: YES includeQueueOrder: includeQueueOrder]; - fTableView.needsDisplay = YES; -} - -- (void) sortTorrentsCallUpdates: (BOOL) callUpdates includeQueueOrder: (BOOL) includeQueueOrder -{ - const BOOL asc = ![fDefaults boolForKey: @"SortReverse"]; - - NSArray * descriptors; - NSSortDescriptor * nameDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"name" ascending: asc selector: @selector(localizedStandardCompare:)]; - - NSString * sortType = [fDefaults stringForKey: @"Sort"]; - if ([sortType isEqualToString: SORT_STATE]) - { - NSSortDescriptor * stateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"stateSortKey" ascending: !asc], - * progressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progress" ascending: !asc], - * ratioDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"ratio" ascending: !asc]; - - descriptors = @[stateDescriptor, progressDescriptor, ratioDescriptor, nameDescriptor]; - } - else if ([sortType isEqualToString: SORT_PROGRESS]) - { - NSSortDescriptor * progressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progress" ascending: asc], - * ratioProgressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progressStopRatio" ascending: asc], - * ratioDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"ratio" ascending: asc]; - - descriptors = @[progressDescriptor, ratioProgressDescriptor, ratioDescriptor, nameDescriptor]; - } - else if ([sortType isEqualToString: SORT_TRACKER]) - { - NSSortDescriptor * trackerDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"trackerSortKey" ascending: asc selector: @selector(localizedCaseInsensitiveCompare:)]; - - descriptors = @[trackerDescriptor, nameDescriptor]; - } - else if ([sortType isEqualToString: SORT_ACTIVITY]) - { - NSSortDescriptor * rateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"totalRate" ascending: !asc]; - NSSortDescriptor * activityDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"dateActivityOrAdd" ascending: !asc]; - - descriptors = @[rateDescriptor, activityDescriptor, nameDescriptor]; - } - else if ([sortType isEqualToString: SORT_DATE]) - { - NSSortDescriptor * dateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"dateAdded" ascending: asc]; - - descriptors = @[dateDescriptor, nameDescriptor]; - } - else if ([sortType isEqualToString: SORT_SIZE]) - { - NSSortDescriptor * sizeDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"size" ascending: asc]; - - descriptors = @[sizeDescriptor, nameDescriptor]; - } - else if ([sortType isEqualToString: SORT_NAME]) - { - descriptors = @[nameDescriptor]; - } - else - { - NSAssert1([sortType isEqualToString: SORT_ORDER], @"Unknown sort type received: %@", sortType); - - if (!includeQueueOrder) - return; - - NSSortDescriptor * orderDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"queuePosition" ascending: asc]; - - descriptors = @[orderDescriptor]; - } - - BOOL beganTableUpdate = !callUpdates; - - //actually sort - if ([fDefaults boolForKey: @"SortByGroup"]) - { - for (TorrentGroup * group in fDisplayedTorrents) - [self rearrangeTorrentTableArray: group.torrents forParent: group withSortDescriptors: descriptors beganTableUpdate: &beganTableUpdate]; - } - else - [self rearrangeTorrentTableArray: fDisplayedTorrents forParent: nil withSortDescriptors: descriptors beganTableUpdate: &beganTableUpdate]; - - if (beganTableUpdate && callUpdates) - { - [fTableView endUpdates]; - } -} - -#warning redo so that we search a copy once again (best explained by changing sorting from ascending to descending) -- (void) rearrangeTorrentTableArray: (NSMutableArray *) rearrangeArray forParent: parent withSortDescriptors: (NSArray *) descriptors beganTableUpdate: (BOOL *) beganTableUpdate -{ - for (NSUInteger currentIndex = 1; currentIndex < rearrangeArray.count; ++currentIndex) - { - //manually do the sorting in-place - const NSUInteger insertIndex = [rearrangeArray indexOfObject: rearrangeArray[currentIndex] inSortedRange: NSMakeRange(0, currentIndex) options: (NSBinarySearchingInsertionIndex | NSBinarySearchingLastEqual) usingComparator: ^NSComparisonResult(id obj1, id obj2) { - for (NSSortDescriptor * descriptor in descriptors) - { - const NSComparisonResult result = [descriptor compareObject: obj1 toObject: obj2]; - if (result != NSOrderedSame) - return result; - } - - return NSOrderedSame; - }]; - - if (insertIndex != currentIndex) - { - if (!*beganTableUpdate) - { - *beganTableUpdate = YES; - [fTableView beginUpdates]; - } - - [rearrangeArray moveObjectAtIndex: currentIndex toIndex: insertIndex]; - [fTableView moveItemAtIndex: currentIndex inParent: parent toIndex: insertIndex inParent: parent]; - } - } - - NSAssert2([rearrangeArray isEqualToArray: [rearrangeArray sortedArrayUsingDescriptors: descriptors]], @"Torrent rearranging didn't work! %@ %@", rearrangeArray, [rearrangeArray sortedArrayUsingDescriptors: descriptors]); -} - -- (void) applyFilter -{ - __block int32_t active = 0, downloading = 0, seeding = 0, paused = 0; - NSString * filterType = [fDefaults stringForKey: @"Filter"]; - BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES; - if ([filterType isEqualToString: FILTER_ACTIVE]) - filterActive = YES; - else if ([filterType isEqualToString: FILTER_DOWNLOAD]) - filterDownload = YES; - else if ([filterType isEqualToString: FILTER_SEED]) - filterSeed = YES; - else if ([filterType isEqualToString: FILTER_PAUSE]) - filterPause = YES; - else - filterStatus = NO; - - const NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"]; - const BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG; - - NSArray * searchStrings = fFilterBar.searchStrings; - if (searchStrings && searchStrings.count == 0) - searchStrings = nil; - const BOOL filterTracker = searchStrings && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER]; - - //filter & get counts of each type - NSIndexSet * indexesOfNonFilteredTorrents = [fTorrents indexesOfObjectsWithOptions: NSEnumerationConcurrent passingTest: ^BOOL(Torrent * torrent, NSUInteger idx, BOOL * stop) { - //check status - if (torrent.active && !torrent.checkingWaiting) - { - const BOOL isActive = !torrent.stalled; - if (isActive) - OSAtomicIncrement32(&active); - - if (torrent.seeding) - { - OSAtomicIncrement32(&seeding); - if (filterStatus && !((filterActive && isActive) || filterSeed)) - return NO; - } - else - { - OSAtomicIncrement32(&downloading); - if (filterStatus && !((filterActive && isActive) || filterDownload)) - return NO; - } - } - else - { - OSAtomicIncrement32(&paused); - if (filterStatus && !filterPause) - return NO; + NSAssert1(NO, @"Unknown sort tag received: %ld", [menuItem tag]); + sortType = SORT_ORDER; } - //checkGroup - if (filterGroup) - if (torrent.groupValue != groupFilterValue) - return NO; - - //check text field - if (searchStrings) - { - __block BOOL removeTextField = NO; - if (filterTracker) - { - NSArray * trackers = torrent.allTrackersFlat; - - //to count, we need each string in at least 1 tracker - [searchStrings enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id searchString, NSUInteger idx, BOOL * stop) { - __block BOOL found = NO; - [trackers enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id tracker, NSUInteger idx, BOOL * stopTracker) { - if ([tracker rangeOfString: searchString options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location != NSNotFound) - { - found = YES; - *stopTracker = YES; - } - }]; - if (!found) - { - removeTextField = YES; - *stop = YES; - } - }]; - } - else - { - [searchStrings enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id searchString, NSUInteger idx, BOOL * stop) { - if ([torrent.name rangeOfString: searchString options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound) - { - removeTextField = YES; - *stop = YES; - } - }]; - } - - if (removeTextField) - return NO; - } - - return YES; - }]; - - NSArray * allTorrents = [fTorrents objectsAtIndexes: indexesOfNonFilteredTorrents]; - - //set button tooltips - if (fFilterBar) - [fFilterBar setCountAll: fTorrents.count active: active downloading: downloading seeding: seeding paused: paused]; - - //if either the previous or current lists are blank, set its value to the other - const BOOL groupRows = allTorrents.count > 0 ? [fDefaults boolForKey: @"SortByGroup"] : (fDisplayedTorrents.count > 0 && [fDisplayedTorrents[0] isKindOfClass: [TorrentGroup class]]); - const BOOL wasGroupRows = fDisplayedTorrents.count > 0 ? [fDisplayedTorrents[0] isKindOfClass: [TorrentGroup class]] : groupRows; - - #warning could probably be merged with later code somehow - //clear display cache for not-shown torrents - if (fDisplayedTorrents.count > 0) - { - //for each torrent, removes the previous piece info if it's not in allTorrents, and keeps track of which torrents we already found in allTorrents - void (^removePreviousFinishedPieces)(id, NSUInteger, BOOL *) = ^(Torrent * torrent, NSUInteger idx, BOOL * stop) { - //we used to keep track of which torrents we already found in allTorrents, but it wasn't safe fo concurrent enumeration - if (![allTorrents containsObject: torrent]) - torrent.previousFinishedPieces = nil; - }; - - if (wasGroupRows) - [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id obj, NSUInteger idx, BOOL * stop) { - [((TorrentGroup *)obj).torrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: removePreviousFinishedPieces]; - }]; - else - [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: removePreviousFinishedPieces]; - } - - BOOL beganUpdates = NO; - - //don't animate torrents when first launching - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - NSAnimationContext.currentContext.duration = 0; - }); - [NSAnimationContext beginGrouping]; - - //add/remove torrents (and rearrange for groups), one by one - if (!groupRows && !wasGroupRows) - { - NSMutableIndexSet * addIndexes = [NSMutableIndexSet indexSet], - * removePreviousIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fDisplayedTorrents.count)]; - - //for each of the torrents to add, find if it already exists (and keep track of those we've already added & those we need to remove) - [allTorrents enumerateObjectsWithOptions: 0 usingBlock: ^(id objAll, NSUInteger previousIndex, BOOL * stop) { - const NSUInteger currentIndex = [fDisplayedTorrents indexOfObjectAtIndexes: removePreviousIndexes options: NSEnumerationConcurrent passingTest: ^(id objDisplay, NSUInteger idx, BOOL *stop) { - return (BOOL)(objAll == objDisplay); - }]; - if (currentIndex == NSNotFound) - [addIndexes addIndex: previousIndex]; - else - [removePreviousIndexes removeIndex: currentIndex]; - }]; - - if (addIndexes.count > 0 || removePreviousIndexes.count > 0) - { - beganUpdates = YES; - [fTableView beginUpdates]; - - //remove torrents we didn't find - if (removePreviousIndexes.count > 0) - { - [fDisplayedTorrents removeObjectsAtIndexes: removePreviousIndexes]; - [fTableView removeItemsAtIndexes: removePreviousIndexes inParent: nil withAnimation: NSTableViewAnimationSlideDown]; - } - - //add new torrents - if (addIndexes.count > 0) - { - //slide new torrents in differently - if (fAddingTransfers) - { - NSIndexSet * newAddIndexes = [allTorrents indexesOfObjectsAtIndexes: addIndexes options: NSEnumerationConcurrent passingTest: ^BOOL(id obj, NSUInteger idx, BOOL * stop) { - return [fAddingTransfers containsObject: obj]; - }]; - - [addIndexes removeIndexes: newAddIndexes]; - - [fDisplayedTorrents addObjectsFromArray: [allTorrents objectsAtIndexes: newAddIndexes]]; - [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(fDisplayedTorrents.count - newAddIndexes.count, newAddIndexes.count)] inParent: nil withAnimation: NSTableViewAnimationSlideLeft]; - } - - [fDisplayedTorrents addObjectsFromArray: [allTorrents objectsAtIndexes: addIndexes]]; - [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(fDisplayedTorrents.count - addIndexes.count, addIndexes.count)] inParent: nil withAnimation: NSTableViewAnimationSlideDown]; - } - } - } - else if (groupRows && wasGroupRows) - { - NSAssert(groupRows && wasGroupRows, @"Should have had group rows and should remain with group rows"); - - #warning don't always do? - beganUpdates = YES; - [fTableView beginUpdates]; - - NSMutableIndexSet * unusedAllTorrentsIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, allTorrents.count)]; - - NSMutableDictionary * groupsByIndex = [NSMutableDictionary dictionaryWithCapacity: fDisplayedTorrents.count]; - for (TorrentGroup * group in fDisplayedTorrents) - groupsByIndex[@(group.groupIndex)] = group; - - const NSUInteger originalGroupCount = fDisplayedTorrents.count; - for (NSUInteger index = 0; index < originalGroupCount; ++index) - { - TorrentGroup * group = fDisplayedTorrents[index]; - - NSMutableIndexSet * removeIndexes = [NSMutableIndexSet indexSet]; - - //needs to be a signed integer - for (NSUInteger indexInGroup = 0; indexInGroup < group.torrents.count; ++indexInGroup) - { - Torrent * torrent = group.torrents[indexInGroup]; - const NSUInteger allIndex = [allTorrents indexOfObjectAtIndexes: unusedAllTorrentsIndexes options: NSEnumerationConcurrent passingTest: ^(id obj, NSUInteger idx, BOOL * stop) { - return (BOOL)(obj == torrent); - }]; - if (allIndex == NSNotFound) - [removeIndexes addIndex: indexInGroup]; - else - { - BOOL markTorrentAsUsed = YES; - - const NSInteger groupValue = torrent.groupValue; - if (groupValue != group.groupIndex) - { - TorrentGroup * newGroup = groupsByIndex[@(groupValue)]; - if (!newGroup) - { - newGroup = [[TorrentGroup alloc] initWithGroup: groupValue]; - groupsByIndex[@(groupValue)] = newGroup; - [fDisplayedTorrents addObject: newGroup]; - - [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: fDisplayedTorrents.count-1] inParent: nil withAnimation: NSTableViewAnimationEffectFade]; - [fTableView isGroupCollapsed: groupValue] ? [fTableView collapseItem: newGroup] : [fTableView expandItem: newGroup]; - } - else //if we haven't processed the other group yet, we have to make sure we don't flag it for removal the next time - { - //ugggh, but shouldn't happen too often - if ([fDisplayedTorrents indexOfObject: newGroup inRange: NSMakeRange(index+1, originalGroupCount-(index+1))] != NSNotFound) - markTorrentAsUsed = NO; - } - - [group.torrents removeObjectAtIndex: indexInGroup]; - [newGroup.torrents addObject: torrent]; - - [fTableView moveItemAtIndex: indexInGroup inParent: group toIndex: newGroup.torrents.count-1 inParent: newGroup]; - - --indexInGroup; - } - - if (markTorrentAsUsed) - [unusedAllTorrentsIndexes removeIndex: allIndex]; - } - } - - if (removeIndexes.count > 0) - { - [group.torrents removeObjectsAtIndexes: removeIndexes]; - [fTableView removeItemsAtIndexes: removeIndexes inParent: group withAnimation: NSTableViewAnimationEffectFade]; - } - } - - //add remaining new torrents - for (Torrent * torrent in [allTorrents objectsAtIndexes: unusedAllTorrentsIndexes]) - { - const NSInteger groupValue = torrent.groupValue; - TorrentGroup * group = groupsByIndex[@(groupValue)]; - if (!group) - { - group = [[TorrentGroup alloc] initWithGroup: groupValue]; - groupsByIndex[@(groupValue)] = group; - [fDisplayedTorrents addObject: group]; - - [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: fDisplayedTorrents.count-1] inParent: nil withAnimation: NSTableViewAnimationEffectFade]; - [fTableView isGroupCollapsed: groupValue] ? [fTableView collapseItem: group] : [fTableView expandItem: group]; - } - - [group.torrents addObject: torrent]; - - const BOOL newTorrent = fAddingTransfers && [fAddingTransfers containsObject: torrent]; - [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: group.torrents.count-1] inParent: group withAnimation: newTorrent ? NSTableViewAnimationSlideLeft : NSTableViewAnimationSlideDown]; - } - - //remove empty groups - NSIndexSet * removeGroupIndexes = [fDisplayedTorrents indexesOfObjectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, originalGroupCount)] options: NSEnumerationConcurrent passingTest: ^BOOL(id obj, NSUInteger idx, BOOL * stop) { - return ((TorrentGroup *)obj).torrents.count == 0; - }]; - - if (removeGroupIndexes.count > 0) - { - [fDisplayedTorrents removeObjectsAtIndexes: removeGroupIndexes]; - [fTableView removeItemsAtIndexes: removeGroupIndexes inParent: nil withAnimation: NSTableViewAnimationEffectFade]; - } - - //now that all groups are there, sort them - don't insert on the fly in case groups were reordered in prefs - NSSortDescriptor * groupDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"groupOrderValue" ascending: YES]; - [self rearrangeTorrentTableArray: fDisplayedTorrents forParent: nil withSortDescriptors: @[groupDescriptor] beganTableUpdate: &beganUpdates]; - } - else - { - NSAssert(groupRows != wasGroupRows, @"Trying toggling group-torrent reordering when we weren't expecting to."); - - //set all groups as expanded - [fTableView removeAllCollapsedGroups]; - - //since we're not doing this the right way (boo buggy animation), we need to remember selected values - #warning when Lion-only and using views instead of cells, this likely won't be needed - NSArray * selectedValues = fTableView.selectedValues; - - beganUpdates = YES; - [fTableView beginUpdates]; - - [fTableView removeItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fDisplayedTorrents.count)] inParent: nil withAnimation: NSTableViewAnimationSlideDown]; - - if (groupRows) - { - //a map for quickly finding groups - NSMutableDictionary * groupsByIndex = [NSMutableDictionary dictionaryWithCapacity: GroupsController.groups.numberOfGroups]; - for (Torrent * torrent in allTorrents) - { - const NSInteger groupValue = torrent.groupValue; - TorrentGroup * group = groupsByIndex[@(groupValue)]; - if (!group) - { - group = [[TorrentGroup alloc] initWithGroup: groupValue]; - groupsByIndex[@(groupValue)] = group; - } - - [group.torrents addObject: torrent]; - } - - [fDisplayedTorrents setArray: groupsByIndex.allValues]; - - //we need the groups to be sorted, and we can do it without moving items in the table, too! - NSSortDescriptor * groupDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"groupOrderValue" ascending: YES]; - [fDisplayedTorrents sortUsingDescriptors: @[groupDescriptor]]; - } - else - [fDisplayedTorrents setArray: allTorrents]; - - [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fDisplayedTorrents.count)] inParent: nil withAnimation: NSTableViewAnimationEffectFade]; - - if (groupRows) - { - //actually expand group rows - for (TorrentGroup * group in fDisplayedTorrents) - [fTableView expandItem: group]; - } - - if (selectedValues) - [fTableView selectValues: selectedValues]; - } - - //sort the torrents (won't sort the groups, though) - [self sortTorrentsCallUpdates: !beganUpdates includeQueueOrder: YES]; - - if (beganUpdates) - [fTableView endUpdates]; - fTableView.needsDisplay = YES; - - [NSAnimationContext endGrouping]; - - [self resetInfo]; //if group is already selected, but the torrents in it change - - [self setBottomCountText: groupRows || filterStatus || filterGroup || searchStrings]; - - [self setWindowSizeToFit]; - - if (fAddingTransfers) - { - fAddingTransfers = nil; - } -} - -- (void) switchFilter: (id) sender -{ - [fFilterBar switchFilter: sender == fNextFilterItem]; -} - -- (IBAction) showGlobalPopover: (id) sender -{ - if (fGlobalPopoverShown) - return; - - NSPopover * popover = [[NSPopover alloc] init]; - popover.behavior = NSPopoverBehaviorTransient; - GlobalOptionsPopoverViewController * viewController = [[GlobalOptionsPopoverViewController alloc] initWithHandle: fLib]; - popover.contentViewController = viewController; - popover.delegate = self; - - NSView *senderView = sender; - [popover showRelativeToRect: senderView.frame ofView: senderView preferredEdge: NSMaxYEdge]; -} - -//don't show multiple popovers when clicking the gear button repeatedly -- (void) popoverWillShow: (NSNotification *) notification -{ - fGlobalPopoverShown = YES; -} - -- (void) popoverWillClose: (NSNotification *) notification -{ - fGlobalPopoverShown = NO; -} - -- (void) menuNeedsUpdate: (NSMenu *) menu -{ - if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu) - { - for (NSInteger i = menu.numberOfItems-1; i >= 0; i--) - [menu removeItemAtIndex: i]; - - NSMenu * groupMenu = [GroupsController.groups groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO]; - - const NSInteger groupMenuCount = groupMenu.numberOfItems; - for (NSInteger i = 0; i < groupMenuCount; i++) - { - NSMenuItem * item = [groupMenu itemAtIndex: 0]; - [groupMenu removeItemAtIndex: 0]; - [menu addItem: item]; - } - } - else if (menu == fShareMenu || menu == fShareContextMenu) { - [menu removeAllItems]; - - for (NSMenuItem * item in ShareTorrentFileHelper.sharedHelper.menuItems) - { - [menu addItem:item]; - } - } - else; -} - -- (void) setGroup: (id) sender -{ - for (Torrent * torrent in fTableView.selectedTorrents) - { - [fTableView removeCollapsedGroup: torrent.groupValue]; //remove old collapsed group - - [torrent setGroupValue: ((NSMenuItem *)sender).tag determinationType: TorrentDeterminationUserSpecified]; - } - - [self applyFilter]; - [self updateUI]; - [self updateTorrentHistory]; -} - -- (void) toggleSpeedLimit: (id) sender -{ - [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"]; - [self speedLimitChanged: sender]; -} - -- (void) speedLimitChanged: (id) sender -{ - tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey: @"SpeedLimit"]); - [fStatusBar updateSpeedFieldsToolTips]; -} - -- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict -{ - const BOOL isLimited = [dict[@"Active"] boolValue]; - - [fDefaults setBool: isLimited forKey: @"SpeedLimit"]; - [fStatusBar updateSpeedFieldsToolTips]; - - if (![dict[@"ByUser"] boolValue]) { - NSUserNotification * notification = [[NSUserNotification alloc] init]; - notification.title = isLimited ? NSLocalizedString(@"Speed Limit Auto Enabled", "notification title") : NSLocalizedString(@"Speed Limit Auto Disabled", "notification title"); - notification.informativeText = NSLocalizedString(@"Bandwidth settings changed", "notification description"); - notification.hasActionButton = NO; - - [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification:notification]; - } -} - -- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying -{ - fSoundPlaying = NO; -} - --(void) VDKQueue: (VDKQueue *) queue receivedNotification: (NSString*) notification forPath: (NSString*) fpath -{ - //don't assume that just because we're watching for write notification, we'll only receive write notifications - - if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"]) - return; - - if (fAutoImportTimer.valid) - [fAutoImportTimer invalidate]; - - //check again in 10 seconds in case torrent file wasn't complete - fAutoImportTimer = [NSTimer scheduledTimerWithTimeInterval: 10.0 target: self - selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO]; - - [self checkAutoImportDirectory]; -} - -- (void) changeAutoImport -{ - if (fAutoImportTimer.valid) - [fAutoImportTimer invalidate]; - fAutoImportTimer = nil; - - fAutoImportedNames = nil; - - [self checkAutoImportDirectory]; -} - -- (void) checkAutoImportDirectory -{ - NSString * path; - if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"])) - return; - - path = path.stringByExpandingTildeInPath; - - NSArray * importedNames; - if (!(importedNames = [NSFileManager.defaultManager contentsOfDirectoryAtPath: path error: NULL])) - return; - - //only check files that have not been checked yet - NSMutableArray * newNames = [importedNames mutableCopy]; - - if (fAutoImportedNames) - [newNames removeObjectsInArray: fAutoImportedNames]; - else - fAutoImportedNames = [[NSMutableArray alloc] init]; - [fAutoImportedNames setArray: importedNames]; - - for (NSString * file in newNames) - { - if ([file hasPrefix: @"."]) - continue; - - NSString * fullFile = [path stringByAppendingPathComponent: file]; - - if (!([[NSWorkspace.sharedWorkspace typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"] - || [fullFile.pathExtension caseInsensitiveCompare: @"torrent"] == NSOrderedSame)) - continue; - - tr_ctor * ctor = tr_ctorNew(fLib); - tr_ctorSetMetainfoFromFile(ctor, fullFile.UTF8String); - - switch (tr_torrentParse(ctor, NULL)) - { - case TR_PARSE_OK: { - [self openFiles: @[fullFile] addType: ADD_AUTO forcePath: nil]; - - NSString * notificationTitle = NSLocalizedString(@"Torrent File Auto Added", "notification title"); - NSUserNotification* notification = [[NSUserNotification alloc] init]; - notification.title = notificationTitle; - notification.informativeText = file; - - notification.hasActionButton = NO; - - [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification: notification]; - break; - } - case TR_PARSE_ERR: - [fAutoImportedNames removeObject: file]; - break; - - case TR_PARSE_DUPLICATE: //let's ignore this (but silence a warning) - break; - } - - tr_ctorFree(ctor); - } -} - -- (void) beginCreateFile: (NSNotification *) notification -{ - if (![fDefaults boolForKey: @"AutoImport"]) - return; - - NSString * location = ((NSURL *)notification.object).path, - * path = [fDefaults stringForKey: @"AutoImportDirectory"]; - - if (location && path && [location.stringByDeletingLastPathComponent.stringByExpandingTildeInPath - isEqualToString: path.stringByExpandingTildeInPath]) - [fAutoImportedNames addObject: location.lastPathComponent]; -} - -- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item -{ - if (item) - return ((TorrentGroup *)item).torrents.count; - else - return fDisplayedTorrents.count; -} - -- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item -{ - if (item) - return ((TorrentGroup *)item).torrents[index]; - else - return fDisplayedTorrents[index]; -} - -- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item -{ - return ![item isKindOfClass: [Torrent class]]; -} - -- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item -{ - if ([item isKindOfClass: [Torrent class]]) { - if (tableColumn) - return nil; - return ((Torrent *)item).hashString; - } - else - { - NSString * ident = tableColumn.identifier; - TorrentGroup * group = (TorrentGroup *)item; - if ([ident isEqualToString: @"Group"]) - { - NSInteger groupIndex = group.groupIndex; - return groupIndex != -1 ? [GroupsController.groups nameForIndex: groupIndex] - : NSLocalizedString(@"No Group", "Group table row"); - } - else if ([ident isEqualToString: @"Color"]) - { - NSInteger groupIndex = group.groupIndex; - return [GroupsController.groups imageForIndex: groupIndex]; - } - else if ([ident isEqualToString: @"DL Image"]) - return [NSImage imageNamed: @"DownArrowGroupTemplate"]; - else if ([ident isEqualToString: @"UL Image"]) - return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"] - ? @"YingYangGroupTemplate" : @"UpArrowGroupTemplate"]; - else - { - if ([fDefaults boolForKey: @"DisplayGroupRowRatio"]) - return [NSString stringForRatio: group.ratio]; - else - { - CGFloat rate = [ident isEqualToString: @"UL"] ? group.uploadRate : group.downloadRate; - return [NSString stringForSpeed: rate]; - } - } - } -} - -- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard -{ - //only allow reordering of rows if sorting by order - if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER]) - { - NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet]; - for (id torrent in items) - { - if (![torrent isKindOfClass: [Torrent class]]) - return NO; - - [indexSet addIndex: [fTableView rowForItem: torrent]]; - } - - [pasteboard declareTypes: @[TORRENT_TABLE_VIEW_DATA_TYPE] owner: self]; - [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE]; - return YES; - } - return NO; -} - -- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item - proposedChildIndex: (NSInteger) index -{ - NSPasteboard * pasteboard = info.draggingPasteboard; - if ([pasteboard.types containsObject: TORRENT_TABLE_VIEW_DATA_TYPE]) - { - if ([fDefaults boolForKey: @"SortByGroup"]) - { - if (!item) - return NSDragOperationNone; - - if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER]) - { - if ([item isKindOfClass: [Torrent class]]) - { - TorrentGroup * group = [fTableView parentForItem: item]; - index = [group.torrents indexOfObject: item] + 1; - item = group; - } - } - else - { - if ([item isKindOfClass: [Torrent class]]) - item = [fTableView parentForItem: item]; - index = NSOutlineViewDropOnItemIndex; - } - } - else - { - if (index == NSOutlineViewDropOnItemIndex) - return NSDragOperationNone; - - if (item) - { - index = [fTableView rowForItem: item] + 1; - item = nil; - } - } - - [fTableView setDropItem: item dropChildIndex: index]; - return NSDragOperationGeneric; - } - - return NSDragOperationNone; -} - -- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item childIndex: (NSInteger) newRow -{ - NSPasteboard * pasteboard = info.draggingPasteboard; - if ([pasteboard.types containsObject: TORRENT_TABLE_VIEW_DATA_TYPE]) - { - NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]]; - - //get the torrents to move - NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: indexes.count]; - for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex: i]) - { - Torrent * torrent = [fTableView itemAtRow: i]; - [movingTorrents addObject: torrent]; - } - - //change groups - if (item) - { - TorrentGroup * group = (TorrentGroup *)item; - const NSInteger groupIndex = group.groupIndex; - - for (Torrent * torrent in movingTorrents) - [torrent setGroupValue: groupIndex determinationType: TorrentDeterminationUserSpecified]; - } - - //reorder queue order - if (newRow != NSOutlineViewDropOnItemIndex) - { - TorrentGroup * group = (TorrentGroup *)item; - //find torrent to place under - NSArray * groupTorrents = group ? group.torrents : fDisplayedTorrents; - Torrent * topTorrent = nil; - for (NSInteger i = newRow-1; i >= 0; i--) - { - Torrent * tempTorrent = groupTorrents[i]; - if (![movingTorrents containsObject: tempTorrent]) - { - topTorrent = tempTorrent; - break; - } - } - - //remove objects to reinsert - [fTorrents removeObjectsInArray: movingTorrents]; - - //insert objects at new location - const NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0; - NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, movingTorrents.count)]; - [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes]; - - //we need to make sure the queue order is updated in the Torrent object before we sort - safest to just reset all queue positions - NSUInteger i = 0; - for (Torrent * torrent in fTorrents) - { - torrent.queuePosition = i++; - [torrent update]; - } - - //do the drag animation here so that the dragged torrents are the ones that are animated as moving, and not the torrents around them - [fTableView beginUpdates]; - - NSUInteger insertDisplayIndex = topTorrent ? [groupTorrents indexOfObject: topTorrent] + 1 : 0; - - for (Torrent * torrent in movingTorrents) - { - TorrentGroup * oldParent = item ? [fTableView parentForItem: torrent] : nil; - NSMutableArray * oldTorrents = oldParent ? oldParent.torrents : fDisplayedTorrents; - const NSUInteger oldIndex = [oldTorrents indexOfObject: torrent]; - - if (item == oldParent) - { - if (oldIndex < insertDisplayIndex) - --insertDisplayIndex; - [oldTorrents moveObjectAtIndex: oldIndex toIndex: insertDisplayIndex]; - } - else - { - NSAssert(item && oldParent, @"Expected to be dragging between group rows"); - - NSMutableArray * newTorrents = ((TorrentGroup *)item).torrents; - [newTorrents insertObject: torrent atIndex: insertDisplayIndex]; - [oldTorrents removeObjectAtIndex: oldIndex]; - } - - [fTableView moveItemAtIndex: oldIndex inParent: oldParent toIndex: insertDisplayIndex inParent: item]; - - ++insertDisplayIndex; - } - - [fTableView endUpdates]; - } - - [self applyFilter]; - } - - return YES; -} - -- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification -{ - [self resetInfo]; - [fWindow.toolbar validateVisibleItems]; -} - -- (NSDragOperation) draggingEntered: (id ) info -{ - NSPasteboard * pasteboard = info.draggingPasteboard; - if ([pasteboard.types containsObject: NSFilenamesPboardType]) - { - //check if any torrent files can be added - BOOL torrent = NO; - NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType]; - for (NSString * file in files) - { - if ([[NSWorkspace.sharedWorkspace typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"] - || [file.pathExtension caseInsensitiveCompare: @"torrent"] == NSOrderedSame) - { - torrent = YES; - tr_ctor * ctor = tr_ctorNew(fLib); - tr_ctorSetMetainfoFromFile(ctor, file.UTF8String); - if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK) - { - if (!fOverlayWindow) - fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow]; - [fOverlayWindow setTorrents: files]; - - return NSDragOperationCopy; - } - tr_ctorFree(ctor); - } - } - - //create a torrent file if a single file - if (!torrent && files.count == 1) - { - if (!fOverlayWindow) - fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow]; - [fOverlayWindow setFile: [files[0] lastPathComponent]]; - - return NSDragOperationCopy; - } - } - else if ([pasteboard.types containsObject: NSURLPboardType]) - { - if (!fOverlayWindow) - fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow]; - [fOverlayWindow setURL: [NSURL URLFromPasteboard: pasteboard].relativeString]; - - return NSDragOperationCopy; - } - else; - - return NSDragOperationNone; -} - -- (void) draggingExited: (id ) info -{ - if (fOverlayWindow) - [fOverlayWindow fadeOut]; -} - -- (BOOL) performDragOperation: (id ) info -{ - if (fOverlayWindow) - [fOverlayWindow fadeOut]; - - NSPasteboard * pasteboard = info.draggingPasteboard; - if ([pasteboard.types containsObject: NSFilenamesPboardType]) - { - BOOL torrent = NO, accept = YES; - - //create an array of files that can be opened - NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType]; - NSMutableArray * filesToOpen = [NSMutableArray arrayWithCapacity: files.count]; - for (NSString * file in files) - { - if ([[NSWorkspace.sharedWorkspace typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"] - || [file.pathExtension caseInsensitiveCompare: @"torrent"] == NSOrderedSame) - { - torrent = YES; - tr_ctor * ctor = tr_ctorNew(fLib); - tr_ctorSetMetainfoFromFile(ctor, file.UTF8String); - if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK) - [filesToOpen addObject: file]; - tr_ctorFree(ctor); - } - } - - if (filesToOpen.count > 0) - [self application: NSApp openFiles: filesToOpen]; - else - { - if (!torrent && files.count == 1) - [CreatorWindowController createTorrentFile: fLib forFile: [NSURL fileURLWithPath: files[0]]]; - else - accept = NO; - } - - return accept; - } - else if ([pasteboard.types containsObject: NSURLPboardType]) - { - NSURL * url; - if ((url = [NSURL URLFromPasteboard: pasteboard])) - { - [self openURL: url.absoluteString]; - return YES; - } - } - else; - - return NO; -} - -- (void) toggleSmallView: (id) sender -{ - BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"]; - [fDefaults setBool: makeSmall forKey: @"SmallView"]; - - fTableView.usesAlternatingRowBackgroundColors = !makeSmall; - - fTableView.rowHeight = makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR; - - [fTableView beginUpdates]; - [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTableView.numberOfRows)]]; - [fTableView endUpdates]; - - //resize for larger min height if not set to auto size - if (![fDefaults boolForKey: @"AutoSize"]) - { - const NSSize contentSize = fWindow.contentView.frame.size; - - NSSize contentMinSize = fWindow.contentMinSize; - contentMinSize.height = self.minWindowContentSizeAllowed; - fWindow.contentMinSize = contentMinSize; - - //make sure the window already isn't too small - if (!makeSmall && contentSize.height < contentMinSize.height) - { - NSRect frame = fWindow.frame; - CGFloat heightChange = contentMinSize.height - contentSize.height; - frame.size.height += heightChange; - frame.origin.y -= heightChange; - - [fWindow setFrame: frame display: YES]; - } - } - else - [self setWindowSizeToFit]; -} - -- (void) togglePiecesBar: (id) sender -{ - [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"]; - [fTableView togglePiecesBar]; -} - -- (void) toggleAvailabilityBar: (id) sender -{ - [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"]; - [fTableView display]; -} - -- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check -{ - NSScrollView * scrollView = fTableView.enclosingScrollView; - - //convert pixels to points - NSRect windowFrame = fWindow.frame; - NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil]; - windowSize.height += height; - - if (check) - { - //we can't call minSize, since it might be set to the current size (auto size) - const CGFloat minHeight = self.minWindowContentSizeAllowed - + (NSHeight(fWindow.frame) - NSHeight(fWindow.contentView.frame)); //contentView to window - - if (windowSize.height <= minHeight) - windowSize.height = minHeight; - else - { - NSScreen * screen = fWindow.screen; - if (screen) - { - NSSize maxSize = [scrollView convertSize: screen.visibleFrame.size fromView: nil]; - if (!fStatusBar) - maxSize.height -= STATUS_BAR_HEIGHT; - if (!fFilterBar) - maxSize.height -= FILTER_BAR_HEIGHT; - if (windowSize.height > maxSize.height) - windowSize.height = maxSize.height; - } - } - } - - //convert points to pixels - windowSize = [scrollView convertSize: windowSize toView: nil]; - - windowFrame.origin.y -= (windowSize.height - windowFrame.size.height); - windowFrame.size.height = windowSize.height; - return windowFrame; -} - -- (void) toggleStatusBar: (id) sender -{ - const BOOL show = fStatusBar == nil; - [self showStatusBar: show animate: YES]; - [fDefaults setBool: show forKey: @"StatusBar"]; -} - -//doesn't save shown state -- (void) showStatusBar: (BOOL) show animate: (BOOL) animate -{ - const BOOL prevShown = fStatusBar != nil; - if (show == prevShown) - return; - - if (show) - { - fStatusBar = [[StatusBarController alloc] initWithLib: fLib]; - - NSView * contentView = fWindow.contentView; - const NSSize windowSize = [contentView convertSize: fWindow.frame.size fromView: nil]; - - NSRect statusBarFrame = fStatusBar.view.frame; - statusBarFrame.size.width = windowSize.width; - fStatusBar.view.frame = statusBarFrame; - - [contentView addSubview: fStatusBar.view]; - [fStatusBar.view setFrameOrigin: NSMakePoint(0.0, NSMaxY(contentView.frame))]; - } - - CGFloat heightChange = fStatusBar.view.frame.size.height; - if (!show) - heightChange *= -1; - - //allow bar to show even if not enough room - if (show && ![fDefaults boolForKey: @"AutoSize"]) - { - NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO]; - - NSScreen * screen = fWindow.screen; - if (screen) - { - CGFloat change = screen.visibleFrame.size.height - frame.size.height; - if (change < 0.0) - { - frame = fWindow.frame; - frame.size.height += change; - frame.origin.y -= change; - [fWindow setFrame: frame display: NO animate: NO]; - } - } - } - - [self updateUI]; - - NSScrollView * scrollView = fTableView.enclosingScrollView; - - //set views to not autoresize - const NSUInteger statsMask = fStatusBar.view.autoresizingMask; - fStatusBar.view.autoresizingMask = NSViewNotSizable; - NSUInteger filterMask; - if (fFilterBar) - { - filterMask = fFilterBar.view.autoresizingMask; - fFilterBar.view.autoresizingMask = NSViewNotSizable; - } - const NSUInteger scrollMask = scrollView.autoresizingMask; - scrollView.autoresizingMask = NSViewNotSizable; - - NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO]; - [fWindow setFrame: frame display: YES animate: animate]; - - //re-enable autoresize - fStatusBar.view.autoresizingMask = statsMask; - if (fFilterBar) - fFilterBar.view.autoresizingMask = filterMask; - scrollView.autoresizingMask = scrollMask; - - if (!show) - { - [fStatusBar.view removeFromSuperviewWithoutNeedingDisplay]; - fStatusBar = nil; - } - - if ([fDefaults boolForKey: @"AutoSize"]) - [self setWindowMinMaxToCurrent]; - else - { - //change min size - NSSize minSize = fWindow.contentMinSize; - minSize.height += heightChange; - fWindow.contentMinSize = minSize; - } -} - -- (void) toggleFilterBar: (id) sender -{ - const BOOL show = fFilterBar == nil; - - //disable filtering when hiding (have to do before showFilterBar:animate:) - if (!show) - [fFilterBar reset: NO]; - - [self showFilterBar: show animate: YES]; - [fDefaults setBool: show forKey: @"FilterBar"]; - [fWindow.toolbar validateVisibleItems]; - - [self applyFilter]; //do even if showing to ensure tooltips are updated -} - -//doesn't save shown state -- (void) showFilterBar: (BOOL) show animate: (BOOL) animate -{ - const BOOL prevShown = fFilterBar != nil; - if (show == prevShown) - return; - - if (show) - { - fFilterBar = [[FilterBarController alloc] init]; - - NSView * contentView = fWindow.contentView; - const NSSize windowSize = [contentView convertSize: fWindow.frame.size fromView: nil]; - - NSRect filterBarFrame = fFilterBar.view.frame; - filterBarFrame.size.width = windowSize.width; - fFilterBar.view.frame = filterBarFrame; - - if (fStatusBar) - [contentView addSubview: fFilterBar.view positioned: NSWindowBelow relativeTo: fStatusBar.view]; - else - [contentView addSubview: fFilterBar.view]; - const CGFloat originY = fStatusBar ? NSMinY(fStatusBar.view.frame) : NSMaxY(contentView.frame); - [fFilterBar.view setFrameOrigin: NSMakePoint(0.0, originY)]; - } - else - [fWindow makeFirstResponder: fTableView]; - - CGFloat heightChange = NSHeight(fFilterBar.view.frame); - if (!show) - heightChange *= -1; - - //allow bar to show even if not enough room - if (show && ![fDefaults boolForKey: @"AutoSize"]) - { - NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO]; - - NSScreen * screen = fWindow.screen; - if (screen) - { - CGFloat change = screen.visibleFrame.size.height - frame.size.height; - if (change < 0.0) - { - frame = fWindow.frame; - frame.size.height += change; - frame.origin.y -= change; - [fWindow setFrame: frame display: NO animate: NO]; - } - } - } - - NSScrollView * scrollView = fTableView.enclosingScrollView; - - //set views to not autoresize - const NSUInteger filterMask = fFilterBar.view.autoresizingMask; - const NSUInteger scrollMask = scrollView.autoresizingMask; - fFilterBar.view.autoresizingMask = NSViewNotSizable; - scrollView.autoresizingMask = NSViewNotSizable; - - const NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO]; - [fWindow setFrame: frame display: YES animate: animate]; - - //re-enable autoresize - fFilterBar.view.autoresizingMask = filterMask; - scrollView.autoresizingMask = scrollMask; - - if (!show) - { - [fFilterBar.view removeFromSuperviewWithoutNeedingDisplay]; - fFilterBar = nil; - } - - if ([fDefaults boolForKey: @"AutoSize"]) - [self setWindowMinMaxToCurrent]; - else - { - //change min size - NSSize minSize = fWindow.contentMinSize; - minSize.height += heightChange; - fWindow.contentMinSize = minSize; - } -} - -- (void) focusFilterField -{ - if (!fFilterBar) - [self toggleFilterBar: self]; - [fFilterBar focusSearchField]; -} - -- (BOOL) acceptsPreviewPanelControl: (QLPreviewPanel *) panel -{ - return !fQuitting; -} - -- (void) beginPreviewPanelControl: (QLPreviewPanel *) panel -{ - fPreviewPanel = panel; - fPreviewPanel.delegate = self; - fPreviewPanel.dataSource = self; -} - -- (void) endPreviewPanelControl: (QLPreviewPanel *) panel -{ - fPreviewPanel = nil; -} - -- (NSArray *) quickLookableTorrents -{ - NSArray * selectedTorrents = fTableView.selectedTorrents; - NSMutableArray * qlArray = [NSMutableArray arrayWithCapacity: selectedTorrents.count]; - - for (Torrent * torrent in selectedTorrents) - if ((torrent.folder || torrent.complete) && torrent.dataLocation) - [qlArray addObject: torrent]; - - return qlArray; -} - -- (NSInteger) numberOfPreviewItemsInPreviewPanel: (QLPreviewPanel *) panel -{ - if (fInfoController.canQuickLook) - return fInfoController.quickLookURLs.count; - else - return [self quickLookableTorrents].count; -} - -- (id ) previewPanel: (QLPreviewPanel *) panel previewItemAtIndex: (NSInteger) index -{ - if (fInfoController.canQuickLook) - return fInfoController.quickLookURLs[index]; - else - return [self quickLookableTorrents][index]; -} - -- (BOOL) previewPanel: (QLPreviewPanel *) panel handleEvent: (NSEvent *) event -{ - /*if ([event type] == NSKeyDown) - { - [super keyDown: event]; - return YES; - }*/ - - return NO; -} - -- (NSRect) previewPanel: (QLPreviewPanel *) panel sourceFrameOnScreenForPreviewItem: (id ) item -{ - if (fInfoController.canQuickLook) - return [fInfoController quickLookSourceFrameForPreviewItem: item]; - else - { - if (!fWindow.visible) - return NSZeroRect; - - const NSInteger row = [fTableView rowForItem: item]; - if (row == -1) - return NSZeroRect; - - NSRect frame = [fTableView iconRectForRow: row]; - - if (!NSIntersectsRect(fTableView.visibleRect, frame)) - return NSZeroRect; - - frame.origin = [fTableView convertPoint: frame.origin toView: nil]; - frame = [fWindow convertRectToScreen: frame]; - frame.origin.y -= frame.size.height; - return frame; - } -} - -- (void) showToolbarShare: (id) sender -{ - NSParameterAssert([sender isKindOfClass:[NSButton class]]); - NSButton *senderButton = sender; - - NSSharingServicePicker * picker = [[NSSharingServicePicker alloc] initWithItems: ShareTorrentFileHelper.sharedHelper.shareTorrentURLs]; - picker.delegate = self; - - [picker showRelativeToRect:senderButton.bounds ofView:senderButton preferredEdge:NSMinYEdge]; -} - -- (id)sharingServicePicker:(NSSharingServicePicker *)sharingServicePicker delegateForSharingService:(NSSharingService *)sharingService -{ - return self; -} - -- (NSWindow *)sharingService:(NSSharingService *)sharingService sourceWindowForShareItems:(NSArray *)items sharingContentScope:(NSSharingContentScope *)sharingContentScope -{ - return fWindow; -} - -- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident -{ - return [self toolbarButtonWithIdentifier: ident forToolbarButtonClass: [ButtonToolbarItem class]]; -} - -- (id) toolbarButtonWithIdentifier: (NSString *) ident forToolbarButtonClass:(Class)class -{ - ButtonToolbarItem * item = [[class alloc] initWithItemIdentifier: ident]; - - NSButton * button = [[NSButton alloc] init]; - button.bezelStyle = NSTexturedRoundedBezelStyle; - button.stringValue = @""; - - item.view = button; - - if (@available(macOS 11.0, *)) { - // not needed - } else { - const NSSize buttonSize = NSMakeSize(36.0, 25.0); - item.minSize = buttonSize; - item.maxSize = buttonSize; - } - - return item; -} - -- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag -{ - if ([ident isEqualToString: TOOLBAR_CREATE]) - { - ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - - item.label = NSLocalizedString(@"Create", "Create toolbar item -> label"); - item.paletteLabel = NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label"); - item.toolTip = NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"doc.badge.plus" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: @"ToolbarCreateTemplate"]; - } - item.target = self; - item.action = @selector(createFile:); - item.autovalidates = NO; - - return item; - } - else if ([ident isEqualToString: TOOLBAR_OPEN_FILE]) - { - ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - - item.label = NSLocalizedString(@"Open", "Open toolbar item -> label"); - item.paletteLabel = NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label"); - item.toolTip = NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"folder" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: @"ToolbarOpenTemplate"]; - } - item.target = self; - item.action = @selector(openShowSheet:); - item.autovalidates = NO; - - return item; - } - else if ([ident isEqualToString: TOOLBAR_OPEN_WEB]) - { - ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - - item.label = NSLocalizedString(@"Open Address", "Open address toolbar item -> label"); - item.paletteLabel = NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label"); - item.toolTip = NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"globe" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: @"ToolbarOpenWebTemplate"]; - } - item.target = self; - item.action = @selector(openURLShowSheet:); - item.autovalidates = NO; - - return item; - } - else if ([ident isEqualToString: TOOLBAR_REMOVE]) - { - ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - - item.label = NSLocalizedString(@"Remove", "Remove toolbar item -> label"); - item.paletteLabel = NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label"); - item.toolTip = NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"nosign" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: @"ToolbarRemoveTemplate"]; - } - item.target = self; - item.action = @selector(removeNoDelete:); - item.visibilityPriority = NSToolbarItemVisibilityPriorityHigh; - - return item; - } - else if ([ident isEqualToString: TOOLBAR_INFO]) - { - ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - ((NSButtonCell *)((NSButton *)item.view).cell).showsStateBy = NSContentsCellMask; //blue when enabled - - item.label = NSLocalizedString(@"Inspector", "Inspector toolbar item -> label"); - item.paletteLabel = NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label"); - item.toolTip = NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"info.circle" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: @"ToolbarInfoTemplate"]; - } - item.target = self; - item.action = @selector(showInfo:); - - return item; - } - else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL]) - { - GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident]; - - NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect]; - segmentedControl.cell = [[ToolbarSegmentedCell alloc] init]; - groupItem.view = segmentedControl; - NSSegmentedCell * segmentedCell = (NSSegmentedCell *)segmentedControl.cell; - segmentedControl.segmentStyle = NSSegmentStyleSeparated; - - segmentedControl.segmentCount = 2; - segmentedCell.trackingMode = NSSegmentSwitchTrackingMomentary; - - if (@available(macOS 11.0, *)) { - // not needed - } else { - const NSSize groupSize = NSMakeSize(72.0, 25.0); - groupItem.minSize = groupSize; - groupItem.maxSize = groupSize; - } - - groupItem.label = NSLocalizedString(@"Apply All", "All toolbar item -> label"); - groupItem.paletteLabel = NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label"); - groupItem.target = self; - groupItem.action = @selector(allToolbarClicked:); - - [groupItem setIdentifiers: @[TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL]]; - - [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG]; - if (@available(macOS 11.0, *)) { - [segmentedControl setImage: [[NSImage imageWithSystemSymbolName: @"pause.circle.fill" accessibilityDescription: nil] imageWithSymbolConfiguration:[NSImageSymbolConfiguration configurationWithScale:NSImageSymbolScaleLarge]] forSegment: TOOLBAR_PAUSE_TAG]; - } else { - [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate"] forSegment: TOOLBAR_PAUSE_TAG]; - } - [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers", - "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG]; - - [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG]; - [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate"] forSegment: TOOLBAR_RESUME_TAG]; - if (@available(macOS 11.0, *)) { - [segmentedControl setImage: [[NSImage imageWithSystemSymbolName: @"arrow.clockwise.circle.fill" accessibilityDescription: nil] imageWithSymbolConfiguration:[NSImageSymbolConfiguration configurationWithScale:NSImageSymbolScaleLarge]] forSegment: TOOLBAR_RESUME_TAG]; - } else { - [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate"] forSegment: TOOLBAR_RESUME_TAG]; - } - [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers", - "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG]; - - [groupItem createMenu: @[NSLocalizedString(@"Pause All", "All toolbar item -> label"), - NSLocalizedString(@"Resume All", "All toolbar item -> label")]]; - - - groupItem.visibilityPriority = NSToolbarItemVisibilityPriorityHigh; - - return groupItem; - } - else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED]) - { - GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident]; - - NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect]; - segmentedControl.cell = [[ToolbarSegmentedCell alloc] init]; - groupItem.view = segmentedControl; - NSSegmentedCell * segmentedCell = (NSSegmentedCell *)segmentedControl.cell; - - segmentedControl.segmentCount = 2; - segmentedCell.trackingMode = NSSegmentSwitchTrackingMomentary; - - if (@available(macOS 11.0, *)) { - // not needed - } else { - const NSSize groupSize = NSMakeSize(72.0, 25.0); - groupItem.minSize = groupSize; - groupItem.maxSize = groupSize; - } - - groupItem.label = NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label"); - groupItem.paletteLabel = NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label"); - groupItem.target = self; - groupItem.action = @selector(selectedToolbarClicked:); - - [groupItem setIdentifiers: @[TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED]]; - - [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG]; - if (@available(macOS 11.0, *)) { - [segmentedControl setImage: [[NSImage imageWithSystemSymbolName: @"pause" accessibilityDescription: nil] imageWithSymbolConfiguration:[NSImageSymbolConfiguration configurationWithScale:NSImageSymbolScaleLarge]] forSegment: TOOLBAR_PAUSE_TAG]; - } else { - [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate"] forSegment: TOOLBAR_PAUSE_TAG]; - } - [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers", - "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG]; - - [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG]; - if (@available(macOS 11.0, *)) { - [segmentedControl setImage: [NSImage imageWithSystemSymbolName: @"arrow.clockwise" accessibilityDescription: nil] forSegment: TOOLBAR_RESUME_TAG]; - } else { - [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate"] forSegment: TOOLBAR_RESUME_TAG]; - } - [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers", - "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG]; - - [groupItem createMenu: @[NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"), - NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label")]]; - - - groupItem.visibilityPriority = NSToolbarItemVisibilityPriorityHigh; - - return groupItem; - } - else if ([ident isEqualToString: TOOLBAR_FILTER]) - { - ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - ((NSButtonCell *)((NSButton *)item.view).cell).showsStateBy = NSContentsCellMask; //blue when enabled - - item.label = NSLocalizedString(@"Filter", "Filter toolbar item -> label"); - item.paletteLabel = NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label"); - item.toolTip = NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"magnifyingglass" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: @"ToolbarFilterTemplate"]; - } - item.target = self; - item.action = @selector(toggleFilterBar:); - - return item; - } - else if ([ident isEqualToString: TOOLBAR_QUICKLOOK]) - { - ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - ((NSButtonCell *)((NSButton *)item.view).cell).showsStateBy = NSContentsCellMask; //blue when enabled - - item.label = NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label"); - item.paletteLabel = NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label"); - item.toolTip = NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip"); - item.image = [NSImage imageNamed: NSImageNameQuickLookTemplate]; - item.target = self; - item.action = @selector(toggleQuickLook:); - item.visibilityPriority = NSToolbarItemVisibilityPriorityLow; - - return item; - } - else if ([ident isEqualToString: TOOLBAR_SHARE]) - { - ShareToolbarItem * item = [self toolbarButtonWithIdentifier: ident forToolbarButtonClass: [ShareToolbarItem class]]; - - item.label = NSLocalizedString(@"Share", "Share toolbar item -> label"); - item.paletteLabel = NSLocalizedString(@"Share", "Share toolbar item -> palette label"); - item.toolTip = NSLocalizedString(@"Share torrent file", "Share toolbar item -> tooltip"); - item.image = [NSImage imageNamed: NSImageNameShareTemplate]; - item.visibilityPriority = NSToolbarItemVisibilityPriorityLow; - - NSButton *itemButton = (NSButton *)item.view; - itemButton.target = self; - itemButton.action = @selector(showToolbarShare:); - [itemButton sendActionOn:NSLeftMouseDownMask]; - - return item; - } - else - return nil; -} - -- (void) allToolbarClicked: (id) sender -{ - NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]] - ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : ((NSControl *)sender).tag; - switch (tagValue) - { - case TOOLBAR_PAUSE_TAG: - [self stopAllTorrents: sender]; - break; - case TOOLBAR_RESUME_TAG: - [self resumeAllTorrents: sender]; - break; - } -} - -- (void) selectedToolbarClicked: (id) sender -{ - NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]] - ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : ((NSControl *)sender).tag; - switch (tagValue) - { - case TOOLBAR_PAUSE_TAG: - [self stopSelectedTorrents: sender]; - break; - case TOOLBAR_RESUME_TAG: - [self resumeSelectedTorrents: sender]; - break; - } -} - -- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar -{ - return @[ TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE, - TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL, - TOOLBAR_SHARE, TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, - NSToolbarSpaceItemIdentifier, - NSToolbarFlexibleSpaceItemIdentifier ]; -} - -- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar -{ - return @[ TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSpaceItemIdentifier, - TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier, - TOOLBAR_SHARE, TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO ]; -} - -- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem -{ - NSString * ident = toolbarItem.itemIdentifier; - - //enable remove item - if ([ident isEqualToString: TOOLBAR_REMOVE]) - return fTableView.numberOfSelectedRows > 0; - - //enable pause all item - if ([ident isEqualToString: TOOLBAR_PAUSE_ALL]) - { - for (Torrent * torrent in fTorrents) - if (torrent.active || torrent.waitingToStart) - return YES; - return NO; - } - - //enable resume all item - if ([ident isEqualToString: TOOLBAR_RESUME_ALL]) - { - for (Torrent * torrent in fTorrents) - if (!torrent.active && !torrent.waitingToStart && !torrent.finishedSeeding) - return YES; - return NO; - } - - //enable pause item - if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED]) - { - for (Torrent * torrent in fTableView.selectedTorrents) - if (torrent.active || torrent.waitingToStart) - return YES; - return NO; - } - - //enable resume item - if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED]) - { - for (Torrent * torrent in fTableView.selectedTorrents) - if (!torrent.active && !torrent.waitingToStart) - return YES; - return NO; - } - - //set info item - if ([ident isEqualToString: TOOLBAR_INFO]) - { - ((NSButton *)toolbarItem.view).state = fInfoController.window.visible; - return YES; - } - - //set filter item - if ([ident isEqualToString: TOOLBAR_FILTER]) - { - ((NSButton *)toolbarItem.view).state = fFilterBar != nil; - return YES; - } - - //set quick look item - if ([ident isEqualToString: TOOLBAR_QUICKLOOK]) - { - ((NSButton *)toolbarItem.view).state = [QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible; - return YES; - } - - //enable share item - if ([ident isEqualToString: TOOLBAR_SHARE]) - return fTableView.numberOfSelectedRows > 0; - - return YES; -} - -- (BOOL) validateMenuItem: (NSMenuItem *) menuItem -{ - SEL action = menuItem.action; - - if (action == @selector(toggleSpeedLimit:)) - { - menuItem.state = [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState; - return YES; - } - - //only enable some items if it is in a context menu or the window is useable - BOOL canUseTable = fWindow.keyWindow || menuItem.menu.supermenu != NSApp.mainMenu; - - //enable open items - if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:)) - return fWindow.attachedSheet == nil; - - //enable sort options - if (action == @selector(setSort:)) - { - NSString * sortType; - switch (menuItem.tag) - { - case SORT_ORDER_TAG: - sortType = SORT_ORDER; - break; - case SORT_DATE_TAG: - sortType = SORT_DATE; - break; - case SORT_NAME_TAG: - sortType = SORT_NAME; - break; - case SORT_PROGRESS_TAG: - sortType = SORT_PROGRESS; - break; - case SORT_STATE_TAG: - sortType = SORT_STATE; - break; - case SORT_TRACKER_TAG: - sortType = SORT_TRACKER; - break; - case SORT_ACTIVITY_TAG: - sortType = SORT_ACTIVITY; - break; - case SORT_SIZE_TAG: - sortType = SORT_SIZE; - break; - default: - NSAssert1(NO, @"Unknown sort tag received: %ld", [menuItem tag]); - sortType = SORT_ORDER; - } - - menuItem.state = [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState; + menuItem.state = [sortType isEqualToString:[fDefaults stringForKey:@"Sort"]] ? NSOnState : NSOffState; return fWindow.visible; } @@ -4123,12 +4751,14 @@ static void removeKeRangerRansomware() BOOL checked = NO; NSInteger index = menuItem.tag; - for (Torrent * torrent in fTableView.selectedTorrents) + for (Torrent* torrent in fTableView.selectedTorrents) + { if (index == torrent.groupValue) { checked = YES; break; } + } menuItem.state = checked ? NSOnState : NSOffState; return canUseTable && fTableView.numberOfSelectedRows > 0; @@ -4136,27 +4766,27 @@ static void removeKeRangerRansomware() if (action == @selector(toggleSmallView:)) { - menuItem.state = [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState; + menuItem.state = [fDefaults boolForKey:@"SmallView"] ? NSOnState : NSOffState; return fWindow.visible; } if (action == @selector(togglePiecesBar:)) { - menuItem.state = [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState; + menuItem.state = [fDefaults boolForKey:@"PiecesBar"] ? NSOnState : NSOffState; return fWindow.visible; } if (action == @selector(toggleAvailabilityBar:)) { - menuItem.state = [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState; + menuItem.state = [fDefaults boolForKey:@"DisplayProgressBarAvailable"] ? NSOnState : NSOffState; return fWindow.visible; } //enable show info if (action == @selector(showInfo:)) { - NSString * title = fInfoController.window.visible ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector") - : NSLocalizedString(@"Show Inspector", "View menu -> Inspector"); + NSString* title = fInfoController.window.visible ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector") : + NSLocalizedString(@"Show Inspector", "View menu -> Inspector"); menuItem.title = title; return YES; @@ -4164,13 +4794,15 @@ static void removeKeRangerRansomware() //enable prev/next inspector tab if (action == @selector(setInfoTab:)) + { return fInfoController.window.visible; + } //enable toggle status bar if (action == @selector(toggleStatusBar:)) { - NSString * title = !fStatusBar ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar") - : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar"); + NSString* title = !fStatusBar ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar") : + NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar"); menuItem.title = title; return fWindow.visible; @@ -4179,8 +4811,8 @@ static void removeKeRangerRansomware() //enable toggle filter bar if (action == @selector(toggleFilterBar:)) { - NSString * title = !fFilterBar ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar") - : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar"); + NSString* title = !fFilterBar ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar") : + NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar"); menuItem.title = title; return fWindow.visible; @@ -4188,26 +4820,32 @@ static void removeKeRangerRansomware() //enable prev/next filter button if (action == @selector(switchFilter:)) + { return fWindow.visible && fFilterBar; + } //enable reveal in finder if (action == @selector(revealFile:)) + { return canUseTable && fTableView.numberOfSelectedRows > 0; + } //enable renaming file/folder if (action == @selector(renameSelected:)) + { return canUseTable && fTableView.numberOfSelectedRows == 1; + } //enable remove items if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)) { BOOL warning = NO; - for (Torrent * torrent in fTableView.selectedTorrents) + for (Torrent* torrent in fTableView.selectedTorrents) { if (torrent.active) { - if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? !torrent.seeding : YES) + if ([fDefaults boolForKey:@"CheckRemoveDownloading"] ? !torrent.seeding : YES) { warning = YES; break; @@ -4216,16 +4854,20 @@ static void removeKeRangerRansomware() } //append or remove ellipsis when needed - NSString * title = menuItem.title, * ellipsis = NSString.ellipsis; - if (warning && [fDefaults boolForKey: @"CheckRemove"]) + NSString *title = menuItem.title, *ellipsis = NSString.ellipsis; + if (warning && [fDefaults boolForKey:@"CheckRemove"]) { - if (![title hasSuffix: ellipsis]) + if (![title hasSuffix:ellipsis]) + { menuItem.title = [title stringByAppendingEllipsis]; + } } else { - if ([title hasSuffix: ellipsis]) - menuItem.title = [title substringToIndex: [title rangeOfString: ellipsis].location]; + if ([title hasSuffix:ellipsis]) + { + menuItem.title = [title substringToIndex:[title rangeOfString:ellipsis].location]; + } } return canUseTable && fTableView.numberOfSelectedRows > 0; @@ -4235,51 +4877,73 @@ static void removeKeRangerRansomware() if (action == @selector(clearCompleted:)) { //append or remove ellipsis when needed - NSString * title = menuItem.title, * ellipsis = NSString.ellipsis; - if ([fDefaults boolForKey: @"WarningRemoveCompleted"]) + NSString *title = menuItem.title, *ellipsis = NSString.ellipsis; + if ([fDefaults boolForKey:@"WarningRemoveCompleted"]) { - if (![title hasSuffix: ellipsis]) + if (![title hasSuffix:ellipsis]) + { menuItem.title = [title stringByAppendingEllipsis]; + } } else { - if ([title hasSuffix: ellipsis]) - menuItem.title = [title substringToIndex: [title rangeOfString: ellipsis].location]; + if ([title hasSuffix:ellipsis]) + { + menuItem.title = [title substringToIndex:[title rangeOfString:ellipsis].location]; + } } - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { if (torrent.finishedSeeding) + { return YES; + } + } return NO; } //enable pause all item if (action == @selector(stopAllTorrents:)) { - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { if (torrent.active || torrent.waitingToStart) + { return YES; + } + } return NO; } //enable resume all item if (action == @selector(resumeAllTorrents:)) { - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { if (!torrent.active && !torrent.waitingToStart && !torrent.finishedSeeding) + { return YES; + } + } return NO; } //enable resume all waiting item if (action == @selector(resumeWaitingTorrents:)) { - if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"]) + if (![fDefaults boolForKey:@"Queue"] && ![fDefaults boolForKey:@"QueueSeed"]) + { return NO; + } - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { if (torrent.waitingToStart) + { return YES; + } + } return NO; } @@ -4287,11 +4951,17 @@ static void removeKeRangerRansomware() if (action == @selector(resumeSelectedTorrentsNoWait:)) { if (!canUseTable) + { return NO; + } - for (Torrent * torrent in fTableView.selectedTorrents) + for (Torrent* torrent in fTableView.selectedTorrents) + { if (!torrent.active) + { return YES; + } + } return NO; } @@ -4299,11 +4969,17 @@ static void removeKeRangerRansomware() if (action == @selector(stopSelectedTorrents:)) { if (!canUseTable) + { return NO; + } - for (Torrent * torrent in fTableView.selectedTorrents) + for (Torrent* torrent in fTableView.selectedTorrents) + { if (torrent.active || torrent.waitingToStart) + { return YES; + } + } return NO; } @@ -4311,11 +4987,17 @@ static void removeKeRangerRansomware() if (action == @selector(resumeSelectedTorrents:)) { if (!canUseTable) + { return NO; + } - for (Torrent * torrent in fTableView.selectedTorrents) + for (Torrent* torrent in fTableView.selectedTorrents) + { if (!torrent.active && !torrent.waitingToStart) + { return YES; + } + } return NO; } @@ -4323,11 +5005,17 @@ static void removeKeRangerRansomware() if (action == @selector(announceSelectedTorrents:)) { if (!canUseTable) + { return NO; + } - for (Torrent * torrent in fTableView.selectedTorrents) + for (Torrent* torrent in fTableView.selectedTorrents) + { if (torrent.canManualAnnounce) + { return YES; + } + } return NO; } @@ -4335,55 +5023,71 @@ static void removeKeRangerRansomware() if (action == @selector(verifySelectedTorrents:)) { if (!canUseTable) + { return NO; + } - for (Torrent * torrent in fTableView.selectedTorrents) + for (Torrent* torrent in fTableView.selectedTorrents) + { if (!torrent.magnet) + { return YES; + } + } return NO; } //enable move torrent file item if (action == @selector(moveDataFilesSelected:)) + { return canUseTable && fTableView.numberOfSelectedRows > 0; + } //enable copy torrent file item if (action == @selector(copyTorrentFiles:)) { if (!canUseTable) + { return NO; + } - for (Torrent * torrent in fTableView.selectedTorrents) + for (Torrent* torrent in fTableView.selectedTorrents) + { if (!torrent.magnet) + { return YES; + } + } return NO; } //enable copy torrent file item if (action == @selector(copyMagnetLinks:)) + { return canUseTable && fTableView.numberOfSelectedRows > 0; + } //enable reverse sort item if (action == @selector(setSortReverse:)) { - const BOOL isReverse = menuItem.tag == SORT_DESC_TAG; - menuItem.state = (isReverse == [fDefaults boolForKey: @"SortReverse"]) ? NSOnState : NSOffState; - return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER]; + BOOL const isReverse = menuItem.tag == SORT_DESC_TAG; + menuItem.state = (isReverse == [fDefaults boolForKey:@"SortReverse"]) ? NSOnState : NSOffState; + return ![[fDefaults stringForKey:@"Sort"] isEqualToString:SORT_ORDER]; } //enable group sort item if (action == @selector(setSortByGroup:)) { - menuItem.state = [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState; + menuItem.state = [fDefaults boolForKey:@"SortByGroup"] ? NSOnState : NSOffState; return YES; } if (action == @selector(toggleQuickLook:)) { - const BOOL visible =[QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible; + BOOL const visible = [QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible; //text consistent with Finder - NSString * title = !visible ? NSLocalizedString(@"Quick Look", "View menu -> Quick Look") - : NSLocalizedString(@"Close Quick Look", "View menu -> Quick Look"); + NSString* title = !visible ? NSLocalizedString(@"Quick Look", "View menu -> Quick Look") : + NSLocalizedString(@"Close Quick Look", "View menu -> Quick Look"); menuItem.title = title; return YES; @@ -4392,18 +5096,20 @@ static void removeKeRangerRansomware() return YES; } -- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument +- (void)sleepCallback:(natural_t)messageType argument:(void*)messageArgument { switch (messageType) { - case kIOMessageSystemWillSleep: + case kIOMessageSystemWillSleep: { //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up BOOL anyActive = NO; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) { if (torrent.active) + { anyActive = YES; + } [torrent sleep]; //have to call on all, regardless if they are active } @@ -4413,112 +5119,126 @@ static void removeKeRangerRansomware() sleep(15); } - IOAllowPowerChange(fRootPort, (long) messageArgument); + IOAllowPowerChange(fRootPort, (long)messageArgument); break; } - case kIOMessageCanSystemSleep: - if ([fDefaults boolForKey: @"SleepPrevent"]) + case kIOMessageCanSystemSleep: + if ([fDefaults boolForKey:@"SleepPrevent"]) + { + //prevent idle sleep unless no torrents are active + for (Torrent* torrent in fTorrents) { - //prevent idle sleep unless no torrents are active - for (Torrent * torrent in fTorrents) - if (torrent.active && !torrent.stalled && !torrent.error) - { - IOCancelPowerChange(fRootPort, (long) messageArgument); - return; - } + if (torrent.active && !torrent.stalled && !torrent.error) + { + IOCancelPowerChange(fRootPort, (long)messageArgument); + return; + } } + } - IOAllowPowerChange(fRootPort, (long) messageArgument); - break; + IOAllowPowerChange(fRootPort, (long)messageArgument); + break; - case kIOMessageSystemHasPoweredOn: - //resume sleeping transfers after we wake up - for (Torrent * torrent in fTorrents) - [torrent wakeUp]; - break; + case kIOMessageSystemHasPoweredOn: + //resume sleeping transfers after we wake up + for (Torrent* torrent in fTorrents) + { + [torrent wakeUp]; + } + break; } } -- (NSMenu *) applicationDockMenu: (NSApplication *) sender +- (NSMenu*)applicationDockMenu:(NSApplication*)sender { if (fQuitting) - return nil; - - NSUInteger seeding = 0, downloading = 0; - for (Torrent * torrent in fTorrents) { - if (torrent.seeding) - seeding++; - else if (torrent.active) - downloading++; - else; + return nil; } - NSMenu * menu = [[NSMenu alloc] init]; + NSUInteger seeding = 0, downloading = 0; + for (Torrent* torrent in fTorrents) + { + if (torrent.seeding) + { + seeding++; + } + else if (torrent.active) + { + downloading++; + } + } + + NSMenu* menu = [[NSMenu alloc] init]; if (seeding > 0) { - NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding]; - [menu addItemWithTitle: title action: nil keyEquivalent: @""]; + NSString* title = [NSString stringWithFormat:NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding]; + [menu addItemWithTitle:title action:nil keyEquivalent:@""]; } if (downloading > 0) { - NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading]; - [menu addItemWithTitle: title action: nil keyEquivalent: @""]; + NSString* title = [NSString stringWithFormat:NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading]; + [menu addItemWithTitle:title action:nil keyEquivalent:@""]; } if (seeding > 0 || downloading > 0) - [menu addItem: [NSMenuItem separatorItem]]; + { + [menu addItem:[NSMenuItem separatorItem]]; + } - [menu addItemWithTitle: NSLocalizedString(@"Pause All", "Dock item") action: @selector(stopAllTorrents:) keyEquivalent: @""]; - [menu addItemWithTitle: NSLocalizedString(@"Resume All", "Dock item") action: @selector(resumeAllTorrents:) keyEquivalent: @""]; - [menu addItem: [NSMenuItem separatorItem]]; - [menu addItemWithTitle: NSLocalizedString(@"Speed Limit", "Dock item") action: @selector(toggleSpeedLimit:) keyEquivalent: @""]; + [menu addItemWithTitle:NSLocalizedString(@"Pause All", "Dock item") action:@selector(stopAllTorrents:) keyEquivalent:@""]; + [menu addItemWithTitle:NSLocalizedString(@"Resume All", "Dock item") action:@selector(resumeAllTorrents:) keyEquivalent:@""]; + [menu addItem:[NSMenuItem separatorItem]]; + [menu addItemWithTitle:NSLocalizedString(@"Speed Limit", "Dock item") action:@selector(toggleSpeedLimit:) keyEquivalent:@""]; return menu; } -- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame +- (NSRect)windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)defaultFrame { //if auto size is enabled, the current frame shouldn't need to change - NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? window.frame : self.sizedWindowFrame; + NSRect frame = [fDefaults boolForKey:@"AutoSize"] ? window.frame : self.sizedWindowFrame; - frame.size.width = [fDefaults boolForKey: @"SmallView"] ? fWindow.minSize.width : WINDOW_REGULAR_WIDTH; + frame.size.width = [fDefaults boolForKey:@"SmallView"] ? fWindow.minSize.width : WINDOW_REGULAR_WIDTH; return frame; } -- (void) setWindowSizeToFit +- (void)setWindowSizeToFit { - if ([fDefaults boolForKey: @"AutoSize"]) + if ([fDefaults boolForKey:@"AutoSize"]) { - NSScrollView * scrollView = fTableView.enclosingScrollView; + NSScrollView* scrollView = fTableView.enclosingScrollView; scrollView.hasVerticalScroller = NO; - [fWindow setFrame: self.sizedWindowFrame display: YES animate: YES]; + [fWindow setFrame:self.sizedWindowFrame display:YES animate:YES]; scrollView.hasVerticalScroller = YES; [self setWindowMinMaxToCurrent]; } } -- (NSRect) sizedWindowFrame +- (NSRect)sizedWindowFrame { - NSUInteger groups = (fDisplayedTorrents.count > 0 && ![fDisplayedTorrents[0] isKindOfClass: [Torrent class]]) - ? fDisplayedTorrents.count : 0; + NSUInteger groups = (fDisplayedTorrents.count > 0 && ![fDisplayedTorrents[0] isKindOfClass:[Torrent class]]) ? + fDisplayedTorrents.count : + 0; - CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + fTableView.intercellSpacing.height) * groups - + (fTableView.rowHeight + fTableView.intercellSpacing.height) * (fTableView.numberOfRows - groups) - - NSHeight(fTableView.enclosingScrollView.frame); + CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + fTableView.intercellSpacing.height) * groups + + (fTableView.rowHeight + fTableView.intercellSpacing.height) * (fTableView.numberOfRows - groups) - + NSHeight(fTableView.enclosingScrollView.frame); - return [self windowFrameByAddingHeight: heightChange checkLimits: YES]; + return [self windowFrameByAddingHeight:heightChange checkLimits:YES]; } -- (void) updateForAutoSize +- (void)updateForAutoSize { - if ([fDefaults boolForKey: @"AutoSize"]) + if ([fDefaults boolForKey:@"AutoSize"]) + { [self setWindowSizeToFit]; + } else { NSSize contentMinSize = fWindow.contentMinSize; @@ -4532,12 +5252,11 @@ static void removeKeRangerRansomware() } } -- (void) setWindowMinMaxToCurrent +- (void)setWindowMinMaxToCurrent { - const CGFloat height = NSHeight(fWindow.contentView.frame); + CGFloat const height = NSHeight(fWindow.contentView.frame); - NSSize minSize = fWindow.contentMinSize, - maxSize = fWindow.contentMaxSize; + NSSize minSize = fWindow.contentMinSize, maxSize = fWindow.contentMaxSize; minSize.height = height; maxSize.height = height; @@ -4545,83 +5264,88 @@ static void removeKeRangerRansomware() fWindow.contentMaxSize = maxSize; } -- (CGFloat) minWindowContentSizeAllowed +- (CGFloat)minWindowContentSizeAllowed { - CGFloat contentMinHeight = NSHeight(fWindow.contentView.frame) - NSHeight(fTableView.enclosingScrollView.frame) - + fTableView.rowHeight + fTableView.intercellSpacing.height; + CGFloat contentMinHeight = NSHeight(fWindow.contentView.frame) - NSHeight(fTableView.enclosingScrollView.frame) + + fTableView.rowHeight + fTableView.intercellSpacing.height; return contentMinHeight; } -- (void) updateForExpandCollape +- (void)updateForExpandCollape { [self setWindowSizeToFit]; - [self setBottomCountText: YES]; + [self setBottomCountText:YES]; } -- (void) showMainWindow: (id) sender +- (void)showMainWindow:(id)sender { - [fWindow makeKeyAndOrderFront: nil]; + [fWindow makeKeyAndOrderFront:nil]; } -- (void) windowDidBecomeMain: (NSNotification *) notification +- (void)windowDidBecomeMain:(NSNotification*)notification { [fBadger clearCompleted]; [self updateUI]; } -- (void) applicationWillUnhide: (NSNotification *) notification +- (void)applicationWillUnhide:(NSNotification*)notification { [self updateUI]; } -- (void) toggleQuickLook: (id) sender +- (void)toggleQuickLook:(id)sender { if ([QLPreviewPanel sharedPreviewPanel].visible) - [[QLPreviewPanel sharedPreviewPanel] orderOut: nil]; + { + [[QLPreviewPanel sharedPreviewPanel] orderOut:nil]; + } else - [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront: nil]; + { + [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; + } } -- (void) linkHomepage: (id) sender +- (void)linkHomepage:(id)sender { - [NSWorkspace.sharedWorkspace openURL: [NSURL URLWithString: WEBSITE_URL]]; + [NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:WEBSITE_URL]]; } -- (void) linkForums: (id) sender +- (void)linkForums:(id)sender { - [NSWorkspace.sharedWorkspace openURL: [NSURL URLWithString: FORUM_URL]]; + [NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:FORUM_URL]]; } -- (void) linkGitHub: (id) sender +- (void)linkGitHub:(id)sender { - [NSWorkspace.sharedWorkspace openURL: [NSURL URLWithString: GITHUB_URL]]; + [NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:GITHUB_URL]]; } -- (void) linkDonate: (id) sender +- (void)linkDonate:(id)sender { - [NSWorkspace.sharedWorkspace openURL: [NSURL URLWithString: DONATE_URL]]; + [NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:DONATE_URL]]; } -- (void) updaterWillRelaunchApplication: (SUUpdater *) updater +- (void)updaterWillRelaunchApplication:(SUUpdater*)updater { fQuitRequested = YES; } -- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct +- (void)rpcCallback:(tr_rpc_callback_type)type forTorrentStruct:(struct tr_torrent*)torrentStruct { @autoreleasepool { //get the torrent - __block Torrent * torrent = nil; + __block Torrent* torrent = nil; if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED && type != TR_RPC_SESSION_CLOSE)) { - [fTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(Torrent * checkTorrent, NSUInteger idx, BOOL *stop) { - if (torrentStruct == checkTorrent.torrentStruct) - { - torrent = checkTorrent; - *stop = YES; - } - }]; + [fTorrents enumerateObjectsWithOptions:NSEnumerationConcurrent + usingBlock:^(Torrent* checkTorrent, NSUInteger idx, BOOL* stop) { + if (torrentStruct == checkTorrent.torrentStruct) + { + torrent = checkTorrent; + *stop = YES; + } + }]; if (!torrent) { @@ -4633,82 +5357,86 @@ static void removeKeRangerRansomware() dispatch_async(dispatch_get_main_queue(), ^{ switch (type) { - case TR_RPC_TORRENT_ADDED: - [self rpcAddTorrentStruct: torrentStruct]; - break; + case TR_RPC_TORRENT_ADDED: + [self rpcAddTorrentStruct:torrentStruct]; + break; - case TR_RPC_TORRENT_STARTED: - case TR_RPC_TORRENT_STOPPED: - [self rpcStartedStoppedTorrent: torrent]; - break; + case TR_RPC_TORRENT_STARTED: + case TR_RPC_TORRENT_STOPPED: + [self rpcStartedStoppedTorrent:torrent]; + break; - case TR_RPC_TORRENT_REMOVING: - [self rpcRemoveTorrent: torrent deleteData: NO]; - break; + case TR_RPC_TORRENT_REMOVING: + [self rpcRemoveTorrent:torrent deleteData:NO]; + break; - case TR_RPC_TORRENT_TRASHING: - [self rpcRemoveTorrent: torrent deleteData: YES]; - break; + case TR_RPC_TORRENT_TRASHING: + [self rpcRemoveTorrent:torrent deleteData:YES]; + break; - case TR_RPC_TORRENT_CHANGED: - [self rpcChangedTorrent: torrent]; - break; + case TR_RPC_TORRENT_CHANGED: + [self rpcChangedTorrent:torrent]; + break; - case TR_RPC_TORRENT_MOVED: - [self rpcMovedTorrent: torrent]; - break; + case TR_RPC_TORRENT_MOVED: + [self rpcMovedTorrent:torrent]; + break; - case TR_RPC_SESSION_QUEUE_POSITIONS_CHANGED: - [self rpcUpdateQueue]; - break; + case TR_RPC_SESSION_QUEUE_POSITIONS_CHANGED: + [self rpcUpdateQueue]; + break; - case TR_RPC_SESSION_CHANGED: - [_prefsController rpcUpdatePrefs]; - break; + case TR_RPC_SESSION_CHANGED: + [_prefsController rpcUpdatePrefs]; + break; - case TR_RPC_SESSION_CLOSE: - fQuitRequested = YES; - [NSApp terminate: self]; - break; + case TR_RPC_SESSION_CLOSE: + fQuitRequested = YES; + [NSApp terminate:self]; + break; - default: - NSAssert1(NO, @"Unknown RPC command received: %d", type); + default: + NSAssert1(NO, @"Unknown RPC command received: %d", type); } }); } } -- (void) rpcAddTorrentStruct: (struct tr_torrent *) torrentStruct +- (void)rpcAddTorrentStruct:(struct tr_torrent*)torrentStruct { - NSString * location = nil; + NSString* location = nil; if (tr_torrentGetDownloadDir(torrentStruct) != NULL) + { location = @(tr_torrentGetDownloadDir(torrentStruct)); + } - Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib]; + Torrent* torrent = [[Torrent alloc] initWithTorrentStruct:torrentStruct location:location lib:fLib]; //change the location if the group calls for it (this has to wait until after the torrent is created) - if ([GroupsController.groups usesCustomDownloadLocationForIndex: torrent.groupValue]) + if ([GroupsController.groups usesCustomDownloadLocationForIndex:torrent.groupValue]) { - location = [GroupsController.groups customDownloadLocationForIndex: torrent.groupValue]; - [torrent changeDownloadFolderBeforeUsing: location determinationType: TorrentDeterminationAutomatic]; + location = [GroupsController.groups customDownloadLocationForIndex:torrent.groupValue]; + [torrent changeDownloadFolderBeforeUsing:location determinationType:TorrentDeterminationAutomatic]; } [torrent update]; - [fTorrents addObject: torrent]; + [fTorrents addObject:torrent]; if (!fAddingTransfers) + { fAddingTransfers = [[NSMutableSet alloc] init]; - [fAddingTransfers addObject: torrent]; + } + [fAddingTransfers addObject:torrent]; [self fullUpdateUI]; } -- (void) rpcRemoveTorrent: (Torrent *) torrent deleteData: (BOOL) deleteData +- (void)rpcRemoveTorrent:(Torrent*)torrent deleteData:(BOOL)deleteData { - [self confirmRemoveTorrents: @[ torrent ] deleteData: deleteData]; + [self confirmRemoveTorrents:@[ torrent ] deleteData:deleteData]; } -- (void) rpcStartedStoppedTorrent: (Torrent *) torrent +- (void)rpcStartedStoppedTorrent:(Torrent*)torrent { [torrent update]; @@ -4717,36 +5445,40 @@ static void removeKeRangerRansomware() [self updateTorrentHistory]; } -- (void) rpcChangedTorrent: (Torrent *) torrent +- (void)rpcChangedTorrent:(Torrent*)torrent { [torrent update]; - if ([fTableView.selectedTorrents containsObject: torrent]) + if ([fTableView.selectedTorrents containsObject:torrent]) { [fInfoController updateInfoStats]; //this will reload the file table [fInfoController updateOptions]; } } -- (void) rpcMovedTorrent: (Torrent *) torrent +- (void)rpcMovedTorrent:(Torrent*)torrent { [torrent update]; [torrent updateTimeMachineExclude]; - if ([fTableView.selectedTorrents containsObject: torrent]) + if ([fTableView.selectedTorrents containsObject:torrent]) + { [fInfoController updateInfoStats]; + } } -- (void) rpcUpdateQueue +- (void)rpcUpdateQueue { - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { [torrent update]; + } - NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey: @"queuePosition" ascending: YES]; - NSArray * descriptors = @[descriptor]; - [fTorrents sortUsingDescriptors: descriptors]; + NSSortDescriptor* descriptor = [NSSortDescriptor sortDescriptorWithKey:@"queuePosition" ascending:YES]; + NSArray* descriptors = @[ descriptor ]; + [fTorrents sortUsingDescriptors:descriptors]; - [self sortTorrents: YES]; + [self sortTorrents:YES]; } @end diff --git a/macosx/CreatorWindowController.h b/macosx/CreatorWindowController.h index 90e8a52ae..bf48654a5 100644 --- a/macosx/CreatorWindowController.h +++ b/macosx/CreatorWindowController.h @@ -27,39 +27,45 @@ @interface CreatorWindowController : NSWindowController { - IBOutlet NSImageView * fIconView; - IBOutlet NSTextField * fNameField, * fStatusField, * fPiecesField, * fLocationField; - IBOutlet NSTableView * fTrackerTable; - IBOutlet NSSegmentedControl * fTrackerAddRemoveControl; - IBOutlet NSTextView * fCommentView; - IBOutlet NSButton * fPrivateCheck, * fOpenCheck; + IBOutlet NSImageView* fIconView; + IBOutlet NSTextField* fNameField; + IBOutlet NSTextField* fStatusField; + IBOutlet NSTextField* fPiecesField; + IBOutlet NSTextField* fLocationField; + IBOutlet NSTableView* fTrackerTable; + IBOutlet NSSegmentedControl* fTrackerAddRemoveControl; + IBOutlet NSTextView* fCommentView; + IBOutlet NSButton* fPrivateCheck; + IBOutlet NSButton* fOpenCheck; - IBOutlet NSView * fProgressView; - IBOutlet NSProgressIndicator * fProgressIndicator; + IBOutlet NSView* fProgressView; + IBOutlet NSProgressIndicator* fProgressIndicator; - tr_metainfo_builder * fInfo; - NSURL * fPath, * fLocation; - NSMutableArray * fTrackers; + tr_metainfo_builder* fInfo; + NSURL* fPath; + NSURL* fLocation; + NSMutableArray* fTrackers; - NSTimer * fTimer; - BOOL fStarted, fOpenWhenCreated; + NSTimer* fTimer; + BOOL fStarted; + BOOL fOpenWhenCreated; - NSUserDefaults * fDefaults; + NSUserDefaults* fDefaults; } -+ (CreatorWindowController *) createTorrentFile: (tr_session *) handle; -+ (CreatorWindowController *) createTorrentFile: (tr_session *) handle forFile: (NSURL *) file; ++ (CreatorWindowController*)createTorrentFile:(tr_session*)handle; ++ (CreatorWindowController*)createTorrentFile:(tr_session*)handle forFile:(NSURL*)file; -- (instancetype) initWithHandle: (tr_session *) handle path: (NSURL *) path; +- (instancetype)initWithHandle:(tr_session*)handle path:(NSURL*)path; -- (IBAction) setLocation: (id) sender; -- (IBAction) create: (id) sender; -- (IBAction) cancelCreateWindow: (id) sender; -- (IBAction) cancelCreateProgress: (id) sender; +- (IBAction)setLocation:(id)sender; +- (IBAction)create:(id)sender; +- (IBAction)cancelCreateWindow:(id)sender; +- (IBAction)cancelCreateProgress:(id)sender; -- (IBAction) addRemoveTracker: (id) sender; +- (IBAction)addRemoveTracker:(id)sender; -- (void) copy: (id) sender; -- (void) paste: (id) sender; +- (void)copy:(id)sender; +- (void)paste:(id)sender; @end diff --git a/macosx/CreatorWindowController.m b/macosx/CreatorWindowController.m index 8e5773d90..3b5105dcc 100644 --- a/macosx/CreatorWindowController.m +++ b/macosx/CreatorWindowController.m @@ -33,44 +33,48 @@ @interface CreatorWindowController (Private) -+ (NSURL *) chooseFile; ++ (NSURL*)chooseFile; -- (void) updateLocationField; -- (void) createReal; -- (void) checkProgress; +- (void)updateLocationField; +- (void)createReal; +- (void)checkProgress; @end -NSMutableSet *creatorWindowControllerSet = nil; +NSMutableSet* creatorWindowControllerSet = nil; + @implementation CreatorWindowController -+ (CreatorWindowController *) createTorrentFile: (tr_session *) handle ++ (CreatorWindowController*)createTorrentFile:(tr_session*)handle { //get file/folder for torrent - NSURL * path; + NSURL* path; if (!(path = [CreatorWindowController chooseFile])) - return nil; - - CreatorWindowController * creator = [[self alloc] initWithHandle: handle path: path]; - [creator showWindow: nil]; - return creator; -} - -+ (CreatorWindowController *) createTorrentFile: (tr_session *) handle forFile: (NSURL *) file -{ - CreatorWindowController * creator = [[self alloc] initWithHandle: handle path: file]; - [creator showWindow: nil]; - return creator; -} - -- (instancetype) initWithHandle: (tr_session *) handle path: (NSURL *) path -{ - if ((self = [super initWithWindowNibName: @"Creator"])) { - if (!creatorWindowControllerSet) { + return nil; + } + + CreatorWindowController* creator = [[self alloc] initWithHandle:handle path:path]; + [creator showWindow:nil]; + return creator; +} + ++ (CreatorWindowController*)createTorrentFile:(tr_session*)handle forFile:(NSURL*)file +{ + CreatorWindowController* creator = [[self alloc] initWithHandle:handle path:file]; + [creator showWindow:nil]; + return creator; +} + +- (instancetype)initWithHandle:(tr_session*)handle path:(NSURL*)path +{ + if ((self = [super initWithWindowNibName:@"Creator"])) + { + if (!creatorWindowControllerSet) + { creatorWindowControllerSet = [NSMutableSet set]; } - + fStarted = NO; fPath = path; @@ -78,11 +82,11 @@ NSMutableSet *creatorWindowControllerSet = nil; if (fInfo->fileCount == 0) { - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> no files -> button")]; - alert.messageText = NSLocalizedString(@"This folder contains no files.", - "Create torrent -> no files -> title"); - alert.informativeText = NSLocalizedString(@"There must be at least one file in a folder to create a torrent file.", + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Create torrent -> no files -> button")]; + alert.messageText = NSLocalizedString(@"This folder contains no files.", "Create torrent -> no files -> title"); + alert.informativeText = NSLocalizedString( + @"There must be at least one file in a folder to create a torrent file.", "Create torrent -> no files -> warning"); alert.alertStyle = NSWarningAlertStyle; @@ -92,12 +96,10 @@ NSMutableSet *creatorWindowControllerSet = nil; } if (fInfo->totalSize == 0) { - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> zero size -> button")]; - alert.messageText = NSLocalizedString(@"The total file size is zero bytes.", - "Create torrent -> zero size -> title"); - alert.informativeText = NSLocalizedString(@"A torrent file cannot be created for files with no size.", - "Create torrent -> zero size -> warning"); + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Create torrent -> zero size -> button")]; + alert.messageText = NSLocalizedString(@"The total file size is zero bytes.", "Create torrent -> zero size -> title"); + alert.informativeText = NSLocalizedString(@"A torrent file cannot be created for files with no size.", "Create torrent -> zero size -> warning"); alert.alertStyle = NSWarningAlertStyle; [alert runModal]; @@ -108,150 +110,167 @@ NSMutableSet *creatorWindowControllerSet = nil; fDefaults = NSUserDefaults.standardUserDefaults; //get list of trackers - if (!(fTrackers = [[fDefaults arrayForKey: @"CreatorTrackers"] mutableCopy])) + if (!(fTrackers = [[fDefaults arrayForKey:@"CreatorTrackers"] mutableCopy])) { fTrackers = [[NSMutableArray alloc] init]; //check for single tracker from versions before 1.3 - NSString * tracker; - if ((tracker = [fDefaults stringForKey: @"CreatorTracker"])) + NSString* tracker; + if ((tracker = [fDefaults stringForKey:@"CreatorTracker"])) { - [fDefaults removeObjectForKey: @"CreatorTracker"]; - if (![tracker isEqualToString: @""]) + [fDefaults removeObjectForKey:@"CreatorTracker"]; + if (![tracker isEqualToString:@""]) { - [fTrackers addObject: tracker]; - [fDefaults setObject: fTrackers forKey: @"CreatorTrackers"]; + [fTrackers addObject:tracker]; + [fDefaults setObject:fTrackers forKey:@"CreatorTrackers"]; } } } //remove potentially invalid addresses - for (NSInteger i = fTrackers.count-1; i >= 0; i--) + for (NSInteger i = fTrackers.count - 1; i >= 0; i--) { if (!tr_urlIsValidTracker([fTrackers[i] UTF8String])) - [fTrackers removeObjectAtIndex: i]; + { + [fTrackers removeObjectAtIndex:i]; + } } - + [creatorWindowControllerSet addObject:self]; } return self; } -- (void) awakeFromNib +- (void)awakeFromNib { self.window.restorationClass = [self class]; - NSString * name = fPath.lastPathComponent; + NSString* name = fPath.lastPathComponent; self.window.title = name; fNameField.stringValue = name; fNameField.toolTip = fPath.path; - const BOOL multifile = fInfo->isFolder; + BOOL const multifile = fInfo->isFolder; - NSImage * icon = [NSWorkspace.sharedWorkspace iconForFileType: multifile - ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) : fPath.pathExtension]; + NSImage* icon = [NSWorkspace.sharedWorkspace + iconForFileType:multifile ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) : fPath.pathExtension]; icon.size = fIconView.frame.size; fIconView.image = icon; - NSString * statusString = [NSString stringForFileSize: fInfo->totalSize]; + NSString* statusString = [NSString stringForFileSize:fInfo->totalSize]; if (multifile) { - NSString * fileString; + NSString* fileString; NSInteger count = fInfo->fileCount; if (count != 1) - fileString = [NSString stringWithFormat: NSLocalizedString(@"%@ files", "Create torrent -> info"), - [NSString formattedUInteger: count]]; + { + fileString = [NSString + stringWithFormat:NSLocalizedString(@"%@ files", "Create torrent -> info"), [NSString formattedUInteger:count]]; + } else + { fileString = NSLocalizedString(@"1 file", "Create torrent -> info"); - statusString = [NSString stringWithFormat: @"%@, %@", fileString, statusString]; + } + statusString = [NSString stringWithFormat:@"%@, %@", fileString, statusString]; } fStatusField.stringValue = statusString; if (fInfo->pieceCount == 1) - fPiecesField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"1 piece, %@", "Create torrent -> info"), - [NSString stringForFileSize: fInfo->pieceSize]]; + { + fPiecesField.stringValue = [NSString stringWithFormat:NSLocalizedString(@"1 piece, %@", "Create torrent -> info"), + [NSString stringForFileSize:fInfo->pieceSize]]; + } else - fPiecesField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"%d pieces, %@ each", "Create torrent -> info"), - fInfo->pieceCount, [NSString stringForFileSize: fInfo->pieceSize]]; + { + fPiecesField.stringValue = [NSString stringWithFormat:NSLocalizedString(@"%d pieces, %@ each", "Create torrent -> info"), + fInfo->pieceCount, + [NSString stringForFileSize:fInfo->pieceSize]]; + } - fLocation = [[fDefaults URLForKey: @"CreatorLocationURL"] URLByAppendingPathComponent: [name stringByAppendingPathExtension: @"torrent"]]; + fLocation = [[fDefaults URLForKey:@"CreatorLocationURL"] URLByAppendingPathComponent:[name stringByAppendingPathExtension:@"torrent"]]; if (!fLocation) { //for 2.5 and earlier - #warning we still store "CreatorLocation" in Defaults.plist, and not "CreatorLocationURL" - NSString * location = [fDefaults stringForKey: @"CreatorLocation"]; - fLocation = [[NSURL alloc] initFileURLWithPath: [location.stringByExpandingTildeInPath stringByAppendingPathComponent: [name stringByAppendingPathExtension: @"torrent"]]]; +#warning we still store "CreatorLocation" in Defaults.plist, and not "CreatorLocationURL" + NSString* location = [fDefaults stringForKey:@"CreatorLocation"]; + fLocation = [[NSURL alloc] initFileURLWithPath:[location.stringByExpandingTildeInPath + stringByAppendingPathComponent:[name stringByAppendingPathExtension:@"torrent"]]]; } [self updateLocationField]; //set previously saved values - if ([fDefaults objectForKey: @"CreatorPrivate"]) - fPrivateCheck.state = [fDefaults boolForKey: @"CreatorPrivate"] ? NSOnState : NSOffState; + if ([fDefaults objectForKey:@"CreatorPrivate"]) + { + fPrivateCheck.state = [fDefaults boolForKey:@"CreatorPrivate"] ? NSOnState : NSOffState; + } - fOpenCheck.state = [fDefaults boolForKey: @"CreatorOpen"] ? NSOnState : NSOffState; + fOpenCheck.state = [fDefaults boolForKey:@"CreatorOpen"] ? NSOnState : NSOffState; } -- (void) dealloc +- (void)dealloc { if (fInfo) + { tr_metaInfoBuilderFree(fInfo); + } [fTimer invalidate]; } -+ (void) restoreWindowWithIdentifier: (NSString *) identifier state: (NSCoder *) state completionHandler: (void (^)(NSWindow *, NSError *)) completionHandler ++ (void)restoreWindowWithIdentifier:(NSString*)identifier + state:(NSCoder*)state + completionHandler:(void (^)(NSWindow*, NSError*))completionHandler { - NSURL * path = [state decodeObjectForKey: @"TRCreatorPath"]; - if (!path || ![path checkResourceIsReachableAndReturnError: nil]) + NSURL* path = [state decodeObjectForKey:@"TRCreatorPath"]; + if (!path || ![path checkResourceIsReachableAndReturnError:nil]) { - completionHandler(nil, [NSError errorWithDomain: NSURLErrorDomain code: NSURLErrorCannotOpenFile userInfo: nil]); + completionHandler(nil, [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotOpenFile userInfo:nil]); return; } - NSWindow * window = [self createTorrentFile: ((Controller *)NSApp.delegate).sessionHandle forFile: path].window; + NSWindow* window = [self createTorrentFile:((Controller*)NSApp.delegate).sessionHandle forFile:path].window; completionHandler(window, nil); } -- (void) window: (NSWindow *) window willEncodeRestorableState: (NSCoder *) state +- (void)window:(NSWindow*)window willEncodeRestorableState:(NSCoder*)state { - [state encodeObject: fPath forKey: @"TRCreatorPath"]; - [state encodeObject: fLocation forKey: @"TRCreatorLocation"]; - [state encodeObject: fTrackers forKey: @"TRCreatorTrackers"]; - [state encodeInteger: fOpenCheck.state forKey: @"TRCreatorOpenCheck"]; - [state encodeInteger: fPrivateCheck.state forKey: @"TRCreatorPrivateCheck"]; - [state encodeObject: fCommentView.string forKey: @"TRCreatorPrivateComment"]; + [state encodeObject:fPath forKey:@"TRCreatorPath"]; + [state encodeObject:fLocation forKey:@"TRCreatorLocation"]; + [state encodeObject:fTrackers forKey:@"TRCreatorTrackers"]; + [state encodeInteger:fOpenCheck.state forKey:@"TRCreatorOpenCheck"]; + [state encodeInteger:fPrivateCheck.state forKey:@"TRCreatorPrivateCheck"]; + [state encodeObject:fCommentView.string forKey:@"TRCreatorPrivateComment"]; } -- (void) window: (NSWindow *) window didDecodeRestorableState: (NSCoder *) coder +- (void)window:(NSWindow*)window didDecodeRestorableState:(NSCoder*)coder { - fLocation = [coder decodeObjectForKey: @"TRCreatorLocation"]; + fLocation = [coder decodeObjectForKey:@"TRCreatorLocation"]; [self updateLocationField]; - fTrackers = [coder decodeObjectForKey: @"TRCreatorTrackers"]; + fTrackers = [coder decodeObjectForKey:@"TRCreatorTrackers"]; [fTrackerTable reloadData]; - fOpenCheck.state = [coder decodeIntegerForKey: @"TRCreatorOpenCheck"]; - fPrivateCheck.state = [coder decodeIntegerForKey: @"TRCreatorPrivateCheck"]; - fCommentView.string = [coder decodeObjectForKey: @"TRCreatorPrivateComment"]; + fOpenCheck.state = [coder decodeIntegerForKey:@"TRCreatorOpenCheck"]; + fPrivateCheck.state = [coder decodeIntegerForKey:@"TRCreatorPrivateCheck"]; + fCommentView.string = [coder decodeObjectForKey:@"TRCreatorPrivateComment"]; } -- (IBAction) setLocation: (id) sender +- (IBAction)setLocation:(id)sender { - NSSavePanel * panel = [NSSavePanel savePanel]; + NSSavePanel* panel = [NSSavePanel savePanel]; panel.prompt = NSLocalizedString(@"Select", "Create torrent -> location sheet -> button"); - panel.message = NSLocalizedString(@"Select the name and location for the torrent file.", - "Create torrent -> location sheet -> message"); + panel.message = NSLocalizedString(@"Select the name and location for the torrent file.", "Create torrent -> location sheet -> message"); - panel.allowedFileTypes = @[@"org.bittorrent.torrent", @"torrent"]; + panel.allowedFileTypes = @[ @"org.bittorrent.torrent", @"torrent" ]; panel.canSelectHiddenExtension = YES; panel.directoryURL = fLocation.URLByDeletingLastPathComponent; panel.nameFieldStringValue = fLocation.lastPathComponent; - [panel beginSheetModalForWindow: self.window completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) { fLocation = panel.URL; @@ -260,201 +279,229 @@ NSMutableSet *creatorWindowControllerSet = nil; }]; } -- (IBAction) create: (id) sender +- (IBAction)create:(id)sender { //make sure the trackers are no longer being verified if (fTrackerTable.editedRow != -1) - [self.window endEditingFor: fTrackerTable]; - - const BOOL isPrivate = fPrivateCheck.state == NSOnState; - if (fTrackers.count == 0 - && [fDefaults boolForKey: isPrivate ? @"WarningCreatorPrivateBlankAddress" : @"WarningCreatorBlankAddress"]) { - NSAlert * alert = [[NSAlert alloc] init]; + [self.window endEditingFor:fTrackerTable]; + } + + BOOL const isPrivate = fPrivateCheck.state == NSOnState; + if (fTrackers.count == 0 && [fDefaults boolForKey:isPrivate ? @"WarningCreatorPrivateBlankAddress" : @"WarningCreatorBlankAddress"]) + { + NSAlert* alert = [[NSAlert alloc] init]; alert.messageText = NSLocalizedString(@"There are no tracker addresses.", "Create torrent -> blank address -> title"); - NSString * infoString = isPrivate - ? NSLocalizedString(@"A transfer marked as private with no tracker addresses will be unable to connect to peers." - " The torrent file will only be useful if you plan to upload the file to a tracker website" - " that will add the addresses for you.", "Create torrent -> blank address -> message") - : NSLocalizedString(@"The transfer will not contact trackers for peers, and will have to rely solely on" - " non-tracker peer discovery methods such as PEX and DHT to download and seed.", - "Create torrent -> blank address -> message"); + NSString* infoString = isPrivate ? + NSLocalizedString( + @"A transfer marked as private with no tracker addresses will be unable to connect to peers." + " The torrent file will only be useful if you plan to upload the file to a tracker website" + " that will add the addresses for you.", + "Create torrent -> blank address -> message") : + NSLocalizedString( + @"The transfer will not contact trackers for peers, and will have to rely solely on" + " non-tracker peer discovery methods such as PEX and DHT to download and seed.", + "Create torrent -> blank address -> message"); alert.informativeText = infoString; - [alert addButtonWithTitle: NSLocalizedString(@"Create", "Create torrent -> blank address -> button")]; - [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Create torrent -> blank address -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Create", "Create torrent -> blank address -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Cancel", "Create torrent -> blank address -> button")]; alert.showsSuppressionButton = YES; [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { if (alert.suppressionButton.state == NSOnState) { - [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningCreatorBlankAddress"]; //set regardless of private/public + [NSUserDefaults.standardUserDefaults setBool:NO forKey:@"WarningCreatorBlankAddress"]; //set regardless of private/public if (fPrivateCheck.state == NSOnState) - [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningCreatorPrivateBlankAddress"]; + { + [NSUserDefaults.standardUserDefaults setBool:NO forKey:@"WarningCreatorPrivateBlankAddress"]; + } } if (returnCode == NSAlertFirstButtonReturn) - [self performSelectorOnMainThread: @selector(createReal) withObject: nil waitUntilDone: NO]; + { + [self performSelectorOnMainThread:@selector(createReal) withObject:nil waitUntilDone:NO]; + } }]; } else + { [self createReal]; + } } -- (IBAction) cancelCreateWindow: (id) sender +- (IBAction)cancelCreateWindow:(id)sender { [self.window close]; } -- (void) windowWillClose: (NSNotification *) notification +- (void)windowWillClose:(NSNotification*)notification { [creatorWindowControllerSet removeObject:self]; } -- (IBAction) cancelCreateProgress: (id) sender +- (IBAction)cancelCreateProgress:(id)sender { fInfo->abortFlag = 1; [fTimer fire]; } -- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView +- (NSInteger)numberOfRowsInTableView:(NSTableView*)tableView { return fTrackers.count; } -- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row +- (id)tableView:(NSTableView*)tableView objectValueForTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row { return fTrackers[row]; } -- (IBAction) addRemoveTracker: (id) sender +- (IBAction)addRemoveTracker:(id)sender { //don't allow add/remove when currently adding - it leads to weird results if (fTrackerTable.editedRow != -1) - return; - - if ([[sender cell] tagForSegment: [sender selectedSegment]] == TRACKER_REMOVE_TAG) { - [fTrackers removeObjectsAtIndexes: fTrackerTable.selectedRowIndexes]; + return; + } - [fTrackerTable deselectAll: self]; + if ([[sender cell] tagForSegment:[sender selectedSegment]] == TRACKER_REMOVE_TAG) + { + [fTrackers removeObjectsAtIndexes:fTrackerTable.selectedRowIndexes]; + + [fTrackerTable deselectAll:self]; [fTrackerTable reloadData]; } else { - [fTrackers addObject: @""]; + [fTrackers addObject:@""]; [fTrackerTable reloadData]; - const NSInteger row = fTrackers.count - 1; - [fTrackerTable selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; - [fTrackerTable editColumn: 0 row: row withEvent: nil select: YES]; + NSInteger const row = fTrackers.count - 1; + [fTrackerTable selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO]; + [fTrackerTable editColumn:0 row:row withEvent:nil select:YES]; } } -- (void) tableView: (NSTableView *) tableView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn - row: (NSInteger) row +- (void)tableView:(NSTableView*)tableView + setObjectValue:(id)object + forTableColumn:(NSTableColumn*)tableColumn + row:(NSInteger)row { - NSString * tracker = (NSString *)object; + NSString* tracker = (NSString*)object; - tracker = [tracker stringByTrimmingCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; + tracker = [tracker stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; - if ([tracker rangeOfString: @"://"].location == NSNotFound) - tracker = [@"http://" stringByAppendingString: tracker]; + if ([tracker rangeOfString:@"://"].location == NSNotFound) + { + tracker = [@"http://" stringByAppendingString:tracker]; + } if (!tr_urlIsValidTracker(tracker.UTF8String)) { NSBeep(); - [fTrackers removeObjectAtIndex: row]; + [fTrackers removeObjectAtIndex:row]; } else + { fTrackers[row] = tracker; + } - [fTrackerTable deselectAll: self]; + [fTrackerTable deselectAll:self]; [fTrackerTable reloadData]; } -- (void) tableViewSelectionDidChange: (NSNotification *) notification +- (void)tableViewSelectionDidChange:(NSNotification*)notification { - [fTrackerAddRemoveControl setEnabled: fTrackerTable.numberOfSelectedRows > 0 forSegment: TRACKER_REMOVE_TAG]; + [fTrackerAddRemoveControl setEnabled:fTrackerTable.numberOfSelectedRows > 0 forSegment:TRACKER_REMOVE_TAG]; } -- (void) copy: (id) sender +- (void)copy:(id)sender { - NSArray * addresses = [fTrackers objectsAtIndexes: fTrackerTable.selectedRowIndexes]; - NSString * text = [addresses componentsJoinedByString: @"\n"]; + NSArray* addresses = [fTrackers objectsAtIndexes:fTrackerTable.selectedRowIndexes]; + NSString* text = [addresses componentsJoinedByString:@"\n"]; - NSPasteboard * pb = NSPasteboard.generalPasteboard; + NSPasteboard* pb = NSPasteboard.generalPasteboard; [pb clearContents]; - [pb writeObjects: @[text]]; + [pb writeObjects:@[ text ]]; } -- (BOOL) validateMenuItem: (NSMenuItem *) menuItem +- (BOOL)validateMenuItem:(NSMenuItem*)menuItem { - const SEL action = menuItem.action; + SEL const action = menuItem.action; if (action == @selector(copy:)) + { return self.window.firstResponder == fTrackerTable && fTrackerTable.numberOfSelectedRows > 0; + } if (action == @selector(paste:)) - return self.window.firstResponder == fTrackerTable - && [NSPasteboard.generalPasteboard canReadObjectForClasses: @[[NSString class]] options: nil]; + { + return self.window.firstResponder == fTrackerTable && + [NSPasteboard.generalPasteboard canReadObjectForClasses:@[ [NSString class] ] options:nil]; + } return YES; } -- (void) paste: (id) sender +- (void)paste:(id)sender { - NSMutableArray * tempTrackers = [NSMutableArray array]; + NSMutableArray* tempTrackers = [NSMutableArray array]; - NSArray * items = [NSPasteboard.generalPasteboard readObjectsForClasses: @[[NSString class]] options: nil]; + NSArray* items = [NSPasteboard.generalPasteboard readObjectsForClasses:@[ [NSString class] ] options:nil]; NSAssert(items != nil, @"no string items to paste; should not be able to call this method"); - for (NSString * pbItem in items) + for (NSString* pbItem in items) { - for (NSString * tracker in [pbItem componentsSeparatedByString: @"\n"]) - [tempTrackers addObject: tracker]; + for (NSString* tracker in [pbItem componentsSeparatedByString:@"\n"]) + { + [tempTrackers addObject:tracker]; + } } BOOL added = NO; - for (__strong NSString * tracker in tempTrackers) + for (__strong NSString* tracker in tempTrackers) { - tracker = [tracker stringByTrimmingCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; + tracker = [tracker stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; - if ([tracker rangeOfString: @"://"].location == NSNotFound) - tracker = [@"http://" stringByAppendingString: tracker]; + if ([tracker rangeOfString:@"://"].location == NSNotFound) + { + tracker = [@"http://" stringByAppendingString:tracker]; + } if (tr_urlIsValidTracker(tracker.UTF8String)) { - [fTrackers addObject: tracker]; + [fTrackers addObject:tracker]; added = YES; } } if (added) { - [fTrackerTable deselectAll: self]; + [fTrackerTable deselectAll:self]; [fTrackerTable reloadData]; } else + { NSBeep(); + } } @end @implementation CreatorWindowController (Private) -- (void) updateLocationField +- (void)updateLocationField { - NSString * pathString = fLocation.path; + NSString* pathString = fLocation.path; fLocationField.stringValue = pathString.stringByAbbreviatingWithTildeInPath; fLocationField.toolTip = pathString; } -+ (NSURL *) chooseFile ++ (NSURL*)chooseFile { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; panel.title = NSLocalizedString(@"Create Torrent File", "Create torrent -> select file"); panel.prompt = NSLocalizedString(@"Select", "Create torrent -> select file"); @@ -469,20 +516,19 @@ NSMutableSet *creatorWindowControllerSet = nil; return success ? panel.URLs[0] : nil; } -- (void) createReal +- (void)createReal { //check if the location currently exists - if (![fLocation.URLByDeletingLastPathComponent checkResourceIsReachableAndReturnError: NULL]) + if (![fLocation.URLByDeletingLastPathComponent checkResourceIsReachableAndReturnError:NULL]) { - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> directory doesn't exist warning -> button")]; - alert.messageText = NSLocalizedString(@"The chosen torrent file location does not exist.", - "Create torrent -> directory doesn't exist warning -> title"); - alert.informativeText = [NSString stringWithFormat: - NSLocalizedString(@"The directory \"%@\" does not currently exist. " - "Create this directory or choose a different one to create the torrent file.", - "Create torrent -> directory doesn't exist warning -> warning"), - fLocation.URLByDeletingLastPathComponent.path]; + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Create torrent -> directory doesn't exist warning -> button")]; + alert.messageText = NSLocalizedString(@"The chosen torrent file location does not exist.", "Create torrent -> directory doesn't exist warning -> title"); + alert.informativeText = [NSString stringWithFormat:NSLocalizedString( + @"The directory \"%@\" does not currently exist. " + "Create this directory or choose a different one to create the torrent file.", + "Create torrent -> directory doesn't exist warning -> warning"), + fLocation.URLByDeletingLastPathComponent.path]; alert.alertStyle = NSWarningAlertStyle; [alert beginSheetModalForWindow:self.window completionHandler:nil]; @@ -490,20 +536,22 @@ NSMutableSet *creatorWindowControllerSet = nil; } //check if a file with the same name and location already exists - if ([fLocation checkResourceIsReachableAndReturnError: NULL]) + if ([fLocation checkResourceIsReachableAndReturnError:NULL]) { - NSArray * pathComponents = fLocation.pathComponents; + NSArray* pathComponents = fLocation.pathComponents; NSInteger count = pathComponents.count; - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> file already exists warning -> button")]; - alert.messageText = NSLocalizedString(@"A torrent file with this name and directory cannot be created.", + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Create torrent -> file already exists warning -> button")]; + alert.messageText = NSLocalizedString( + @"A torrent file with this name and directory cannot be created.", "Create torrent -> file already exists warning -> title"); - alert.informativeText = [NSString stringWithFormat: - NSLocalizedString(@"A file with the name \"%@\" already exists in the directory \"%@\". " - "Choose a new name or directory to create the torrent file.", - "Create torrent -> file already exists warning -> warning"), - pathComponents[count-1], pathComponents[count-2]]; + alert.informativeText = [NSString stringWithFormat:NSLocalizedString( + @"A file with the name \"%@\" already exists in the directory \"%@\". " + "Choose a new name or directory to create the torrent file.", + "Create torrent -> file already exists warning -> warning"), + pathComponents[count - 1], + pathComponents[count - 2]]; alert.alertStyle = NSWarningAlertStyle; [alert beginSheetModalForWindow:self.window completionHandler:nil]; @@ -511,75 +559,93 @@ NSMutableSet *creatorWindowControllerSet = nil; } //parse non-empty tracker strings - tr_tracker_info * trackerInfo = tr_new0(tr_tracker_info, fTrackers.count); + tr_tracker_info* trackerInfo = tr_new0(tr_tracker_info, fTrackers.count); for (NSUInteger i = 0; i < fTrackers.count; i++) { - trackerInfo[i].announce = (char *)[fTrackers[i] UTF8String]; + trackerInfo[i].announce = (char*)[fTrackers[i] UTF8String]; trackerInfo[i].tier = i; } //store values - [fDefaults setObject: fTrackers forKey: @"CreatorTrackers"]; - [fDefaults setBool: fPrivateCheck.state == NSOnState forKey: @"CreatorPrivate"]; - [fDefaults setBool: fOpenCheck.state == NSOnState forKey: @"CreatorOpen"]; + [fDefaults setObject:fTrackers forKey:@"CreatorTrackers"]; + [fDefaults setBool:fPrivateCheck.state == NSOnState forKey:@"CreatorPrivate"]; + [fDefaults setBool:fOpenCheck.state == NSOnState forKey:@"CreatorOpen"]; fOpenWhenCreated = fOpenCheck.state == NSOnState; //need this since the check box might not exist, and value in prefs might have changed from another creator window - [fDefaults setURL: fLocation.URLByDeletingLastPathComponent forKey: @"CreatorLocationURL"]; + [fDefaults setURL:fLocation.URLByDeletingLastPathComponent forKey:@"CreatorLocationURL"]; self.window.restorable = NO; - [NSNotificationCenter.defaultCenter postNotificationName: @"BeginCreateTorrentFile" object: fLocation userInfo: nil]; - tr_makeMetaInfo(fInfo, fLocation.path.UTF8String, trackerInfo, fTrackers.count, fCommentView.string.UTF8String, fPrivateCheck.state == NSOnState); + [NSNotificationCenter.defaultCenter postNotificationName:@"BeginCreateTorrentFile" object:fLocation userInfo:nil]; + tr_makeMetaInfo( + fInfo, + fLocation.path.UTF8String, + trackerInfo, + fTrackers.count, + fCommentView.string.UTF8String, + fPrivateCheck.state == NSOnState); tr_free(trackerInfo); - fTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector(checkProgress) userInfo: nil repeats: YES]; + fTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(checkProgress) userInfo:nil repeats:YES]; } -- (void) checkProgress +- (void)checkProgress { if (fInfo->isDone) { [fTimer invalidate]; fTimer = nil; - NSAlert * alert; + NSAlert* alert; switch (fInfo->result) { - case TR_MAKEMETA_OK: - if (fOpenWhenCreated) - { - NSDictionary * dict = @{@"File": fLocation.path, @"Path": fPath.URLByDeletingLastPathComponent.path}; - [NSNotificationCenter.defaultCenter postNotificationName: @"OpenCreatedTorrentFile" object: self userInfo: dict]; - } + case TR_MAKEMETA_OK: + if (fOpenWhenCreated) + { + NSDictionary* dict = @{ @"File" : fLocation.path, @"Path" : fPath.URLByDeletingLastPathComponent.path }; + [NSNotificationCenter.defaultCenter postNotificationName:@"OpenCreatedTorrentFile" object:self userInfo:dict]; + } + [self.window close]; + break; + + case TR_MAKEMETA_CANCELLED: + [self.window close]; + break; + + default: + alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Create torrent -> failed -> button")]; + alert.messageText = [NSString stringWithFormat:NSLocalizedString(@"Creation of \"%@\" failed.", "Create torrent -> failed -> title"), + fLocation.lastPathComponent]; + alert.alertStyle = NSWarningAlertStyle; + + if (fInfo->result == TR_MAKEMETA_IO_READ) + { + alert.informativeText = [NSString + stringWithFormat:NSLocalizedString(@"Could not read \"%s\": %s.", "Create torrent -> failed -> warning"), + fInfo->errfile, + strerror(fInfo->my_errno)]; + } + else if (fInfo->result == TR_MAKEMETA_IO_WRITE) + { + alert.informativeText = [NSString + stringWithFormat:NSLocalizedString(@"Could not write \"%s\": %s.", "Create torrent -> failed -> warning"), + fInfo->errfile, + strerror(fInfo->my_errno)]; + } + else //invalid url should have been caught before creating + { + alert.informativeText = [NSString + stringWithFormat:@"%@ (%d)", + NSLocalizedString(@"An unknown error has occurred.", "Create torrent -> failed -> warning"), + fInfo->result]; + } + + [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { + [alert.window orderOut:nil]; [self.window close]; - break; - - case TR_MAKEMETA_CANCELLED: - [self.window close]; - break; - - default: - alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> failed -> button")]; - alert.messageText = [NSString stringWithFormat: NSLocalizedString(@"Creation of \"%@\" failed.", - "Create torrent -> failed -> title"), fLocation.lastPathComponent]; - alert.alertStyle = NSWarningAlertStyle; - - if (fInfo->result == TR_MAKEMETA_IO_READ) - alert.informativeText = [NSString stringWithFormat: NSLocalizedString(@"Could not read \"%s\": %s.", - "Create torrent -> failed -> warning"), fInfo->errfile, strerror(fInfo->my_errno)]; - else if (fInfo->result == TR_MAKEMETA_IO_WRITE) - alert.informativeText = [NSString stringWithFormat: NSLocalizedString(@"Could not write \"%s\": %s.", - "Create torrent -> failed -> warning"), fInfo->errfile, strerror(fInfo->my_errno)]; - else //invalid url should have been caught before creating - alert.informativeText = [NSString stringWithFormat: @"%@ (%d)", - NSLocalizedString(@"An unknown error has occurred.", "Create torrent -> failed -> warning"), fInfo->result]; - - [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { - [alert.window orderOut: nil]; - [self.window close]; - }]; + }]; } } else @@ -592,7 +658,7 @@ NSMutableSet *creatorWindowControllerSet = nil; fProgressView.hidden = YES; - NSWindow * window = self.window; + NSWindow* window = self.window; window.frameAutosaveName = @""; NSRect windowRect = window.frame; @@ -606,10 +672,10 @@ NSMutableSet *creatorWindowControllerSet = nil; window.maxSize = NSMakeSize(window.maxSize.width, height); window.contentView = fProgressView; - [window setFrame: windowRect display: YES animate: YES]; + [window setFrame:windowRect display:YES animate:YES]; fProgressView.hidden = NO; - [window standardWindowButton: NSWindowCloseButton].enabled = NO; + [window standardWindowButton:NSWindowCloseButton].enabled = NO; } } } diff --git a/macosx/DragOverlayView.h b/macosx/DragOverlayView.h index 1f9b3ec4a..b6649c0c4 100644 --- a/macosx/DragOverlayView.h +++ b/macosx/DragOverlayView.h @@ -24,11 +24,12 @@ @interface DragOverlayView : NSView { - NSImage * fBadge; + NSImage* fBadge; - NSDictionary * fMainLineAttributes, * fSubLineAttributes; + NSDictionary* fMainLineAttributes; + NSDictionary* fSubLineAttributes; } -- (void) setOverlay: (NSImage *) icon mainLine: (NSString *) mainLine subLine: (NSString *) subLine; +- (void)setOverlay:(NSImage*)icon mainLine:(NSString*)mainLine subLine:(NSString*)subLine; @end diff --git a/macosx/DragOverlayView.m b/macosx/DragOverlayView.m index 123d1386c..a0954374e 100644 --- a/macosx/DragOverlayView.m +++ b/macosx/DragOverlayView.m @@ -27,75 +27,85 @@ @implementation DragOverlayView -- (instancetype) initWithFrame: (NSRect) frame +- (instancetype)initWithFrame:(NSRect)frame { - if ((self = [super initWithFrame: frame])) + if ((self = [super initWithFrame:frame])) { //create attributes - NSShadow * stringShadow = [[NSShadow alloc] init]; + NSShadow* stringShadow = [[NSShadow alloc] init]; stringShadow.shadowOffset = NSMakeSize(2.0, -2.0); stringShadow.shadowBlurRadius = 4.0; - NSFont * bigFont = [NSFont boldSystemFontOfSize: 18.0], - * smallFont = [NSFont systemFontOfSize: 14.0]; + NSFont *bigFont = [NSFont boldSystemFontOfSize:18.0], *smallFont = [NSFont systemFontOfSize:14.0]; - NSMutableParagraphStyle * paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + NSMutableParagraphStyle* paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; paragraphStyle.lineBreakMode = NSLineBreakByTruncatingMiddle; - fMainLineAttributes = @{NSForegroundColorAttributeName: NSColor.whiteColor, NSFontAttributeName: bigFont, - NSShadowAttributeName: stringShadow, NSParagraphStyleAttributeName: paragraphStyle}; - - fSubLineAttributes = @{NSForegroundColorAttributeName: NSColor.whiteColor, NSFontAttributeName: smallFont, - NSShadowAttributeName: stringShadow, NSParagraphStyleAttributeName: paragraphStyle}; + fMainLineAttributes = @{ + NSForegroundColorAttributeName : NSColor.whiteColor, + NSFontAttributeName : bigFont, + NSShadowAttributeName : stringShadow, + NSParagraphStyleAttributeName : paragraphStyle + }; + fSubLineAttributes = @{ + NSForegroundColorAttributeName : NSColor.whiteColor, + NSFontAttributeName : smallFont, + NSShadowAttributeName : stringShadow, + NSParagraphStyleAttributeName : paragraphStyle + }; } return self; } - -- (void) setOverlay: (NSImage *) icon mainLine: (NSString *) mainLine subLine: (NSString *) subLine +- (void)setOverlay:(NSImage*)icon mainLine:(NSString*)mainLine subLine:(NSString*)subLine { - //create badge - const NSRect badgeRect = NSMakeRect(0.0, 0.0, 325.0, 84.0); + NSRect const badgeRect = NSMakeRect(0.0, 0.0, 325.0, 84.0); - fBadge = [[NSImage alloc] initWithSize: badgeRect.size]; + fBadge = [[NSImage alloc] initWithSize:badgeRect.size]; [fBadge lockFocus]; - NSBezierPath * bp = [NSBezierPath bezierPathWithRoundedRect: badgeRect xRadius: 15.0 yRadius: 15.0]; - [[NSColor colorWithCalibratedWhite: 0.0 alpha: 0.75] set]; + NSBezierPath* bp = [NSBezierPath bezierPathWithRoundedRect:badgeRect xRadius:15.0 yRadius:15.0]; + [[NSColor colorWithCalibratedWhite:0.0 alpha:0.75] set]; [bp fill]; //place icon - [icon drawInRect: NSMakeRect(PADDING, (NSHeight(badgeRect) - ICON_WIDTH) * 0.5, ICON_WIDTH, ICON_WIDTH) fromRect: NSZeroRect - operation: NSCompositeSourceOver fraction: 1.0]; + [icon drawInRect:NSMakeRect(PADDING, (NSHeight(badgeRect) - ICON_WIDTH) * 0.5, ICON_WIDTH, ICON_WIDTH) fromRect:NSZeroRect + operation:NSCompositeSourceOver + fraction:1.0]; //place main text - const NSSize mainLineSize = [mainLine sizeWithAttributes: fMainLineAttributes]; - const NSSize subLineSize = [subLine sizeWithAttributes: fSubLineAttributes]; + NSSize const mainLineSize = [mainLine sizeWithAttributes:fMainLineAttributes]; + NSSize const subLineSize = [subLine sizeWithAttributes:fSubLineAttributes]; - NSRect lineRect = NSMakeRect(PADDING + ICON_WIDTH + 5.0, - (NSHeight(badgeRect) + (subLineSize.height + 2.0 - mainLineSize.height)) * 0.5, - NSWidth(badgeRect) - (PADDING + ICON_WIDTH + 2.0) - PADDING, mainLineSize.height); - [mainLine drawInRect: lineRect withAttributes: fMainLineAttributes]; + NSRect lineRect = NSMakeRect( + PADDING + ICON_WIDTH + 5.0, + (NSHeight(badgeRect) + (subLineSize.height + 2.0 - mainLineSize.height)) * 0.5, + NSWidth(badgeRect) - (PADDING + ICON_WIDTH + 2.0) - PADDING, + mainLineSize.height); + [mainLine drawInRect:lineRect withAttributes:fMainLineAttributes]; //place sub text lineRect.origin.y -= subLineSize.height + 2.0; lineRect.size.height = subLineSize.height; - [subLine drawInRect: lineRect withAttributes: fSubLineAttributes]; + [subLine drawInRect:lineRect withAttributes:fSubLineAttributes]; [fBadge unlockFocus]; self.needsDisplay = YES; } --(void) drawRect: (NSRect) rect +- (void)drawRect:(NSRect)rect { if (fBadge) { - const NSRect frame = self.frame; - const NSSize imageSize = fBadge.size; - [fBadge drawAtPoint: NSMakePoint((NSWidth(frame) - imageSize.width) * 0.5, (NSHeight(frame) - imageSize.height) * 0.5) fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0]; + NSRect const frame = self.frame; + NSSize const imageSize = fBadge.size; + [fBadge drawAtPoint:NSMakePoint((NSWidth(frame) - imageSize.width) * 0.5, (NSHeight(frame) - imageSize.height) * 0.5) + fromRect:NSZeroRect + operation:NSCompositeSourceOver + fraction:1.0]; } } diff --git a/macosx/DragOverlayWindow.h b/macosx/DragOverlayWindow.h index 923997591..95c16db64 100644 --- a/macosx/DragOverlayWindow.h +++ b/macosx/DragOverlayWindow.h @@ -26,18 +26,19 @@ @interface DragOverlayWindow : NSWindow { - tr_session * fLib; + tr_session* fLib; - NSViewAnimation * fFadeInAnimation, * fFadeOutAnimation; + NSViewAnimation* fFadeInAnimation; + NSViewAnimation* fFadeOutAnimation; } -- (instancetype) initWithLib: (tr_session *) lib forWindow: (NSWindow *) window; +- (instancetype)initWithLib:(tr_session*)lib forWindow:(NSWindow*)window; -- (void) setTorrents: (NSArray *) files; -- (void) setFile: (NSString *) file; -- (void) setURL: (NSString *) url; +- (void)setTorrents:(NSArray*)files; +- (void)setFile:(NSString*)file; +- (void)setURL:(NSString*)url; -- (void) fadeIn; -- (void) fadeOut; +- (void)fadeIn; +- (void)fadeOut; @end diff --git a/macosx/DragOverlayWindow.m b/macosx/DragOverlayWindow.m index cb128ce02..8b3d56190 100644 --- a/macosx/DragOverlayWindow.m +++ b/macosx/DragOverlayWindow.m @@ -26,72 +26,69 @@ @interface DragOverlayWindow (Private) -- (void) resizeWindow; +- (void)resizeWindow; @end @implementation DragOverlayWindow -- (instancetype) initWithLib: (tr_session *) lib forWindow: (NSWindow *) window +- (instancetype)initWithLib:(tr_session*)lib forWindow:(NSWindow*)window { - if ((self = ([super initWithContentRect: window.frame styleMask: NSBorderlessWindowMask - backing: NSBackingStoreBuffered defer: NO]))) + if ((self = ([super initWithContentRect:window.frame styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO]))) { fLib = lib; - self.backgroundColor = [NSColor colorWithCalibratedWhite: 0.0 alpha: 0.5]; + self.backgroundColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.5]; self.alphaValue = 0.0; self.opaque = NO; self.hasShadow = NO; - DragOverlayView * view = [[DragOverlayView alloc] initWithFrame: self.frame]; + DragOverlayView* view = [[DragOverlayView alloc] initWithFrame:self.frame]; self.contentView = view; self.releasedWhenClosed = NO; self.ignoresMouseEvents = YES; - fFadeInAnimation = [[NSViewAnimation alloc] initWithViewAnimations: @[ - @{NSViewAnimationTargetKey: self, - NSViewAnimationEffectKey: NSViewAnimationFadeInEffect} - ]]; + fFadeInAnimation = [[NSViewAnimation alloc] initWithViewAnimations:@[ + @{ NSViewAnimationTargetKey : self, NSViewAnimationEffectKey : NSViewAnimationFadeInEffect } + ]]; fFadeInAnimation.duration = 0.15; fFadeInAnimation.animationBlockingMode = NSAnimationNonblockingThreaded; - fFadeOutAnimation = [[NSViewAnimation alloc] initWithViewAnimations: @[ - @{NSViewAnimationTargetKey: self, - NSViewAnimationEffectKey: NSViewAnimationFadeOutEffect} - ]]; + fFadeOutAnimation = [[NSViewAnimation alloc] initWithViewAnimations:@[ + @{ NSViewAnimationTargetKey : self, NSViewAnimationEffectKey : NSViewAnimationFadeOutEffect } + ]]; fFadeOutAnimation.duration = 0.5; fFadeOutAnimation.animationBlockingMode = NSAnimationNonblockingThreaded; - [window addChildWindow: self ordered: NSWindowAbove]; + [window addChildWindow:self ordered:NSWindowAbove]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(resizeWindow) - name: NSWindowDidResizeNotification object: window]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(resizeWindow) name:NSWindowDidResizeNotification + object:window]; } return self; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; } -- (void) setTorrents: (NSArray *) files +- (void)setTorrents:(NSArray*)files { uint64_t size = 0; NSInteger count = 0; - NSString * name; + NSString* name; BOOL folder; NSInteger fileCount = 0; - for (NSString * file in files) + for (NSString* file in files) { - if ([[NSWorkspace.sharedWorkspace typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"] - || [file.pathExtension caseInsensitiveCompare: @"torrent"] == NSOrderedSame) + if ([[NSWorkspace.sharedWorkspace typeOfFile:file error:NULL] isEqualToString:@"org.bittorrent.torrent"] || + [file.pathExtension caseInsensitiveCompare:@"torrent"] == NSOrderedSame) { - tr_ctor * ctor = tr_ctorNew(fLib); + tr_ctor* ctor = tr_ctorNew(fLib); tr_ctorSetMetainfoFromFile(ctor, file.UTF8String); tr_info info; if (tr_torrentParse(ctor, &info) == TR_PARSE_OK) @@ -113,51 +110,60 @@ } if (count <= 0) + { return; + } //set strings and icon - NSString * secondString = [NSString stringForFileSize: size]; + NSString* secondString = [NSString stringForFileSize:size]; if (count > 1 || folder) { - NSString * fileString; + NSString* fileString; if (fileCount == 1) + { fileString = NSLocalizedString(@"1 file", "Drag overlay -> torrents"); + } else - fileString= [NSString stringWithFormat: NSLocalizedString(@"%@ files", "Drag overlay -> torrents"), - [NSString formattedUInteger: fileCount]]; - secondString = [NSString stringWithFormat: @"%@, %@", fileString, secondString]; + { + fileString = [NSString stringWithFormat:NSLocalizedString(@"%@ files", "Drag overlay -> torrents"), + [NSString formattedUInteger:fileCount]]; + } + secondString = [NSString stringWithFormat:@"%@, %@", fileString, secondString]; } - NSImage * icon; + NSImage* icon; if (count == 1) - icon = [NSWorkspace.sharedWorkspace iconForFileType: folder ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) : name.pathExtension]; + { + icon = [NSWorkspace.sharedWorkspace iconForFileType:folder ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) : name.pathExtension]; + } else { - name = [NSString stringWithFormat: NSLocalizedString(@"%@ Torrent Files", "Drag overlay -> torrents"), - [NSString formattedUInteger: count]]; - secondString = [secondString stringByAppendingString: @" total"]; - icon = [NSImage imageNamed: @"TransmissionDocument.icns"]; + name = [NSString stringWithFormat:NSLocalizedString(@"%@ Torrent Files", "Drag overlay -> torrents"), + [NSString formattedUInteger:count]]; + secondString = [secondString stringByAppendingString:@" total"]; + icon = [NSImage imageNamed:@"TransmissionDocument.icns"]; } - [self.contentView setOverlay: icon mainLine: name subLine: secondString]; + [self.contentView setOverlay:icon mainLine:name subLine:secondString]; [self fadeIn]; } -- (void) setFile: (NSString *) file +- (void)setFile:(NSString*)file { - [self.contentView setOverlay: [NSImage imageNamed: @"CreateLarge"] - mainLine: NSLocalizedString(@"Create a Torrent File", "Drag overlay -> file") subLine: file]; + [self.contentView setOverlay:[NSImage imageNamed:@"CreateLarge"] + mainLine:NSLocalizedString(@"Create a Torrent File", "Drag overlay -> file") + subLine:file]; [self fadeIn]; } -- (void) setURL: (NSString *) url +- (void)setURL:(NSString*)url { - [self.contentView setOverlay: [NSImage imageNamed: @"Globe"] - mainLine: NSLocalizedString(@"Web Address", "Drag overlay -> url") subLine: url]; + [self.contentView setOverlay:[NSImage imageNamed:@"Globe"] mainLine:NSLocalizedString(@"Web Address", "Drag overlay -> url") + subLine:url]; [self fadeIn]; } -- (void) fadeIn +- (void)fadeIn { //stop other animation and set to same progress if (fFadeOutAnimation.animating) @@ -168,7 +174,7 @@ [fFadeInAnimation startAnimation]; } -- (void) fadeOut +- (void)fadeOut { //stop other animation and set to same progress if (fFadeInAnimation.animating) @@ -177,16 +183,18 @@ fFadeOutAnimation.currentProgress = 1.0 - fFadeInAnimation.currentProgress; } if (self.alphaValue > 0.0) + { [fFadeOutAnimation startAnimation]; + } } @end @implementation DragOverlayWindow (Private) -- (void) resizeWindow +- (void)resizeWindow { - [self setFrame: self.parentWindow.frame display: NO]; + [self setFrame:self.parentWindow.frame display:NO]; } @end diff --git a/macosx/ExpandedPathToIconTransformer.m b/macosx/ExpandedPathToIconTransformer.m index 5ba26d553..439914721 100644 --- a/macosx/ExpandedPathToIconTransformer.m +++ b/macosx/ExpandedPathToIconTransformer.m @@ -26,28 +26,34 @@ @implementation ExpandedPathToIconTransformer -+ (Class) transformedValueClass ++ (Class)transformedValueClass { return [NSImage class]; } -+ (BOOL) allowsReverseTransformation ++ (BOOL)allowsReverseTransformation { return NO; } -- (id) transformedValue: (id) value +- (id)transformedValue:(id)value { if (!value) + { return nil; + } - NSString * path = [value stringByExpandingTildeInPath]; - NSImage * icon; + NSString* path = [value stringByExpandingTildeInPath]; + NSImage* icon; //show a folder icon if the folder doesn't exist - if ([path.pathExtension isEqualToString: @""] && ![NSFileManager.defaultManager fileExistsAtPath: path]) - icon = [NSWorkspace.sharedWorkspace iconForFileType: NSFileTypeForHFSTypeCode(kGenericFolderIcon)]; + if ([path.pathExtension isEqualToString:@""] && ![NSFileManager.defaultManager fileExistsAtPath:path]) + { + icon = [NSWorkspace.sharedWorkspace iconForFileType:NSFileTypeForHFSTypeCode(kGenericFolderIcon)]; + } else - icon = [NSWorkspace.sharedWorkspace iconForFile: path]; + { + icon = [NSWorkspace.sharedWorkspace iconForFile:path]; + } icon.size = NSMakeSize(16.0, 16.0); diff --git a/macosx/ExpandedPathToPathTransformer.m b/macosx/ExpandedPathToPathTransformer.m index d112c0177..bb79554f7 100644 --- a/macosx/ExpandedPathToPathTransformer.m +++ b/macosx/ExpandedPathToPathTransformer.m @@ -24,19 +24,19 @@ @implementation ExpandedPathToPathTransformer -+ (Class) transformedValueClass ++ (Class)transformedValueClass { return [NSString class]; } -+ (BOOL) allowsReverseTransformation ++ (BOOL)allowsReverseTransformation { return NO; } -- (id) transformedValue: (id) value +- (id)transformedValue:(id)value { - return value == nil ? nil : [NSFileManager.defaultManager displayNameAtPath: value]; + return value == nil ? nil : [NSFileManager.defaultManager displayNameAtPath:value]; } @end diff --git a/macosx/FileListNode.h b/macosx/FileListNode.h index 79dc757bc..1d57510ac 100644 --- a/macosx/FileListNode.h +++ b/macosx/FileListNode.h @@ -24,28 +24,32 @@ @class Torrent; -@interface FileListNode : NSObject +@interface FileListNode : NSObject -@property (nonatomic, readonly) NSString * name; -@property (nonatomic, readonly) NSString * path; +@property(nonatomic, readonly) NSString* name; +@property(nonatomic, readonly) NSString* path; -@property (nonatomic, weak, readonly) Torrent * torrent; +@property(nonatomic, weak, readonly) Torrent* torrent; -@property (nonatomic, readonly) uint64_t size; -@property (nonatomic, readonly) NSImage * icon; -@property (nonatomic, readonly) BOOL isFolder; -@property (nonatomic, readonly) NSMutableArray * children; +@property(nonatomic, readonly) uint64_t size; +@property(nonatomic, readonly) NSImage* icon; +@property(nonatomic, readonly) BOOL isFolder; +@property(nonatomic, readonly) NSMutableArray* children; -@property (nonatomic, readonly) NSIndexSet * indexes; +@property(nonatomic, readonly) NSIndexSet* indexes; -- (instancetype) initWithFolderName: (NSString *) name path: (NSString *) path torrent: (Torrent *) torrent; -- (instancetype) initWithFileName: (NSString *) name path: (NSString *) path size: (uint64_t) size index: (NSUInteger) index torrent: (Torrent *) torrent; +- (instancetype)initWithFolderName:(NSString*)name path:(NSString*)path torrent:(Torrent*)torrent; +- (instancetype)initWithFileName:(NSString*)name + path:(NSString*)path + size:(uint64_t)size + index:(NSUInteger)index + torrent:(Torrent*)torrent; -- (void) insertChild: (FileListNode *) child; -- (void) insertIndex: (NSUInteger) index withSize: (uint64_t) size; +- (void)insertChild:(FileListNode*)child; +- (void)insertIndex:(NSUInteger)index withSize:(uint64_t)size; -@property (nonatomic, readonly) NSString *description; +@property(nonatomic, readonly) NSString* description; -- (BOOL) updateFromOldName: (NSString *) oldName toNewName: (NSString *) newName inPath: (NSString *) path; +- (BOOL)updateFromOldName:(NSString*)oldName toNewName:(NSString*)newName inPath:(NSString*)path; @end diff --git a/macosx/FileListNode.m b/macosx/FileListNode.m index 749196f1c..a8fb6326b 100644 --- a/macosx/FileListNode.m +++ b/macosx/FileListNode.m @@ -24,20 +24,20 @@ @interface FileListNode (Private) -- (instancetype) initWithFolder: (BOOL) isFolder name: (NSString *) name path: (NSString *) path torrent: (Torrent *) torrent; +- (instancetype)initWithFolder:(BOOL)isFolder name:(NSString*)name path:(NSString*)path torrent:(Torrent*)torrent; @end @implementation FileListNode { - NSMutableIndexSet * _indexes; - NSImage * _icon; - NSMutableArray * _children; + NSMutableIndexSet* _indexes; + NSImage* _icon; + NSMutableArray* _children; } -- (instancetype) initWithFolderName: (NSString *) name path: (NSString *) path torrent: (Torrent *) torrent +- (instancetype)initWithFolderName:(NSString*)name path:(NSString*)path torrent:(Torrent*)torrent { - if ((self = [self initWithFolder: YES name: name path: path torrent: torrent])) + if ((self = [self initWithFolder:YES name:name path:path torrent:torrent])) { _children = [[NSMutableArray alloc] init]; _size = 0; @@ -46,79 +46,87 @@ return self; } -- (instancetype) initWithFileName: (NSString *) name path: (NSString *) path size: (uint64_t) size index: (NSUInteger) index torrent: (Torrent *) torrent +- (instancetype)initWithFileName:(NSString*)name + path:(NSString*)path + size:(uint64_t)size + index:(NSUInteger)index + torrent:(Torrent*)torrent { - if ((self = [self initWithFolder: NO name: name path: path torrent: torrent])) + if ((self = [self initWithFolder:NO name:name path:path torrent:torrent])) { _size = size; - [_indexes addIndex: index]; + [_indexes addIndex:index]; } return self; } -- (void) insertChild: (FileListNode *) child +- (void)insertChild:(FileListNode*)child { NSAssert(_isFolder, @"method can only be invoked on folders"); - [_children addObject: child]; + [_children addObject:child]; } -- (void) insertIndex: (NSUInteger) index withSize: (uint64_t) size +- (void)insertIndex:(NSUInteger)index withSize:(uint64_t)size { NSAssert(_isFolder, @"method can only be invoked on folders"); - [_indexes addIndex: index]; + [_indexes addIndex:index]; _size += size; } -- (id) copyWithZone: (NSZone *) zone +- (id)copyWithZone:(NSZone*)zone { //this object is essentially immutable after initial setup return self; } - -- (NSString *) description +- (NSString*)description { if (!_isFolder) - return [NSString stringWithFormat: @"%@ (%ld)", _name, _indexes.firstIndex]; + { + return [NSString stringWithFormat:@"%@ (%ld)", _name, _indexes.firstIndex]; + } else - return [NSString stringWithFormat: @"%@ (folder: %@)", _name, _indexes]; + { + return [NSString stringWithFormat:@"%@ (folder: %@)", _name, _indexes]; + } } -- (NSImage *) icon +- (NSImage*)icon { if (!_icon) - _icon = [NSWorkspace.sharedWorkspace iconForFileType: _isFolder ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) - : _name.pathExtension]; + { + _icon = [NSWorkspace.sharedWorkspace iconForFileType:_isFolder ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) : _name.pathExtension]; + } return _icon; } -- (NSMutableArray *) children +- (NSMutableArray*)children { NSAssert(_isFolder, @"method can only be invoked on folders"); return _children; } -- (NSIndexSet *) indexes +- (NSIndexSet*)indexes { return _indexes; } -- (BOOL) updateFromOldName: (NSString *) oldName toNewName: (NSString *) newName inPath: (NSString *) path +- (BOOL)updateFromOldName:(NSString*)oldName toNewName:(NSString*)newName inPath:(NSString*)path { NSParameterAssert(oldName != nil); NSParameterAssert(newName != nil); NSParameterAssert(path != nil); - NSArray * lookupPathComponents = path.pathComponents; - NSArray * thesePathComponents = self.path.pathComponents; + NSArray* lookupPathComponents = path.pathComponents; + NSArray* thesePathComponents = self.path.pathComponents; - if ([lookupPathComponents isEqualToArray: thesePathComponents]) //this node represents what's being renamed + if ([lookupPathComponents isEqualToArray:thesePathComponents]) //this node represents what's being renamed { - if ([oldName isEqualToString: self.name]) + if ([oldName isEqualToString:self.name]) { _name = [newName copy]; _icon = nil; @@ -127,17 +135,19 @@ } else if (lookupPathComponents.count < thesePathComponents.count) //what's being renamed is part of this node's path { - lookupPathComponents = [lookupPathComponents arrayByAddingObject: oldName]; - const BOOL allSame = NSNotFound == [lookupPathComponents indexOfObjectWithOptions: NSEnumerationConcurrent passingTest: ^BOOL(NSString * name, NSUInteger idx, BOOL * stop) { - return ![name isEqualToString: thesePathComponents[idx]]; - }]; + lookupPathComponents = [lookupPathComponents arrayByAddingObject:oldName]; + BOOL const allSame = NSNotFound == + [lookupPathComponents indexOfObjectWithOptions:NSEnumerationConcurrent + passingTest:^BOOL(NSString* name, NSUInteger idx, BOOL* stop) { + return ![name isEqualToString:thesePathComponents[idx]]; + }]; if (allSame) { - NSString * oldPathPrefix = [path stringByAppendingPathComponent: oldName]; - NSString * newPathPrefix = [path stringByAppendingPathComponent: newName]; + NSString* oldPathPrefix = [path stringByAppendingPathComponent:oldName]; + NSString* newPathPrefix = [path stringByAppendingPathComponent:newName]; - _path = [_path stringByReplacingCharactersInRange: NSMakeRange(0, oldPathPrefix.length) withString: newPathPrefix]; + _path = [_path stringByReplacingCharactersInRange:NSMakeRange(0, oldPathPrefix.length) withString:newPathPrefix]; return YES; } } @@ -149,7 +159,7 @@ @implementation FileListNode (Private) -- (instancetype) initWithFolder: (BOOL) isFolder name: (NSString *) name path: (NSString *) path torrent: (Torrent *) torrent +- (instancetype)initWithFolder:(BOOL)isFolder name:(NSString*)name path:(NSString*)path torrent:(Torrent*)torrent { if ((self = [super init])) { diff --git a/macosx/FileNameCell.h b/macosx/FileNameCell.h index d3c65a3e3..f4f18face 100644 --- a/macosx/FileNameCell.h +++ b/macosx/FileNameCell.h @@ -24,9 +24,10 @@ @interface FileNameCell : NSActionCell { - NSMutableDictionary * fTitleAttributes, * fStatusAttributes; + NSMutableDictionary* fTitleAttributes; + NSMutableDictionary* fStatusAttributes; } -- (NSRect) imageRectForBounds: (NSRect) bounds; +- (NSRect)imageRectForBounds:(NSRect)bounds; @end diff --git a/macosx/FileNameCell.m b/macosx/FileNameCell.m index d0b29ff4c..18b69af1f 100644 --- a/macosx/FileNameCell.m +++ b/macosx/FileNameCell.m @@ -40,42 +40,38 @@ @interface FileNameCell (Private) -- (NSRect) rectForTitleWithString: (NSAttributedString *) string inBounds: (NSRect) bounds; -- (NSRect) rectForStatusWithString: (NSAttributedString *) string withTitleRect: (NSRect) titleRect inBounds: (NSRect) bounds; +- (NSRect)rectForTitleWithString:(NSAttributedString*)string inBounds:(NSRect)bounds; +- (NSRect)rectForStatusWithString:(NSAttributedString*)string withTitleRect:(NSRect)titleRect inBounds:(NSRect)bounds; -@property (nonatomic, readonly) NSAttributedString *attributedTitle; -@property (nonatomic, readonly) NSAttributedString *attributedStatus; +@property(nonatomic, readonly) NSAttributedString* attributedTitle; +@property(nonatomic, readonly) NSAttributedString* attributedStatus; @end @implementation FileNameCell -- (instancetype) init +- (instancetype)init { if ((self = [super init])) { - NSMutableParagraphStyle * paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + NSMutableParagraphStyle* paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; paragraphStyle.lineBreakMode = NSLineBreakByTruncatingMiddle; - fTitleAttributes = [[NSMutableDictionary alloc] initWithObjectsAndKeys: - [NSFont messageFontOfSize: 12.0], NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, nil]; + fTitleAttributes = [[NSMutableDictionary alloc] + initWithObjectsAndKeys:[NSFont messageFontOfSize:12.0], NSFontAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil]; - NSMutableParagraphStyle * statusParagraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + NSMutableParagraphStyle* statusParagraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; statusParagraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; - fStatusAttributes = [[NSMutableDictionary alloc] initWithObjectsAndKeys: - [NSFont messageFontOfSize: 9.0], NSFontAttributeName, - statusParagraphStyle, NSParagraphStyleAttributeName, nil]; - + fStatusAttributes = [[NSMutableDictionary alloc] + initWithObjectsAndKeys:[NSFont messageFontOfSize:9.0], NSFontAttributeName, statusParagraphStyle, NSParagraphStyleAttributeName, nil]; } return self; } - -- (id) copyWithZone: (NSZone *) zone +- (id)copyWithZone:(NSZone*)zone { - FileNameCell * copy = [super copyWithZone: zone]; + FileNameCell* copy = [super copyWithZone:zone]; copy->fTitleAttributes = fTitleAttributes; copy->fStatusAttributes = fStatusAttributes; @@ -83,36 +79,42 @@ return copy; } -- (NSImage *) image +- (NSImage*)image { - FileListNode * node = (FileListNode *)self.objectValue; + FileListNode* node = (FileListNode*)self.objectValue; return node.icon; } -- (NSRect) imageRectForBounds: (NSRect) bounds +- (NSRect)imageRectForBounds:(NSRect)bounds { NSRect result = bounds; result.origin.x += PADDING_HORIZONAL; - const CGFloat IMAGE_SIZE = ((FileListNode *)self.objectValue).isFolder ? IMAGE_FOLDER_SIZE : IMAGE_ICON_SIZE; + CGFloat const IMAGE_SIZE = ((FileListNode*)self.objectValue).isFolder ? IMAGE_FOLDER_SIZE : IMAGE_ICON_SIZE; result.origin.y += (result.size.height - IMAGE_SIZE) * 0.5; result.size = NSMakeSize(IMAGE_SIZE, IMAGE_SIZE); return result; } -- (void) drawWithFrame: (NSRect) cellFrame inView: (NSView *) controlView +- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView { //icon - [self.image drawInRect: [self imageRectForBounds: cellFrame] fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; + [self.image drawInRect:[self imageRectForBounds:cellFrame] fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 + respectFlipped:YES + hints:nil]; - NSColor * titleColor, * statusColor; - FileListNode * node = self.objectValue; + NSColor *titleColor, *statusColor; + FileListNode* node = self.objectValue; if (self.backgroundStyle == NSBackgroundStyleDark) + { titleColor = statusColor = NSColor.whiteColor; - else if ([node.torrent checkForFiles: node.indexes] == NSOffState) + } + else if ([node.torrent checkForFiles:node.indexes] == NSOffState) + { titleColor = statusColor = NSColor.disabledControlTextColor; + } else { titleColor = NSColor.controlTextColor; @@ -123,23 +125,23 @@ fStatusAttributes[NSForegroundColorAttributeName] = statusColor; //title - NSAttributedString * titleString = self.attributedTitle; - NSRect titleRect = [self rectForTitleWithString: titleString inBounds: cellFrame]; - [titleString drawInRect: titleRect]; + NSAttributedString* titleString = self.attributedTitle; + NSRect titleRect = [self rectForTitleWithString:titleString inBounds:cellFrame]; + [titleString drawInRect:titleRect]; //status - NSAttributedString * statusString = self.attributedStatus; - NSRect statusRect = [self rectForStatusWithString: statusString withTitleRect: titleRect inBounds: cellFrame]; - [statusString drawInRect: statusRect]; + NSAttributedString* statusString = self.attributedStatus; + NSRect statusRect = [self rectForStatusWithString:statusString withTitleRect:titleRect inBounds:cellFrame]; + [statusString drawInRect:statusRect]; } -- (NSRect) expansionFrameWithFrame: (NSRect) cellFrame inView: (NSView *) view +- (NSRect)expansionFrameWithFrame:(NSRect)cellFrame inView:(NSView*)view { - NSAttributedString * titleString = self.attributedTitle; - NSRect realRect = [self rectForTitleWithString: titleString inBounds: cellFrame]; + NSAttributedString* titleString = self.attributedTitle; + NSRect realRect = [self rectForTitleWithString:titleString inBounds:cellFrame]; - if ([titleString size].width > NSWidth(realRect) - && NSMouseInRect([view convertPoint: view.window.mouseLocationOutsideOfEventStream fromView: nil], realRect, view.flipped)) + if ([titleString size].width > NSWidth(realRect) && + NSMouseInRect([view convertPoint:view.window.mouseLocationOutsideOfEventStream fromView:nil], realRect, view.flipped)) { realRect.size.width = [titleString size].width; return NSInsetRect(realRect, -PADDING_EXPANSION_FRAME, -PADDING_EXPANSION_FRAME); @@ -148,27 +150,27 @@ return NSZeroRect; } -- (void) drawWithExpansionFrame: (NSRect) cellFrame inView: (NSView *)view +- (void)drawWithExpansionFrame:(NSRect)cellFrame inView:(NSView*)view { cellFrame.origin.x += PADDING_EXPANSION_FRAME; cellFrame.origin.y += PADDING_EXPANSION_FRAME; fTitleAttributes[NSForegroundColorAttributeName] = NSColor.controlTextColor; - NSAttributedString * titleString = self.attributedTitle; - [titleString drawInRect: cellFrame]; + NSAttributedString* titleString = self.attributedTitle; + [titleString drawInRect:cellFrame]; } @end @implementation FileNameCell (Private) -- (NSRect) rectForTitleWithString: (NSAttributedString *) string inBounds: (NSRect) bounds +- (NSRect)rectForTitleWithString:(NSAttributedString*)string inBounds:(NSRect)bounds { - const NSSize titleSize = [string size]; + NSSize const titleSize = [string size]; //no right padding, so that there's not too much space between this and the priority image NSRect result; - if (!((FileListNode *)self.objectValue).isFolder) + if (!((FileListNode*)self.objectValue).isFolder) { result.origin.x = NSMinX(bounds) + PADDING_HORIZONAL + IMAGE_ICON_SIZE + PADDING_BETWEEN_IMAGE_AND_TITLE; result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE_FILE; @@ -185,12 +187,12 @@ return result; } -- (NSRect) rectForStatusWithString: (NSAttributedString *) string withTitleRect: (NSRect) titleRect inBounds: (NSRect) bounds +- (NSRect)rectForStatusWithString:(NSAttributedString*)string withTitleRect:(NSRect)titleRect inBounds:(NSRect)bounds { - const NSSize statusSize = [string size]; + NSSize const statusSize = [string size]; NSRect result; - if (!((FileListNode *)self.objectValue).isFolder) + if (!((FileListNode*)self.objectValue).isFolder) { result.origin.x = NSMinX(titleRect); result.origin.y = NSMaxY(bounds) - PADDING_BELOW_STATUS_FILE - statusSize.height; @@ -207,24 +209,25 @@ return result; } -- (NSAttributedString *) attributedTitle +- (NSAttributedString*)attributedTitle { - NSString * title = ((FileListNode *)self.objectValue).name; - return [[NSAttributedString alloc] initWithString: title attributes: fTitleAttributes]; + NSString* title = ((FileListNode*)self.objectValue).name; + return [[NSAttributedString alloc] initWithString:title attributes:fTitleAttributes]; } -- (NSAttributedString *) attributedStatus +- (NSAttributedString*)attributedStatus { - FileListNode * node = (FileListNode *)self.objectValue; - Torrent * torrent = node.torrent; + FileListNode* node = (FileListNode*)self.objectValue; + Torrent* torrent = node.torrent; - const CGFloat progress = [torrent fileProgress: node]; - NSString * percentString = [NSString percentString: progress longDecimals: YES]; + CGFloat const progress = [torrent fileProgress:node]; + NSString* percentString = [NSString percentString:progress longDecimals:YES]; - NSString * status = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", - "Inspector -> Files tab -> file status string"), percentString, [NSString stringForFileSize: node.size]]; + NSString* status = [NSString stringWithFormat:NSLocalizedString(@"%@ of %@", "Inspector -> Files tab -> file status string"), + percentString, + [NSString stringForFileSize:node.size]]; - return [[NSAttributedString alloc] initWithString: status attributes: fStatusAttributes]; + return [[NSAttributedString alloc] initWithString:status attributes:fStatusAttributes]; } @end diff --git a/macosx/FileOutlineController.h b/macosx/FileOutlineController.h index 99a6d7c04..54ed16c47 100644 --- a/macosx/FileOutlineController.h +++ b/macosx/FileOutlineController.h @@ -27,30 +27,30 @@ @interface FileOutlineController : NSObject { - Torrent * fTorrent; - NSMutableArray * fFileList; + Torrent* fTorrent; + NSMutableArray* fFileList; - IBOutlet FileOutlineView * fOutline; + IBOutlet FileOutlineView* fOutline; - NSString * fFilterText; + NSString* fFilterText; } -@property (nonatomic, readonly) FileOutlineView *outlineView; +@property(nonatomic, readonly) FileOutlineView* outlineView; -- (void) setTorrent: (Torrent *) torrent; +- (void)setTorrent:(Torrent*)torrent; -- (void) setFilterText: (NSString *) text; +- (void)setFilterText:(NSString*)text; -- (void) refresh; +- (void)refresh; -- (void) setCheck: (id) sender; -- (void) setOnlySelectedCheck: (id) sender; -- (void) checkAll; -- (void) uncheckAll; -- (void) setPriority: (id) sender; +- (void)setCheck:(id)sender; +- (void)setOnlySelectedCheck:(id)sender; +- (void)checkAll; +- (void)uncheckAll; +- (void)setPriority:(id)sender; -- (void) revealFile: (id) sender; +- (void)revealFile:(id)sender; -- (void) renameSelected: (id) sender; +- (void)renameSelected:(id)sender; @end diff --git a/macosx/FileOutlineController.m b/macosx/FileOutlineController.m index ed8760595..a563782cf 100644 --- a/macosx/FileOutlineController.m +++ b/macosx/FileOutlineController.m @@ -34,12 +34,12 @@ #define ROW_SMALL_HEIGHT 18.0 -typedef NS_ENUM(unsigned int, fileCheckMenuTag) { +typedef NS_ENUM(unsigned int, fileCheckMenuTag) { // FILE_CHECK_TAG, FILE_UNCHECK_TAG }; -typedef NS_ENUM(unsigned int, filePriorityMenuTag) { +typedef NS_ENUM(unsigned int, filePriorityMenuTag) { // FILE_PRIORITY_HIGH_TAG, FILE_PRIORITY_NORMAL_TAG, FILE_PRIORITY_LOW_TAG @@ -47,15 +47,19 @@ typedef NS_ENUM(unsigned int, filePriorityMenuTag) { @interface FileOutlineController (Private) -@property (nonatomic, readonly) NSMenu *menu; +@property(nonatomic, readonly) NSMenu* menu; -- (NSUInteger) findFileNode: (FileListNode *) node inList: (NSArray *) list atIndexes: (NSIndexSet *) range currentParent: (FileListNode *) currentParent finalParent: (FileListNode **) parent; +- (NSUInteger)findFileNode:(FileListNode*)node + inList:(NSArray*)list + atIndexes:(NSIndexSet*)range + currentParent:(FileListNode*)currentParent + finalParent:(FileListNode**)parent; @end @implementation FileOutlineController -- (void) awakeFromNib +- (void)awakeFromNib { fFileList = [[NSMutableArray alloc] init]; @@ -63,60 +67,61 @@ typedef NS_ENUM(unsigned int, filePriorityMenuTag) { fOutline.target = self; //set table header tool tips - [fOutline tableColumnWithIdentifier: @"Check"].headerToolTip = NSLocalizedString(@"Download", "file table -> header tool tip"); - [fOutline tableColumnWithIdentifier: @"Priority"].headerToolTip = NSLocalizedString(@"Priority", "file table -> header tool tip"); + [fOutline tableColumnWithIdentifier:@"Check"].headerToolTip = NSLocalizedString(@"Download", "file table -> header tool tip"); + [fOutline tableColumnWithIdentifier:@"Priority"].headerToolTip = NSLocalizedString(@"Priority", "file table -> header tool tip"); fOutline.menu = self.menu; - [self setTorrent: nil]; + [self setTorrent:nil]; } - -- (FileOutlineView *) outlineView +- (FileOutlineView*)outlineView { return fOutline; } -- (void) setTorrent: (Torrent *) torrent +- (void)setTorrent:(Torrent*)torrent { fTorrent = torrent; - [fFileList setArray: fTorrent.fileList]; + [fFileList setArray:fTorrent.fileList]; fFilterText = nil; [fOutline reloadData]; - [fOutline deselectAll: nil]; //do this after reloading the data #4575 + [fOutline deselectAll:nil]; //do this after reloading the data #4575 } -- (void) setFilterText: (NSString *) text +- (void)setFilterText:(NSString*)text { - NSArray * components = [text betterComponentsSeparatedByCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; + NSArray* components = [text betterComponentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; if (!components || components.count == 0) { text = nil; components = nil; } - if ((!text && !fFilterText) || (text && fFilterText && [text isEqualToString: fFilterText])) + if ((!text && !fFilterText) || (text && fFilterText && [text isEqualToString:fFilterText])) + { return; + } [fOutline beginUpdates]; NSUInteger currentIndex = 0, totalCount = 0; - NSMutableArray * itemsToAdd = [NSMutableArray array]; - NSMutableIndexSet * itemsToAddIndexes = [NSMutableIndexSet indexSet]; + NSMutableArray* itemsToAdd = [NSMutableArray array]; + NSMutableIndexSet* itemsToAddIndexes = [NSMutableIndexSet indexSet]; - NSMutableDictionary * removedIndexesForParents = nil; //ugly, but we can't modify the actual file nodes + NSMutableDictionary* removedIndexesForParents = nil; //ugly, but we can't modify the actual file nodes - NSArray * tempList = !text ? fTorrent.fileList : fTorrent.flatFileList; - for (FileListNode * item in tempList) + NSArray* tempList = !text ? fTorrent.fileList : fTorrent.flatFileList; + for (FileListNode* item in tempList) { __block BOOL filter = NO; if (components) { - [components enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id obj, NSUInteger idx, BOOL * stop) { - if ([item.name rangeOfString: (NSString *)obj options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound) + [components enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL* stop) { + if ([item.name rangeOfString:(NSString*)obj options:(NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound) { filter = YES; *stop = YES; @@ -126,13 +131,18 @@ typedef NS_ENUM(unsigned int, filePriorityMenuTag) { if (!filter) { - FileListNode * parent = nil; - NSUInteger previousIndex = !item.isFolder ? [self findFileNode: item inList: fFileList atIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(currentIndex, fFileList.count-currentIndex)] currentParent: nil finalParent: &parent] : NSNotFound; + FileListNode* parent = nil; + NSUInteger previousIndex = !item.isFolder ? + [self findFileNode:item inList:fFileList + atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(currentIndex, fFileList.count - currentIndex)] + currentParent:nil + finalParent:&parent] : + NSNotFound; if (previousIndex == NSNotFound) { - [itemsToAdd addObject: item]; - [itemsToAddIndexes addIndex: totalCount]; + [itemsToAdd addObject:item]; + [itemsToAddIndexes addIndex:totalCount]; } else { @@ -140,33 +150,41 @@ typedef NS_ENUM(unsigned int, filePriorityMenuTag) { if (!parent) { if (previousIndex != currentIndex) - [fFileList moveObjectAtIndex: previousIndex toIndex: currentIndex]; + { + [fFileList moveObjectAtIndex:previousIndex toIndex:currentIndex]; + } else + { move = NO; + } } else { - [fFileList insertObject: item atIndex: currentIndex]; + [fFileList insertObject:item atIndex:currentIndex]; //figure out the index within the semi-edited table - UGLY if (!removedIndexesForParents) + { removedIndexesForParents = [NSMutableDictionary dictionary]; + } - NSMutableIndexSet * removedIndexes = removedIndexesForParents[parent]; + NSMutableIndexSet* removedIndexes = removedIndexesForParents[parent]; if (!removedIndexes) { - removedIndexes = [NSMutableIndexSet indexSetWithIndex: previousIndex]; + removedIndexes = [NSMutableIndexSet indexSetWithIndex:previousIndex]; removedIndexesForParents[parent] = removedIndexes; } else { - [removedIndexes addIndex: previousIndex]; - previousIndex -= [removedIndexes countOfIndexesInRange: NSMakeRange(0, previousIndex)]; + [removedIndexes addIndex:previousIndex]; + previousIndex -= [removedIndexes countOfIndexesInRange:NSMakeRange(0, previousIndex)]; } } if (move) - [fOutline moveItemAtIndex: previousIndex inParent: parent toIndex: currentIndex inParent: nil]; + { + [fOutline moveItemAtIndex:previousIndex inParent:parent toIndex:currentIndex inParent:nil]; + } ++currentIndex; } @@ -176,328 +194,372 @@ typedef NS_ENUM(unsigned int, filePriorityMenuTag) { } //remove trailing items - those are the unused - if (currentIndex < fFileList.count) + if (currentIndex < fFileList.count) { - const NSRange removeRange = NSMakeRange(currentIndex, fFileList.count-currentIndex); - [fFileList removeObjectsInRange: removeRange]; - [fOutline removeItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: removeRange] inParent: nil withAnimation: NSTableViewAnimationSlideDown]; + NSRange const removeRange = NSMakeRange(currentIndex, fFileList.count - currentIndex); + [fFileList removeObjectsInRange:removeRange]; + [fOutline removeItemsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:removeRange] inParent:nil + withAnimation:NSTableViewAnimationSlideDown]; } //add new items - [fFileList insertObjects: itemsToAdd atIndexes: itemsToAddIndexes]; - [fOutline insertItemsAtIndexes: itemsToAddIndexes inParent: nil withAnimation: NSTableViewAnimationSlideUp]; + [fFileList insertObjects:itemsToAdd atIndexes:itemsToAddIndexes]; + [fOutline insertItemsAtIndexes:itemsToAddIndexes inParent:nil withAnimation:NSTableViewAnimationSlideUp]; [fOutline endUpdates]; fFilterText = text; } -- (void) refresh +- (void)refresh { [fTorrent updateFileStat]; fOutline.needsDisplay = YES; } -- (void) outlineViewSelectionDidChange: (NSNotification *) notification +- (void)outlineViewSelectionDidChange:(NSNotification*)notification { if ([QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible) + { [[QLPreviewPanel sharedPreviewPanel] reloadData]; + } } -- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item +- (NSInteger)outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item { if (!item) + { return fFileList ? fFileList.count : 0; + } else { - FileListNode * node = (FileListNode *)item; + FileListNode* node = (FileListNode*)item; return node.isFolder ? node.children.count : 0; } } -- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item +- (BOOL)outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item { - return ((FileListNode *)item).isFolder; + return ((FileListNode*)item).isFolder; } -- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item +- (id)outlineView:(NSOutlineView*)outlineView child:(NSInteger)index ofItem:(id)item { - return (item ? ((FileListNode *)item).children : fFileList)[index]; + return (item ? ((FileListNode*)item).children : fFileList)[index]; } -- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item +- (id)outlineView:(NSOutlineView*)outlineView objectValueForTableColumn:(NSTableColumn*)tableColumn byItem:(id)item { - if ([tableColumn.identifier isEqualToString: @"Check"]) - return @([fTorrent checkForFiles: ((FileListNode *)item).indexes]); - else - return item; -} - -- (void) outlineView: (NSOutlineView *) outlineView willDisplayCell: (id) cell forTableColumn: (NSTableColumn *) tableColumn item: (id) item -{ - NSString * identifier = tableColumn.identifier; - if ([identifier isEqualToString: @"Check"]) - [cell setEnabled: [fTorrent canChangeDownloadCheckForFiles: ((FileListNode *)item).indexes]]; - else if ([identifier isEqualToString: @"Priority"]) + if ([tableColumn.identifier isEqualToString:@"Check"]) { - [cell setRepresentedObject: item]; + return @([fTorrent checkForFiles:((FileListNode*)item).indexes]); + } + else + { + return item; + } +} + +- (void)outlineView:(NSOutlineView*)outlineView + willDisplayCell:(id)cell + forTableColumn:(NSTableColumn*)tableColumn + item:(id)item +{ + NSString* identifier = tableColumn.identifier; + if ([identifier isEqualToString:@"Check"]) + { + [cell setEnabled:[fTorrent canChangeDownloadCheckForFiles:((FileListNode*)item).indexes]]; + } + else if ([identifier isEqualToString:@"Priority"]) + { + [cell setRepresentedObject:item]; NSInteger hoveredRow = fOutline.hoveredRow; - [(FilePriorityCell *)cell setHovered: hoveredRow != -1 && hoveredRow == [fOutline rowForItem: item]]; + [(FilePriorityCell*)cell setHovered:hoveredRow != -1 && hoveredRow == [fOutline rowForItem:item]]; } - else; } -- (void) outlineView: (NSOutlineView *) outlineView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn byItem: (id) item +- (void)outlineView:(NSOutlineView*)outlineView + setObjectValue:(id)object + forTableColumn:(NSTableColumn*)tableColumn + byItem:(id)item { - NSString * identifier = tableColumn.identifier; - if ([identifier isEqualToString: @"Check"]) + NSString* identifier = tableColumn.identifier; + if ([identifier isEqualToString:@"Check"]) { - NSIndexSet * indexSet; + NSIndexSet* indexSet; if (NSEvent.modifierFlags & NSAlternateKeyMask) - indexSet = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTorrent.fileCount)]; + { + indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fTorrent.fileCount)]; + } else - indexSet = ((FileListNode *)item).indexes; + { + indexSet = ((FileListNode*)item).indexes; + } - [fTorrent setFileCheckState: [object intValue] != NSOffState ? NSOnState : NSOffState forIndexes: indexSet]; + [fTorrent setFileCheckState:[object intValue] != NSOffState ? NSOnState : NSOffState forIndexes:indexSet]; fOutline.needsDisplay = YES; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; } } -- (NSString *) outlineView: (NSOutlineView *) outlineView typeSelectStringForTableColumn: (NSTableColumn *) tableColumn item: (id) item +- (NSString*)outlineView:(NSOutlineView*)outlineView typeSelectStringForTableColumn:(NSTableColumn*)tableColumn item:(id)item { - return ((FileListNode *)item).name; + return ((FileListNode*)item).name; } -- (NSString *) outlineView: (NSOutlineView *) outlineView toolTipForCell: (NSCell *) cell rect: (NSRectPointer) rect - tableColumn: (NSTableColumn *) tableColumn item: (id) item mouseLocation: (NSPoint) mouseLocation +- (NSString*)outlineView:(NSOutlineView*)outlineView + toolTipForCell:(NSCell*)cell + rect:(NSRectPointer)rect + tableColumn:(NSTableColumn*)tableColumn + item:(id)item + mouseLocation:(NSPoint)mouseLocation { - NSString * ident = tableColumn.identifier; - if ([ident isEqualToString: @"Name"]) + NSString* ident = tableColumn.identifier; + if ([ident isEqualToString:@"Name"]) { - NSString * path = [fTorrent fileLocation: item]; - if (!path) { - FileListNode * node = (FileListNode *)item; - path = [node.path stringByAppendingPathComponent: node.name]; + NSString* path = [fTorrent fileLocation:item]; + if (!path) + { + FileListNode* node = (FileListNode*)item; + path = [node.path stringByAppendingPathComponent:node.name]; } return path; } - else if ([ident isEqualToString: @"Check"]) + else if ([ident isEqualToString:@"Check"]) { switch (cell.state) { - case NSOffState: - return NSLocalizedString(@"Don't Download", "files tab -> tooltip"); - case NSOnState: - return NSLocalizedString(@"Download", "files tab -> tooltip"); - case NSMixedState: - return NSLocalizedString(@"Download Some", "files tab -> tooltip"); + case NSOffState: + return NSLocalizedString(@"Don't Download", "files tab -> tooltip"); + case NSOnState: + return NSLocalizedString(@"Download", "files tab -> tooltip"); + case NSMixedState: + return NSLocalizedString(@"Download Some", "files tab -> tooltip"); } } - else if ([ident isEqualToString: @"Priority"]) + else if ([ident isEqualToString:@"Priority"]) { - NSSet * priorities = [fTorrent filePrioritiesForIndexes: ((FileListNode *)item).indexes]; + NSSet* priorities = [fTorrent filePrioritiesForIndexes:((FileListNode*)item).indexes]; switch (priorities.count) { - case 0: - return NSLocalizedString(@"Priority Not Available", "files tab -> tooltip"); - case 1: - switch ([[priorities anyObject] intValue]) - { - case TR_PRI_LOW: - return NSLocalizedString(@"Low Priority", "files tab -> tooltip"); - case TR_PRI_HIGH: - return NSLocalizedString(@"High Priority", "files tab -> tooltip"); - case TR_PRI_NORMAL: - return NSLocalizedString(@"Normal Priority", "files tab -> tooltip"); - } - break; - default: - return NSLocalizedString(@"Multiple Priorities", "files tab -> tooltip"); + case 0: + return NSLocalizedString(@"Priority Not Available", "files tab -> tooltip"); + case 1: + switch ([[priorities anyObject] intValue]) + { + case TR_PRI_LOW: + return NSLocalizedString(@"Low Priority", "files tab -> tooltip"); + case TR_PRI_HIGH: + return NSLocalizedString(@"High Priority", "files tab -> tooltip"); + case TR_PRI_NORMAL: + return NSLocalizedString(@"Normal Priority", "files tab -> tooltip"); + } + break; + default: + return NSLocalizedString(@"Multiple Priorities", "files tab -> tooltip"); } } - else; return nil; } -- (CGFloat) outlineView: (NSOutlineView *) outlineView heightOfRowByItem: (id) item +- (CGFloat)outlineView:(NSOutlineView*)outlineView heightOfRowByItem:(id)item { - if (((FileListNode *)item).isFolder) + if (((FileListNode*)item).isFolder) + { return ROW_SMALL_HEIGHT; + } else + { return outlineView.rowHeight; + } } -- (void) setCheck: (id) sender +- (void)setCheck:(id)sender { NSInteger state = [sender tag] == FILE_UNCHECK_TAG ? NSOffState : NSOnState; - NSIndexSet * indexSet = fOutline.selectedRowIndexes; - NSMutableIndexSet * itemIndexes = [NSMutableIndexSet indexSet]; - for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) + NSIndexSet* indexSet = fOutline.selectedRowIndexes; + NSMutableIndexSet* itemIndexes = [NSMutableIndexSet indexSet]; + for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) { - FileListNode * item = [fOutline itemAtRow: i]; - [itemIndexes addIndexes: item.indexes]; + FileListNode* item = [fOutline itemAtRow:i]; + [itemIndexes addIndexes:item.indexes]; } - [fTorrent setFileCheckState: state forIndexes: itemIndexes]; + [fTorrent setFileCheckState:state forIndexes:itemIndexes]; fOutline.needsDisplay = YES; } -- (void) setOnlySelectedCheck: (id) sender +- (void)setOnlySelectedCheck:(id)sender { - NSIndexSet * indexSet = fOutline.selectedRowIndexes; - NSMutableIndexSet * itemIndexes = [NSMutableIndexSet indexSet]; - for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) + NSIndexSet* indexSet = fOutline.selectedRowIndexes; + NSMutableIndexSet* itemIndexes = [NSMutableIndexSet indexSet]; + for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) { - FileListNode * item = [fOutline itemAtRow: i]; - [itemIndexes addIndexes: item.indexes]; + FileListNode* item = [fOutline itemAtRow:i]; + [itemIndexes addIndexes:item.indexes]; } - [fTorrent setFileCheckState: NSOnState forIndexes: itemIndexes]; + [fTorrent setFileCheckState:NSOnState forIndexes:itemIndexes]; - NSMutableIndexSet * remainingItemIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTorrent.fileCount)]; - [remainingItemIndexes removeIndexes: itemIndexes]; - [fTorrent setFileCheckState: NSOffState forIndexes: remainingItemIndexes]; + NSMutableIndexSet* remainingItemIndexes = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fTorrent.fileCount)]; + [remainingItemIndexes removeIndexes:itemIndexes]; + [fTorrent setFileCheckState:NSOffState forIndexes:remainingItemIndexes]; fOutline.needsDisplay = YES; } -- (void) checkAll +- (void)checkAll { - NSIndexSet * indexSet = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTorrent.fileCount)]; - [fTorrent setFileCheckState: NSOnState forIndexes: indexSet]; + NSIndexSet* indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fTorrent.fileCount)]; + [fTorrent setFileCheckState:NSOnState forIndexes:indexSet]; fOutline.needsDisplay = YES; } -- (void) uncheckAll +- (void)uncheckAll { - NSIndexSet * indexSet = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTorrent.fileCount)]; - [fTorrent setFileCheckState: NSOffState forIndexes: indexSet]; + NSIndexSet* indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fTorrent.fileCount)]; + [fTorrent setFileCheckState:NSOffState forIndexes:indexSet]; fOutline.needsDisplay = YES; } -- (void) setPriority: (id) sender +- (void)setPriority:(id)sender { tr_priority_t priority; switch ([sender tag]) { - case FILE_PRIORITY_HIGH_TAG: - priority = TR_PRI_HIGH; - break; - case FILE_PRIORITY_NORMAL_TAG: - priority = TR_PRI_NORMAL; - break; - case FILE_PRIORITY_LOW_TAG: - priority = TR_PRI_LOW; + case FILE_PRIORITY_HIGH_TAG: + priority = TR_PRI_HIGH; + break; + case FILE_PRIORITY_NORMAL_TAG: + priority = TR_PRI_NORMAL; + break; + case FILE_PRIORITY_LOW_TAG: + priority = TR_PRI_LOW; } - NSIndexSet * indexSet = fOutline.selectedRowIndexes; - NSMutableIndexSet * itemIndexes = [NSMutableIndexSet indexSet]; - for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) + NSIndexSet* indexSet = fOutline.selectedRowIndexes; + NSMutableIndexSet* itemIndexes = [NSMutableIndexSet indexSet]; + for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) { - FileListNode * item = [fOutline itemAtRow: i]; - [itemIndexes addIndexes: item.indexes]; + FileListNode* item = [fOutline itemAtRow:i]; + [itemIndexes addIndexes:item.indexes]; } - [fTorrent setFilePriority: priority forIndexes: itemIndexes]; + [fTorrent setFilePriority:priority forIndexes:itemIndexes]; fOutline.needsDisplay = YES; } -- (void) revealFile: (id) sender +- (void)revealFile:(id)sender { - NSIndexSet * indexes = fOutline.selectedRowIndexes; - NSMutableArray * paths = [NSMutableArray arrayWithCapacity: indexes.count]; - for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex: i]) + NSIndexSet* indexes = fOutline.selectedRowIndexes; + NSMutableArray* paths = [NSMutableArray arrayWithCapacity:indexes.count]; + for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex:i]) { - NSString * path = [fTorrent fileLocation: [fOutline itemAtRow: i]]; + NSString* path = [fTorrent fileLocation:[fOutline itemAtRow:i]]; if (path) - [paths addObject: [NSURL fileURLWithPath: path]]; + { + [paths addObject:[NSURL fileURLWithPath:path]]; + } } if (paths.count > 0) - [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs: paths]; + { + [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs:paths]; + } } -- (void) renameSelected: (id) sender +- (void)renameSelected:(id)sender { - NSIndexSet * indexes = fOutline.selectedRowIndexes; + NSIndexSet* indexes = fOutline.selectedRowIndexes; NSAssert(indexes.count == 1, @"1 file needs to be selected to rename, but %ld are selected", indexes.count); - FileListNode * node = [fOutline itemAtRow: indexes.firstIndex]; - Torrent * torrent = node.torrent; + FileListNode* node = [fOutline itemAtRow:indexes.firstIndex]; + Torrent* torrent = node.torrent; if (!torrent.folder) { - [FileRenameSheetController presentSheetForTorrent: torrent modalForWindow: fOutline.window completionHandler: ^(BOOL didRename) { + [FileRenameSheetController presentSheetForTorrent:torrent modalForWindow:fOutline.window completionHandler:^(BOOL didRename) { if (didRename) { - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateQueue" object: self]; - [NSNotificationCenter.defaultCenter postNotificationName: @"ResetInspector" object: self userInfo: @{ @"Torrent" : torrent }]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateQueue" object:self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"ResetInspector" object:self + userInfo:@{ @"Torrent" : torrent }]; } }]; } else { - [FileRenameSheetController presentSheetForFileListNode: node modalForWindow: fOutline.window completionHandler: ^(BOOL didRename) { - #warning instead of calling reset inspector, just resort? + [FileRenameSheetController presentSheetForFileListNode:node modalForWindow:fOutline.window completionHandler:^(BOOL didRename) { +#warning instead of calling reset inspector, just resort? if (didRename) - [NSNotificationCenter.defaultCenter postNotificationName: @"ResetInspector" object: self userInfo: @{ @"Torrent" : torrent }]; + [NSNotificationCenter.defaultCenter postNotificationName:@"ResetInspector" object:self + userInfo:@{ @"Torrent" : torrent }]; }]; } } #warning make real view controller (Leopard-only) so that Command-R will work -- (BOOL) validateMenuItem: (NSMenuItem *) menuItem +- (BOOL)validateMenuItem:(NSMenuItem*)menuItem { if (!fTorrent) + { return NO; + } SEL action = menuItem.action; if (action == @selector(revealFile:)) { - NSIndexSet * indexSet = fOutline.selectedRowIndexes; - for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) - if ([fTorrent fileLocation: [fOutline itemAtRow: i]] != nil) + NSIndexSet* indexSet = fOutline.selectedRowIndexes; + for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) + { + if ([fTorrent fileLocation:[fOutline itemAtRow:i]] != nil) + { return YES; + } + } return NO; } if (action == @selector(setCheck:)) { if (fOutline.numberOfSelectedRows == 0) - return NO; - - NSIndexSet * indexSet = fOutline.selectedRowIndexes; - NSMutableIndexSet * itemIndexes = [NSMutableIndexSet indexSet]; - for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) { - FileListNode * node = [fOutline itemAtRow: i]; - [itemIndexes addIndexes: node.indexes]; + return NO; + } + + NSIndexSet* indexSet = fOutline.selectedRowIndexes; + NSMutableIndexSet* itemIndexes = [NSMutableIndexSet indexSet]; + for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) + { + FileListNode* node = [fOutline itemAtRow:i]; + [itemIndexes addIndexes:node.indexes]; } NSInteger state = (menuItem.tag == FILE_CHECK_TAG) ? NSOnState : NSOffState; - return [fTorrent checkForFiles: itemIndexes] != state && [fTorrent canChangeDownloadCheckForFiles: itemIndexes]; + return [fTorrent checkForFiles:itemIndexes] != state && [fTorrent canChangeDownloadCheckForFiles:itemIndexes]; } if (action == @selector(setOnlySelectedCheck:)) { if (fOutline.numberOfSelectedRows == 0) - return NO; - - NSIndexSet * indexSet = fOutline.selectedRowIndexes; - NSMutableIndexSet * itemIndexes = [NSMutableIndexSet indexSet]; - for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) { - FileListNode * node = [fOutline itemAtRow: i]; - [itemIndexes addIndexes: node.indexes]; + return NO; } - return [fTorrent canChangeDownloadCheckForFiles: itemIndexes]; + NSIndexSet* indexSet = fOutline.selectedRowIndexes; + NSMutableIndexSet* itemIndexes = [NSMutableIndexSet indexSet]; + for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) + { + FileListNode* node = [fOutline itemAtRow:i]; + [itemIndexes addIndexes:node.indexes]; + } + + return [fTorrent canChangeDownloadCheckForFiles:itemIndexes]; } if (action == @selector(setPriority:)) @@ -509,31 +571,33 @@ typedef NS_ENUM(unsigned int, filePriorityMenuTag) { } //determine which priorities are checked - NSIndexSet * indexSet = fOutline.selectedRowIndexes; + NSIndexSet* indexSet = fOutline.selectedRowIndexes; tr_priority_t priority; switch (menuItem.tag) { - case FILE_PRIORITY_HIGH_TAG: - priority = TR_PRI_HIGH; - break; - case FILE_PRIORITY_NORMAL_TAG: - priority = TR_PRI_NORMAL; - break; - case FILE_PRIORITY_LOW_TAG: - priority = TR_PRI_LOW; - break; + case FILE_PRIORITY_HIGH_TAG: + priority = TR_PRI_HIGH; + break; + case FILE_PRIORITY_NORMAL_TAG: + priority = TR_PRI_NORMAL; + break; + case FILE_PRIORITY_LOW_TAG: + priority = TR_PRI_LOW; + break; } BOOL current = NO, canChange = NO; - for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) + for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) { - FileListNode * node = [fOutline itemAtRow: i]; - NSIndexSet * fileIndexSet = node.indexes; - if (![fTorrent canChangeDownloadCheckForFiles: fileIndexSet]) + FileListNode* node = [fOutline itemAtRow:i]; + NSIndexSet* fileIndexSet = node.indexes; + if (![fTorrent canChangeDownloadCheckForFiles:fileIndexSet]) + { continue; + } canChange = YES; - if ([fTorrent hasFilePriority: priority forIndexes: fileIndexSet]) + if ([fTorrent hasFilePriority:priority forIndexes:fileIndexSet]) { current = YES; break; @@ -556,104 +620,121 @@ typedef NS_ENUM(unsigned int, filePriorityMenuTag) { @implementation FileOutlineController (Private) -- (NSMenu *) menu +- (NSMenu*)menu { - NSMenu * menu = [[NSMenu alloc] initWithTitle: @"File Outline Menu"]; + NSMenu* menu = [[NSMenu alloc] initWithTitle:@"File Outline Menu"]; //check and uncheck - NSMenuItem * item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Check Selected", "File Outline -> Menu") - action: @selector(setCheck:) keyEquivalent: @""]; + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Check Selected", "File Outline -> Menu") + action:@selector(setCheck:) + keyEquivalent:@""]; item.target = self; item.tag = FILE_CHECK_TAG; - [menu addItem: item]; + [menu addItem:item]; - item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Uncheck Selected", "File Outline -> Menu") - action: @selector(setCheck:) keyEquivalent: @""]; + item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Uncheck Selected", "File Outline -> Menu") + action:@selector(setCheck:) + keyEquivalent:@""]; item.target = self; item.tag = FILE_UNCHECK_TAG; - [menu addItem: item]; + [menu addItem:item]; //only check selected - item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Only Check Selected", "File Outline -> Menu") - action: @selector(setOnlySelectedCheck:) keyEquivalent: @""]; + item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Only Check Selected", "File Outline -> Menu") + action:@selector(setOnlySelectedCheck:) + keyEquivalent:@""]; item.target = self; - [menu addItem: item]; + [menu addItem:item]; - [menu addItem: [NSMenuItem separatorItem]]; + [menu addItem:[NSMenuItem separatorItem]]; //priority - item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Priority", "File Outline -> Menu") action: NULL keyEquivalent: @""]; - NSMenu * priorityMenu = [[NSMenu alloc] initWithTitle: @"File Priority Menu"]; + item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Priority", "File Outline -> Menu") action:NULL keyEquivalent:@""]; + NSMenu* priorityMenu = [[NSMenu alloc] initWithTitle:@"File Priority Menu"]; item.submenu = priorityMenu; - [menu addItem: item]; + [menu addItem:item]; - item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"High", "File Outline -> Priority Menu") - action: @selector(setPriority:) keyEquivalent: @""]; + item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"High", "File Outline -> Priority Menu") + action:@selector(setPriority:) + keyEquivalent:@""]; item.target = self; item.tag = FILE_PRIORITY_HIGH_TAG; - item.image = [NSImage imageNamed: @"PriorityHighTemplate"]; - [priorityMenu addItem: item]; + item.image = [NSImage imageNamed:@"PriorityHighTemplate"]; + [priorityMenu addItem:item]; - item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Normal", "File Outline -> Priority Menu") - action: @selector(setPriority:) keyEquivalent: @""]; + item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Normal", "File Outline -> Priority Menu") + action:@selector(setPriority:) + keyEquivalent:@""]; item.target = self; item.tag = FILE_PRIORITY_NORMAL_TAG; - item.image = [NSImage imageNamed: @"PriorityNormalTemplate"]; - [priorityMenu addItem: item]; + item.image = [NSImage imageNamed:@"PriorityNormalTemplate"]; + [priorityMenu addItem:item]; - item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Low", "File Outline -> Priority Menu") - action: @selector(setPriority:) keyEquivalent: @""]; + item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Low", "File Outline -> Priority Menu") + action:@selector(setPriority:) + keyEquivalent:@""]; item.target = self; item.tag = FILE_PRIORITY_LOW_TAG; - item.image = [NSImage imageNamed: @"PriorityLowTemplate"]; - [priorityMenu addItem: item]; + item.image = [NSImage imageNamed:@"PriorityLowTemplate"]; + [priorityMenu addItem:item]; - - [menu addItem: [NSMenuItem separatorItem]]; + [menu addItem:[NSMenuItem separatorItem]]; //reveal in finder - item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Show in Finder", "File Outline -> Menu") - action: @selector(revealFile:) keyEquivalent: @""]; + item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Show in Finder", "File Outline -> Menu") + action:@selector(revealFile:) + keyEquivalent:@""]; item.target = self; - [menu addItem: item]; + [menu addItem:item]; - [menu addItem: [NSMenuItem separatorItem]]; + [menu addItem:[NSMenuItem separatorItem]]; //rename - item = [[NSMenuItem alloc] initWithTitle: [NSLocalizedString(@"Rename File", "File Outline -> Menu") stringByAppendingEllipsis] - action: @selector(renameSelected:) keyEquivalent: @""]; + item = [[NSMenuItem alloc] initWithTitle:[NSLocalizedString(@"Rename File", "File Outline -> Menu") stringByAppendingEllipsis] + action:@selector(renameSelected:) + keyEquivalent:@""]; item.target = self; - [menu addItem: item]; + [menu addItem:item]; return menu; } -- (NSUInteger) findFileNode: (FileListNode *) node inList: (NSArray *) list atIndexes: (NSIndexSet *) indexes currentParent: (FileListNode *) currentParent finalParent: (FileListNode * __autoreleasing *) parent +- (NSUInteger)findFileNode:(FileListNode*)node + inList:(NSArray*)list + atIndexes:(NSIndexSet*)indexes + currentParent:(FileListNode*)currentParent + finalParent:(FileListNode* __autoreleasing*)parent { NSAssert(!node.isFolder, @"Looking up folder node!"); __block NSUInteger retIndex = NSNotFound; - [list enumerateObjectsAtIndexes: indexes options: NSEnumerationConcurrent usingBlock: ^(FileListNode * checkNode, NSUInteger index, BOOL * stop) { - if ([checkNode.indexes containsIndex: node.indexes.firstIndex]) - { - if (!checkNode.isFolder) - { - NSAssert2([checkNode isEqualTo: node], @"Expected file nodes to be equal: %@ %@", checkNode, node); + [list enumerateObjectsAtIndexes:indexes options:NSEnumerationConcurrent + usingBlock:^(FileListNode* checkNode, NSUInteger index, BOOL* stop) { + if ([checkNode.indexes containsIndex:node.indexes.firstIndex]) + { + if (!checkNode.isFolder) + { + NSAssert2([checkNode isEqualTo:node], @"Expected file nodes to be equal: %@ %@", checkNode, node); - *parent = currentParent; - retIndex = index; - } - else - { - const NSUInteger subIndex = [self findFileNode: node inList: checkNode.children atIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, checkNode.children.count)] currentParent: checkNode finalParent: parent]; - NSAssert(subIndex != NSNotFound, @"We didn't find an expected file node."); - retIndex = subIndex; - } + *parent = currentParent; + retIndex = index; + } + else + { + NSUInteger const subIndex = [self + findFileNode:node + inList:checkNode.children + atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, checkNode.children.count)] + currentParent:checkNode + finalParent:parent]; + NSAssert(subIndex != NSNotFound, @"We didn't find an expected file node."); + retIndex = subIndex; + } - *stop = YES; - } - }]; + *stop = YES; + } + }]; return retIndex; } diff --git a/macosx/FileOutlineView.h b/macosx/FileOutlineView.h index d3f28d9e8..419e43fa0 100644 --- a/macosx/FileOutlineView.h +++ b/macosx/FileOutlineView.h @@ -29,8 +29,8 @@ NSInteger fMouseRow; } -- (NSRect) iconRectForRow: (int) row; +- (NSRect)iconRectForRow:(int)row; -@property (nonatomic, readonly) NSInteger hoveredRow; +@property(nonatomic, readonly) NSInteger hoveredRow; @end diff --git a/macosx/FileOutlineView.m b/macosx/FileOutlineView.m index 28bdb0e9c..6535cd0db 100644 --- a/macosx/FileOutlineView.m +++ b/macosx/FileOutlineView.m @@ -29,13 +29,13 @@ @implementation FileOutlineView -- (void) awakeFromNib +- (void)awakeFromNib { - FileNameCell * nameCell = [[FileNameCell alloc] init]; - [self tableColumnWithIdentifier: @"Name"].dataCell = nameCell; + FileNameCell* nameCell = [[FileNameCell alloc] init]; + [self tableColumnWithIdentifier:@"Name"].dataCell = nameCell; - FilePriorityCell * priorityCell = [[FilePriorityCell alloc] init]; - [self tableColumnWithIdentifier: @"Priority"].dataCell = priorityCell; + FilePriorityCell* priorityCell = [[FilePriorityCell alloc] init]; + [self tableColumnWithIdentifier:@"Priority"].dataCell = priorityCell; self.autoresizesOutlineColumn = NO; self.indentationPerLevel = 14.0; @@ -43,84 +43,91 @@ fMouseRow = -1; } - -- (void) mouseDown: (NSEvent *) event +- (void)mouseDown:(NSEvent*)event { [self.window makeKeyWindow]; - [super mouseDown: event]; + [super mouseDown:event]; } -- (NSMenu *) menuForEvent: (NSEvent *) event +- (NSMenu*)menuForEvent:(NSEvent*)event { - const NSInteger row = [self rowAtPoint: [self convertPoint: event.locationInWindow fromView: nil]]; + NSInteger const row = [self rowAtPoint:[self convertPoint:event.locationInWindow fromView:nil]]; if (row >= 0) { - if (![self isRowSelected: row]) - [self selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; + if (![self isRowSelected:row]) + { + [self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO]; + } } else - [self deselectAll: self]; + { + [self deselectAll:self]; + } return self.menu; } -- (NSRect) iconRectForRow: (int) row +- (NSRect)iconRectForRow:(int)row { - FileNameCell * cell = (FileNameCell *)[self preparedCellAtColumn: [self columnWithIdentifier: @"Name"] row: row]; - NSRect iconRect = [cell imageRectForBounds: [self rectOfRow: row]]; + FileNameCell* cell = (FileNameCell*)[self preparedCellAtColumn:[self columnWithIdentifier:@"Name"] row:row]; + NSRect iconRect = [cell imageRectForBounds:[self rectOfRow:row]]; - iconRect.origin.x += self.indentationPerLevel * (CGFloat)([self levelForRow: row] + 1); + iconRect.origin.x += self.indentationPerLevel * (CGFloat)([self levelForRow:row] + 1); return iconRect; } -- (void) updateTrackingAreas +- (void)updateTrackingAreas { [super updateTrackingAreas]; - for (NSTrackingArea * area in self.trackingAreas) + for (NSTrackingArea* area in self.trackingAreas) { if (area.owner == self && area.userInfo[@"Row"]) - [self removeTrackingArea: area]; + { + [self removeTrackingArea:area]; + } } - NSRange visibleRows = [self rowsInRect: self.visibleRect]; + NSRange visibleRows = [self rowsInRect:self.visibleRect]; if (visibleRows.length == 0) - return; - - NSPoint mouseLocation = [self convertPoint: self.window.mouseLocationOutsideOfEventStream fromView: nil]; - - for (NSInteger row = visibleRows.location, col = [self columnWithIdentifier: @"Priority"]; (NSUInteger)row < NSMaxRange(visibleRows); row++) { - FilePriorityCell * cell = (FilePriorityCell *)[self preparedCellAtColumn: col row: row]; + return; + } - NSDictionary * userInfo = @{@"Row": @(row)}; - [cell addTrackingAreasForView: self inRect: [self frameOfCellAtColumn: col row: row] withUserInfo: userInfo - mouseLocation: mouseLocation]; + NSPoint mouseLocation = [self convertPoint:self.window.mouseLocationOutsideOfEventStream fromView:nil]; + + for (NSInteger row = visibleRows.location, col = [self columnWithIdentifier:@"Priority"]; (NSUInteger)row < NSMaxRange(visibleRows); row++) + { + FilePriorityCell* cell = (FilePriorityCell*)[self preparedCellAtColumn:col row:row]; + + NSDictionary* userInfo = @{ @"Row" : @(row) }; + [cell addTrackingAreasForView:self inRect:[self frameOfCellAtColumn:col row:row] withUserInfo:userInfo + mouseLocation:mouseLocation]; } } -- (NSInteger) hoveredRow +- (NSInteger)hoveredRow { return fMouseRow; } -- (void) mouseEntered: (NSEvent *) event +- (void)mouseEntered:(NSEvent*)event { - NSNumber * row; - if ((row = ((NSDictionary *)event.userData)[@"Row"])) + NSNumber* row; + if ((row = ((NSDictionary*)event.userData)[@"Row"])) { fMouseRow = row.intValue; - [self setNeedsDisplayInRect: [self frameOfCellAtColumn: [self columnWithIdentifier: @"Priority"] row: fMouseRow]]; + [self setNeedsDisplayInRect:[self frameOfCellAtColumn:[self columnWithIdentifier:@"Priority"] row:fMouseRow]]; } } -- (void) mouseExited: (NSEvent *) event +- (void)mouseExited:(NSEvent*)event { - NSNumber * row; - if ((row = ((NSDictionary *)event.userData)[@"Row"])) + NSNumber* row; + if ((row = ((NSDictionary*)event.userData)[@"Row"])) { - [self setNeedsDisplayInRect: [self frameOfCellAtColumn: [self columnWithIdentifier: @"Priority"] row: row.intValue]]; + [self setNeedsDisplayInRect:[self frameOfCellAtColumn:[self columnWithIdentifier:@"Priority"] row:row.intValue]]; fMouseRow = -1; } } diff --git a/macosx/FilePriorityCell.h b/macosx/FilePriorityCell.h index 423d45ddd..0a0b6462d 100644 --- a/macosx/FilePriorityCell.h +++ b/macosx/FilePriorityCell.h @@ -29,9 +29,11 @@ BOOL fHoverRow; } -- (void) addTrackingAreasForView: (NSView *) controlView inRect: (NSRect) cellFrame withUserInfo: (NSDictionary *) userInfo - mouseLocation: (NSPoint) mouseLocation; +- (void)addTrackingAreasForView:(NSView*)controlView + inRect:(NSRect)cellFrame + withUserInfo:(NSDictionary*)userInfo + mouseLocation:(NSPoint)mouseLocation; -- (void) setHovered: (BOOL) hovered; +- (void)setHovered:(BOOL)hovered; @end diff --git a/macosx/FilePriorityCell.m b/macosx/FilePriorityCell.m index acf5a5966..07cc6d254 100644 --- a/macosx/FilePriorityCell.m +++ b/macosx/FilePriorityCell.m @@ -30,7 +30,7 @@ @implementation FilePriorityCell -- (instancetype) init +- (instancetype)init { if ((self = [super init])) { @@ -40,138 +40,147 @@ for (NSInteger i = 0; i < self.segmentCount; i++) { - [self setLabel: @"" forSegment: i]; - [self setWidth: 9.0f forSegment: i]; //9 is minimum size to get proper look + [self setLabel:@"" forSegment:i]; + [self setWidth:9.0f forSegment:i]; //9 is minimum size to get proper look } - [self setImage: [NSImage imageNamed: @"PriorityControlLow"] forSegment: 0]; - [self setImage: [NSImage imageNamed: @"PriorityControlNormal"] forSegment: 1]; - [self setImage: [NSImage imageNamed: @"PriorityControlHigh"] forSegment: 2]; + [self setImage:[NSImage imageNamed:@"PriorityControlLow"] forSegment:0]; + [self setImage:[NSImage imageNamed:@"PriorityControlNormal"] forSegment:1]; + [self setImage:[NSImage imageNamed:@"PriorityControlHigh"] forSegment:2]; fHoverRow = NO; } return self; } -- (id) copyWithZone: (NSZone *) zone +- (id)copyWithZone:(NSZone*)zone { - id value = [super copyWithZone: zone]; - [value setRepresentedObject: self.representedObject]; + id value = [super copyWithZone:zone]; + [value setRepresentedObject:self.representedObject]; return value; } -- (void) setSelected: (BOOL) flag forSegment: (NSInteger) segment +- (void)setSelected:(BOOL)flag forSegment:(NSInteger)segment { - [super setSelected: flag forSegment: segment]; + [super setSelected:flag forSegment:segment]; //only for when clicking manually NSInteger priority; switch (segment) { - case 0: - priority = TR_PRI_LOW; - break; - case 1: - priority = TR_PRI_NORMAL; - break; - case 2: - priority = TR_PRI_HIGH; - break; + case 0: + priority = TR_PRI_LOW; + break; + case 1: + priority = TR_PRI_NORMAL; + break; + case 2: + priority = TR_PRI_HIGH; + break; } - FileListNode * node = self.representedObject; - Torrent * torrent = node.torrent; - [torrent setFilePriority: priority forIndexes: node.indexes]; + FileListNode* node = self.representedObject; + Torrent* torrent = node.torrent; + [torrent setFilePriority:priority forIndexes:node.indexes]; - FileOutlineView * controlView = (FileOutlineView *)self.controlView; + FileOutlineView* controlView = (FileOutlineView*)self.controlView; controlView.needsDisplay = YES; } -- (void) addTrackingAreasForView: (NSView *) controlView inRect: (NSRect) cellFrame withUserInfo: (NSDictionary *) userInfo - mouseLocation: (NSPoint) mouseLocation +- (void)addTrackingAreasForView:(NSView*)controlView + inRect:(NSRect)cellFrame + withUserInfo:(NSDictionary*)userInfo + mouseLocation:(NSPoint)mouseLocation { NSTrackingAreaOptions options = NSTrackingEnabledDuringMouseDrag | NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways; if (NSMouseInRect(mouseLocation, cellFrame, controlView.flipped)) { options |= NSTrackingAssumeInside; - [controlView setNeedsDisplayInRect: cellFrame]; + [controlView setNeedsDisplayInRect:cellFrame]; } - NSTrackingArea * area = [[NSTrackingArea alloc] initWithRect: cellFrame options: options owner: controlView userInfo: userInfo]; - [controlView addTrackingArea: area]; + NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect:cellFrame options:options owner:controlView userInfo:userInfo]; + [controlView addTrackingArea:area]; } -- (void) setHovered: (BOOL) hovered +- (void)setHovered:(BOOL)hovered { fHoverRow = hovered; } -- (void) drawWithFrame: (NSRect) cellFrame inView: (NSView *) controlView +- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView { - FileListNode * node = self.representedObject; - Torrent * torrent = node.torrent; - NSSet * priorities = [torrent filePrioritiesForIndexes: node.indexes]; + FileListNode* node = self.representedObject; + Torrent* torrent = node.torrent; + NSSet* priorities = [torrent filePrioritiesForIndexes:node.indexes]; - const NSUInteger count = priorities.count; + NSUInteger const count = priorities.count; if (fHoverRow && count > 0) { - [super setSelected: [priorities containsObject: @(TR_PRI_LOW)] forSegment: 0]; - [super setSelected: [priorities containsObject: @(TR_PRI_NORMAL)] forSegment: 1]; - [super setSelected: [priorities containsObject: @(TR_PRI_HIGH)] forSegment: 2]; + [super setSelected:[priorities containsObject:@(TR_PRI_LOW)] forSegment:0]; + [super setSelected:[priorities containsObject:@(TR_PRI_NORMAL)] forSegment:1]; + [super setSelected:[priorities containsObject:@(TR_PRI_HIGH)] forSegment:2]; - [super drawWithFrame: cellFrame inView: controlView]; + [super drawWithFrame:cellFrame inView:controlView]; } else { - NSMutableArray * images = [NSMutableArray arrayWithCapacity: MAX(count, 1u)]; + NSMutableArray* images = [NSMutableArray arrayWithCapacity:MAX(count, 1u)]; CGFloat totalWidth; if (count == 0) { //if ([self backgroundStyle] != NSBackgroundStyleDark) { - NSImage * image = [[NSImage imageNamed: @"PriorityNormalTemplate"] imageWithColor: NSColor.lightGrayColor]; - [images addObject: image]; + NSImage* image = [[NSImage imageNamed:@"PriorityNormalTemplate"] imageWithColor:NSColor.lightGrayColor]; + [images addObject:image]; totalWidth = image.size.width; } } else { - NSColor * priorityColor = self.backgroundStyle == NSBackgroundStyleDark ? NSColor.whiteColor : NSColor.darkGrayColor; + NSColor* priorityColor = self.backgroundStyle == NSBackgroundStyleDark ? NSColor.whiteColor : NSColor.darkGrayColor; totalWidth = 0.0; - if ([priorities containsObject: @(TR_PRI_LOW)]) + if ([priorities containsObject:@(TR_PRI_LOW)]) { - NSImage * image = [[NSImage imageNamed: @"PriorityLowTemplate"] imageWithColor: priorityColor]; - [images addObject: image]; + NSImage* image = [[NSImage imageNamed:@"PriorityLowTemplate"] imageWithColor:priorityColor]; + [images addObject:image]; totalWidth += image.size.width; } - if ([priorities containsObject: @(TR_PRI_NORMAL)]) + if ([priorities containsObject:@(TR_PRI_NORMAL)]) { - NSImage * image = [[NSImage imageNamed: @"PriorityNormalTemplate"] imageWithColor: priorityColor]; - [images addObject: image]; + NSImage* image = [[NSImage imageNamed:@"PriorityNormalTemplate"] imageWithColor:priorityColor]; + [images addObject:image]; totalWidth += image.size.width; } - if ([priorities containsObject: @(TR_PRI_HIGH)]) + if ([priorities containsObject:@(TR_PRI_HIGH)]) { - NSImage * image = [[NSImage imageNamed: @"PriorityHighTemplate"] imageWithColor: priorityColor]; - [images addObject: image]; + NSImage* image = [[NSImage imageNamed:@"PriorityHighTemplate"] imageWithColor:priorityColor]; + [images addObject:image]; totalWidth += image.size.width; } } if (count > 1) - totalWidth -= IMAGE_OVERLAP * (count-1); + { + totalWidth -= IMAGE_OVERLAP * (count - 1); + } CGFloat currentWidth = floor(NSMidX(cellFrame) - totalWidth * 0.5); - for (NSImage * image in images) + for (NSImage* image in images) { - const NSSize imageSize = image.size; - const NSRect imageRect = NSMakeRect(currentWidth, floor(NSMidY(cellFrame) - imageSize.height * 0.5), imageSize.width, imageSize.height); + NSSize const imageSize = image.size; + NSRect const imageRect = NSMakeRect( + currentWidth, + floor(NSMidY(cellFrame) - imageSize.height * 0.5), + imageSize.width, + imageSize.height); - [image drawInRect: imageRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; + [image drawInRect:imageRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 respectFlipped:YES + hints:nil]; currentWidth += imageSize.width - IMAGE_OVERLAP; } diff --git a/macosx/FileRenameSheetController.h b/macosx/FileRenameSheetController.h index 2e230b82f..dc2ba3ae1 100644 --- a/macosx/FileRenameSheetController.h +++ b/macosx/FileRenameSheetController.h @@ -13,15 +13,19 @@ @interface FileRenameSheetController : NSWindowController -+ (void) presentSheetForTorrent: (Torrent *) torrent modalForWindow: (NSWindow *) window completionHandler: (void (^)(BOOL didRename)) completionHandler; -+ (void) presentSheetForFileListNode: (FileListNode *) node modalForWindow: (NSWindow *) window completionHandler: (void (^)(BOOL didRename)) completionHandler; ++ (void)presentSheetForTorrent:(Torrent*)torrent + modalForWindow:(NSWindow*)window + completionHandler:(void (^)(BOOL didRename))completionHandler; ++ (void)presentSheetForFileListNode:(FileListNode*)node + modalForWindow:(NSWindow*)window + completionHandler:(void (^)(BOOL didRename))completionHandler; -@property (weak) IBOutlet NSTextField * labelField; -@property (weak) IBOutlet NSTextField * inputField; -@property (weak) IBOutlet NSButton * renameButton; -@property (weak) IBOutlet NSButton * cancelButton; +@property(weak) IBOutlet NSTextField* labelField; +@property(weak) IBOutlet NSTextField* inputField; +@property(weak) IBOutlet NSButton* renameButton; +@property(weak) IBOutlet NSButton* cancelButton; -- (IBAction) rename: (id) sender; -- (IBAction) cancelRename: (id) sender; +- (IBAction)rename:(id)sender; +- (IBAction)cancelRename:(id)sender; @end diff --git a/macosx/FileRenameSheetController.m b/macosx/FileRenameSheetController.m index 08dafaa41..9d808f0e8 100644 --- a/macosx/FileRenameSheetController.m +++ b/macosx/FileRenameSheetController.m @@ -14,72 +14,79 @@ typedef void (^CompletionBlock)(BOOL); @interface FileRenameSheetController () -@property (nonatomic) Torrent * torrent; -@property (nonatomic) FileListNode * node; -@property (nonatomic, copy) CompletionBlock completionHandler; +@property(nonatomic) Torrent* torrent; +@property(nonatomic) FileListNode* node; +@property(nonatomic, copy) CompletionBlock completionHandler; -@property (nonatomic, copy) NSString * originalName; +@property(nonatomic, copy) NSString* originalName; @end @implementation FileRenameSheetController -+ (void) presentSheetForTorrent: (Torrent *) torrent modalForWindow: (NSWindow *) window completionHandler: (void (^)(BOOL didRename)) completionHandler ++ (void)presentSheetForTorrent:(Torrent*)torrent + modalForWindow:(NSWindow*)window + completionHandler:(void (^)(BOOL didRename))completionHandler { NSParameterAssert(torrent != nil); NSParameterAssert(window != nil); - FileRenameSheetController * renamer = [[FileRenameSheetController alloc] initWithWindowNibName: @"FileRenameSheetController"]; + FileRenameSheetController* renamer = [[FileRenameSheetController alloc] initWithWindowNibName:@"FileRenameSheetController"]; renamer.torrent = torrent; renamer.completionHandler = completionHandler; - [NSApp beginSheet: renamer.window modalForWindow: window modalDelegate: self didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:) contextInfo: (__bridge_retained void *)(renamer)]; + [NSApp beginSheet:renamer.window modalForWindow:window modalDelegate:self + didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) + contextInfo:(__bridge_retained void*)(renamer)]; } -+ (void) presentSheetForFileListNode: (FileListNode *) node modalForWindow: (NSWindow *) window completionHandler: (void (^)(BOOL didRename)) completionHandler ++ (void)presentSheetForFileListNode:(FileListNode*)node + modalForWindow:(NSWindow*)window + completionHandler:(void (^)(BOOL didRename))completionHandler { NSParameterAssert(node != nil); NSParameterAssert(window != nil); - FileRenameSheetController * renamer = [[FileRenameSheetController alloc] initWithWindowNibName: @"FileRenameSheetController"]; + FileRenameSheetController* renamer = [[FileRenameSheetController alloc] initWithWindowNibName:@"FileRenameSheetController"]; renamer.torrent = node.torrent; renamer.node = node; renamer.completionHandler = completionHandler; - [NSApp beginSheet: renamer.window modalForWindow: window modalDelegate: self didEndSelector: @selector(sheetDidEnd:returnCode:contextInfo:) contextInfo: (__bridge_retained void *)(renamer)]; + [NSApp beginSheet:renamer.window modalForWindow:window modalDelegate:self + didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) + contextInfo:(__bridge_retained void*)(renamer)]; } -+ (void) sheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo ++ (void)sheetDidEnd:(NSWindow*)sheet returnCode:(NSInteger)returnCode contextInfo:(void*)contextInfo { - FileRenameSheetController * renamer = (__bridge_transfer FileRenameSheetController *)(contextInfo); + FileRenameSheetController* renamer = (__bridge_transfer FileRenameSheetController*)(contextInfo); NSParameterAssert([renamer isKindOfClass:[FileRenameSheetController class]]); renamer.completionHandler(returnCode == NSOKButton); - [sheet orderOut: self]; + [sheet orderOut:self]; } - -- (void) windowDidLoad +- (void)windowDidLoad { [super windowDidLoad]; self.originalName = self.node.name ?: self.torrent.name; - NSString * label = [NSString stringWithFormat: NSLocalizedString(@"Rename the file \"%@\":", "rename sheet label"), self.originalName]; + NSString* label = [NSString stringWithFormat:NSLocalizedString(@"Rename the file \"%@\":", "rename sheet label"), self.originalName]; self.labelField.stringValue = label; self.inputField.stringValue = self.originalName; self.renameButton.enabled = NO; //resize the buttons so that they're long enough and the same width - const NSRect oldRenameFrame = self.renameButton.frame; - const NSRect oldCancelFrame = self.cancelButton.frame; + NSRect const oldRenameFrame = self.renameButton.frame; + NSRect const oldCancelFrame = self.cancelButton.frame; //get the extra width of the rename button from the English xib - the width from sizeToFit is too squished [self.renameButton sizeToFit]; - const CGFloat extra = NSWidth(oldRenameFrame) - NSWidth(self.renameButton.frame); + CGFloat const extra = NSWidth(oldRenameFrame) - NSWidth(self.renameButton.frame); self.renameButton.title = NSLocalizedString(@"Rename", "rename sheet button"); self.cancelButton.title = NSLocalizedString(@"Cancel", "rename sheet button"); @@ -91,41 +98,48 @@ typedef void (^CompletionBlock)(BOOL); newRenameFrame.size.width = MAX(NSWidth(newRenameFrame), NSWidth(newCancelFrame)) + extra; newCancelFrame.size.width = MAX(NSWidth(newRenameFrame), NSWidth(newCancelFrame)) + extra; - const CGFloat renameWidthIncrease = NSWidth(newRenameFrame) - NSWidth(oldRenameFrame); + CGFloat const renameWidthIncrease = NSWidth(newRenameFrame) - NSWidth(oldRenameFrame); newRenameFrame.origin.x -= renameWidthIncrease; self.renameButton.frame = newRenameFrame; - const CGFloat cancelWidthIncrease = NSWidth(newCancelFrame) - NSWidth(oldCancelFrame); + CGFloat const cancelWidthIncrease = NSWidth(newCancelFrame) - NSWidth(oldCancelFrame); newCancelFrame.origin.x -= renameWidthIncrease + cancelWidthIncrease; self.cancelButton.frame = newCancelFrame; } -- (IBAction) rename: (id) sender +- (IBAction)rename:(id)sender { void (^completionHandler)(BOOL) = ^(BOOL didRename) { if (didRename) - [NSApp endSheet: self.window returnCode: NSOKButton]; + { + [NSApp endSheet:self.window returnCode:NSOKButton]; + } else { - #warning more thorough error +#warning more thorough error NSBeep(); } }; if (self.node) - [self.torrent renameFileNode: self.node withName: self.inputField.stringValue completionHandler: completionHandler]; + { + [self.torrent renameFileNode:self.node withName:self.inputField.stringValue completionHandler:completionHandler]; + } else - [self.torrent renameTorrent: self.inputField.stringValue completionHandler: completionHandler]; + { + [self.torrent renameTorrent:self.inputField.stringValue completionHandler:completionHandler]; + } } -- (IBAction) cancelRename: (id) sender +- (IBAction)cancelRename:(id)sender { - [NSApp endSheet: self.window returnCode: NSCancelButton]; + [NSApp endSheet:self.window returnCode:NSCancelButton]; } -- (void) controlTextDidChange: (NSNotification *) notification +- (void)controlTextDidChange:(NSNotification*)notification { - self.renameButton.enabled = ![self.inputField.stringValue isEqualToString: @""] && ![self.inputField.stringValue isEqualToString: self.originalName]; + self.renameButton.enabled = ![self.inputField.stringValue isEqualToString:@""] && + ![self.inputField.stringValue isEqualToString:self.originalName]; } @end diff --git a/macosx/FilterBarController.h b/macosx/FilterBarController.h index 1191a549a..2d2370389 100644 --- a/macosx/FilterBarController.h +++ b/macosx/FilterBarController.h @@ -24,41 +24,46 @@ @class FilterButton; -#define FILTER_NONE @"None" -#define FILTER_ACTIVE @"Active" +#define FILTER_NONE @"None" +#define FILTER_ACTIVE @"Active" #define FILTER_DOWNLOAD @"Download" -#define FILTER_SEED @"Seed" -#define FILTER_PAUSE @"Pause" +#define FILTER_SEED @"Seed" +#define FILTER_PAUSE @"Pause" -#define FILTER_TYPE_NAME @"Name" +#define FILTER_TYPE_NAME @"Name" #define FILTER_TYPE_TRACKER @"Tracker" #define GROUP_FILTER_ALL_TAG -2 @interface FilterBarController : NSViewController { - IBOutlet FilterButton * fNoFilterButton, * fActiveFilterButton, * fDownloadFilterButton, - * fSeedFilterButton, * fPauseFilterButton; + IBOutlet FilterButton* fNoFilterButton; + IBOutlet FilterButton* fActiveFilterButton; + IBOutlet FilterButton* fDownloadFilterButton; + IBOutlet FilterButton* fSeedFilterButton; + IBOutlet FilterButton* fPauseFilterButton; - IBOutlet NSSearchField * fSearchField; + IBOutlet NSSearchField* fSearchField; - IBOutlet NSPopUpButton * fGroupsButton; + IBOutlet NSPopUpButton* fGroupsButton; } -- (instancetype) init; +- (instancetype)init; -- (void) setFilter: (id) sender; -- (void) switchFilter: (BOOL) right; -- (void) setSearchText: (id) sender; -- (void) setSearchType: (id) sender; -- (void) setGroupFilter: (id) sender; -- (void) reset: (BOOL) updateUI; +- (void)setFilter:(id)sender; +- (void)switchFilter:(BOOL)right; +- (void)setSearchText:(id)sender; +- (void)setSearchType:(id)sender; +- (void)setGroupFilter:(id)sender; +- (void)reset:(BOOL)updateUI; -@property (nonatomic, readonly) NSArray *searchStrings; -- (void) focusSearchField; - -- (void) setCountAll: (NSUInteger) all active: (NSUInteger) active downloading: (NSUInteger) downloading - seeding: (NSUInteger) seeding paused: (NSUInteger) paused; +@property(nonatomic, readonly) NSArray* searchStrings; +- (void)focusSearchField; +- (void)setCountAll:(NSUInteger)all + active:(NSUInteger)active + downloading:(NSUInteger)downloading + seeding:(NSUInteger)seeding + paused:(NSUInteger)paused; @end diff --git a/macosx/FilterBarController.m b/macosx/FilterBarController.m index c8a2b869f..b0247b416 100644 --- a/macosx/FilterBarController.m +++ b/macosx/FilterBarController.m @@ -25,7 +25,7 @@ #import "GroupsController.h" #import "NSStringAdditions.h" -#define FILTER_TYPE_TAG_NAME 401 +#define FILTER_TYPE_TAG_NAME 401 #define FILTER_TYPE_TAG_TRACKER 402 #define SEARCH_MIN_WIDTH 48.0 @@ -33,20 +33,20 @@ @interface FilterBarController (Private) -- (void) resizeBar; -- (void) updateGroupsButton; -- (void) updateGroups: (NSNotification *) notification; +- (void)resizeBar; +- (void)updateGroupsButton; +- (void)updateGroups:(NSNotification*)notification; @end @implementation FilterBarController -- (instancetype) init +- (instancetype)init { - return (self = [super initWithNibName: @"FilterBar" bundle: nil]); + return (self = [super initWithNibName:@"FilterBar" bundle:nil]); } -- (void) awakeFromNib +- (void)awakeFromNib { //localizations fNoFilterButton.title = NSLocalizedString(@"All", "Filter Bar -> filter button"); @@ -61,247 +61,310 @@ fSeedFilterButton.cell.backgroundStyle = NSBackgroundStyleRaised; fPauseFilterButton.cell.backgroundStyle = NSBackgroundStyleRaised; - [fSearchField.searchMenuTemplate itemWithTag: FILTER_TYPE_TAG_NAME].title = - NSLocalizedString(@"Name", "Filter Bar -> filter menu"); - [fSearchField.searchMenuTemplate itemWithTag: FILTER_TYPE_TAG_TRACKER].title = - NSLocalizedString(@"Tracker", "Filter Bar -> filter menu"); + [fSearchField.searchMenuTemplate itemWithTag:FILTER_TYPE_TAG_NAME].title = NSLocalizedString(@"Name", "Filter Bar -> filter menu"); + [fSearchField.searchMenuTemplate itemWithTag:FILTER_TYPE_TAG_TRACKER].title = NSLocalizedString(@"Tracker", "Filter Bar -> filter menu"); - [fGroupsButton.menu itemWithTag: GROUP_FILTER_ALL_TAG].title = - NSLocalizedString(@"All Groups", "Filter Bar -> group filter menu"); + [fGroupsButton.menu itemWithTag:GROUP_FILTER_ALL_TAG].title = NSLocalizedString(@"All Groups", "Filter Bar -> group filter menu"); [self resizeBar]; //set current filter - NSString * filterType = [NSUserDefaults.standardUserDefaults stringForKey: @"Filter"]; + NSString* filterType = [NSUserDefaults.standardUserDefaults stringForKey:@"Filter"]; - NSButton * currentFilterButton; - if ([filterType isEqualToString: FILTER_ACTIVE]) + NSButton* currentFilterButton; + if ([filterType isEqualToString:FILTER_ACTIVE]) + { currentFilterButton = fActiveFilterButton; - else if ([filterType isEqualToString: FILTER_PAUSE]) + } + else if ([filterType isEqualToString:FILTER_PAUSE]) + { currentFilterButton = fPauseFilterButton; - else if ([filterType isEqualToString: FILTER_SEED]) + } + else if ([filterType isEqualToString:FILTER_SEED]) + { currentFilterButton = fSeedFilterButton; - else if ([filterType isEqualToString: FILTER_DOWNLOAD]) + } + else if ([filterType isEqualToString:FILTER_DOWNLOAD]) + { currentFilterButton = fDownloadFilterButton; + } else { //safety - if (![filterType isEqualToString: FILTER_NONE]) - [NSUserDefaults.standardUserDefaults setObject: FILTER_NONE forKey: @"Filter"]; + if (![filterType isEqualToString:FILTER_NONE]) + { + [NSUserDefaults.standardUserDefaults setObject:FILTER_NONE forKey:@"Filter"]; + } currentFilterButton = fNoFilterButton; } currentFilterButton.state = NSOnState; //set filter search type - NSString * filterSearchType = [NSUserDefaults.standardUserDefaults stringForKey: @"FilterSearchType"]; + NSString* filterSearchType = [NSUserDefaults.standardUserDefaults stringForKey:@"FilterSearchType"]; - NSMenu * filterSearchMenu = fSearchField.searchMenuTemplate; - NSString * filterSearchTypeTitle; - if ([filterSearchType isEqualToString: FILTER_TYPE_TRACKER]) - filterSearchTypeTitle = [filterSearchMenu itemWithTag: FILTER_TYPE_TAG_TRACKER].title; + NSMenu* filterSearchMenu = fSearchField.searchMenuTemplate; + NSString* filterSearchTypeTitle; + if ([filterSearchType isEqualToString:FILTER_TYPE_TRACKER]) + { + filterSearchTypeTitle = [filterSearchMenu itemWithTag:FILTER_TYPE_TAG_TRACKER].title; + } else { //safety - if (![filterType isEqualToString: FILTER_TYPE_NAME]) - [NSUserDefaults.standardUserDefaults setObject: FILTER_TYPE_NAME forKey: @"FilterSearchType"]; - filterSearchTypeTitle = [filterSearchMenu itemWithTag: FILTER_TYPE_TAG_NAME].title; + if (![filterType isEqualToString:FILTER_TYPE_NAME]) + { + [NSUserDefaults.standardUserDefaults setObject:FILTER_TYPE_NAME forKey:@"FilterSearchType"]; + } + filterSearchTypeTitle = [filterSearchMenu itemWithTag:FILTER_TYPE_TAG_NAME].title; } fSearchField.placeholderString = filterSearchTypeTitle; - NSString * searchString; - if ((searchString = [NSUserDefaults.standardUserDefaults stringForKey: @"FilterSearchString"])) + NSString* searchString; + if ((searchString = [NSUserDefaults.standardUserDefaults stringForKey:@"FilterSearchString"])) + { fSearchField.stringValue = searchString; + } [self updateGroupsButton]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(resizeBar) - name: NSWindowDidResizeNotification object: self.view.window]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(resizeBar) name:NSWindowDidResizeNotification + object:self.view.window]; //update when groups change - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateGroups:) - name: @"UpdateGroups" object: nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateGroups:) name:@"UpdateGroups" object:nil]; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; } -- (void) setFilter: (id) sender +- (void)setFilter:(id)sender { - NSString * oldFilterType = [NSUserDefaults.standardUserDefaults stringForKey: @"Filter"]; + NSString* oldFilterType = [NSUserDefaults.standardUserDefaults stringForKey:@"Filter"]; - NSButton * prevFilterButton; - if ([oldFilterType isEqualToString: FILTER_PAUSE]) + NSButton* prevFilterButton; + if ([oldFilterType isEqualToString:FILTER_PAUSE]) + { prevFilterButton = fPauseFilterButton; - else if ([oldFilterType isEqualToString: FILTER_ACTIVE]) + } + else if ([oldFilterType isEqualToString:FILTER_ACTIVE]) + { prevFilterButton = fActiveFilterButton; - else if ([oldFilterType isEqualToString: FILTER_SEED]) + } + else if ([oldFilterType isEqualToString:FILTER_SEED]) + { prevFilterButton = fSeedFilterButton; - else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD]) + } + else if ([oldFilterType isEqualToString:FILTER_DOWNLOAD]) + { prevFilterButton = fDownloadFilterButton; + } else + { prevFilterButton = fNoFilterButton; + } if (sender != prevFilterButton) { prevFilterButton.state = NSOffState; - [sender setState: NSOnState]; + [sender setState:NSOnState]; - NSString * filterType; + NSString* filterType; if (sender == fActiveFilterButton) + { filterType = FILTER_ACTIVE; + } else if (sender == fDownloadFilterButton) + { filterType = FILTER_DOWNLOAD; + } else if (sender == fPauseFilterButton) + { filterType = FILTER_PAUSE; + } else if (sender == fSeedFilterButton) + { filterType = FILTER_SEED; + } else + { filterType = FILTER_NONE; + } - [NSUserDefaults.standardUserDefaults setObject: filterType forKey: @"Filter"]; + [NSUserDefaults.standardUserDefaults setObject:filterType forKey:@"Filter"]; } else - [sender setState: NSOnState]; + { + [sender setState:NSOnState]; + } - [NSNotificationCenter.defaultCenter postNotificationName: @"ApplyFilter" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"ApplyFilter" object:nil]; } -- (void) switchFilter: (BOOL) right +- (void)switchFilter:(BOOL)right { - NSString * filterType = [NSUserDefaults.standardUserDefaults stringForKey: @"Filter"]; + NSString* filterType = [NSUserDefaults.standardUserDefaults stringForKey:@"Filter"]; - NSButton * button; - if ([filterType isEqualToString: FILTER_NONE]) + NSButton* button; + if ([filterType isEqualToString:FILTER_NONE]) + { button = right ? fActiveFilterButton : fPauseFilterButton; - else if ([filterType isEqualToString: FILTER_ACTIVE]) + } + else if ([filterType isEqualToString:FILTER_ACTIVE]) + { button = right ? fDownloadFilterButton : fNoFilterButton; - else if ([filterType isEqualToString: FILTER_DOWNLOAD]) + } + else if ([filterType isEqualToString:FILTER_DOWNLOAD]) + { button = right ? fSeedFilterButton : fActiveFilterButton; - else if ([filterType isEqualToString: FILTER_SEED]) + } + else if ([filterType isEqualToString:FILTER_SEED]) + { button = right ? fPauseFilterButton : fDownloadFilterButton; - else if ([filterType isEqualToString: FILTER_PAUSE]) + } + else if ([filterType isEqualToString:FILTER_PAUSE]) + { button = right ? fNoFilterButton : fSeedFilterButton; + } else + { button = fNoFilterButton; + } - [self setFilter: button]; + [self setFilter:button]; } -- (void) setSearchText: (id) sender +- (void)setSearchText:(id)sender { - [NSUserDefaults.standardUserDefaults setObject: fSearchField.stringValue forKey: @"FilterSearchString"]; - [NSNotificationCenter.defaultCenter postNotificationName: @"ApplyFilter" object: nil]; + [NSUserDefaults.standardUserDefaults setObject:fSearchField.stringValue forKey:@"FilterSearchString"]; + [NSNotificationCenter.defaultCenter postNotificationName:@"ApplyFilter" object:nil]; } -- (void) focusSearchField +- (void)focusSearchField { - [self.view.window makeFirstResponder: fSearchField]; + [self.view.window makeFirstResponder:fSearchField]; } -- (void) setSearchType: (id) sender +- (void)setSearchType:(id)sender { - NSString * oldFilterType = [NSUserDefaults.standardUserDefaults stringForKey: @"FilterSearchType"]; + NSString* oldFilterType = [NSUserDefaults.standardUserDefaults stringForKey:@"FilterSearchType"]; NSInteger prevTag, currentTag = [sender tag]; - if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER]) + if ([oldFilterType isEqualToString:FILTER_TYPE_TRACKER]) + { prevTag = FILTER_TYPE_TAG_TRACKER; + } else + { prevTag = FILTER_TYPE_TAG_NAME; + } if (currentTag != prevTag) { - NSString * filterType; + NSString* filterType; if (currentTag == FILTER_TYPE_TAG_TRACKER) + { filterType = FILTER_TYPE_TRACKER; + } else + { filterType = FILTER_TYPE_NAME; + } - [NSUserDefaults.standardUserDefaults setObject: filterType forKey: @"FilterSearchType"]; + [NSUserDefaults.standardUserDefaults setObject:filterType forKey:@"FilterSearchType"]; fSearchField.placeholderString = [sender title]; } - [NSNotificationCenter.defaultCenter postNotificationName: @"ApplyFilter" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"ApplyFilter" object:nil]; } -- (void) setGroupFilter: (id) sender +- (void)setGroupFilter:(id)sender { - [NSUserDefaults.standardUserDefaults setInteger: [sender tag] forKey: @"FilterGroup"]; + [NSUserDefaults.standardUserDefaults setInteger:[sender tag] forKey:@"FilterGroup"]; [self updateGroupsButton]; - [NSNotificationCenter.defaultCenter postNotificationName: @"ApplyFilter" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"ApplyFilter" object:nil]; } -- (void) reset: (BOOL) updateUI +- (void)reset:(BOOL)updateUI { - [NSUserDefaults.standardUserDefaults setInteger: GROUP_FILTER_ALL_TAG forKey: @"FilterGroup"]; + [NSUserDefaults.standardUserDefaults setInteger:GROUP_FILTER_ALL_TAG forKey:@"FilterGroup"]; if (updateUI) { [self updateGroupsButton]; - [self setFilter: fNoFilterButton]; + [self setFilter:fNoFilterButton]; fSearchField.stringValue = @""; - [self setSearchText: fSearchField]; + [self setSearchText:fSearchField]; } else { - [NSUserDefaults.standardUserDefaults setObject: FILTER_NONE forKey: @"Filter"]; - [NSUserDefaults.standardUserDefaults removeObjectForKey: @"FilterSearchString"]; + [NSUserDefaults.standardUserDefaults setObject:FILTER_NONE forKey:@"Filter"]; + [NSUserDefaults.standardUserDefaults removeObjectForKey:@"FilterSearchString"]; } } -- (NSArray *) searchStrings +- (NSArray*)searchStrings { - return [fSearchField.stringValue betterComponentsSeparatedByCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; + return [fSearchField.stringValue betterComponentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; } -- (void) setCountAll: (NSUInteger) all active: (NSUInteger) active downloading: (NSUInteger) downloading - seeding: (NSUInteger) seeding paused: (NSUInteger) paused +- (void)setCountAll:(NSUInteger)all + active:(NSUInteger)active + downloading:(NSUInteger)downloading + seeding:(NSUInteger)seeding + paused:(NSUInteger)paused { - [fNoFilterButton setCount: all]; - [fActiveFilterButton setCount: active]; - [fDownloadFilterButton setCount: downloading]; - [fSeedFilterButton setCount: seeding]; - [fPauseFilterButton setCount: paused]; + [fNoFilterButton setCount:all]; + [fActiveFilterButton setCount:active]; + [fDownloadFilterButton setCount:downloading]; + [fSeedFilterButton setCount:seeding]; + [fPauseFilterButton setCount:paused]; } -- (void) menuNeedsUpdate: (NSMenu *) menu +- (void)menuNeedsUpdate:(NSMenu*)menu { if (menu == fGroupsButton.menu) { - for (NSInteger i = menu.numberOfItems-1; i >= 3; i--) - [menu removeItemAtIndex: i]; + for (NSInteger i = menu.numberOfItems - 1; i >= 3; i--) + { + [menu removeItemAtIndex:i]; + } - NSMenu * groupMenu = [GroupsController.groups groupMenuWithTarget: self action: @selector(setGroupFilter:) isSmall: YES]; + NSMenu* groupMenu = [GroupsController.groups groupMenuWithTarget:self action:@selector(setGroupFilter:) isSmall:YES]; - const NSInteger groupMenuCount = groupMenu.numberOfItems; + NSInteger const groupMenuCount = groupMenu.numberOfItems; for (NSInteger i = 0; i < groupMenuCount; i++) { - NSMenuItem * item = [groupMenu itemAtIndex: 0]; - [groupMenu removeItemAtIndex: 0]; - [menu addItem: item]; + NSMenuItem* item = [groupMenu itemAtIndex:0]; + [groupMenu removeItemAtIndex:0]; + [menu addItem:item]; } } } -- (BOOL) validateMenuItem: (NSMenuItem *) menuItem +- (BOOL)validateMenuItem:(NSMenuItem*)menuItem { - const SEL action = menuItem.action; + SEL const action = menuItem.action; //check proper filter search item if (action == @selector(setSearchType:)) { - NSString * filterType = [NSUserDefaults.standardUserDefaults stringForKey: @"FilterSearchType"]; + NSString* filterType = [NSUserDefaults.standardUserDefaults stringForKey:@"FilterSearchType"]; BOOL state; if (menuItem.tag == FILTER_TYPE_TAG_TRACKER) - state = [filterType isEqualToString: FILTER_TYPE_TRACKER]; + { + state = [filterType isEqualToString:FILTER_TYPE_TRACKER]; + } else - state = [filterType isEqualToString: FILTER_TYPE_NAME]; + { + state = [filterType isEqualToString:FILTER_TYPE_NAME]; + } menuItem.state = state ? NSOnState : NSOffState; return YES; @@ -309,8 +372,7 @@ if (action == @selector(setGroupFilter:)) { - menuItem.state = menuItem.tag == [NSUserDefaults.standardUserDefaults integerForKey: @"FilterGroup"] - ? NSOnState : NSOffState; + menuItem.state = menuItem.tag == [NSUserDefaults.standardUserDefaults integerForKey:@"FilterGroup"] ? NSOnState : NSOffState; return YES; } @@ -321,7 +383,7 @@ @implementation FilterBarController (Private) -- (void) resizeBar +- (void)resizeBar { //replace all buttons [fNoFilterButton sizeToFit]; @@ -353,19 +415,18 @@ searchFrame.size.width = SEARCH_MIN_WIDTH; //calculate width the buttons can take up - const CGFloat allowedWidth = (searchFrame.origin.x - 5.0) - allRect.origin.x; - const CGFloat currentWidth = NSWidth(allRect) + NSWidth(activeRect) + NSWidth(downloadRect) + NSWidth(seedRect) - + NSWidth(pauseRect) + 4.0; //add 4 for space between buttons - const CGFloat ratio = allowedWidth / currentWidth; + CGFloat const allowedWidth = (searchFrame.origin.x - 5.0) - allRect.origin.x; + CGFloat const currentWidth = NSWidth(allRect) + NSWidth(activeRect) + NSWidth(downloadRect) + NSWidth(seedRect) + + NSWidth(pauseRect) + 4.0; //add 4 for space between buttons + CGFloat const ratio = allowedWidth / currentWidth; //decrease button widths proportionally - allRect.size.width = NSWidth(allRect) * ratio; + allRect.size.width = NSWidth(allRect) * ratio; activeRect.size.width = NSWidth(activeRect) * ratio; downloadRect.size.width = NSWidth(downloadRect) * ratio; seedRect.size.width = NSWidth(seedRect) * ratio; pauseRect.size.width = NSWidth(pauseRect) * ratio; } - else; activeRect.origin.x = NSMaxX(allRect) + 1.0; downloadRect.origin.x = NSMaxX(activeRect) + 1.0; @@ -381,30 +442,30 @@ fSearchField.frame = searchFrame; } -- (void) updateGroupsButton +- (void)updateGroupsButton { - const NSInteger groupIndex = [NSUserDefaults.standardUserDefaults integerForKey: @"FilterGroup"]; + NSInteger const groupIndex = [NSUserDefaults.standardUserDefaults integerForKey:@"FilterGroup"]; - NSImage * icon; - NSString * toolTip; + NSImage* icon; + NSString* toolTip; if (groupIndex == GROUP_FILTER_ALL_TAG) { - icon = [NSImage imageNamed: @"PinTemplate"]; + icon = [NSImage imageNamed:@"PinTemplate"]; toolTip = NSLocalizedString(@"All Groups", "Groups -> Button"); } else { - icon = [GroupsController.groups imageForIndex: groupIndex]; - NSString * groupName = groupIndex != -1 ? [GroupsController.groups nameForIndex: groupIndex] - : NSLocalizedString(@"None", "Groups -> Button"); - toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat: @": %@", groupName]; + icon = [GroupsController.groups imageForIndex:groupIndex]; + NSString* groupName = groupIndex != -1 ? [GroupsController.groups nameForIndex:groupIndex] : + NSLocalizedString(@"None", "Groups -> Button"); + toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat:@": %@", groupName]; } - [fGroupsButton.menu itemAtIndex: 0].image = icon; + [fGroupsButton.menu itemAtIndex:0].image = icon; fGroupsButton.toolTip = toolTip; } -- (void) updateGroups: (NSNotification *) notification +- (void)updateGroups:(NSNotification*)notification { [self updateGroupsButton]; } diff --git a/macosx/FilterBarView.m b/macosx/FilterBarView.m index 886f77e9c..05d6582ef 100644 --- a/macosx/FilterBarView.m +++ b/macosx/FilterBarView.m @@ -25,22 +25,22 @@ @implementation FilterBarView -- (BOOL) mouseDownCanMoveWindow +- (BOOL)mouseDownCanMoveWindow { return NO; } -- (BOOL) isOpaque +- (BOOL)isOpaque { return YES; } -- (void) drawRect: (NSRect) rect +- (void)drawRect:(NSRect)rect { [NSColor.windowBackgroundColor setFill]; NSRectFill(rect); - - const NSRect lineBorderRect = NSMakeRect(NSMinX(rect), 0.0, NSWidth(rect), 1.0); + + NSRect const lineBorderRect = NSMakeRect(NSMinX(rect), 0.0, NSWidth(rect), 1.0); if (NSIntersectsRect(lineBorderRect, rect)) { [NSColor.gridColor setFill]; diff --git a/macosx/FilterButton.h b/macosx/FilterButton.h index 8cd6f3804..4ab7700c2 100644 --- a/macosx/FilterButton.h +++ b/macosx/FilterButton.h @@ -27,6 +27,6 @@ NSUInteger fCount; } -- (void) setCount: (NSUInteger) count; +- (void)setCount:(NSUInteger)count; @end diff --git a/macosx/FilterButton.m b/macosx/FilterButton.m index cb967d6b8..69fce714d 100644 --- a/macosx/FilterButton.m +++ b/macosx/FilterButton.m @@ -25,25 +25,27 @@ @implementation FilterButton -- (instancetype) initWithCoder: (NSCoder *) coder +- (instancetype)initWithCoder:(NSCoder*)coder { - if ((self = [super initWithCoder: coder])) + if ((self = [super initWithCoder:coder])) { fCount = NSNotFound; } return self; } -- (void) setCount: (NSUInteger) count +- (void)setCount:(NSUInteger)count { if (count == fCount) + { return; + } fCount = count; - self.toolTip = fCount == 1 ? NSLocalizedString(@"1 transfer", "Filter Button -> tool tip") - : [NSString stringWithFormat: NSLocalizedString(@"%@ transfers", "Filter Bar Button -> tool tip"), - [NSString formattedUInteger: fCount]]; + self.toolTip = fCount == 1 ? NSLocalizedString(@"1 transfer", "Filter Button -> tool tip") : + [NSString stringWithFormat:NSLocalizedString(@"%@ transfers", "Filter Bar Button -> tool tip"), + [NSString formattedUInteger:fCount]]; } @end diff --git a/macosx/GlobalOptionsPopoverViewController.h b/macosx/GlobalOptionsPopoverViewController.h index a9aac3a89..eef98b325 100644 --- a/macosx/GlobalOptionsPopoverViewController.h +++ b/macosx/GlobalOptionsPopoverViewController.h @@ -26,30 +26,32 @@ @interface GlobalOptionsPopoverViewController : NSViewController { - tr_session * fHandle; - NSUserDefaults * fDefaults; + tr_session* fHandle; + NSUserDefaults* fDefaults; - IBOutlet NSTextField * fUploadLimitField, * fDownloadLimitField; + IBOutlet NSTextField* fUploadLimitField; + IBOutlet NSTextField* fDownloadLimitField; - IBOutlet NSTextField * fRatioStopField, * fIdleStopField; + IBOutlet NSTextField* fRatioStopField; + IBOutlet NSTextField* fIdleStopField; - NSString * fInitialString; + NSString* fInitialString; } -- (instancetype) initWithHandle: (tr_session *) handle; +- (instancetype)initWithHandle:(tr_session*)handle; -- (IBAction) updatedDisplayString: (id) sender; +- (IBAction)updatedDisplayString:(id)sender; -- (IBAction) setDownSpeedSetting: (id) sender; -- (IBAction) setDownSpeedLimit: (id) sender; +- (IBAction)setDownSpeedSetting:(id)sender; +- (IBAction)setDownSpeedLimit:(id)sender; -- (IBAction) setUpSpeedSetting: (id) sender; -- (IBAction) setUpSpeedLimit: (id) sender; +- (IBAction)setUpSpeedSetting:(id)sender; +- (IBAction)setUpSpeedLimit:(id)sender; -- (IBAction) setRatioStopSetting: (id) sender; -- (IBAction) setRatioStopLimit: (id) sender; +- (IBAction)setRatioStopSetting:(id)sender; +- (IBAction)setRatioStopLimit:(id)sender; -- (IBAction) setIdleStopSetting: (id) sender; -- (IBAction) setIdleStopLimit: (id) sender; +- (IBAction)setIdleStopSetting:(id)sender; +- (IBAction)setIdleStopLimit:(id)sender; @end diff --git a/macosx/GlobalOptionsPopoverViewController.m b/macosx/GlobalOptionsPopoverViewController.m index 86e422798..67fb7439d 100644 --- a/macosx/GlobalOptionsPopoverViewController.m +++ b/macosx/GlobalOptionsPopoverViewController.m @@ -24,9 +24,9 @@ @implementation GlobalOptionsPopoverViewController -- (instancetype) initWithHandle: (tr_session *) handle +- (instancetype)initWithHandle:(tr_session*)handle { - if ((self = [super initWithNibName: @"GlobalOptionsPopover" bundle: nil])) + if ((self = [super initWithNibName:@"GlobalOptionsPopover" bundle:nil])) { fHandle = handle; @@ -36,116 +36,116 @@ return self; } -- (void) awakeFromNib +- (void)awakeFromNib { - fUploadLimitField.intValue = [fDefaults integerForKey: @"UploadLimit"]; - fDownloadLimitField.intValue = [fDefaults integerForKey: @"DownloadLimit"]; + fUploadLimitField.intValue = [fDefaults integerForKey:@"UploadLimit"]; + fDownloadLimitField.intValue = [fDefaults integerForKey:@"DownloadLimit"]; - fRatioStopField.floatValue = [fDefaults floatForKey: @"RatioLimit"]; - fIdleStopField.integerValue = [fDefaults integerForKey: @"IdleLimitMinutes"]; + fRatioStopField.floatValue = [fDefaults floatForKey:@"RatioLimit"]; + fIdleStopField.integerValue = [fDefaults integerForKey:@"IdleLimitMinutes"]; - [self.view setFrameSize: self.view.fittingSize]; + [self.view setFrameSize:self.view.fittingSize]; } -- (IBAction) updatedDisplayString: (id) sender +- (IBAction)updatedDisplayString:(id)sender { - [NSNotificationCenter.defaultCenter postNotificationName: @"RefreshTorrentTable" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"RefreshTorrentTable" object:nil]; } -- (IBAction) setDownSpeedSetting: (id) sender +- (IBAction)setDownSpeedSetting:(id)sender { - tr_sessionLimitSpeed(fHandle, TR_DOWN, [fDefaults boolForKey: @"CheckDownload"]); + tr_sessionLimitSpeed(fHandle, TR_DOWN, [fDefaults boolForKey:@"CheckDownload"]); - [NSNotificationCenter.defaultCenter postNotificationName: @"SpeedLimitUpdate" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"SpeedLimitUpdate" object:nil]; } -- (IBAction) setDownSpeedLimit: (id) sender +- (IBAction)setDownSpeedLimit:(id)sender { - const NSInteger limit = [sender integerValue]; - [fDefaults setInteger: limit forKey: @"DownloadLimit"]; + NSInteger const limit = [sender integerValue]; + [fDefaults setInteger:limit forKey:@"DownloadLimit"]; tr_sessionSetSpeedLimit_KBps(fHandle, TR_DOWN, limit); - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateSpeedLimitValuesOutsidePrefs" object: nil]; - [NSNotificationCenter.defaultCenter postNotificationName: @"SpeedLimitUpdate" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateSpeedLimitValuesOutsidePrefs" object:nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"SpeedLimitUpdate" object:nil]; } -- (IBAction) setUpSpeedSetting: (id) sender +- (IBAction)setUpSpeedSetting:(id)sender { - tr_sessionLimitSpeed(fHandle, TR_UP, [fDefaults boolForKey: @"CheckUpload"]); + tr_sessionLimitSpeed(fHandle, TR_UP, [fDefaults boolForKey:@"CheckUpload"]); - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateSpeedLimitValuesOutsidePrefs" object: nil]; - [NSNotificationCenter.defaultCenter postNotificationName: @"SpeedLimitUpdate" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateSpeedLimitValuesOutsidePrefs" object:nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"SpeedLimitUpdate" object:nil]; } -- (IBAction) setUpSpeedLimit: (id) sender +- (IBAction)setUpSpeedLimit:(id)sender { - const NSInteger limit = [sender integerValue]; - [fDefaults setInteger: limit forKey: @"UploadLimit"]; + NSInteger const limit = [sender integerValue]; + [fDefaults setInteger:limit forKey:@"UploadLimit"]; tr_sessionSetSpeedLimit_KBps(fHandle, TR_UP, limit); - [NSNotificationCenter.defaultCenter postNotificationName: @"SpeedLimitUpdate" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"SpeedLimitUpdate" object:nil]; } -- (IBAction) setRatioStopSetting: (id) sender +- (IBAction)setRatioStopSetting:(id)sender { - tr_sessionSetRatioLimited(fHandle, [fDefaults boolForKey: @"RatioCheck"]); + tr_sessionSetRatioLimited(fHandle, [fDefaults boolForKey:@"RatioCheck"]); //reload main table for seeding progress - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; //reload global settings in inspector - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGlobalOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGlobalOptions" object:nil]; } -- (IBAction) setRatioStopLimit: (id) sender +- (IBAction)setRatioStopLimit:(id)sender { - const CGFloat value = [sender floatValue]; - [fDefaults setFloat: value forKey: @"RatioLimit"]; + CGFloat const value = [sender floatValue]; + [fDefaults setFloat:value forKey:@"RatioLimit"]; tr_sessionSetRatioLimit(fHandle, value); - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateRatioStopValueOutsidePrefs" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateRatioStopValueOutsidePrefs" object:nil]; //reload main table for seeding progress - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; //reload global settings in inspector - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGlobalOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGlobalOptions" object:nil]; } -- (IBAction) setIdleStopSetting: (id) sender +- (IBAction)setIdleStopSetting:(id)sender { - tr_sessionSetIdleLimited(fHandle, [fDefaults boolForKey: @"IdleLimitCheck"]); + tr_sessionSetIdleLimited(fHandle, [fDefaults boolForKey:@"IdleLimitCheck"]); //reload main table for remaining seeding time - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; //reload global settings in inspector - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGlobalOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGlobalOptions" object:nil]; } -- (IBAction) setIdleStopLimit: (id) sender +- (IBAction)setIdleStopLimit:(id)sender { - const NSInteger value = [sender integerValue]; - [fDefaults setInteger: value forKey: @"IdleLimitMinutes"]; + NSInteger const value = [sender integerValue]; + [fDefaults setInteger:value forKey:@"IdleLimitMinutes"]; tr_sessionSetIdleLimit(fHandle, value); - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateIdleStopValueOutsidePrefs" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateIdleStopValueOutsidePrefs" object:nil]; //reload main table for remaining seeding time - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; //reload global settings in inspector - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGlobalOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGlobalOptions" object:nil]; } -- (BOOL) control: (NSControl *) control textShouldBeginEditing: (NSText *) fieldEditor +- (BOOL)control:(NSControl*)control textShouldBeginEditing:(NSText*)fieldEditor { fInitialString = control.stringValue; return YES; } -- (BOOL) control: (NSControl *) control didFailToFormatString: (NSString *) string errorDescription: (NSString *) error +- (BOOL)control:(NSControl*)control didFailToFormatString:(NSString*)string errorDescription:(NSString*)error { NSBeep(); if (fInitialString) diff --git a/macosx/GroupToolbarItem.h b/macosx/GroupToolbarItem.h index c5d4e5312..d54c245b9 100644 --- a/macosx/GroupToolbarItem.h +++ b/macosx/GroupToolbarItem.h @@ -24,11 +24,11 @@ @interface GroupToolbarItem : NSToolbarItem { - NSArray * fIdentifiers; + NSArray* fIdentifiers; } -- (void) setIdentifiers: (NSArray *) identifiers; +- (void)setIdentifiers:(NSArray*)identifiers; -- (void) createMenu: (NSArray *) labels; +- (void)createMenu:(NSArray*)labels; @end diff --git a/macosx/GroupToolbarItem.m b/macosx/GroupToolbarItem.m index 65aefce7e..8b5fbf17c 100644 --- a/macosx/GroupToolbarItem.m +++ b/macosx/GroupToolbarItem.m @@ -24,50 +24,53 @@ @implementation GroupToolbarItem - -- (void) setIdentifiers: (NSArray *) identifiers +- (void)setIdentifiers:(NSArray*)identifiers { fIdentifiers = identifiers; } -- (void) validate +- (void)validate { - NSSegmentedControl * control = (NSSegmentedControl *)self.view; + NSSegmentedControl* control = (NSSegmentedControl*)self.view; for (NSInteger i = 0; i < control.segmentCount; i++) - [control setEnabled: [self.target validateToolbarItem: - [[NSToolbarItem alloc] initWithItemIdentifier: fIdentifiers[i]]] forSegment: i]; + { + [control setEnabled:[self.target validateToolbarItem:[[NSToolbarItem alloc] initWithItemIdentifier:fIdentifiers[i]]] + forSegment:i]; + } } -- (void) createMenu: (NSArray *) labels +- (void)createMenu:(NSArray*)labels { - NSMenuItem * menuItem = [[NSMenuItem alloc] initWithTitle: self.label action: NULL keyEquivalent: @""]; - NSMenu * menu = [[NSMenu alloc] initWithTitle: self.label]; + NSMenuItem* menuItem = [[NSMenuItem alloc] initWithTitle:self.label action:NULL keyEquivalent:@""]; + NSMenu* menu = [[NSMenu alloc] initWithTitle:self.label]; menuItem.submenu = menu; menu.autoenablesItems = NO; - const NSInteger count = ((NSSegmentedControl *)self.view).segmentCount; + NSInteger const count = ((NSSegmentedControl*)self.view).segmentCount; for (NSInteger i = 0; i < count; i++) { - NSMenuItem * addItem = [[NSMenuItem alloc] initWithTitle: labels[i] action: self.action keyEquivalent: @""]; + NSMenuItem* addItem = [[NSMenuItem alloc] initWithTitle:labels[i] action:self.action keyEquivalent:@""]; addItem.target = self.target; addItem.tag = i; - [menu addItem: addItem]; + [menu addItem:addItem]; } self.menuFormRepresentation = menuItem; } -- (NSMenuItem *) menuFormRepresentation +- (NSMenuItem*)menuFormRepresentation { - NSMenuItem * menuItem = super.menuFormRepresentation; + NSMenuItem* menuItem = super.menuFormRepresentation; - const NSInteger count = ((NSSegmentedControl *)self.view).segmentCount; + NSInteger const count = ((NSSegmentedControl*)self.view).segmentCount; for (NSInteger i = 0; i < count; i++) - [menuItem.submenu itemAtIndex: i].enabled = [self.target validateToolbarItem: - [[NSToolbarItem alloc] initWithItemIdentifier: fIdentifiers[i]]]; + { + [menuItem.submenu itemAtIndex:i].enabled = [self.target + validateToolbarItem:[[NSToolbarItem alloc] initWithItemIdentifier:fIdentifiers[i]]]; + } return menuItem; } diff --git a/macosx/GroupsController.h b/macosx/GroupsController.h index 1766b1ece..068ce126c 100644 --- a/macosx/GroupsController.h +++ b/macosx/GroupsController.h @@ -26,42 +26,42 @@ @interface GroupsController : NSObject { - NSMutableArray * fGroups; + NSMutableArray* fGroups; } -@property (nonatomic, class, readonly) GroupsController * groups; +@property(nonatomic, class, readonly) GroupsController* groups; -@property (nonatomic, readonly) NSInteger numberOfGroups; +@property(nonatomic, readonly) NSInteger numberOfGroups; -- (NSInteger) rowValueForIndex: (NSInteger) index; -- (NSInteger) indexForRow: (NSInteger) row; +- (NSInteger)rowValueForIndex:(NSInteger)index; +- (NSInteger)indexForRow:(NSInteger)row; -- (NSString *) nameForIndex: (NSInteger) index; -- (void) setName: (NSString *) name forIndex: (NSInteger) index; +- (NSString*)nameForIndex:(NSInteger)index; +- (void)setName:(NSString*)name forIndex:(NSInteger)index; -- (NSImage *) imageForIndex: (NSInteger) index; +- (NSImage*)imageForIndex:(NSInteger)index; -- (NSColor *) colorForIndex: (NSInteger) index; -- (void) setColor: (NSColor *) color forIndex: (NSInteger) index; +- (NSColor*)colorForIndex:(NSInteger)index; +- (void)setColor:(NSColor*)color forIndex:(NSInteger)index; -- (BOOL) usesCustomDownloadLocationForIndex: (NSInteger) index; -- (void) setUsesCustomDownloadLocation: (BOOL) useCustomLocation forIndex: (NSInteger) index; +- (BOOL)usesCustomDownloadLocationForIndex:(NSInteger)index; +- (void)setUsesCustomDownloadLocation:(BOOL)useCustomLocation forIndex:(NSInteger)index; -- (NSString *) customDownloadLocationForIndex: (NSInteger) index; -- (void) setCustomDownloadLocation: (NSString *) location forIndex: (NSInteger) index; +- (NSString*)customDownloadLocationForIndex:(NSInteger)index; +- (void)setCustomDownloadLocation:(NSString*)location forIndex:(NSInteger)index; -- (BOOL) usesAutoAssignRulesForIndex: (NSInteger) index; -- (void) setUsesAutoAssignRules: (BOOL) useAutoAssignRules forIndex: (NSInteger) index; +- (BOOL)usesAutoAssignRulesForIndex:(NSInteger)index; +- (void)setUsesAutoAssignRules:(BOOL)useAutoAssignRules forIndex:(NSInteger)index; -- (NSPredicate *) autoAssignRulesForIndex: (NSInteger) index; -- (void) setAutoAssignRules: (NSPredicate *) predicate forIndex: (NSInteger) index; +- (NSPredicate*)autoAssignRulesForIndex:(NSInteger)index; +- (void)setAutoAssignRules:(NSPredicate*)predicate forIndex:(NSInteger)index; -- (void) addNewGroup; -- (void) removeGroupWithRowIndex: (NSInteger) row; +- (void)addNewGroup; +- (void)removeGroupWithRowIndex:(NSInteger)row; -- (void) moveGroupAtRow: (NSInteger) oldRow toRow: (NSInteger) newRow; +- (void)moveGroupAtRow:(NSInteger)oldRow toRow:(NSInteger)newRow; -- (NSMenu *) groupMenuWithTarget: (id) target action: (SEL) action isSmall: (BOOL) small; +- (NSMenu*)groupMenuWithTarget:(id)target action:(SEL)action isSmall:(BOOL)small; -- (NSInteger) groupIndexForTorrent: (Torrent *) torrent; +- (NSInteger)groupIndexForTorrent:(Torrent*)torrent; @end diff --git a/macosx/GroupsController.m b/macosx/GroupsController.m index 856cc468f..4e704904c 100644 --- a/macosx/GroupsController.m +++ b/macosx/GroupsController.m @@ -28,76 +28,67 @@ @interface GroupsController (Private) -- (void) saveGroups; +- (void)saveGroups; -- (NSImage *) imageForGroup: (NSMutableDictionary *) dict; +- (NSImage*)imageForGroup:(NSMutableDictionary*)dict; -- (BOOL) torrent: (Torrent *) torrent doesMatchRulesForGroupAtIndex: (NSInteger) index; +- (BOOL)torrent:(Torrent*)torrent doesMatchRulesForGroupAtIndex:(NSInteger)index; @end @implementation GroupsController -GroupsController * fGroupsInstance = nil; -+ (GroupsController *) groups +GroupsController* fGroupsInstance = nil; + ++ (GroupsController*)groups { if (!fGroupsInstance) + { fGroupsInstance = [[GroupsController alloc] init]; + } return fGroupsInstance; } -- (instancetype) init +- (instancetype)init { if ((self = [super init])) { - NSData * data; - if ((data = [NSUserDefaults.standardUserDefaults dataForKey: @"GroupDicts"])) - fGroups = [NSKeyedUnarchiver unarchiveObjectWithData: data]; - else if ((data = [NSUserDefaults.standardUserDefaults dataForKey: @"Groups"])) //handle old groups + NSData* data; + if ((data = [NSUserDefaults.standardUserDefaults dataForKey:@"GroupDicts"])) { - fGroups = [NSUnarchiver unarchiveObjectWithData: data]; - [NSUserDefaults.standardUserDefaults removeObjectForKey: @"Groups"]; + fGroups = [NSKeyedUnarchiver unarchiveObjectWithData:data]; + } + else if ((data = [NSUserDefaults.standardUserDefaults dataForKey:@"Groups"])) //handle old groups + { + fGroups = [NSUnarchiver unarchiveObjectWithData:data]; + [NSUserDefaults.standardUserDefaults removeObjectForKey:@"Groups"]; [self saveGroups]; } else { //default groups - NSMutableDictionary * red = [NSMutableDictionary dictionaryWithObjectsAndKeys: - NSColor.redColor, @"Color", - NSLocalizedString(@"Red", "Groups -> Name"), @"Name", - @0, @"Index", nil]; + NSMutableDictionary* red = [NSMutableDictionary + dictionaryWithObjectsAndKeys:NSColor.redColor, @"Color", NSLocalizedString(@"Red", "Groups -> Name"), @"Name", @0, @"Index", nil]; - NSMutableDictionary * orange = [NSMutableDictionary dictionaryWithObjectsAndKeys: - NSColor.orangeColor, @"Color", - NSLocalizedString(@"Orange", "Groups -> Name"), @"Name", - @1, @"Index", nil]; + NSMutableDictionary* orange = [NSMutableDictionary + dictionaryWithObjectsAndKeys:NSColor.orangeColor, @"Color", NSLocalizedString(@"Orange", "Groups -> Name"), @"Name", @1, @"Index", nil]; - NSMutableDictionary * yellow = [NSMutableDictionary dictionaryWithObjectsAndKeys: - NSColor.yellowColor, @"Color", - NSLocalizedString(@"Yellow", "Groups -> Name"), @"Name", - @2, @"Index", nil]; + NSMutableDictionary* yellow = [NSMutableDictionary + dictionaryWithObjectsAndKeys:NSColor.yellowColor, @"Color", NSLocalizedString(@"Yellow", "Groups -> Name"), @"Name", @2, @"Index", nil]; - NSMutableDictionary * green = [NSMutableDictionary dictionaryWithObjectsAndKeys: - NSColor.greenColor, @"Color", - NSLocalizedString(@"Green", "Groups -> Name"), @"Name", - @3, @"Index", nil]; + NSMutableDictionary* green = [NSMutableDictionary + dictionaryWithObjectsAndKeys:NSColor.greenColor, @"Color", NSLocalizedString(@"Green", "Groups -> Name"), @"Name", @3, @"Index", nil]; - NSMutableDictionary * blue = [NSMutableDictionary dictionaryWithObjectsAndKeys: - NSColor.blueColor, @"Color", - NSLocalizedString(@"Blue", "Groups -> Name"), @"Name", - @4, @"Index", nil]; + NSMutableDictionary* blue = [NSMutableDictionary + dictionaryWithObjectsAndKeys:NSColor.blueColor, @"Color", NSLocalizedString(@"Blue", "Groups -> Name"), @"Name", @4, @"Index", nil]; - NSMutableDictionary * purple = [NSMutableDictionary dictionaryWithObjectsAndKeys: - NSColor.purpleColor, @"Color", - NSLocalizedString(@"Purple", "Groups -> Name"), @"Name", - @5, @"Index", nil]; + NSMutableDictionary* purple = [NSMutableDictionary + dictionaryWithObjectsAndKeys:NSColor.purpleColor, @"Color", NSLocalizedString(@"Purple", "Groups -> Name"), @"Name", @5, @"Index", nil]; - NSMutableDictionary * gray = [NSMutableDictionary dictionaryWithObjectsAndKeys: - NSColor.grayColor, @"Color", - NSLocalizedString(@"Gray", "Groups -> Name"), @"Name", - @6, @"Index", nil]; + NSMutableDictionary* gray = [NSMutableDictionary + dictionaryWithObjectsAndKeys:NSColor.grayColor, @"Color", NSLocalizedString(@"Gray", "Groups -> Name"), @"Name", @6, @"Index", nil]; - fGroups = [[NSMutableArray alloc] initWithObjects: red, orange, yellow, green, blue, purple, gray, nil]; + fGroups = [[NSMutableArray alloc] initWithObjects:red, orange, yellow, green, blue, purple, gray, nil]; [self saveGroups]; //make sure this is saved right away } } @@ -105,130 +96,138 @@ GroupsController * fGroupsInstance = nil; return self; } - -- (NSInteger) numberOfGroups +- (NSInteger)numberOfGroups { return fGroups.count; } -- (NSInteger) rowValueForIndex: (NSInteger) index +- (NSInteger)rowValueForIndex:(NSInteger)index { if (index != -1) { for (NSUInteger i = 0; i < fGroups.count; i++) + { if (index == [fGroups[i][@"Index"] integerValue]) + { return i; + } + } } return -1; } -- (NSInteger) indexForRow: (NSInteger) row +- (NSInteger)indexForRow:(NSInteger)row { return [fGroups[row][@"Index"] integerValue]; } -- (NSString *) nameForIndex: (NSInteger) index +- (NSString*)nameForIndex:(NSInteger)index { - NSInteger orderIndex = [self rowValueForIndex: index]; + NSInteger orderIndex = [self rowValueForIndex:index]; return orderIndex != -1 ? fGroups[orderIndex][@"Name"] : nil; } -- (void) setName: (NSString *) name forIndex: (NSInteger) index +- (void)setName:(NSString*)name forIndex:(NSInteger)index { - NSInteger orderIndex = [self rowValueForIndex: index]; + NSInteger orderIndex = [self rowValueForIndex:index]; fGroups[orderIndex][@"Name"] = name; [self saveGroups]; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGroups" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGroups" object:self]; } -- (NSImage *) imageForIndex: (NSInteger) index +- (NSImage*)imageForIndex:(NSInteger)index { - NSInteger orderIndex = [self rowValueForIndex: index]; - return orderIndex != -1 ? [self imageForGroup: fGroups[orderIndex]] - : [NSImage imageNamed: @"GroupsNoneTemplate"]; + NSInteger orderIndex = [self rowValueForIndex:index]; + return orderIndex != -1 ? [self imageForGroup:fGroups[orderIndex]] : [NSImage imageNamed:@"GroupsNoneTemplate"]; } -- (NSColor *) colorForIndex: (NSInteger) index +- (NSColor*)colorForIndex:(NSInteger)index { - NSInteger orderIndex = [self rowValueForIndex: index]; + NSInteger orderIndex = [self rowValueForIndex:index]; return orderIndex != -1 ? fGroups[orderIndex][@"Color"] : nil; } -- (void) setColor: (NSColor *) color forIndex: (NSInteger) index +- (void)setColor:(NSColor*)color forIndex:(NSInteger)index { - NSMutableDictionary * dict = fGroups[[self rowValueForIndex: index]]; - [dict removeObjectForKey: @"Icon"]; + NSMutableDictionary* dict = fGroups[[self rowValueForIndex:index]]; + [dict removeObjectForKey:@"Icon"]; dict[@"Color"] = color; [GroupsController.groups saveGroups]; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGroups" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGroups" object:self]; } -- (BOOL) usesCustomDownloadLocationForIndex: (NSInteger) index +- (BOOL)usesCustomDownloadLocationForIndex:(NSInteger)index { - if (![self customDownloadLocationForIndex: index]) + if (![self customDownloadLocationForIndex:index]) + { return NO; + } - NSInteger orderIndex = [self rowValueForIndex: index]; + NSInteger orderIndex = [self rowValueForIndex:index]; return [fGroups[orderIndex][@"UsesCustomDownloadLocation"] boolValue]; } -- (void) setUsesCustomDownloadLocation: (BOOL) useCustomLocation forIndex: (NSInteger) index +- (void)setUsesCustomDownloadLocation:(BOOL)useCustomLocation forIndex:(NSInteger)index { - NSMutableDictionary * dict = fGroups[[self rowValueForIndex: index]]; + NSMutableDictionary* dict = fGroups[[self rowValueForIndex:index]]; dict[@"UsesCustomDownloadLocation"] = @(useCustomLocation); [GroupsController.groups saveGroups]; } -- (NSString *) customDownloadLocationForIndex: (NSInteger) index +- (NSString*)customDownloadLocationForIndex:(NSInteger)index { - NSInteger orderIndex = [self rowValueForIndex: index]; + NSInteger orderIndex = [self rowValueForIndex:index]; return orderIndex != -1 ? fGroups[orderIndex][@"CustomDownloadLocation"] : nil; } -- (void) setCustomDownloadLocation: (NSString *) location forIndex: (NSInteger) index +- (void)setCustomDownloadLocation:(NSString*)location forIndex:(NSInteger)index { - NSMutableDictionary * dict = fGroups[[self rowValueForIndex: index]]; + NSMutableDictionary* dict = fGroups[[self rowValueForIndex:index]]; dict[@"CustomDownloadLocation"] = location; [GroupsController.groups saveGroups]; } -- (BOOL) usesAutoAssignRulesForIndex: (NSInteger) index +- (BOOL)usesAutoAssignRulesForIndex:(NSInteger)index { - NSInteger orderIndex = [self rowValueForIndex: index]; + NSInteger orderIndex = [self rowValueForIndex:index]; if (orderIndex == -1) + { return NO; + } - NSNumber * assignRules = fGroups[orderIndex][@"UsesAutoGroupRules"]; + NSNumber* assignRules = fGroups[orderIndex][@"UsesAutoGroupRules"]; return assignRules && assignRules.boolValue; } -- (void) setUsesAutoAssignRules: (BOOL) useAutoAssignRules forIndex: (NSInteger) index +- (void)setUsesAutoAssignRules:(BOOL)useAutoAssignRules forIndex:(NSInteger)index { - NSMutableDictionary * dict = fGroups[[self rowValueForIndex: index]]; + NSMutableDictionary* dict = fGroups[[self rowValueForIndex:index]]; dict[@"UsesAutoGroupRules"] = @(useAutoAssignRules); [GroupsController.groups saveGroups]; } -- (NSPredicate *) autoAssignRulesForIndex: (NSInteger) index +- (NSPredicate*)autoAssignRulesForIndex:(NSInteger)index { - NSInteger orderIndex = [self rowValueForIndex: index]; + NSInteger orderIndex = [self rowValueForIndex:index]; if (orderIndex == -1) + { return nil; + } return fGroups[orderIndex][@"AutoGroupRules"]; } -- (void) setAutoAssignRules: (NSPredicate *) predicate forIndex: (NSInteger) index +- (void)setAutoAssignRules:(NSPredicate*)predicate forIndex:(NSInteger)index { - NSMutableDictionary * dict = fGroups[[self rowValueForIndex: index]]; + NSMutableDictionary* dict = fGroups[[self rowValueForIndex:index]]; if (predicate) { @@ -237,60 +236,70 @@ GroupsController * fGroupsInstance = nil; } else { - [dict removeObjectForKey: @"AutoGroupRules"]; - [self setUsesAutoAssignRules: NO forIndex: index]; + [dict removeObjectForKey:@"AutoGroupRules"]; + [self setUsesAutoAssignRules:NO forIndex:index]; } } -- (void) addNewGroup +- (void)addNewGroup { //find the lowest index - NSMutableIndexSet * candidates = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fGroups.count+1)]; - for (NSDictionary * dict in fGroups) - [candidates removeIndex: [dict[@"Index"] integerValue]]; + NSMutableIndexSet* candidates = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fGroups.count + 1)]; + for (NSDictionary* dict in fGroups) + { + [candidates removeIndex:[dict[@"Index"] integerValue]]; + } - const NSInteger index = candidates.firstIndex; + NSInteger const index = candidates.firstIndex; - [fGroups addObject: [NSMutableDictionary dictionaryWithObjectsAndKeys: @(index), @"Index", - [NSColor colorWithCalibratedRed: 0.0 green: 0.65 blue: 1.0 alpha: 1.0], @"Color", @"", @"Name", nil]]; + [fGroups addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@(index), + @"Index", + [NSColor colorWithCalibratedRed:0.0 green:0.65 blue:1.0 + alpha:1.0], + @"Color", + @"", + @"Name", + nil]]; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGroups" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGroups" object:self]; [self saveGroups]; } -- (void) removeGroupWithRowIndex: (NSInteger) row +- (void)removeGroupWithRowIndex:(NSInteger)row { NSInteger index = [fGroups[row][@"Index"] integerValue]; - [fGroups removeObjectAtIndex: row]; + [fGroups removeObjectAtIndex:row]; - [NSNotificationCenter.defaultCenter postNotificationName: @"GroupValueRemoved" object: self userInfo: - @{@"Index": @(index)}]; + [NSNotificationCenter.defaultCenter postNotificationName:@"GroupValueRemoved" object:self + userInfo:@{ @"Index" : @(index) }]; - if (index == [NSUserDefaults.standardUserDefaults integerForKey: @"FilterGroup"]) - [NSUserDefaults.standardUserDefaults setInteger: -2 forKey: @"FilterGroup"]; + if (index == [NSUserDefaults.standardUserDefaults integerForKey:@"FilterGroup"]) + { + [NSUserDefaults.standardUserDefaults setInteger:-2 forKey:@"FilterGroup"]; + } - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGroups" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGroups" object:self]; [self saveGroups]; } -- (void) moveGroupAtRow: (NSInteger) oldRow toRow: (NSInteger) newRow +- (void)moveGroupAtRow:(NSInteger)oldRow toRow:(NSInteger)newRow { - [fGroups moveObjectAtIndex: oldRow toIndex: newRow]; + [fGroups moveObjectAtIndex:oldRow toIndex:newRow]; [self saveGroups]; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGroups" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGroups" object:self]; } -- (NSMenu *) groupMenuWithTarget: (id) target action: (SEL) action isSmall: (BOOL) small +- (NSMenu*)groupMenuWithTarget:(id)target action:(SEL)action isSmall:(BOOL)small { - NSMenu * menu = [[NSMenu alloc] initWithTitle: @"Groups"]; + NSMenu* menu = [[NSMenu alloc] initWithTitle:@"Groups"]; - NSMenuItem * item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"None", "Groups -> Menu") action: action - keyEquivalent: @""]; + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"None", "Groups -> Menu") action:action + keyEquivalent:@""]; item.target = target; item.tag = -1; - NSImage * icon = [NSImage imageNamed: @"GroupsNoneTemplate"]; + NSImage* icon = [NSImage imageNamed:@"GroupsNoneTemplate"]; if (small) { icon = [icon copy]; @@ -299,18 +308,20 @@ GroupsController * fGroupsInstance = nil; item.image = icon; } else - item.image = icon; - - [menu addItem: item]; - - for (NSMutableDictionary * dict in fGroups) { - item = [[NSMenuItem alloc] initWithTitle: dict[@"Name"] action: action keyEquivalent: @""]; + item.image = icon; + } + + [menu addItem:item]; + + for (NSMutableDictionary* dict in fGroups) + { + item = [[NSMenuItem alloc] initWithTitle:dict[@"Name"] action:action keyEquivalent:@""]; item.target = target; item.tag = [dict[@"Index"] integerValue]; - NSImage * icon = [self imageForGroup: dict]; + NSImage* icon = [self imageForGroup:dict]; if (small) { icon = [icon copy]; @@ -319,21 +330,25 @@ GroupsController * fGroupsInstance = nil; item.image = icon; } else + { item.image = icon; + } - [menu addItem: item]; + [menu addItem:item]; } return menu; } -- (NSInteger) groupIndexForTorrent: (Torrent *) torrent +- (NSInteger)groupIndexForTorrent:(Torrent*)torrent { - for (NSDictionary * group in fGroups) + for (NSDictionary* group in fGroups) { NSInteger row = [group[@"Index"] integerValue]; - if ([self torrent: torrent doesMatchRulesForGroupAtIndex: row]) + if ([self torrent:torrent doesMatchRulesForGroupAtIndex:row]) + { return row; + } } return -1; } @@ -342,45 +357,47 @@ GroupsController * fGroupsInstance = nil; @implementation GroupsController (Private) -- (void) saveGroups +- (void)saveGroups { //don't archive the icon - NSMutableArray * groups = [NSMutableArray arrayWithCapacity: fGroups.count]; - for (NSDictionary * dict in fGroups) + NSMutableArray* groups = [NSMutableArray arrayWithCapacity:fGroups.count]; + for (NSDictionary* dict in fGroups) { - NSMutableDictionary * tempDict = [dict mutableCopy]; - [tempDict removeObjectForKey: @"Icon"]; - [groups addObject: tempDict]; + NSMutableDictionary* tempDict = [dict mutableCopy]; + [tempDict removeObjectForKey:@"Icon"]; + [groups addObject:tempDict]; } - [NSUserDefaults.standardUserDefaults setObject: [NSKeyedArchiver archivedDataWithRootObject: groups] forKey: @"GroupDicts"]; + [NSUserDefaults.standardUserDefaults setObject:[NSKeyedArchiver archivedDataWithRootObject:groups] forKey:@"GroupDicts"]; } -- (NSImage *) imageForGroup: (NSMutableDictionary *) dict +- (NSImage*)imageForGroup:(NSMutableDictionary*)dict { - NSImage * image; + NSImage* image; if ((image = dict[@"Icon"])) + { return image; + } NSRect rect = NSMakeRect(0.0, 0.0, ICON_WIDTH, ICON_WIDTH); - NSBezierPath * bp = [NSBezierPath bezierPathWithRoundedRect: rect xRadius: 3.0 yRadius: 3.0]; - NSImage * icon = [[NSImage alloc] initWithSize: rect.size]; + NSBezierPath* bp = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:3.0 yRadius:3.0]; + NSImage* icon = [[NSImage alloc] initWithSize:rect.size]; - NSColor * color = dict[@"Color"]; + NSColor* color = dict[@"Color"]; [icon lockFocus]; //border - NSGradient * gradient = [[NSGradient alloc] initWithStartingColor: [color blendedColorWithFraction: 0.45 ofColor: - NSColor.whiteColor] endingColor: color]; - [gradient drawInBezierPath: bp angle: 270.0]; + NSGradient* gradient = [[NSGradient alloc] initWithStartingColor:[color blendedColorWithFraction:0.45 ofColor:NSColor.whiteColor] + endingColor:color]; + [gradient drawInBezierPath:bp angle:270.0]; //inside - bp = [NSBezierPath bezierPathWithRoundedRect: NSInsetRect(rect, 1.0, 1.0) xRadius: 3.0 yRadius: 3.0]; - gradient = [[NSGradient alloc] initWithStartingColor: [color blendedColorWithFraction: 0.75 ofColor: NSColor.whiteColor] - endingColor: [color blendedColorWithFraction: 0.2 ofColor: NSColor.whiteColor]]; - [gradient drawInBezierPath: bp angle: 270.0]; + bp = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(rect, 1.0, 1.0) xRadius:3.0 yRadius:3.0]; + gradient = [[NSGradient alloc] initWithStartingColor:[color blendedColorWithFraction:0.75 ofColor:NSColor.whiteColor] + endingColor:[color blendedColorWithFraction:0.2 ofColor:NSColor.whiteColor]]; + [gradient drawInBezierPath:bp angle:270.0]; [icon unlockFocus]; @@ -389,18 +406,20 @@ GroupsController * fGroupsInstance = nil; return icon; } -- (BOOL) torrent: (Torrent *) torrent doesMatchRulesForGroupAtIndex: (NSInteger) index +- (BOOL)torrent:(Torrent*)torrent doesMatchRulesForGroupAtIndex:(NSInteger)index { - if (![self usesAutoAssignRulesForIndex: index]) + if (![self usesAutoAssignRulesForIndex:index]) + { return NO; + } - NSPredicate * predicate = [self autoAssignRulesForIndex: index]; + NSPredicate* predicate = [self autoAssignRulesForIndex:index]; BOOL eval = NO; @try { - eval = [predicate evaluateWithObject: torrent]; + eval = [predicate evaluateWithObject:torrent]; } - @catch (NSException * exception) + @catch (NSException* exception) { NSLog(@"Error when evaluating predicate (%@) - %@", predicate, exception); } diff --git a/macosx/GroupsPrefsController.h b/macosx/GroupsPrefsController.h index 52d275073..073e9adc3 100644 --- a/macosx/GroupsPrefsController.h +++ b/macosx/GroupsPrefsController.h @@ -24,25 +24,25 @@ @interface GroupsPrefsController : NSObject { - IBOutlet NSTableView * fTableView; - IBOutlet NSSegmentedControl * fAddRemoveControl; + IBOutlet NSTableView* fTableView; + IBOutlet NSSegmentedControl* fAddRemoveControl; - IBOutlet NSColorWell * fSelectedColorView; - IBOutlet NSTextField * fSelectedColorNameField; - IBOutlet NSButton * fCustomLocationEnableCheck; - IBOutlet NSPopUpButton * fCustomLocationPopUp; + IBOutlet NSColorWell* fSelectedColorView; + IBOutlet NSTextField* fSelectedColorNameField; + IBOutlet NSButton* fCustomLocationEnableCheck; + IBOutlet NSPopUpButton* fCustomLocationPopUp; - IBOutlet NSButton * fAutoAssignRulesEnableCheck; - IBOutlet NSButton * fAutoAssignRulesEditButton; + IBOutlet NSButton* fAutoAssignRulesEnableCheck; + IBOutlet NSButton* fAutoAssignRulesEditButton; } -- (void) addRemoveGroup: (id) sender; +- (void)addRemoveGroup:(id)sender; -- (IBAction) toggleUseCustomDownloadLocation: (id) sender; -- (IBAction) customDownloadLocationSheetShow: (id) sender; +- (IBAction)toggleUseCustomDownloadLocation:(id)sender; +- (IBAction)customDownloadLocationSheetShow:(id)sender; -- (IBAction) toggleUseAutoAssignRules: (id) sender; -- (IBAction) orderFrontRulesSheet: (id) sender; -- (IBAction) cancelRules: (id) sender; -- (IBAction) saveRules: (id) sender; +- (IBAction)toggleUseAutoAssignRules:(id)sender; +- (IBAction)orderFrontRulesSheet:(id)sender; +- (IBAction)cancelRules:(id)sender; +- (IBAction)saveRules:(id)sender; @end diff --git a/macosx/GroupsPrefsController.m b/macosx/GroupsPrefsController.m index 1e8ac1a02..c2fa8233e 100644 --- a/macosx/GroupsPrefsController.m +++ b/macosx/GroupsPrefsController.m @@ -33,16 +33,16 @@ @interface GroupsPrefsController () -@property (nonatomic) IBOutlet NSWindow * groupRulesSheetWindow; -@property (nonatomic, weak) IBOutlet NSPredicateEditor * ruleEditor; -@property (nonatomic, weak) IBOutlet NSLayoutConstraint * ruleEditorHeightConstraint; +@property(nonatomic) IBOutlet NSWindow* groupRulesSheetWindow; +@property(nonatomic, weak) IBOutlet NSPredicateEditor* ruleEditor; +@property(nonatomic, weak) IBOutlet NSLayoutConstraint* ruleEditorHeightConstraint; @end @interface GroupsPrefsController (Private) -- (void) updateSelectedGroup; -- (void) refreshCustomLocationWithSingleGroup; +- (void)updateSelectedGroup; +- (void)refreshCustomLocationWithSingleGroup; @end @@ -52,154 +52,167 @@ @synthesize ruleEditor; @synthesize ruleEditorHeightConstraint; -- (void) awakeFromNib +- (void)awakeFromNib { - [fTableView registerForDraggedTypes: @[GROUP_TABLE_VIEW_DATA_TYPE]]; + [fTableView registerForDraggedTypes:@[ GROUP_TABLE_VIEW_DATA_TYPE ]]; - [fSelectedColorView addObserver: self forKeyPath: @"color" options: 0 context: NULL]; + [fSelectedColorView addObserver:self forKeyPath:@"color" options:0 context:NULL]; [self updateSelectedGroup]; } -- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableview +- (NSInteger)numberOfRowsInTableView:(NSTableView*)tableview { return GroupsController.groups.numberOfGroups; } -- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row +- (id)tableView:(NSTableView*)tableView objectValueForTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row { - GroupsController * groupsController = GroupsController.groups; - NSInteger groupsIndex = [groupsController indexForRow: row]; + GroupsController* groupsController = GroupsController.groups; + NSInteger groupsIndex = [groupsController indexForRow:row]; - NSString * identifier = tableColumn.identifier; - if ([identifier isEqualToString: @"Color"]) - return [groupsController imageForIndex: groupsIndex]; + NSString* identifier = tableColumn.identifier; + if ([identifier isEqualToString:@"Color"]) + { + return [groupsController imageForIndex:groupsIndex]; + } else - return [groupsController nameForIndex: groupsIndex]; + { + return [groupsController nameForIndex:groupsIndex]; + } } -- (void) tableViewSelectionDidChange: (NSNotification *) notification +- (void)tableViewSelectionDidChange:(NSNotification*)notification { [self updateSelectedGroup]; } -- (void) observeValueForKeyPath: (NSString *) keyPath ofObject: (id) object change: (NSDictionary *) change context: (void *) context +- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context { if (object == fSelectedColorView && fTableView.numberOfSelectedRows == 1) { - NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; - [GroupsController.groups setColor: fSelectedColorView.color forIndex: index]; - fTableView.needsDisplay = YES; + NSInteger index = [GroupsController.groups indexForRow:fTableView.selectedRow]; + [GroupsController.groups setColor:fSelectedColorView.color forIndex:index]; + fTableView.needsDisplay = YES; } } -- (void) controlTextDidEndEditing: (NSNotification *) notification +- (void)controlTextDidEndEditing:(NSNotification*)notification { if (notification.object == fSelectedColorNameField) { - NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; - [GroupsController.groups setName: fSelectedColorNameField.stringValue forIndex: index]; - fTableView.needsDisplay = YES; + NSInteger index = [GroupsController.groups indexForRow:fTableView.selectedRow]; + [GroupsController.groups setName:fSelectedColorNameField.stringValue forIndex:index]; + fTableView.needsDisplay = YES; } } -- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) rowIndexes toPasteboard: (NSPasteboard *) pboard +- (BOOL)tableView:(NSTableView*)tableView writeRowsWithIndexes:(NSIndexSet*)rowIndexes toPasteboard:(NSPasteboard*)pboard { - [pboard declareTypes: @[GROUP_TABLE_VIEW_DATA_TYPE] owner: self]; - [pboard setData: [NSKeyedArchiver archivedDataWithRootObject: rowIndexes] forType: GROUP_TABLE_VIEW_DATA_TYPE]; + [pboard declareTypes:@[ GROUP_TABLE_VIEW_DATA_TYPE ] owner:self]; + [pboard setData:[NSKeyedArchiver archivedDataWithRootObject:rowIndexes] forType:GROUP_TABLE_VIEW_DATA_TYPE]; return YES; } -- (NSDragOperation) tableView: (NSTableView *) tableView validateDrop: (id ) info - proposedRow: (NSInteger) row proposedDropOperation: (NSTableViewDropOperation) operation +- (NSDragOperation)tableView:(NSTableView*)tableView + validateDrop:(id)info + proposedRow:(NSInteger)row + proposedDropOperation:(NSTableViewDropOperation)operation { - NSPasteboard * pasteboard = info.draggingPasteboard; - if ([pasteboard.types containsObject: GROUP_TABLE_VIEW_DATA_TYPE]) + NSPasteboard* pasteboard = info.draggingPasteboard; + if ([pasteboard.types containsObject:GROUP_TABLE_VIEW_DATA_TYPE]) { - [fTableView setDropRow: row dropOperation: NSTableViewDropAbove]; + [fTableView setDropRow:row dropOperation:NSTableViewDropAbove]; return NSDragOperationGeneric; } return NSDragOperationNone; } -- (BOOL) tableView: (NSTableView *) tableView acceptDrop: (id ) info row: (NSInteger) newRow - dropOperation: (NSTableViewDropOperation) operation +- (BOOL)tableView:(NSTableView*)tableView + acceptDrop:(id)info + row:(NSInteger)newRow + dropOperation:(NSTableViewDropOperation)operation { - NSPasteboard * pasteboard = info.draggingPasteboard; - if ([pasteboard.types containsObject: GROUP_TABLE_VIEW_DATA_TYPE]) + NSPasteboard* pasteboard = info.draggingPasteboard; + if ([pasteboard.types containsObject:GROUP_TABLE_VIEW_DATA_TYPE]) { - NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: GROUP_TABLE_VIEW_DATA_TYPE]]; + NSIndexSet* indexes = [NSKeyedUnarchiver unarchiveObjectWithData:[pasteboard dataForType:GROUP_TABLE_VIEW_DATA_TYPE]]; NSInteger oldRow = indexes.firstIndex; if (oldRow < newRow) + { newRow--; + } [fTableView beginUpdates]; - [GroupsController.groups moveGroupAtRow: oldRow toRow: newRow]; + [GroupsController.groups moveGroupAtRow:oldRow toRow:newRow]; - [fTableView moveRowAtIndex: oldRow toIndex: newRow]; + [fTableView moveRowAtIndex:oldRow toIndex:newRow]; [fTableView endUpdates]; } return YES; } -- (void) addRemoveGroup: (id) sender +- (void)addRemoveGroup:(id)sender { if (NSColorPanel.sharedColorPanelExists) + { [NSColorPanel.sharedColorPanel close]; + } NSInteger row; - switch ([[sender cell] tagForSegment: [sender selectedSegment]]) + switch ([[sender cell] tagForSegment:[sender selectedSegment]]) { - case ADD_TAG: - [fTableView beginUpdates]; + case ADD_TAG: + [fTableView beginUpdates]; - [GroupsController.groups addNewGroup]; + [GroupsController.groups addNewGroup]; - row = fTableView.numberOfRows; + row = fTableView.numberOfRows; - [fTableView insertRowsAtIndexes: [NSIndexSet indexSetWithIndex: row] withAnimation: NSTableViewAnimationSlideUp]; - [fTableView endUpdates]; + [fTableView insertRowsAtIndexes:[NSIndexSet indexSetWithIndex:row] withAnimation:NSTableViewAnimationSlideUp]; + [fTableView endUpdates]; - [fTableView selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; - [fTableView scrollRowToVisible: row]; + [fTableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO]; + [fTableView scrollRowToVisible:row]; - [fSelectedColorNameField.window makeFirstResponder: fSelectedColorNameField]; + [fSelectedColorNameField.window makeFirstResponder:fSelectedColorNameField]; - break; + break; - case REMOVE_TAG: - row = fTableView.selectedRow; + case REMOVE_TAG: + row = fTableView.selectedRow; + [fTableView beginUpdates]; - [fTableView beginUpdates]; + [GroupsController.groups removeGroupWithRowIndex:row]; - [GroupsController.groups removeGroupWithRowIndex: row]; + [fTableView removeRowsAtIndexes:[NSIndexSet indexSetWithIndex:row] withAnimation:NSTableViewAnimationSlideUp]; + [fTableView endUpdates]; - [fTableView removeRowsAtIndexes: [NSIndexSet indexSetWithIndex: row] withAnimation: NSTableViewAnimationSlideUp]; - [fTableView endUpdates]; - - if (fTableView.numberOfRows > 0) + if (fTableView.numberOfRows > 0) + { + if (row == fTableView.numberOfRows) { - if (row == fTableView.numberOfRows) - --row; - [fTableView selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; - [fTableView scrollRowToVisible: row]; + --row; } + [fTableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO]; + [fTableView scrollRowToVisible:row]; + } - break; + break; } [self updateSelectedGroup]; } -- (void) customDownloadLocationSheetShow: (id) sender +- (void)customDownloadLocationSheetShow:(id)sender { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; panel.prompt = NSLocalizedString(@"Select", "Preferences -> Open panel prompt"); panel.allowsMultipleSelection = NO; @@ -207,38 +220,46 @@ panel.canChooseDirectories = YES; panel.canCreateDirectories = YES; - [panel beginSheetModalForWindow: fCustomLocationPopUp.window completionHandler: ^(NSInteger result) { - const NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; + [panel beginSheetModalForWindow:fCustomLocationPopUp.window completionHandler:^(NSInteger result) { + NSInteger const index = [GroupsController.groups indexForRow:fTableView.selectedRow]; if (result == NSFileHandlingPanelOKButton) { - NSString * path = panel.URLs[0].path; - [GroupsController.groups setCustomDownloadLocation: path forIndex: index]; - [GroupsController.groups setUsesCustomDownloadLocation: YES forIndex: index]; + NSString* path = panel.URLs[0].path; + [GroupsController.groups setCustomDownloadLocation:path forIndex:index]; + [GroupsController.groups setUsesCustomDownloadLocation:YES forIndex:index]; } else { - if (![GroupsController.groups customDownloadLocationForIndex: index]) - [GroupsController.groups setUsesCustomDownloadLocation: NO forIndex: index]; + if (![GroupsController.groups customDownloadLocationForIndex:index]) + { + [GroupsController.groups setUsesCustomDownloadLocation:NO forIndex:index]; + } } [self refreshCustomLocationWithSingleGroup]; - [fCustomLocationPopUp selectItemAtIndex: 0]; + [fCustomLocationPopUp selectItemAtIndex:0]; }]; } -- (IBAction) toggleUseCustomDownloadLocation: (id) sender +- (IBAction)toggleUseCustomDownloadLocation:(id)sender { - NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; + NSInteger index = [GroupsController.groups indexForRow:fTableView.selectedRow]; if (fCustomLocationEnableCheck.state == NSOnState) { - if ([GroupsController.groups customDownloadLocationForIndex: index]) - [GroupsController.groups setUsesCustomDownloadLocation: YES forIndex: index]; + if ([GroupsController.groups customDownloadLocationForIndex:index]) + { + [GroupsController.groups setUsesCustomDownloadLocation:YES forIndex:index]; + } else - [self customDownloadLocationSheetShow: nil]; + { + [self customDownloadLocationSheetShow:nil]; + } } else - [GroupsController.groups setUsesCustomDownloadLocation: NO forIndex: index]; + { + [GroupsController.groups setUsesCustomDownloadLocation:NO forIndex:index]; + } fCustomLocationPopUp.enabled = (fCustomLocationEnableCheck.state == NSOnState); } @@ -246,75 +267,85 @@ #pragma mark - #pragma mark Rule editor -- (IBAction) toggleUseAutoAssignRules: (id) sender +- (IBAction)toggleUseAutoAssignRules:(id)sender { - NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; + NSInteger index = [GroupsController.groups indexForRow:fTableView.selectedRow]; if (fAutoAssignRulesEnableCheck.state == NSOnState) { - if ([GroupsController.groups autoAssignRulesForIndex: index]) - [GroupsController.groups setUsesAutoAssignRules: YES forIndex: index]; + if ([GroupsController.groups autoAssignRulesForIndex:index]) + { + [GroupsController.groups setUsesAutoAssignRules:YES forIndex:index]; + } else - [self orderFrontRulesSheet: nil]; + { + [self orderFrontRulesSheet:nil]; + } } else - [GroupsController.groups setUsesAutoAssignRules: NO forIndex: index]; + { + [GroupsController.groups setUsesAutoAssignRules:NO forIndex:index]; + } fAutoAssignRulesEditButton.enabled = fAutoAssignRulesEnableCheck.state == NSOnState; } -- (IBAction) orderFrontRulesSheet: (id) sender +- (IBAction)orderFrontRulesSheet:(id)sender { if (!self.groupRulesSheetWindow) - [NSBundle.mainBundle loadNibNamed: @"GroupRules" owner: self topLevelObjects: NULL]; + { + [NSBundle.mainBundle loadNibNamed:@"GroupRules" owner:self topLevelObjects:NULL]; + } - NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; - NSPredicate *predicate = [GroupsController.groups autoAssignRulesForIndex: index]; + NSInteger index = [GroupsController.groups indexForRow:fTableView.selectedRow]; + NSPredicate* predicate = [GroupsController.groups autoAssignRulesForIndex:index]; self.ruleEditor.objectValue = predicate; if (self.ruleEditor.numberOfRows == 0) - [self.ruleEditor addRow: nil]; + { + [self.ruleEditor addRow:nil]; + } [fTableView.window beginSheet:self.groupRulesSheetWindow completionHandler:nil]; } -- (IBAction) cancelRules: (id) sender +- (IBAction)cancelRules:(id)sender { - [self.groupRulesSheetWindow orderOut: nil]; - [NSApp endSheet: self.groupRulesSheetWindow]; + [self.groupRulesSheetWindow orderOut:nil]; + [NSApp endSheet:self.groupRulesSheetWindow]; - NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; - if (![GroupsController.groups autoAssignRulesForIndex: index]) + NSInteger index = [GroupsController.groups indexForRow:fTableView.selectedRow]; + if (![GroupsController.groups autoAssignRulesForIndex:index]) { - [GroupsController.groups setUsesAutoAssignRules: NO forIndex: index]; + [GroupsController.groups setUsesAutoAssignRules:NO forIndex:index]; fAutoAssignRulesEnableCheck.state = NO; fAutoAssignRulesEditButton.enabled = NO; } } -- (IBAction) saveRules: (id) sender +- (IBAction)saveRules:(id)sender { - [self.groupRulesSheetWindow orderOut: nil]; - [NSApp endSheet: self.groupRulesSheetWindow]; + [self.groupRulesSheetWindow orderOut:nil]; + [NSApp endSheet:self.groupRulesSheetWindow]; - NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; - [GroupsController.groups setUsesAutoAssignRules: YES forIndex: index]; + NSInteger index = [GroupsController.groups indexForRow:fTableView.selectedRow]; + [GroupsController.groups setUsesAutoAssignRules:YES forIndex:index]; - NSPredicate * predicate = self.ruleEditor.objectValue; - [GroupsController.groups setAutoAssignRules: predicate forIndex: index]; + NSPredicate* predicate = self.ruleEditor.objectValue; + [GroupsController.groups setAutoAssignRules:predicate forIndex:index]; - fAutoAssignRulesEnableCheck.state = [GroupsController.groups usesAutoAssignRulesForIndex: index]; + fAutoAssignRulesEnableCheck.state = [GroupsController.groups usesAutoAssignRulesForIndex:index]; fAutoAssignRulesEditButton.enabled = fAutoAssignRulesEnableCheck.state == NSOnState; } -- (void) ruleEditorRowsDidChange: (NSNotification *) notification +- (void)ruleEditorRowsDidChange:(NSNotification*)notification { - NSScrollView * ruleEditorScrollView = self.ruleEditor.enclosingScrollView; + NSScrollView* ruleEditorScrollView = self.ruleEditor.enclosingScrollView; - const CGFloat rowHeight = self.ruleEditor.rowHeight; - const CGFloat bordersHeight = ruleEditorScrollView.frame.size.height - ruleEditorScrollView.contentSize.height; + CGFloat const rowHeight = self.ruleEditor.rowHeight; + CGFloat const bordersHeight = ruleEditorScrollView.frame.size.height - ruleEditorScrollView.contentSize.height; - const CGFloat requiredRowCount = self.ruleEditor.numberOfRows; - const CGFloat maxVisibleRowCount = (long)((NSHeight(self.ruleEditor.window.screen.visibleFrame) * 2 / 3) / rowHeight); + CGFloat const requiredRowCount = self.ruleEditor.numberOfRows; + CGFloat const maxVisibleRowCount = (long)((NSHeight(self.ruleEditor.window.screen.visibleFrame) * 2 / 3) / rowHeight); self.ruleEditorHeightConstraint.constant = MIN(requiredRowCount, maxVisibleRowCount) * rowHeight + bordersHeight; ruleEditorScrollView.hasVerticalScroller = requiredRowCount > maxVisibleRowCount; @@ -324,20 +355,20 @@ @implementation GroupsPrefsController (Private) -- (void) updateSelectedGroup +- (void)updateSelectedGroup { - [fAddRemoveControl setEnabled: fTableView.numberOfSelectedRows > 0 forSegment: REMOVE_TAG]; + [fAddRemoveControl setEnabled:fTableView.numberOfSelectedRows > 0 forSegment:REMOVE_TAG]; if (fTableView.numberOfSelectedRows == 1) { - const NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; - fSelectedColorView.color = [GroupsController.groups colorForIndex: index]; + NSInteger const index = [GroupsController.groups indexForRow:fTableView.selectedRow]; + fSelectedColorView.color = [GroupsController.groups colorForIndex:index]; fSelectedColorView.enabled = YES; - fSelectedColorNameField.stringValue = [GroupsController.groups nameForIndex: index]; + fSelectedColorNameField.stringValue = [GroupsController.groups nameForIndex:index]; fSelectedColorNameField.enabled = YES; [self refreshCustomLocationWithSingleGroup]; - fAutoAssignRulesEnableCheck.state = [GroupsController.groups usesAutoAssignRulesForIndex: index]; + fAutoAssignRulesEnableCheck.state = [GroupsController.groups usesAutoAssignRulesForIndex:index]; fAutoAssignRulesEnableCheck.enabled = YES; fAutoAssignRulesEditButton.enabled = (fAutoAssignRulesEnableCheck.state == NSOnState); } @@ -354,27 +385,27 @@ } } -- (void) refreshCustomLocationWithSingleGroup +- (void)refreshCustomLocationWithSingleGroup { - const NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; + NSInteger const index = [GroupsController.groups indexForRow:fTableView.selectedRow]; - const BOOL hasCustomLocation = [GroupsController.groups usesCustomDownloadLocationForIndex: index]; + BOOL const hasCustomLocation = [GroupsController.groups usesCustomDownloadLocationForIndex:index]; fCustomLocationEnableCheck.state = hasCustomLocation; fCustomLocationEnableCheck.enabled = YES; fCustomLocationPopUp.enabled = hasCustomLocation; - NSString * location = [GroupsController.groups customDownloadLocationForIndex: index]; + NSString* location = [GroupsController.groups customDownloadLocationForIndex:index]; if (location) { - ExpandedPathToPathTransformer * pathTransformer = [[ExpandedPathToPathTransformer alloc] init]; - [fCustomLocationPopUp itemAtIndex: 0].title = [pathTransformer transformedValue: location]; - ExpandedPathToIconTransformer * iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; - [fCustomLocationPopUp itemAtIndex: 0].image = [iconTransformer transformedValue: location]; + ExpandedPathToPathTransformer* pathTransformer = [[ExpandedPathToPathTransformer alloc] init]; + [fCustomLocationPopUp itemAtIndex:0].title = [pathTransformer transformedValue:location]; + ExpandedPathToIconTransformer* iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; + [fCustomLocationPopUp itemAtIndex:0].image = [iconTransformer transformedValue:location]; } else { - [fCustomLocationPopUp itemAtIndex: 0].title = @""; - [fCustomLocationPopUp itemAtIndex: 0].image = nil; + [fCustomLocationPopUp itemAtIndex:0].title = @""; + [fCustomLocationPopUp itemAtIndex:0].image = nil; } } diff --git a/macosx/InfoActivityViewController.h b/macosx/InfoActivityViewController.h index 487d27211..8879d5f71 100644 --- a/macosx/InfoActivityViewController.h +++ b/macosx/InfoActivityViewController.h @@ -27,36 +27,54 @@ @class PiecesView; @class Torrent; -@interface InfoActivityViewController : NSViewController +@interface InfoActivityViewController : NSViewController { - NSArray * fTorrents; + NSArray* fTorrents; BOOL fSet; - IBOutlet NSTextField * fDateAddedField, * fDateCompletedField, * fDateActivityField, - * fStateField, * fProgressField, - * fHaveField, * fDownloadedTotalField, * fUploadedTotalField, * fFailedHashField, - * fRatioField, - * fDownloadTimeField, * fSeedTimeField; - IBOutlet NSTextView * fErrorMessageView; + IBOutlet NSTextField* fDateAddedField; + IBOutlet NSTextField* fDateCompletedField; + IBOutlet NSTextField* fDateActivityField; + IBOutlet NSTextField* fStateField; + IBOutlet NSTextField* fProgressField; + IBOutlet NSTextField* fHaveField; + IBOutlet NSTextField* fDownloadedTotalField; + IBOutlet NSTextField* fUploadedTotalField; + IBOutlet NSTextField* fFailedHashField; + IBOutlet NSTextField* fRatioField; + IBOutlet NSTextField* fDownloadTimeField; + IBOutlet NSTextField* fSeedTimeField; + IBOutlet NSTextView* fErrorMessageView; - IBOutlet PiecesView * fPiecesView; - IBOutlet NSSegmentedControl * fPiecesControl; + IBOutlet PiecesView* fPiecesView; + IBOutlet NSSegmentedControl* fPiecesControl; //remove when we switch to auto layout on 10.7 - IBOutlet NSTextField * fTransferSectionLabel, * fDatesSectionLabel, * fTimeSectionLabel; - IBOutlet NSTextField * fStateLabel, * fProgressLabel, * fHaveLabel, * fDownloadedLabel, * fUploadedLabel, - * fFailedDLLabel, * fRatioLabel, * fErrorLabel, - * fDateAddedLabel, * fDateCompletedLabel, * fDateActivityLabel, - * fDownloadTimeLabel, * fSeedTimeLabel; - IBOutlet NSScrollView * fErrorScrollView; + IBOutlet NSTextField* fTransferSectionLabel; + IBOutlet NSTextField* fDatesSectionLabel; + IBOutlet NSTextField* fTimeSectionLabel; + IBOutlet NSTextField* fStateLabel; + IBOutlet NSTextField* fProgressLabel; + IBOutlet NSTextField* fHaveLabel; + IBOutlet NSTextField* fDownloadedLabel; + IBOutlet NSTextField* fUploadedLabel; + IBOutlet NSTextField* fFailedDLLabel; + IBOutlet NSTextField* fRatioLabel; + IBOutlet NSTextField* fErrorLabel; + IBOutlet NSTextField* fDateAddedLabel; + IBOutlet NSTextField* fDateCompletedLabel; + IBOutlet NSTextField* fDateActivityLabel; + IBOutlet NSTextField* fDownloadTimeLabel; + IBOutlet NSTextField* fSeedTimeLabel; + IBOutlet NSScrollView* fErrorScrollView; } -- (void) setInfoForTorrents: (NSArray *) torrents; -- (void) updateInfo; +- (void)setInfoForTorrents:(NSArray*)torrents; +- (void)updateInfo; -- (IBAction) setPiecesView: (id) sender; -- (IBAction) updatePiecesView: (id) sender; -- (void) clearView; +- (IBAction)setPiecesView:(id)sender; +- (IBAction)updatePiecesView:(id)sender; +- (void)clearView; @end diff --git a/macosx/InfoActivityViewController.m b/macosx/InfoActivityViewController.m index 21ef9579f..8ebc19ee5 100644 --- a/macosx/InfoActivityViewController.m +++ b/macosx/InfoActivityViewController.m @@ -34,15 +34,15 @@ @interface InfoActivityViewController (Private) -- (void) setupInfo; +- (void)setupInfo; @end @implementation InfoActivityViewController -- (instancetype) init +- (instancetype)init { - if ((self = [super initWithNibName: @"InfoActivityView" bundle: nil])) + if ((self = [super initWithNibName:@"InfoActivityView" bundle:nil])) { self.title = NSLocalizedString(@"Activity", "Inspector view -> title"); } @@ -50,18 +50,32 @@ return self; } -- (void) awakeFromNib +- (void)awakeFromNib { [fTransferSectionLabel sizeToFit]; [fDatesSectionLabel sizeToFit]; [fTimeSectionLabel sizeToFit]; - NSArray * labels = @[ fStateLabel, fProgressLabel, fHaveLabel, fDownloadedLabel, fUploadedLabel, fFailedDLLabel, fRatioLabel, fErrorLabel, fDateAddedLabel, fDateCompletedLabel, fDateActivityLabel, fDownloadTimeLabel, fSeedTimeLabel ]; + NSArray* labels = @[ + fStateLabel, + fProgressLabel, + fHaveLabel, + fDownloadedLabel, + fUploadedLabel, + fFailedDLLabel, + fRatioLabel, + fErrorLabel, + fDateAddedLabel, + fDateCompletedLabel, + fDateActivityLabel, + fDownloadTimeLabel, + fSeedTimeLabel + ]; CGFloat oldMaxWidth = 0.0, originX, newMaxWidth = 0.0; - for (NSTextField * label in labels) + for (NSTextField* label in labels) { - const NSRect oldFrame = label.frame; + NSRect const oldFrame = label.frame; if (oldFrame.size.width > oldMaxWidth) { oldMaxWidth = oldFrame.size.width; @@ -69,22 +83,39 @@ } [label sizeToFit]; - const CGFloat newWidth = label.bounds.size.width; + CGFloat const newWidth = label.bounds.size.width; if (newWidth > newMaxWidth) + { newMaxWidth = newWidth; + } } - for (NSTextField * label in labels) + for (NSTextField* label in labels) { NSRect frame = label.frame; frame.origin.x = originX + (newMaxWidth - frame.size.width); label.frame = frame; } - NSArray * fields = @[ fDateAddedField, fDateCompletedField, fDateActivityField, fStateField, fProgressField, fHaveField, fDownloadedTotalField, fUploadedTotalField, fFailedHashField, fRatioField, fDownloadTimeField, fSeedTimeField, fErrorScrollView ]; + NSArray* fields = @[ + fDateAddedField, + fDateCompletedField, + fDateActivityField, + fStateField, + fProgressField, + fHaveField, + fDownloadedTotalField, + fUploadedTotalField, + fFailedHashField, + fRatioField, + fDownloadTimeField, + fSeedTimeField, + fErrorScrollView + ]; - const CGFloat widthIncrease = newMaxWidth - oldMaxWidth; - for (NSView * field in fields) { + CGFloat const widthIncrease = newMaxWidth - oldMaxWidth; + for (NSView* field in fields) + { NSRect frame = field.frame; frame.origin.x += widthIncrease; frame.size.width -= widthIncrease; @@ -92,17 +123,17 @@ } //set the click action of the pieces view - #warning after 2.8 just hook this up in the xib +#warning after 2.8 just hook this up in the xib fPiecesView.action = @selector(updatePiecesView:); fPiecesView.target = self; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; } -- (void) setInfoForTorrents: (NSArray *) torrents +- (void)setInfoForTorrents:(NSArray*)torrents { //don't check if it's the same in case the metadata changed fTorrents = torrents; @@ -110,18 +141,22 @@ fSet = NO; } -- (void) updateInfo +- (void)updateInfo { if (!fSet) + { [self setupInfo]; + } - const NSInteger numberSelected = fTorrents.count; + NSInteger const numberSelected = fTorrents.count; if (numberSelected == 0) + { return; + } uint64_t have = 0, haveVerified = 0, downloadedTotal = 0, uploadedTotal = 0, failedHash = 0; - NSDate * lastActivity = nil; - for (Torrent * torrent in fTorrents) + NSDate* lastActivity = nil; + for (Torrent* torrent in fTorrents) { have += torrent.haveTotal; haveVerified += torrent.haveVerified; @@ -129,57 +164,65 @@ uploadedTotal += torrent.uploadedTotal; failedHash += torrent.failedHash; - NSDate * nextLastActivity; + NSDate* nextLastActivity; if ((nextLastActivity = torrent.dateActivity)) - lastActivity = lastActivity ? [lastActivity laterDate: nextLastActivity] : nextLastActivity; + { + lastActivity = lastActivity ? [lastActivity laterDate:nextLastActivity] : nextLastActivity; + } } if (have == 0) - fHaveField.stringValue = [NSString stringForFileSize: 0]; + { + fHaveField.stringValue = [NSString stringForFileSize:0]; + } else { - NSString * verifiedString = [NSString stringWithFormat: NSLocalizedString(@"%@ verified", "Inspector -> Activity tab -> have"), - [NSString stringForFileSize: haveVerified]]; + NSString* verifiedString = [NSString stringWithFormat:NSLocalizedString(@"%@ verified", "Inspector -> Activity tab -> have"), + [NSString stringForFileSize:haveVerified]]; if (have == haveVerified) + { fHaveField.stringValue = verifiedString; + } else - fHaveField.stringValue = [NSString stringWithFormat: @"%@ (%@)", [NSString stringForFileSize: have], verifiedString]; + { + fHaveField.stringValue = [NSString stringWithFormat:@"%@ (%@)", [NSString stringForFileSize:have], verifiedString]; + } } - fDownloadedTotalField.stringValue = [NSString stringForFileSize: downloadedTotal]; - fUploadedTotalField.stringValue = [NSString stringForFileSize: uploadedTotal]; - fFailedHashField.stringValue = [NSString stringForFileSize: failedHash]; + fDownloadedTotalField.stringValue = [NSString stringForFileSize:downloadedTotal]; + fUploadedTotalField.stringValue = [NSString stringForFileSize:uploadedTotal]; + fFailedHashField.stringValue = [NSString stringForFileSize:failedHash]; fDateActivityField.objectValue = lastActivity; if (numberSelected == 1) { - Torrent * torrent = fTorrents[0]; + Torrent* torrent = fTorrents[0]; fStateField.stringValue = torrent.stateString; - NSString * progressString = [NSString percentString: torrent.progress longDecimals: YES]; + NSString* progressString = [NSString percentString:torrent.progress longDecimals:YES]; if (torrent.folder) { - NSString * progressSelectedString = [NSString stringWithFormat: - NSLocalizedString(@"%@ selected", "Inspector -> Activity tab -> progress"), - [NSString percentString: torrent.progressDone longDecimals: YES]]; - progressString = [progressString stringByAppendingFormat: @" (%@)", progressSelectedString]; + NSString* progressSelectedString = [NSString + stringWithFormat:NSLocalizedString(@"%@ selected", "Inspector -> Activity tab -> progress"), + [NSString percentString:torrent.progressDone longDecimals:YES]]; + progressString = [progressString stringByAppendingFormat:@" (%@)", progressSelectedString]; } fProgressField.stringValue = progressString; - fRatioField.stringValue = [NSString stringForRatio: torrent.ratio]; + fRatioField.stringValue = [NSString stringForRatio:torrent.ratio]; - NSString * errorMessage = torrent.errorMessage; - if (![errorMessage isEqualToString: fErrorMessageView.string]) + NSString* errorMessage = torrent.errorMessage; + if (![errorMessage isEqualToString:fErrorMessageView.string]) fErrorMessageView.string = errorMessage; fDateCompletedField.objectValue = torrent.dateCompleted; //uses a relative date, so can't be set once fDateAddedField.objectValue = torrent.dateAdded; - - static NSDateComponentsFormatter *timeFormatter; + + static NSDateComponentsFormatter* timeFormatter; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ timeFormatter = [NSDateComponentsFormatter new]; @@ -187,38 +230,36 @@ timeFormatter.allowedUnits = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; timeFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropLeading; }); - + fDownloadTimeField.stringValue = [timeFormatter stringFromTimeInterval:torrent.secondsDownloading]; fSeedTimeField.stringValue = [timeFormatter stringFromTimeInterval:torrent.secondsSeeding]; - + [fPiecesView updateView]; } else if (numberSelected > 1) { - fRatioField.stringValue = [NSString stringForRatio: tr_getRatio(uploadedTotal, downloadedTotal)]; + fRatioField.stringValue = [NSString stringForRatio:tr_getRatio(uploadedTotal, downloadedTotal)]; } - else; } -- (void) setPiecesView: (id) sender +- (void)setPiecesView:(id)sender { - const BOOL availability = [sender selectedSegment] == PIECES_CONTROL_AVAILABLE; - [NSUserDefaults.standardUserDefaults setBool: availability forKey: @"PiecesViewShowAvailability"]; + BOOL const availability = [sender selectedSegment] == PIECES_CONTROL_AVAILABLE; + [NSUserDefaults.standardUserDefaults setBool:availability forKey:@"PiecesViewShowAvailability"]; [self updatePiecesView:nil]; } - -- (void) updatePiecesView: (id) sender +- (void)updatePiecesView:(id)sender { - const BOOL piecesAvailableSegment = [NSUserDefaults.standardUserDefaults boolForKey: @"PiecesViewShowAvailability"]; + BOOL const piecesAvailableSegment = [NSUserDefaults.standardUserDefaults boolForKey:@"PiecesViewShowAvailability"]; - [fPiecesControl setSelected: piecesAvailableSegment forSegment: PIECES_CONTROL_AVAILABLE]; - [fPiecesControl setSelected: !piecesAvailableSegment forSegment: PIECES_CONTROL_PROGRESS]; + [fPiecesControl setSelected:piecesAvailableSegment forSegment:PIECES_CONTROL_AVAILABLE]; + [fPiecesControl setSelected:!piecesAvailableSegment forSegment:PIECES_CONTROL_PROGRESS]; [fPiecesView updateView]; } -- (void) clearView +- (void)clearView { [fPiecesView clearView]; } @@ -227,9 +268,9 @@ @implementation InfoActivityViewController (Private) -- (void) setupInfo +- (void)setupInfo { - const NSUInteger count = fTorrents.count; + NSUInteger const count = fTorrents.count; if (count != 1) { if (count == 0) @@ -254,21 +295,21 @@ fDownloadTimeField.stringValue = @""; fSeedTimeField.stringValue = @""; - [fPiecesControl setSelected: NO forSegment: PIECES_CONTROL_AVAILABLE]; - [fPiecesControl setSelected: NO forSegment: PIECES_CONTROL_PROGRESS]; - fPiecesControl.enabled = NO; - [fPiecesView setTorrent: nil]; + [fPiecesControl setSelected:NO forSegment:PIECES_CONTROL_AVAILABLE]; + [fPiecesControl setSelected:NO forSegment:PIECES_CONTROL_PROGRESS]; + fPiecesControl.enabled = NO; + [fPiecesView setTorrent:nil]; } else { - Torrent * torrent = fTorrents[0]; + Torrent* torrent = fTorrents[0]; - const BOOL piecesAvailableSegment = [NSUserDefaults.standardUserDefaults boolForKey: @"PiecesViewShowAvailability"]; - [fPiecesControl setSelected: piecesAvailableSegment forSegment: PIECES_CONTROL_AVAILABLE]; - [fPiecesControl setSelected: !piecesAvailableSegment forSegment: PIECES_CONTROL_PROGRESS]; + BOOL const piecesAvailableSegment = [NSUserDefaults.standardUserDefaults boolForKey:@"PiecesViewShowAvailability"]; + [fPiecesControl setSelected:piecesAvailableSegment forSegment:PIECES_CONTROL_AVAILABLE]; + [fPiecesControl setSelected:!piecesAvailableSegment forSegment:PIECES_CONTROL_PROGRESS]; fPiecesControl.enabled = YES; - [fPiecesView setTorrent: torrent]; + [fPiecesView setTorrent:torrent]; } fSet = YES; diff --git a/macosx/InfoFileViewController.h b/macosx/InfoFileViewController.h index 68cb4ff7a..3acd8b155 100644 --- a/macosx/InfoFileViewController.h +++ b/macosx/InfoFileViewController.h @@ -27,29 +27,30 @@ @class FileOutlineController; -@interface InfoFileViewController : NSViewController +@interface InfoFileViewController : NSViewController { - NSArray * fTorrents; + NSArray* fTorrents; BOOL fSet; - IBOutlet FileOutlineController * fFileController; + IBOutlet FileOutlineController* fFileController; - IBOutlet NSSearchField * fFileFilterField; - IBOutlet NSButton * fCheckAllButton, *fUncheckAllButton; + IBOutlet NSSearchField* fFileFilterField; + IBOutlet NSButton* fCheckAllButton; + IBOutlet NSButton* fUncheckAllButton; } -- (void) setInfoForTorrents: (NSArray *) torrents; -- (void) updateInfo; +- (void)setInfoForTorrents:(NSArray*)torrents; +- (void)updateInfo; -- (void) saveViewSize; +- (void)saveViewSize; -- (IBAction) setFileFilterText: (id) sender; -- (IBAction) checkAll: (id) sender; -- (IBAction) uncheckAll: (id) sender; +- (IBAction)setFileFilterText:(id)sender; +- (IBAction)checkAll:(id)sender; +- (IBAction)uncheckAll:(id)sender; -@property (nonatomic, readonly) NSArray *quickLookURLs; -@property (nonatomic, readonly) BOOL canQuickLook; -- (NSRect) quickLookSourceFrameForPreviewItem: (id ) item; +@property(nonatomic, readonly) NSArray* quickLookURLs; +@property(nonatomic, readonly) BOOL canQuickLook; +- (NSRect)quickLookSourceFrameForPreviewItem:(id)item; @end diff --git a/macosx/InfoFileViewController.m b/macosx/InfoFileViewController.m index 86642ff3f..7d4bbc4e7 100644 --- a/macosx/InfoFileViewController.m +++ b/macosx/InfoFileViewController.m @@ -28,17 +28,17 @@ @interface InfoFileViewController (Private) -- (void) setupInfo; +- (void)setupInfo; -- (BOOL) canQuickLookFile: (FileListNode *) item; +- (BOOL)canQuickLookFile:(FileListNode*)item; @end @implementation InfoFileViewController -- (instancetype) init +- (instancetype)init { - if ((self = [super initWithNibName: @"InfoFileView" bundle: nil])) + if ((self = [super initWithNibName:@"InfoFileView" bundle:nil])) { self.title = NSLocalizedString(@"Files", "Inspector view -> title"); } @@ -46,9 +46,9 @@ return self; } -- (void) awakeFromNib +- (void)awakeFromNib { - const CGFloat height = [NSUserDefaults.standardUserDefaults floatForKey: @"InspectorContentHeightFiles"]; + CGFloat const height = [NSUserDefaults.standardUserDefaults floatForKey:@"InspectorContentHeightFiles"]; if (height != 0.0) { NSRect viewRect = self.view.frame; @@ -56,7 +56,7 @@ self.view.frame = viewRect; } - [fFileFilterField.cell setPlaceholderString: NSLocalizedString(@"Filter", "inspector -> file filter")]; + [fFileFilterField.cell setPlaceholderString:NSLocalizedString(@"Filter", "inspector -> file filter")]; //localize and place all and none buttons fCheckAllButton.title = NSLocalizedString(@"All", "inspector -> check all"); @@ -64,26 +64,25 @@ NSRect checkAllFrame = fCheckAllButton.frame; NSRect uncheckAllFrame = fUncheckAllButton.frame; - const CGFloat oldAllWidth = checkAllFrame.size.width; - const CGFloat oldNoneWidth = uncheckAllFrame.size.width; + CGFloat const oldAllWidth = checkAllFrame.size.width; + CGFloat const oldNoneWidth = uncheckAllFrame.size.width; [fCheckAllButton sizeToFit]; [fUncheckAllButton sizeToFit]; - const CGFloat newWidth = MAX(fCheckAllButton.bounds.size.width, fUncheckAllButton.bounds.size.width); + CGFloat const newWidth = MAX(fCheckAllButton.bounds.size.width, fUncheckAllButton.bounds.size.width); - const CGFloat uncheckAllChange = newWidth - oldNoneWidth; + CGFloat const uncheckAllChange = newWidth - oldNoneWidth; uncheckAllFrame.size.width = newWidth; uncheckAllFrame.origin.x -= uncheckAllChange; fUncheckAllButton.frame = uncheckAllFrame; - const CGFloat checkAllChange = newWidth - oldAllWidth; + CGFloat const checkAllChange = newWidth - oldAllWidth; checkAllFrame.size.width = newWidth; checkAllFrame.origin.x -= (checkAllChange + uncheckAllChange); fCheckAllButton.frame = checkAllFrame; } - -- (void) setInfoForTorrents: (NSArray *) torrents +- (void)setInfoForTorrents:(NSArray*)torrents { //don't check if it's the same in case the metadata changed fTorrents = torrents; @@ -91,102 +90,117 @@ fSet = NO; } -- (void) updateInfo +- (void)updateInfo { if (!fSet) + { [self setupInfo]; + } if (fTorrents.count == 1) { [fFileController refresh]; - #warning use TorrentFileCheckChange notification as well - Torrent * torrent = fTorrents[0]; +#warning use TorrentFileCheckChange notification as well + Torrent* torrent = fTorrents[0]; if (torrent.folder) { - const NSInteger filesCheckState = [torrent checkForFiles: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, torrent.fileCount)]]; + NSInteger const filesCheckState = [torrent + checkForFiles:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, torrent.fileCount)]]; fCheckAllButton.enabled = filesCheckState != NSOnState; //if anything is unchecked fUncheckAllButton.enabled = !torrent.allDownloaded; //if there are any checked files that aren't finished } } } -- (void) saveViewSize +- (void)saveViewSize { - [NSUserDefaults.standardUserDefaults setFloat: NSHeight(self.view.frame) forKey: @"InspectorContentHeightFiles"]; + [NSUserDefaults.standardUserDefaults setFloat:NSHeight(self.view.frame) forKey:@"InspectorContentHeightFiles"]; } -- (void) setFileFilterText: (id) sender +- (void)setFileFilterText:(id)sender { - [fFileController setFilterText: [sender stringValue]]; + [fFileController setFilterText:[sender stringValue]]; } -- (IBAction) checkAll: (id) sender +- (IBAction)checkAll:(id)sender { [fFileController checkAll]; } -- (IBAction) uncheckAll: (id) sender +- (IBAction)uncheckAll:(id)sender { [fFileController uncheckAll]; } -- (NSArray *) quickLookURLs +- (NSArray*)quickLookURLs { - FileOutlineView * fileOutlineView = fFileController.outlineView; - Torrent * torrent = fTorrents[0]; - NSIndexSet * indexes = fileOutlineView.selectedRowIndexes; - NSMutableArray * urlArray = [NSMutableArray arrayWithCapacity: indexes.count]; + FileOutlineView* fileOutlineView = fFileController.outlineView; + Torrent* torrent = fTorrents[0]; + NSIndexSet* indexes = fileOutlineView.selectedRowIndexes; + NSMutableArray* urlArray = [NSMutableArray arrayWithCapacity:indexes.count]; - for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex: i]) + for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex:i]) { - FileListNode * item = [fileOutlineView itemAtRow: i]; - if ([self canQuickLookFile: item]) - [urlArray addObject: [NSURL fileURLWithPath: [torrent fileLocation: item]]]; + FileListNode* item = [fileOutlineView itemAtRow:i]; + if ([self canQuickLookFile:item]) + { + [urlArray addObject:[NSURL fileURLWithPath:[torrent fileLocation:item]]]; + } } return urlArray; } -- (BOOL) canQuickLook +- (BOOL)canQuickLook { if (fTorrents.count != 1) + { return NO; + } - Torrent * torrent = fTorrents[0]; + Torrent* torrent = fTorrents[0]; if (!torrent.folder) + { return NO; + } - FileOutlineView * fileOutlineView = fFileController.outlineView; - NSIndexSet * indexes = fileOutlineView.selectedRowIndexes; + FileOutlineView* fileOutlineView = fFileController.outlineView; + NSIndexSet* indexes = fileOutlineView.selectedRowIndexes; - for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex: i]) - if ([self canQuickLookFile: [fileOutlineView itemAtRow: i]]) + for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex:i]) + { + if ([self canQuickLookFile:[fileOutlineView itemAtRow:i]]) + { return YES; + } + } return NO; } -- (NSRect) quickLookSourceFrameForPreviewItem: (id ) item +- (NSRect)quickLookSourceFrameForPreviewItem:(id)item { - FileOutlineView * fileOutlineView = fFileController.outlineView; + FileOutlineView* fileOutlineView = fFileController.outlineView; - NSString * fullPath = ((NSURL *)item).path; - Torrent * torrent = fTorrents[0]; - NSRange visibleRows = [fileOutlineView rowsInRect: fileOutlineView.bounds]; + NSString* fullPath = ((NSURL*)item).path; + Torrent* torrent = fTorrents[0]; + NSRange visibleRows = [fileOutlineView rowsInRect:fileOutlineView.bounds]; for (NSUInteger row = visibleRows.location; row < NSMaxRange(visibleRows); row++) { - FileListNode * rowItem = [fileOutlineView itemAtRow: row]; - if ([[torrent fileLocation: rowItem] isEqualToString: fullPath]) + FileListNode* rowItem = [fileOutlineView itemAtRow:row]; + if ([[torrent fileLocation:rowItem] isEqualToString:fullPath]) { - NSRect frame = [fileOutlineView iconRectForRow: row]; + NSRect frame = [fileOutlineView iconRectForRow:row]; if (!NSIntersectsRect(fileOutlineView.visibleRect, frame)) + { return NSZeroRect; + } - frame.origin = [fileOutlineView convertPoint: frame.origin toView: nil]; - frame = [self.view.window convertRectToScreen: frame]; + frame.origin = [fileOutlineView convertPoint:frame.origin toView:nil]; + frame = [self.view.window convertRectToScreen:frame]; frame.origin.y -= frame.size.height; return frame; } @@ -199,17 +213,17 @@ @implementation InfoFileViewController (Private) -- (void) setupInfo +- (void)setupInfo { fFileFilterField.stringValue = @""; if (fTorrents.count == 1) { - Torrent * torrent = fTorrents[0]; + Torrent* torrent = fTorrents[0]; - [fFileController setTorrent: torrent]; + [fFileController setTorrent:torrent]; - const BOOL isFolder = torrent.folder; + BOOL const isFolder = torrent.folder; fFileFilterField.enabled = isFolder; if (!isFolder) @@ -220,7 +234,7 @@ } else { - [fFileController setTorrent: nil]; + [fFileController setTorrent:nil]; fFileFilterField.enabled = NO; @@ -231,10 +245,10 @@ fSet = YES; } -- (BOOL) canQuickLookFile: (FileListNode *) item +- (BOOL)canQuickLookFile:(FileListNode*)item { - Torrent * torrent = fTorrents[0]; - return (item.isFolder || [torrent fileProgress: item] >= 1.0) && [torrent fileLocation: item]; + Torrent* torrent = fTorrents[0]; + return (item.isFolder || [torrent fileProgress:item] >= 1.0) && [torrent fileLocation:item]; } @end diff --git a/macosx/InfoGeneralViewController.h b/macosx/InfoGeneralViewController.h index 171f31fc4..43e7e2cde 100644 --- a/macosx/InfoGeneralViewController.h +++ b/macosx/InfoGeneralViewController.h @@ -24,32 +24,39 @@ #import "InfoViewController.h" -@interface InfoGeneralViewController : NSViewController +@interface InfoGeneralViewController : NSViewController { - NSArray * fTorrents; + NSArray* fTorrents; BOOL fSet; - IBOutlet NSTextField * fPiecesField, * fHashField, * fSecureField, - * fDataLocationField, - * fCreatorField, * fDateCreatedField; + IBOutlet NSTextField* fPiecesField; + IBOutlet NSTextField* fHashField; + IBOutlet NSTextField* fSecureField; + IBOutlet NSTextField* fDataLocationField; + IBOutlet NSTextField* fCreatorField; + IBOutlet NSTextField* fDateCreatedField; - IBOutlet NSTextView * fCommentView; + IBOutlet NSTextView* fCommentView; - IBOutlet NSButton * fRevealDataButton; + IBOutlet NSButton* fRevealDataButton; //remove when we switch to auto layout on 10.7 - IBOutlet NSTextField * fPiecesLabel, * fHashLabel, * fSecureLabel, - * fCreatorLabel, * fDateCreatedLabel, - * fCommentLabel, - * fDataLocationLabel; - IBOutlet NSTextField * fInfoSectionLabel, * fWhereSectionLabel; - IBOutlet NSScrollView * fCommentScrollView; + IBOutlet NSTextField* fPiecesLabel; + IBOutlet NSTextField* fHashLabel; + IBOutlet NSTextField* fSecureLabel; + IBOutlet NSTextField* fCreatorLabel; + IBOutlet NSTextField* fDateCreatedLabel; + IBOutlet NSTextField* fCommentLabel; + IBOutlet NSTextField* fDataLocationLabel; + IBOutlet NSTextField* fInfoSectionLabel; + IBOutlet NSTextField* fWhereSectionLabel; + IBOutlet NSScrollView* fCommentScrollView; } -- (void) setInfoForTorrents: (NSArray *) torrents; -- (void) updateInfo; +- (void)setInfoForTorrents:(NSArray*)torrents; +- (void)updateInfo; -- (void) revealDataFile: (id) sender; +- (void)revealDataFile:(id)sender; @end diff --git a/macosx/InfoGeneralViewController.m b/macosx/InfoGeneralViewController.m index 26f081faa..0f68a50ca 100644 --- a/macosx/InfoGeneralViewController.m +++ b/macosx/InfoGeneralViewController.m @@ -26,15 +26,15 @@ @interface InfoGeneralViewController (Private) -- (void) setupInfo; +- (void)setupInfo; @end @implementation InfoGeneralViewController -- (instancetype) init +- (instancetype)init { - if ((self = [super initWithNibName: @"InfoGeneralView" bundle: nil])) + if ((self = [super initWithNibName:@"InfoGeneralView" bundle:nil])) { self.title = NSLocalizedString(@"General Info", "Inspector view -> title"); } @@ -42,19 +42,26 @@ return self; } - -- (void) awakeFromNib +- (void)awakeFromNib { - #warning remove when 10.7-only with auto layout +#warning remove when 10.7-only with auto layout [fInfoSectionLabel sizeToFit]; [fWhereSectionLabel sizeToFit]; - NSArray * labels = @[ fPiecesLabel, fHashLabel, fSecureLabel, fCreatorLabel, fDateCreatedLabel, fCommentLabel, fDataLocationLabel ]; + NSArray* labels = @[ + fPiecesLabel, + fHashLabel, + fSecureLabel, + fCreatorLabel, + fDateCreatedLabel, + fCommentLabel, + fDataLocationLabel, + ]; CGFloat oldMaxWidth = 0.0, originX, newMaxWidth = 0.0; - for (NSTextField * label in labels) + for (NSTextField* label in labels) { - const NSRect oldFrame = label.frame; + NSRect const oldFrame = label.frame; if (oldFrame.size.width > oldMaxWidth) { oldMaxWidth = oldFrame.size.width; @@ -62,22 +69,33 @@ } [label sizeToFit]; - const CGFloat newWidth = label.bounds.size.width; + CGFloat const newWidth = label.bounds.size.width; if (newWidth > newMaxWidth) + { newMaxWidth = newWidth; + } } - for (NSTextField * label in labels) + for (NSTextField* label in labels) { NSRect frame = label.frame; frame.origin.x = originX + (newMaxWidth - frame.size.width); label.frame = frame; } - NSArray * fields = @[ fPiecesField, fHashField, fSecureField, fCreatorField, fDateCreatedField, fCommentScrollView, fDataLocationField ]; + NSArray* fields = @[ + fPiecesField, + fHashField, + fSecureField, + fCreatorField, + fDateCreatedField, + fCommentScrollView, + fDataLocationField, + ]; - const CGFloat widthIncrease = newMaxWidth - oldMaxWidth; - for (NSView * field in fields) { + CGFloat const widthIncrease = newMaxWidth - oldMaxWidth; + for (NSView* field in fields) + { NSRect frame = field.frame; frame.origin.x += widthIncrease; frame.size.width -= widthIncrease; @@ -85,7 +103,7 @@ } } -- (void) setInfoForTorrents: (NSArray *) torrents +- (void)setInfoForTorrents:(NSArray*)torrents { //don't check if it's the same in case the metadata changed fTorrents = torrents; @@ -93,60 +111,67 @@ fSet = NO; } -- (void) updateInfo +- (void)updateInfo { if (!fSet) + { [self setupInfo]; + } if (fTorrents.count != 1) + { return; + } - Torrent * torrent = fTorrents[0]; + Torrent* torrent = fTorrents[0]; - NSString * location = torrent.dataLocation; + NSString* location = torrent.dataLocation; fDataLocationField.stringValue = location ? location.stringByAbbreviatingWithTildeInPath : @""; fDataLocationField.toolTip = location ? location : @""; fRevealDataButton.hidden = !location; } -- (void) revealDataFile: (id) sender +- (void)revealDataFile:(id)sender { - Torrent * torrent = fTorrents[0]; - NSString * location = torrent.dataLocation; + Torrent* torrent = fTorrents[0]; + NSString* location = torrent.dataLocation; if (!location) + { return; + } - NSURL * file = [NSURL fileURLWithPath: location]; - [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs: @[file]]; + NSURL* file = [NSURL fileURLWithPath:location]; + [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs:@[ file ]]; } @end @implementation InfoGeneralViewController (Private) -- (void) setupInfo +- (void)setupInfo { if (fTorrents.count == 1) { - Torrent * torrent = fTorrents[0]; + Torrent* torrent = fTorrents[0]; - #warning candidate for localizedStringWithFormat (although then we'll get two commas) - NSString * piecesString = !torrent.magnet ? [NSString stringWithFormat: @"%ld, %@", torrent.pieceCount, - [NSString stringForFileSize: torrent.pieceSize]] : @""; +#warning candidate for localizedStringWithFormat (although then we'll get two commas) + NSString* piecesString = !torrent.magnet ? + [NSString stringWithFormat:@"%ld, %@", torrent.pieceCount, [NSString stringForFileSize:torrent.pieceSize]] : + @""; fPiecesField.stringValue = piecesString; - NSString * hashString = torrent.hashString; + NSString* hashString = torrent.hashString; fHashField.stringValue = hashString; fHashField.toolTip = hashString; - fSecureField.stringValue = torrent.privateTorrent - ? NSLocalizedString(@"Private Torrent, non-tracker peer discovery disabled", "Inspector -> private torrent") - : NSLocalizedString(@"Public Torrent", "Inspector -> private torrent"); + fSecureField.stringValue = torrent.privateTorrent ? + NSLocalizedString(@"Private Torrent, non-tracker peer discovery disabled", "Inspector -> private torrent") : + NSLocalizedString(@"Public Torrent", "Inspector -> private torrent"); - NSString * commentString = torrent.comment; + NSString* commentString = torrent.comment; fCommentView.string = commentString; - NSString * creatorString = torrent.creator; + NSString* creatorString = torrent.creator; fCreatorField.stringValue = creatorString; fDateCreatedField.objectValue = torrent.dateCreated; } @@ -171,4 +196,3 @@ } @end - diff --git a/macosx/InfoOptionsViewController.h b/macosx/InfoOptionsViewController.h index 517e47a74..4c437b791 100644 --- a/macosx/InfoOptionsViewController.h +++ b/macosx/InfoOptionsViewController.h @@ -24,45 +24,62 @@ #import "InfoViewController.h" -@interface InfoOptionsViewController : NSViewController +@interface InfoOptionsViewController : NSViewController { - NSArray * fTorrents; + NSArray* fTorrents; BOOL fSet; - IBOutlet NSPopUpButton * fPriorityPopUp, * fRatioPopUp, * fIdlePopUp; - IBOutlet NSButton * fUploadLimitCheck, * fDownloadLimitCheck, * fGlobalLimitCheck, * fRemoveSeedingCompleteCheck; - IBOutlet NSTextField * fUploadLimitField, * fDownloadLimitField, * fRatioLimitField, * fIdleLimitField, - * fUploadLimitLabel, * fDownloadLimitLabel, * fIdleLimitLabel, - * fRatioLimitGlobalLabel, * fIdleLimitGlobalLabel, - * fPeersConnectLabel, * fPeersConnectField; + IBOutlet NSPopUpButton* fPriorityPopUp; + IBOutlet NSPopUpButton* fRatioPopUp; + IBOutlet NSPopUpButton* fIdlePopUp; + IBOutlet NSButton* fUploadLimitCheck; + IBOutlet NSButton* fDownloadLimitCheck; + IBOutlet NSButton* fGlobalLimitCheck; + IBOutlet NSButton* fRemoveSeedingCompleteCheck; + IBOutlet NSTextField* fUploadLimitField; + IBOutlet NSTextField* fDownloadLimitField; + IBOutlet NSTextField* fRatioLimitField; + IBOutlet NSTextField* fIdleLimitField; + IBOutlet NSTextField* fUploadLimitLabel; + IBOutlet NSTextField* fDownloadLimitLabel; + IBOutlet NSTextField* fIdleLimitLabel; + IBOutlet NSTextField* fRatioLimitGlobalLabel; + IBOutlet NSTextField* fIdleLimitGlobalLabel; + IBOutlet NSTextField* fPeersConnectLabel; + IBOutlet NSTextField* fPeersConnectField; //remove when we switch to auto layout on 10.7 - IBOutlet NSTextField * fTransferBandwidthSectionLabel, * fPrioritySectionLabel, * fPriorityLabel; - IBOutlet NSTextField * fSeedingLimitsSectionLabel, * fRatioLabel, * fInactivityLabel; - IBOutlet NSTextField * fAdvancedSectionLabel, * fMaxConnectionsLabel; + IBOutlet NSTextField* fTransferBandwidthSectionLabel; + IBOutlet NSTextField* fPrioritySectionLabel; + IBOutlet NSTextField* fPriorityLabel; + IBOutlet NSTextField* fSeedingLimitsSectionLabel; + IBOutlet NSTextField* fRatioLabel; + IBOutlet NSTextField* fInactivityLabel; + IBOutlet NSTextField* fAdvancedSectionLabel; + IBOutlet NSTextField* fMaxConnectionsLabel; - NSString * fInitialString; + NSString* fInitialString; } -- (void) setInfoForTorrents: (NSArray *) torrents; -- (void) updateInfo; -- (void) updateOptions; +- (void)setInfoForTorrents:(NSArray*)torrents; +- (void)updateInfo; +- (void)updateOptions; -- (IBAction) setUseSpeedLimit: (id) sender; -- (IBAction) setSpeedLimit: (id) sender; -- (IBAction) setUseGlobalSpeedLimit: (id) sender; +- (IBAction)setUseSpeedLimit:(id)sender; +- (IBAction)setSpeedLimit:(id)sender; +- (IBAction)setUseGlobalSpeedLimit:(id)sender; -- (IBAction) setRatioSetting: (id) sender; -- (IBAction) setRatioLimit: (id) sender; +- (IBAction)setRatioSetting:(id)sender; +- (IBAction)setRatioLimit:(id)sender; -- (IBAction) setIdleSetting: (id) sender; -- (IBAction) setIdleLimit: (id) sender; +- (IBAction)setIdleSetting:(id)sender; +- (IBAction)setIdleLimit:(id)sender; -- (IBAction) setRemoveWhenSeedingCompletes: (id) sender; +- (IBAction)setRemoveWhenSeedingCompletes:(id)sender; -- (IBAction) setPriority: (id) sender; +- (IBAction)setPriority:(id)sender; -- (IBAction) setPeersConnectLimit: (id) sender; +- (IBAction)setPeersConnectLimit:(id)sender; @end diff --git a/macosx/InfoOptionsViewController.m b/macosx/InfoOptionsViewController.m index efba95fb9..5e671bb70 100644 --- a/macosx/InfoOptionsViewController.m +++ b/macosx/InfoOptionsViewController.m @@ -36,17 +36,17 @@ @interface InfoOptionsViewController (Private) -- (void) setupInfo; -- (void) setGlobalLabels; -- (void) updateOptionsNotification: (NSNotification *) notification; +- (void)setupInfo; +- (void)setGlobalLabels; +- (void)updateOptionsNotification:(NSNotification*)notification; @end @implementation InfoOptionsViewController -- (instancetype) init +- (instancetype)init { - if ((self = [super initWithNibName: @"InfoOptionsView" bundle: nil])) + if ((self = [super initWithNibName:@"InfoOptionsView" bundle:nil])) { self.title = NSLocalizedString(@"Options", "Inspector view -> title"); } @@ -54,20 +54,22 @@ return self; } -- (void) awakeFromNib +- (void)awakeFromNib { [self setGlobalLabels]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(setGlobalLabels) name: @"UpdateGlobalOptions" object: nil]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateOptionsNotification:) name: @"UpdateOptionsNotification" object: nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(setGlobalLabels) name:@"UpdateGlobalOptions" object:nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateOptionsNotification:) + name:@"UpdateOptionsNotification" + object:nil]; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; } -- (void) setInfoForTorrents: (NSArray *) torrents +- (void)setInfoForTorrents:(NSArray*)torrents { //don't check if it's the same in case the metadata changed fTorrents = torrents; @@ -75,48 +77,61 @@ fSet = NO; } -- (void) updateInfo +- (void)updateInfo { if (!fSet) + { [self setupInfo]; + } fSet = YES; } -- (void) updateOptions +- (void)updateOptions { if (fTorrents.count == 0) + { return; + } //get bandwidth info - NSEnumerator * enumerator = [fTorrents objectEnumerator]; - Torrent * torrent = [enumerator nextObject]; //first torrent + NSEnumerator* enumerator = [fTorrents objectEnumerator]; + Torrent* torrent = [enumerator nextObject]; //first torrent - NSInteger uploadUseSpeedLimit = [torrent usesSpeedLimit: YES] ? NSOnState : NSOffState, - uploadSpeedLimit = [torrent speedLimit: YES], - downloadUseSpeedLimit = [torrent usesSpeedLimit: NO] ? NSOnState : NSOffState, - downloadSpeedLimit = [torrent speedLimit: NO], - globalUseSpeedLimit = torrent.usesGlobalSpeedLimit ? NSOnState : NSOffState; + NSInteger uploadUseSpeedLimit = [torrent usesSpeedLimit:YES] ? NSOnState : NSOffState; + NSInteger uploadSpeedLimit = [torrent speedLimit:YES]; + NSInteger downloadUseSpeedLimit = [torrent usesSpeedLimit:NO] ? NSOnState : NSOffState; + NSInteger downloadSpeedLimit = [torrent speedLimit:NO]; + NSInteger globalUseSpeedLimit = torrent.usesGlobalSpeedLimit ? NSOnState : NSOffState; - while ((torrent = [enumerator nextObject]) - && (uploadUseSpeedLimit != NSMixedState || uploadSpeedLimit != INVALID - || downloadUseSpeedLimit != NSMixedState || downloadSpeedLimit != INVALID - || globalUseSpeedLimit != NSMixedState)) + while ((torrent = [enumerator nextObject]) && + (uploadUseSpeedLimit != NSMixedState || uploadSpeedLimit != INVALID || downloadUseSpeedLimit != NSMixedState || + downloadSpeedLimit != INVALID || globalUseSpeedLimit != NSMixedState)) { - if (uploadUseSpeedLimit != NSMixedState && uploadUseSpeedLimit != ([torrent usesSpeedLimit: YES] ? NSOnState : NSOffState)) + if (uploadUseSpeedLimit != NSMixedState && uploadUseSpeedLimit != ([torrent usesSpeedLimit:YES] ? NSOnState : NSOffState)) + { uploadUseSpeedLimit = NSMixedState; + } - if (uploadSpeedLimit != INVALID && uploadSpeedLimit != [torrent speedLimit: YES]) + if (uploadSpeedLimit != INVALID && uploadSpeedLimit != [torrent speedLimit:YES]) + { uploadSpeedLimit = INVALID; + } - if (downloadUseSpeedLimit != NSMixedState && downloadUseSpeedLimit != ([torrent usesSpeedLimit: NO] ? NSOnState : NSOffState)) + if (downloadUseSpeedLimit != NSMixedState && downloadUseSpeedLimit != ([torrent usesSpeedLimit:NO] ? NSOnState : NSOffState)) + { downloadUseSpeedLimit = NSMixedState; + } - if (downloadSpeedLimit != INVALID && downloadSpeedLimit != [torrent speedLimit: NO]) + if (downloadSpeedLimit != INVALID && downloadSpeedLimit != [torrent speedLimit:NO]) + { downloadSpeedLimit = INVALID; + } if (globalUseSpeedLimit != NSMixedState && globalUseSpeedLimit != (torrent.usesGlobalSpeedLimit ? NSOnState : NSOffState)) + { globalUseSpeedLimit = NSMixedState; + } } //set upload view @@ -126,9 +141,13 @@ fUploadLimitLabel.enabled = uploadUseSpeedLimit == NSOnState; fUploadLimitField.enabled = uploadUseSpeedLimit == NSOnState; if (uploadSpeedLimit != INVALID) + { fUploadLimitField.intValue = uploadSpeedLimit; + } else + { fUploadLimitField.stringValue = @""; + } //set download view fDownloadLimitCheck.state = downloadUseSpeedLimit; @@ -137,9 +156,13 @@ fDownloadLimitLabel.enabled = downloadUseSpeedLimit == NSOnState; fDownloadLimitField.enabled = downloadUseSpeedLimit == NSOnState; if (downloadSpeedLimit != INVALID) + { fDownloadLimitField.intValue = downloadSpeedLimit; + } else + { fDownloadLimitField.stringValue = @""; + } //set global check fGlobalLimitCheck.state = globalUseSpeedLimit; @@ -149,68 +172,103 @@ enumerator = [fTorrents objectEnumerator]; torrent = [enumerator nextObject]; //first torrent - NSInteger checkRatio = torrent.ratioSetting, checkIdle = torrent.idleSetting, - removeWhenFinishSeeding = torrent.removeWhenFinishSeeding ? NSOnState : NSOffState; + NSInteger checkRatio = torrent.ratioSetting; + NSInteger checkIdle = torrent.idleSetting; + NSInteger removeWhenFinishSeeding = torrent.removeWhenFinishSeeding ? NSOnState : NSOffState; CGFloat ratioLimit = torrent.ratioLimit; NSUInteger idleLimit = torrent.idleLimitMinutes; - while ((torrent = [enumerator nextObject]) - && (checkRatio != INVALID || ratioLimit != INVALID || checkIdle != INVALID || idleLimit != INVALID)) + while ((torrent = [enumerator nextObject]) && + (checkRatio != INVALID || ratioLimit != INVALID || checkIdle != INVALID || idleLimit != INVALID)) { if (checkRatio != INVALID && checkRatio != torrent.ratioSetting) + { checkRatio = INVALID; + } if (ratioLimit != INVALID && ratioLimit != torrent.ratioLimit) + { ratioLimit = INVALID; + } if (checkIdle != INVALID && checkIdle != torrent.idleSetting) + { checkIdle = INVALID; + } if (idleLimit != INVALID && idleLimit != torrent.idleLimitMinutes) + { idleLimit = INVALID; + } if (removeWhenFinishSeeding != NSMixedState && removeWhenFinishSeeding != (torrent.removeWhenFinishSeeding ? NSOnState : NSOffState)) + { removeWhenFinishSeeding = NSMixedState; + } } //set ratio view NSInteger index; if (checkRatio == TR_RATIOLIMIT_SINGLE) + { index = OPTION_POPUP_LIMIT; + } else if (checkRatio == TR_RATIOLIMIT_UNLIMITED) + { index = OPTION_POPUP_NO_LIMIT; + } else if (checkRatio == TR_RATIOLIMIT_GLOBAL) + { index = OPTION_POPUP_GLOBAL; + } else + { index = -1; - [fRatioPopUp selectItemAtIndex: index]; + } + [fRatioPopUp selectItemAtIndex:index]; fRatioPopUp.enabled = YES; fRatioLimitField.hidden = checkRatio != TR_RATIOLIMIT_SINGLE; if (ratioLimit != INVALID) + { fRatioLimitField.floatValue = ratioLimit; + } else + { fRatioLimitField.stringValue = @""; + } fRatioLimitGlobalLabel.hidden = checkRatio != TR_RATIOLIMIT_GLOBAL; //set idle view if (checkIdle == TR_IDLELIMIT_SINGLE) + { index = OPTION_POPUP_LIMIT; + } else if (checkIdle == TR_IDLELIMIT_UNLIMITED) + { index = OPTION_POPUP_NO_LIMIT; + } else if (checkIdle == TR_IDLELIMIT_GLOBAL) + { index = OPTION_POPUP_GLOBAL; + } else + { index = -1; - [fIdlePopUp selectItemAtIndex: index]; + } + [fIdlePopUp selectItemAtIndex:index]; fIdlePopUp.enabled = YES; fIdleLimitField.hidden = checkIdle != TR_IDLELIMIT_SINGLE; if (idleLimit != INVALID) + { fIdleLimitField.integerValue = idleLimit; + } else + { fIdleLimitField.stringValue = @""; + } fIdleLimitLabel.hidden = checkIdle != TR_IDLELIMIT_SINGLE; fIdleLimitGlobalLabel.hidden = checkIdle != TR_IDLELIMIT_GLOBAL; @@ -228,19 +286,29 @@ while ((torrent = [enumerator nextObject]) && priority != INVALID) { if (priority != INVALID && priority != torrent.priority) + { priority = INVALID; + } } //set priority view if (priority == TR_PRI_HIGH) + { index = OPTION_POPUP_PRIORITY_HIGH; + } else if (priority == TR_PRI_NORMAL) + { index = OPTION_POPUP_PRIORITY_NORMAL; + } else if (priority == TR_PRI_LOW) + { index = OPTION_POPUP_PRIORITY_LOW; + } else + { index = -1; - [fPriorityPopUp selectItemAtIndex: index]; + } + [fPriorityPopUp selectItemAtIndex:index]; fPriorityPopUp.enabled = YES; //get peer info @@ -262,209 +330,239 @@ fPeersConnectField.enabled = YES; fPeersConnectLabel.enabled = YES; if (maxPeers != INVALID) + { fPeersConnectField.intValue = maxPeers; + } else + { fPeersConnectField.stringValue = @""; + } } -- (void) setUseSpeedLimit: (id) sender +- (void)setUseSpeedLimit:(id)sender { - const BOOL upload = sender == fUploadLimitCheck; + BOOL const upload = sender == fUploadLimitCheck; - if (((NSButton *)sender).state == NSMixedState) - [sender setState: NSOnState]; - const BOOL limit = ((NSButton *)sender).state == NSOnState; + if (((NSButton*)sender).state == NSMixedState) + { + [sender setState:NSOnState]; + } + BOOL const limit = ((NSButton*)sender).state == NSOnState; - for (Torrent * torrent in fTorrents) - [torrent setUseSpeedLimit: limit upload: upload]; + for (Torrent* torrent in fTorrents) + { + [torrent setUseSpeedLimit:limit upload:upload]; + } - NSTextField * field = upload ? fUploadLimitField : fDownloadLimitField; + NSTextField* field = upload ? fUploadLimitField : fDownloadLimitField; field.enabled = limit; if (limit) { - [field selectText: self]; - [self.view.window makeKeyAndOrderFront: self]; + [field selectText:self]; + [self.view.window makeKeyAndOrderFront:self]; } - NSTextField * label = upload ? fUploadLimitLabel : fDownloadLimitLabel; + NSTextField* label = upload ? fUploadLimitLabel : fDownloadLimitLabel; label.enabled = limit; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptionsNotification" object:self]; } -- (void) setUseGlobalSpeedLimit: (id) sender +- (void)setUseGlobalSpeedLimit:(id)sender { - if (((NSButton *)sender).state == NSMixedState) - [sender setState: NSOnState]; - const BOOL limit = ((NSButton *)sender).state == NSOnState; + if (((NSButton*)sender).state == NSMixedState) + { + [sender setState:NSOnState]; + } + BOOL const limit = ((NSButton*)sender).state == NSOnState; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { torrent.usesGlobalSpeedLimit = limit; + } - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptionsNotification" object:self]; } -- (void) setSpeedLimit: (id) sender +- (void)setSpeedLimit:(id)sender { - const BOOL upload = sender == fUploadLimitField; - const NSInteger limit = [sender intValue]; + BOOL const upload = sender == fUploadLimitField; + NSInteger const limit = [sender intValue]; - for (Torrent * torrent in fTorrents) - [torrent setSpeedLimit: limit upload: upload]; + for (Torrent* torrent in fTorrents) + { + [torrent setSpeedLimit:limit upload:upload]; + } - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptionsNotification" object:self]; } -- (void) setRatioSetting: (id) sender +- (void)setRatioSetting:(id)sender { NSInteger setting; BOOL single = NO; switch ([sender indexOfSelectedItem]) { - case OPTION_POPUP_LIMIT: - setting = TR_RATIOLIMIT_SINGLE; - single = YES; - break; - case OPTION_POPUP_NO_LIMIT: - setting = TR_RATIOLIMIT_UNLIMITED; - break; - case OPTION_POPUP_GLOBAL: - setting = TR_RATIOLIMIT_GLOBAL; - break; - default: - NSAssert1(NO, @"Unknown option selected in ratio popup: %ld", [sender indexOfSelectedItem]); - return; + case OPTION_POPUP_LIMIT: + setting = TR_RATIOLIMIT_SINGLE; + single = YES; + break; + case OPTION_POPUP_NO_LIMIT: + setting = TR_RATIOLIMIT_UNLIMITED; + break; + case OPTION_POPUP_GLOBAL: + setting = TR_RATIOLIMIT_GLOBAL; + break; + default: + NSAssert1(NO, @"Unknown option selected in ratio popup: %ld", [sender indexOfSelectedItem]); + return; } - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { torrent.ratioSetting = setting; + } fRatioLimitField.hidden = !single; if (single) { - [fRatioLimitField selectText: self]; - [self.view.window makeKeyAndOrderFront: self]; + [fRatioLimitField selectText:self]; + [self.view.window makeKeyAndOrderFront:self]; } fRatioLimitGlobalLabel.hidden = setting != TR_RATIOLIMIT_GLOBAL; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptionsNotification" object:self]; } -- (void) setRatioLimit: (id) sender +- (void)setRatioLimit:(id)sender { - const CGFloat limit = [sender floatValue]; + CGFloat const limit = [sender floatValue]; - for (Torrent * torrent in fTorrents) - torrent.ratioLimit = limit; + for (Torrent* torrent in fTorrents) + { + torrent.ratioLimit = limit; + } - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptionsNotification" object:self]; } -- (void) setIdleSetting: (id) sender +- (void)setIdleSetting:(id)sender { NSInteger setting; BOOL single = NO; switch ([sender indexOfSelectedItem]) { - case OPTION_POPUP_LIMIT: - setting = TR_IDLELIMIT_SINGLE; - single = YES; - break; - case OPTION_POPUP_NO_LIMIT: - setting = TR_IDLELIMIT_UNLIMITED; - break; - case OPTION_POPUP_GLOBAL: - setting = TR_IDLELIMIT_GLOBAL; - break; - default: - NSAssert1(NO, @"Unknown option selected in idle popup: %ld", [sender indexOfSelectedItem]); - return; + case OPTION_POPUP_LIMIT: + setting = TR_IDLELIMIT_SINGLE; + single = YES; + break; + case OPTION_POPUP_NO_LIMIT: + setting = TR_IDLELIMIT_UNLIMITED; + break; + case OPTION_POPUP_GLOBAL: + setting = TR_IDLELIMIT_GLOBAL; + break; + default: + NSAssert1(NO, @"Unknown option selected in idle popup: %ld", [sender indexOfSelectedItem]); + return; } - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { torrent.idleSetting = setting; + } fIdleLimitField.hidden = !single; fIdleLimitLabel.hidden = !single; if (single) { - [fIdleLimitField selectText: self]; - [self.view.window makeKeyAndOrderFront: self]; + [fIdleLimitField selectText:self]; + [self.view.window makeKeyAndOrderFront:self]; } fIdleLimitGlobalLabel.hidden = setting != TR_IDLELIMIT_GLOBAL; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptionsNotification" object:self]; } -- (void) setIdleLimit: (id) sender +- (void)setIdleLimit:(id)sender { - const NSUInteger limit = [sender integerValue]; + NSUInteger const limit = [sender integerValue]; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { torrent.idleLimitMinutes = limit; + } - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptionsNotification" object:self]; } -- (IBAction) setRemoveWhenSeedingCompletes: (id) sender +- (IBAction)setRemoveWhenSeedingCompletes:(id)sender { - if (((NSButton *)sender).state == NSMixedState) - [sender setState: NSOnState]; - const BOOL enable = ((NSButton *)sender).state == NSOnState; + if (((NSButton*)sender).state == NSMixedState) + { + [sender setState:NSOnState]; + } + BOOL const enable = ((NSButton*)sender).state == NSOnState; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { torrent.removeWhenFinishSeeding = enable; + } - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptionsNotification" object:self]; } -- (void) setPriority: (id) sender +- (void)setPriority:(id)sender { tr_priority_t priority; switch ([sender indexOfSelectedItem]) { - case OPTION_POPUP_PRIORITY_HIGH: - priority = TR_PRI_HIGH; - break; - case OPTION_POPUP_PRIORITY_NORMAL: - priority = TR_PRI_NORMAL; - break; - case OPTION_POPUP_PRIORITY_LOW: - priority = TR_PRI_LOW; - break; - default: - NSAssert1(NO, @"Unknown option selected in priority popup: %ld", [sender indexOfSelectedItem]); - return; + case OPTION_POPUP_PRIORITY_HIGH: + priority = TR_PRI_HIGH; + break; + case OPTION_POPUP_PRIORITY_NORMAL: + priority = TR_PRI_NORMAL; + break; + case OPTION_POPUP_PRIORITY_LOW: + priority = TR_PRI_LOW; + break; + default: + NSAssert1(NO, @"Unknown option selected in priority popup: %ld", [sender indexOfSelectedItem]); + return; } - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { torrent.priority = priority; + } - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptionsNotification" object:self]; } -- (void) setPeersConnectLimit: (id) sender +- (void)setPeersConnectLimit:(id)sender { NSInteger limit = [sender intValue]; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { torrent.maxPeerConnect = limit; + } - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptionsNotification" object:self]; } -- (BOOL) control: (NSControl *) control textShouldBeginEditing: (NSText *) fieldEditor +- (BOOL)control:(NSControl*)control textShouldBeginEditing:(NSText*)fieldEditor { fInitialString = control.stringValue; return YES; } -- (BOOL) control: (NSControl *) control didFailToFormatString: (NSString *) string errorDescription: (NSString *) error +- (BOOL)control:(NSControl*)control didFailToFormatString:(NSString*)string errorDescription:(NSString*)error { NSBeep(); if (fInitialString) @@ -479,7 +577,7 @@ @implementation InfoOptionsViewController (Private) -- (void) setupInfo +- (void)setupInfo { if (fTorrents.count == 0) { @@ -499,16 +597,16 @@ fGlobalLimitCheck.state = NSOffState; fPriorityPopUp.enabled = NO; - [fPriorityPopUp selectItemAtIndex: -1]; + [fPriorityPopUp selectItemAtIndex:-1]; fRatioPopUp.enabled = NO; - [fRatioPopUp selectItemAtIndex: -1]; + [fRatioPopUp selectItemAtIndex:-1]; fRatioLimitField.hidden = YES; fRatioLimitField.stringValue = @""; fRatioLimitGlobalLabel.hidden = YES; fIdlePopUp.enabled = NO; - [fIdlePopUp selectItemAtIndex: -1]; + [fIdlePopUp selectItemAtIndex:-1]; fIdleLimitField.hidden = YES; fIdleLimitField.stringValue = @""; fIdleLimitLabel.hidden = YES; @@ -522,33 +620,40 @@ fPeersConnectLabel.enabled = NO; } else + { [self updateOptions]; + } } -- (void) setGlobalLabels +- (void)setGlobalLabels { - NSString * global = [NSUserDefaults.standardUserDefaults boolForKey: @"RatioCheck"] - ? [NSString stringForRatio: [NSUserDefaults.standardUserDefaults floatForKey: @"RatioLimit"]] - : NSLocalizedString(@"disabled", "Info options -> global setting"); + NSString* global = [NSUserDefaults.standardUserDefaults boolForKey:@"RatioCheck"] ? + [NSString stringForRatio:[NSUserDefaults.standardUserDefaults floatForKey:@"RatioLimit"]] : + NSLocalizedString(@"disabled", "Info options -> global setting"); fRatioLimitGlobalLabel.stringValue = global; //idle field - NSString * globalIdle; - if ([NSUserDefaults.standardUserDefaults boolForKey: @"IdleLimitCheck"]) + NSString* globalIdle; + if ([NSUserDefaults.standardUserDefaults boolForKey:@"IdleLimitCheck"]) { - const NSInteger globalMin = [NSUserDefaults.standardUserDefaults integerForKey: @"IdleLimitMinutes"]; - globalIdle = globalMin == 1 ? NSLocalizedString(@"1 minute", "Info options -> global setting") - : [NSString localizedStringWithFormat: NSLocalizedString(@"%d minutes", "Info options -> global setting"), globalMin]; + NSInteger const globalMin = [NSUserDefaults.standardUserDefaults integerForKey:@"IdleLimitMinutes"]; + globalIdle = globalMin == 1 ? + NSLocalizedString(@"1 minute", "Info options -> global setting") : + [NSString localizedStringWithFormat:NSLocalizedString(@"%d minutes", "Info options -> global setting"), globalMin]; } else + { globalIdle = NSLocalizedString(@"disabled", "Info options -> global setting"); + } fIdleLimitGlobalLabel.stringValue = globalIdle; } -- (void) updateOptionsNotification: (NSNotification *) notification +- (void)updateOptionsNotification:(NSNotification*)notification { if (notification.object != self) + { [self updateOptions]; + } } @end diff --git a/macosx/InfoPeersViewController.h b/macosx/InfoPeersViewController.h index 686a7d981..e0e642969 100644 --- a/macosx/InfoPeersViewController.h +++ b/macosx/InfoPeersViewController.h @@ -26,27 +26,28 @@ @class WebSeedTableView; -@interface InfoPeersViewController : NSViewController +@interface InfoPeersViewController : NSViewController { - NSArray * fTorrents; + NSArray* fTorrents; BOOL fSet; - NSMutableArray * fPeers, * fWebSeeds; + NSMutableArray* fPeers; + NSMutableArray* fWebSeeds; - IBOutlet NSTableView * fPeerTable; - IBOutlet WebSeedTableView * fWebSeedTable; + IBOutlet NSTableView* fPeerTable; + IBOutlet WebSeedTableView* fWebSeedTable; - IBOutlet NSTextField * fConnectedPeersField; + IBOutlet NSTextField* fConnectedPeersField; CGFloat fViewTopMargin; - IBOutlet NSLayoutConstraint * fWebSeedTableTopConstraint; + IBOutlet NSLayoutConstraint* fWebSeedTableTopConstraint; } -- (void) setInfoForTorrents: (NSArray *) torrents; -- (void) updateInfo; +- (void)setInfoForTorrents:(NSArray*)torrents; +- (void)updateInfo; -- (void) saveViewSize; -- (void) clearView; +- (void)saveViewSize; +- (void)clearView; @end diff --git a/macosx/InfoPeersViewController.m b/macosx/InfoPeersViewController.m index 2c7dfd97a..798dd87ca 100644 --- a/macosx/InfoPeersViewController.m +++ b/macosx/InfoPeersViewController.m @@ -33,20 +33,20 @@ #define ANIMATION_ID_KEY @"animationId" #define WEB_SEED_ANIMATION_ID @"webSeed" -@interface InfoPeersViewController (Private) +@interface InfoPeersViewController (Private) -- (void) setupInfo; +- (void)setupInfo; -- (void) setWebSeedTableHidden: (BOOL) hide animate: (BOOL) animate; -@property (nonatomic, readonly) NSArray *peerSortDescriptors; +- (void)setWebSeedTableHidden:(BOOL)hide animate:(BOOL)animate; +@property(nonatomic, readonly) NSArray* peerSortDescriptors; @end @implementation InfoPeersViewController -- (instancetype) init +- (instancetype)init { - if ((self = [super initWithNibName: @"InfoPeersView" bundle: nil])) + if ((self = [super initWithNibName:@"InfoPeersView" bundle:nil])) { self.title = NSLocalizedString(@"Peers", "Inspector view -> title"); } @@ -54,9 +54,9 @@ return self; } -- (void) awakeFromNib +- (void)awakeFromNib { - const CGFloat height = [NSUserDefaults.standardUserDefaults floatForKey: @"InspectorContentHeightPeers"]; + CGFloat const height = [NSUserDefaults.standardUserDefaults floatForKey:@"InspectorContentHeightPeers"]; if (height != 0.0) { NSRect viewRect = self.view.frame; @@ -65,49 +65,39 @@ } //set table header text - [fPeerTable tableColumnWithIdentifier: @"IP"].headerCell.stringValue = NSLocalizedString(@"IP Address", - "inspector -> peer table -> header"); - [fPeerTable tableColumnWithIdentifier: @"Client"].headerCell.stringValue = NSLocalizedString(@"Client", - "inspector -> peer table -> header"); - [fPeerTable tableColumnWithIdentifier: @"DL From"].headerCell.stringValue = NSLocalizedString(@"DL", - "inspector -> peer table -> header"); - [fPeerTable tableColumnWithIdentifier: @"UL To"].headerCell.stringValue = NSLocalizedString(@"UL", - "inspector -> peer table -> header"); + [fPeerTable tableColumnWithIdentifier:@"IP"].headerCell.stringValue = NSLocalizedString(@"IP Address", "inspector -> peer table -> header"); + [fPeerTable tableColumnWithIdentifier:@"Client"].headerCell.stringValue = NSLocalizedString(@"Client", "inspector -> peer table -> header"); + [fPeerTable tableColumnWithIdentifier:@"DL From"].headerCell.stringValue = NSLocalizedString(@"DL", "inspector -> peer table -> header"); + [fPeerTable tableColumnWithIdentifier:@"UL To"].headerCell.stringValue = NSLocalizedString(@"UL", "inspector -> peer table -> header"); - [fWebSeedTable tableColumnWithIdentifier: @"Address"].headerCell.stringValue = NSLocalizedString(@"Web Seeds", - "inspector -> web seed table -> header"); - [fWebSeedTable tableColumnWithIdentifier: @"DL From"].headerCell.stringValue = NSLocalizedString(@"DL", - "inspector -> web seed table -> header"); + [fWebSeedTable tableColumnWithIdentifier:@"Address"].headerCell.stringValue = NSLocalizedString(@"Web Seeds", "inspector -> web seed table -> header"); + [fWebSeedTable tableColumnWithIdentifier:@"DL From"].headerCell.stringValue = NSLocalizedString(@"DL", "inspector -> web seed table -> header"); //set table header tool tips - [fPeerTable tableColumnWithIdentifier: @"Encryption"].headerToolTip = NSLocalizedString(@"Encrypted Connection", - "inspector -> peer table -> header tool tip"); - [fPeerTable tableColumnWithIdentifier: @"Progress"].headerToolTip = NSLocalizedString(@"Available", - "inspector -> peer table -> header tool tip"); - [fPeerTable tableColumnWithIdentifier: @"DL From"].headerToolTip = NSLocalizedString(@"Downloading From Peer", - "inspector -> peer table -> header tool tip"); - [fPeerTable tableColumnWithIdentifier: @"UL To"].headerToolTip = NSLocalizedString(@"Uploading To Peer", - "inspector -> peer table -> header tool tip"); + [fPeerTable tableColumnWithIdentifier:@"Encryption"].headerToolTip = NSLocalizedString(@"Encrypted Connection", "inspector -> peer table -> header tool tip"); + [fPeerTable tableColumnWithIdentifier:@"Progress"].headerToolTip = NSLocalizedString(@"Available", "inspector -> peer table -> header tool tip"); + [fPeerTable tableColumnWithIdentifier:@"DL From"].headerToolTip = NSLocalizedString(@"Downloading From Peer", "inspector -> peer table -> header tool tip"); + [fPeerTable tableColumnWithIdentifier:@"UL To"].headerToolTip = NSLocalizedString(@"Uploading To Peer", "inspector -> peer table -> header tool tip"); - [fWebSeedTable tableColumnWithIdentifier: @"DL From"].headerToolTip = NSLocalizedString(@"Downloading From Web Seed", + [fWebSeedTable tableColumnWithIdentifier:@"DL From"].headerToolTip = NSLocalizedString( + @"Downloading From Web Seed", "inspector -> web seed table -> header tool tip"); //prepare for animating peer table and web seed table fViewTopMargin = fWebSeedTableTopConstraint.constant; - CABasicAnimation * webSeedTableAnimation = [CABasicAnimation animation]; - webSeedTableAnimation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear]; + CABasicAnimation* webSeedTableAnimation = [CABasicAnimation animation]; + webSeedTableAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; webSeedTableAnimation.duration = 0.125; webSeedTableAnimation.delegate = self; - [webSeedTableAnimation setValue: WEB_SEED_ANIMATION_ID forKey: ANIMATION_ID_KEY]; - fWebSeedTableTopConstraint.animations = @{ @"constant": webSeedTableAnimation }; + [webSeedTableAnimation setValue:WEB_SEED_ANIMATION_ID forKey:ANIMATION_ID_KEY]; + fWebSeedTableTopConstraint.animations = @{ @"constant" : webSeedTableAnimation }; - [self setWebSeedTableHidden: YES animate: NO]; + [self setWebSeedTableHidden:YES animate:NO]; } - #warning subclass? -- (void) setInfoForTorrents: (NSArray *) torrents +- (void)setInfoForTorrents:(NSArray*)torrents { //don't check if it's the same in case the metadata changed fTorrents = torrents; @@ -115,38 +105,60 @@ fSet = NO; } -- (void) updateInfo +- (void)updateInfo { if (!fSet) + { [self setupInfo]; + } if (fTorrents.count == 0) + { return; + } if (!fPeers) + { fPeers = [[NSMutableArray alloc] init]; + } else + { [fPeers removeAllObjects]; + } if (!fWebSeeds) + { fWebSeeds = [[NSMutableArray alloc] init]; + } else + { [fWebSeeds removeAllObjects]; + } - NSUInteger connected = 0, tracker = 0, incoming = 0, cache = 0, lpd = 0, pex = 0, dht = 0, ltep = 0, - toUs = 0, fromUs = 0; + NSUInteger connected = 0; + NSUInteger tracker = 0; + NSUInteger incoming = 0; + NSUInteger cache = 0; + NSUInteger lpd = 0; + NSUInteger pex = 0; + NSUInteger dht = 0; + NSUInteger ltep = 0; + NSUInteger toUs = 0; + NSUInteger fromUs = 0; BOOL anyActive = false; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) { if (torrent.webSeedCount > 0) - [fWebSeeds addObjectsFromArray: torrent.webSeeds]; + { + [fWebSeeds addObjectsFromArray:torrent.webSeeds]; + } if (torrent.active) { anyActive = YES; - [fPeers addObjectsFromArray: torrent.peers]; + [fPeers addObjectsFromArray:torrent.peers]; - const NSUInteger connectedThis = torrent.totalPeersConnected; + NSUInteger const connectedThis = torrent.totalPeersConnected; if (connectedThis > 0) { connected += torrent.totalPeersConnected; @@ -164,152 +176,186 @@ } } - [fPeers sortUsingDescriptors: self.peerSortDescriptors]; + [fPeers sortUsingDescriptors:self.peerSortDescriptors]; [fPeerTable reloadData]; - [fWebSeeds sortUsingDescriptors: fWebSeedTable.sortDescriptors]; + [fWebSeeds sortUsingDescriptors:fWebSeedTable.sortDescriptors]; [fWebSeedTable reloadData]; - [fWebSeedTable setWebSeeds: fWebSeeds]; + [fWebSeedTable setWebSeeds:fWebSeeds]; if (anyActive) { - NSString * connectedText = [NSString stringWithFormat: NSLocalizedString(@"%d Connected", "Inspector -> Peers tab -> peers"), - connected]; + NSString* connectedText = [NSString stringWithFormat:NSLocalizedString(@"%d Connected", "Inspector -> Peers tab -> peers"), connected]; if (connected > 0) { - NSMutableArray * upDownComponents = [NSMutableArray arrayWithCapacity: 2]; + NSMutableArray* upDownComponents = [NSMutableArray arrayWithCapacity:2]; if (toUs > 0) - [upDownComponents addObject: [NSString stringWithFormat: - NSLocalizedString(@"DL from %d", "Inspector -> Peers tab -> peers"), toUs]]; + { + [upDownComponents + addObject:[NSString stringWithFormat:NSLocalizedString(@"DL from %d", "Inspector -> Peers tab -> peers"), toUs]]; + } if (fromUs > 0) - [upDownComponents addObject: [NSString stringWithFormat: - NSLocalizedString(@"UL to %d", "Inspector -> Peers tab -> peers"), fromUs]]; + { + [upDownComponents + addObject:[NSString stringWithFormat:NSLocalizedString(@"UL to %d", "Inspector -> Peers tab -> peers"), fromUs]]; + } if (upDownComponents.count > 0) - connectedText = [connectedText stringByAppendingFormat: @": %@", [upDownComponents componentsJoinedByString: @", "]]; + { + connectedText = [connectedText stringByAppendingFormat:@": %@", [upDownComponents componentsJoinedByString:@", "]]; + } - NSMutableArray * fromComponents = [NSMutableArray arrayWithCapacity: 7]; + NSMutableArray* fromComponents = [NSMutableArray arrayWithCapacity:7]; if (tracker > 0) - [fromComponents addObject: [NSString stringWithFormat: - NSLocalizedString(@"%d tracker", "Inspector -> Peers tab -> peers"), tracker]]; + { + [fromComponents + addObject:[NSString stringWithFormat:NSLocalizedString(@"%d tracker", "Inspector -> Peers tab -> peers"), tracker]]; + } if (incoming > 0) - [fromComponents addObject: [NSString stringWithFormat: - NSLocalizedString(@"%d incoming", "Inspector -> Peers tab -> peers"), incoming]]; + { + [fromComponents + addObject:[NSString stringWithFormat:NSLocalizedString(@"%d incoming", "Inspector -> Peers tab -> peers"), incoming]]; + } if (cache > 0) - [fromComponents addObject: [NSString stringWithFormat: - NSLocalizedString(@"%d cache", "Inspector -> Peers tab -> peers"), cache]]; + { + [fromComponents + addObject:[NSString stringWithFormat:NSLocalizedString(@"%d cache", "Inspector -> Peers tab -> peers"), cache]]; + } if (lpd > 0) - [fromComponents addObject: [NSString stringWithFormat: - NSLocalizedString(@"%d local discovery", "Inspector -> Peers tab -> peers"), lpd]]; + { + [fromComponents + addObject:[NSString stringWithFormat:NSLocalizedString(@"%d local discovery", "Inspector -> Peers tab -> peers"), lpd]]; + } if (pex > 0) - [fromComponents addObject: [NSString stringWithFormat: - NSLocalizedString(@"%d PEX", "Inspector -> Peers tab -> peers"), pex]]; + { + [fromComponents addObject:[NSString stringWithFormat:NSLocalizedString(@"%d PEX", "Inspector -> Peers tab -> peers"), pex]]; + } if (dht > 0) - [fromComponents addObject: [NSString stringWithFormat: - NSLocalizedString(@"%d DHT", "Inspector -> Peers tab -> peers"), dht]]; + { + [fromComponents addObject:[NSString stringWithFormat:NSLocalizedString(@"%d DHT", "Inspector -> Peers tab -> peers"), dht]]; + } if (ltep > 0) - [fromComponents addObject: [NSString stringWithFormat: - NSLocalizedString(@"%d LTEP", "Inspector -> Peers tab -> peers"), ltep]]; + { + [fromComponents + addObject:[NSString stringWithFormat:NSLocalizedString(@"%d LTEP", "Inspector -> Peers tab -> peers"), ltep]]; + } - connectedText = [connectedText stringByAppendingFormat: @"\n%@", [fromComponents componentsJoinedByString: @", "]]; + connectedText = [connectedText stringByAppendingFormat:@"\n%@", [fromComponents componentsJoinedByString:@", "]]; } fConnectedPeersField.stringValue = connectedText; } else { - NSString * notActiveString; + NSString* notActiveString; if (fTorrents.count == 1) + { notActiveString = NSLocalizedString(@"Transfer Not Active", "Inspector -> Peers tab -> peers"); + } else + { notActiveString = NSLocalizedString(@"Transfers Not Active", "Inspector -> Peers tab -> peers"); + } fConnectedPeersField.stringValue = notActiveString; } } -- (void) saveViewSize +- (void)saveViewSize { - [NSUserDefaults.standardUserDefaults setFloat: NSHeight(self.view.frame) forKey: @"InspectorContentHeightPeers"]; + [NSUserDefaults.standardUserDefaults setFloat:NSHeight(self.view.frame) forKey:@"InspectorContentHeightPeers"]; } -- (void) clearView +- (void)clearView { fPeers = nil; fWebSeeds = nil; } -- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView +- (NSInteger)numberOfRowsInTableView:(NSTableView*)tableView { if (tableView == fWebSeedTable) + { return fWebSeeds ? fWebSeeds.count : 0; + } else + { return fPeers ? fPeers.count : 0; + } } -- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (NSInteger) row +- (id)tableView:(NSTableView*)tableView objectValueForTableColumn:(NSTableColumn*)column row:(NSInteger)row { if (tableView == fWebSeedTable) { - NSString * ident = column.identifier; - NSDictionary * webSeed = fWebSeeds[row]; + NSString* ident = column.identifier; + NSDictionary* webSeed = fWebSeeds[row]; - if ([ident isEqualToString: @"DL From"]) + if ([ident isEqualToString:@"DL From"]) { - NSNumber * rate; - return (rate = webSeed[@"DL From Rate"]) ? [NSString stringForSpeedAbbrev: rate.doubleValue] : @""; + NSNumber* rate; + return (rate = webSeed[@"DL From Rate"]) ? [NSString stringForSpeedAbbrev:rate.doubleValue] : @""; } else + { return webSeed[@"Address"]; + } } else { - NSString * ident = column.identifier; - NSDictionary * peer = fPeers[row]; + NSString* ident = column.identifier; + NSDictionary* peer = fPeers[row]; - if ([ident isEqualToString: @"Encryption"]) - return [peer[@"Encryption"] boolValue] ? [NSImage imageNamed: @"Lock"] : nil; - else if ([ident isEqualToString: @"Client"]) - return peer[@"Client"]; - else if ([ident isEqualToString: @"Progress"]) - return peer[@"Progress"]; - else if ([ident isEqualToString: @"UL To"]) + if ([ident isEqualToString:@"Encryption"]) { - NSNumber * rate; - return (rate = peer[@"UL To Rate"]) ? [NSString stringForSpeedAbbrev: rate.doubleValue] : @""; + return [peer[@"Encryption"] boolValue] ? [NSImage imageNamed:@"Lock"] : nil; } - else if ([ident isEqualToString: @"DL From"]) + else if ([ident isEqualToString:@"Client"]) { - NSNumber * rate; - return (rate = peer[@"DL From Rate"]) ? [NSString stringForSpeedAbbrev: rate.doubleValue] : @""; + return peer[@"Client"]; + } + else if ([ident isEqualToString:@"Progress"]) + { + return peer[@"Progress"]; + } + else if ([ident isEqualToString:@"UL To"]) + { + NSNumber* rate; + return (rate = peer[@"UL To Rate"]) ? [NSString stringForSpeedAbbrev:rate.doubleValue] : @""; + } + else if ([ident isEqualToString:@"DL From"]) + { + NSNumber* rate; + return (rate = peer[@"DL From Rate"]) ? [NSString stringForSpeedAbbrev:rate.doubleValue] : @""; } else + { return peer[@"IP"]; + } } } -- (void) tableView: (NSTableView *) tableView willDisplayCell: (id) cell forTableColumn: (NSTableColumn *) tableColumn - row: (NSInteger) row +- (void)tableView:(NSTableView*)tableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row { if (tableView == fPeerTable) { - NSString * ident = tableColumn.identifier; + NSString* ident = tableColumn.identifier; - if ([ident isEqualToString: @"Progress"]) + if ([ident isEqualToString:@"Progress"]) { - NSDictionary * peer = fPeers[row]; - [(PeerProgressIndicatorCell *)cell setSeed: [peer[@"Seed"] boolValue]]; + NSDictionary* peer = fPeers[row]; + [(PeerProgressIndicatorCell*)cell setSeed:[peer[@"Seed"] boolValue]]; } } } -- (void) tableView: (NSTableView *) tableView didClickTableColumn: (NSTableColumn *) tableColumn +- (void)tableView:(NSTableView*)tableView didClickTableColumn:(NSTableColumn*)tableColumn { if (tableView == fWebSeedTable) { if (fWebSeeds) { - [fWebSeeds sortUsingDescriptors: fWebSeedTable.sortDescriptors]; + [fWebSeeds sortUsingDescriptors:fWebSeedTable.sortDescriptors]; [tableView reloadData]; } } @@ -317,137 +363,163 @@ { if (fPeers) { - [fPeers sortUsingDescriptors: self.peerSortDescriptors]; + [fPeers sortUsingDescriptors:self.peerSortDescriptors]; [tableView reloadData]; } } } -- (BOOL) tableView: (NSTableView *) tableView shouldSelectRow: (NSInteger) row +- (BOOL)tableView:(NSTableView*)tableView shouldSelectRow:(NSInteger)row { return tableView != fPeerTable; } -- (NSString *) tableView: (NSTableView *) tableView toolTipForCell: (NSCell *) cell rect: (NSRectPointer) rect - tableColumn: (NSTableColumn *) column row: (NSInteger) row mouseLocation: (NSPoint) mouseLocation +- (NSString*)tableView:(NSTableView*)tableView + toolTipForCell:(NSCell*)cell + rect:(NSRectPointer)rect + tableColumn:(NSTableColumn*)column + row:(NSInteger)row + mouseLocation:(NSPoint)mouseLocation { if (tableView == fPeerTable) { - const BOOL multiple = fTorrents.count > 1; + BOOL const multiple = fTorrents.count > 1; - NSDictionary * peer = fPeers[row]; - NSMutableArray * components = [NSMutableArray arrayWithCapacity: multiple ? 6 : 5]; + NSDictionary* peer = fPeers[row]; + NSMutableArray* components = [NSMutableArray arrayWithCapacity:multiple ? 6 : 5]; if (multiple) - [components addObject: peer[@"Name"]]; + { + [components addObject:peer[@"Name"]]; + } - const CGFloat progress = [peer[@"Progress"] floatValue]; - NSString * progressString = [NSString stringWithFormat: NSLocalizedString(@"Progress: %@", - "Inspector -> Peers tab -> table row tooltip"), - [NSString percentString: progress longDecimals: NO]]; + CGFloat const progress = [peer[@"Progress"] floatValue]; + NSString* progressString = [NSString stringWithFormat:NSLocalizedString(@"Progress: %@", "Inspector -> Peers tab -> table row tooltip"), + [NSString percentString:progress longDecimals:NO]]; if (progress < 1.0 && [peer[@"Seed"] boolValue]) - progressString = [progressString stringByAppendingFormat: @" (%@)", NSLocalizedString(@"Partial Seed", - "Inspector -> Peers tab -> table row tooltip")]; - [components addObject: progressString]; + { + progressString = [progressString + stringByAppendingFormat:@" (%@)", NSLocalizedString(@"Partial Seed", "Inspector -> Peers tab -> table row tooltip")]; + } + [components addObject:progressString]; - NSString * protocolString = [peer[@"uTP"] boolValue] ? @"\u00b5TP" : @"TCP"; + NSString* protocolString = [peer[@"uTP"] boolValue] ? @"\u00b5TP" : @"TCP"; if ([peer[@"Encryption"] boolValue]) - protocolString = [protocolString stringByAppendingFormat: @" (%@)", - NSLocalizedString(@"encrypted", "Inspector -> Peers tab -> table row tooltip")]; - [components addObject: [NSString stringWithFormat: - NSLocalizedString(@"Protocol: %@", "Inspector -> Peers tab -> table row tooltip"), - protocolString]]; + { + protocolString = [protocolString + stringByAppendingFormat:@" (%@)", NSLocalizedString(@"encrypted", "Inspector -> Peers tab -> table row tooltip")]; + } + [components addObject:[NSString stringWithFormat:NSLocalizedString(@"Protocol: %@", "Inspector -> Peers tab -> table row tooltip"), + protocolString]]; - NSString * portString; + NSString* portString; NSInteger port; if ((port = [peer[@"Port"] intValue]) > 0) - portString = [NSString stringWithFormat: @"%ld", port]; + { + portString = [NSString stringWithFormat:@"%ld", port]; + } else + { portString = NSLocalizedString(@"N/A", "Inspector -> Peers tab -> table row tooltip"); - [components addObject: [NSString stringWithFormat: @"%@: %@", NSLocalizedString(@"Port", - "Inspector -> Peers tab -> table row tooltip"), portString]]; + } + [components addObject:[NSString stringWithFormat:@"%@: %@", + NSLocalizedString(@"Port", "Inspector -> Peers tab -> table row tooltip"), + portString]]; - const NSInteger peerFrom = [peer[@"From"] integerValue]; + NSInteger const peerFrom = [peer[@"From"] integerValue]; switch (peerFrom) { - case TR_PEER_FROM_TRACKER: - [components addObject: NSLocalizedString(@"From: tracker", "Inspector -> Peers tab -> table row tooltip")]; - break; - case TR_PEER_FROM_INCOMING: - [components addObject: NSLocalizedString(@"From: incoming connection", "Inspector -> Peers tab -> table row tooltip")]; - break; - case TR_PEER_FROM_RESUME: - [components addObject: NSLocalizedString(@"From: cache", "Inspector -> Peers tab -> table row tooltip")]; - break; - case TR_PEER_FROM_LPD: - [components addObject: NSLocalizedString(@"From: local peer discovery", "Inspector -> Peers tab -> table row tooltip")]; - break; - case TR_PEER_FROM_PEX: - [components addObject: NSLocalizedString(@"From: peer exchange", "Inspector -> Peers tab -> table row tooltip")]; - break; - case TR_PEER_FROM_DHT: - [components addObject: NSLocalizedString(@"From: distributed hash table", "Inspector -> Peers tab -> table row tooltip")]; - break; - case TR_PEER_FROM_LTEP: - [components addObject: NSLocalizedString(@"From: libtorrent extension protocol handshake", - "Inspector -> Peers tab -> table row tooltip")]; - break; - default: - NSAssert1(NO, @"Peer from unknown source: %ld", peerFrom); + case TR_PEER_FROM_TRACKER: + [components addObject:NSLocalizedString(@"From: tracker", "Inspector -> Peers tab -> table row tooltip")]; + break; + case TR_PEER_FROM_INCOMING: + [components addObject:NSLocalizedString(@"From: incoming connection", "Inspector -> Peers tab -> table row tooltip")]; + break; + case TR_PEER_FROM_RESUME: + [components addObject:NSLocalizedString(@"From: cache", "Inspector -> Peers tab -> table row tooltip")]; + break; + case TR_PEER_FROM_LPD: + [components addObject:NSLocalizedString(@"From: local peer discovery", "Inspector -> Peers tab -> table row tooltip")]; + break; + case TR_PEER_FROM_PEX: + [components addObject:NSLocalizedString(@"From: peer exchange", "Inspector -> Peers tab -> table row tooltip")]; + break; + case TR_PEER_FROM_DHT: + [components addObject:NSLocalizedString(@"From: distributed hash table", "Inspector -> Peers tab -> table row tooltip")]; + break; + case TR_PEER_FROM_LTEP: + [components addObject:NSLocalizedString(@"From: libtorrent extension protocol handshake", "Inspector -> Peers tab -> table row tooltip")]; + break; + default: + NSAssert1(NO, @"Peer from unknown source: %ld", peerFrom); } //determing status strings from flags - NSMutableArray * statusArray = [NSMutableArray arrayWithCapacity: 6]; - NSString * flags = peer[@"Flags"]; + NSMutableArray* statusArray = [NSMutableArray arrayWithCapacity:6]; + NSString* flags = peer[@"Flags"]; - if ([flags rangeOfString: @"D"].location != NSNotFound) - [statusArray addObject: NSLocalizedString(@"Currently downloading (interested and not choked)", - "Inspector -> peer -> status")]; - if ([flags rangeOfString: @"d"].location != NSNotFound) - [statusArray addObject: NSLocalizedString(@"You want to download, but peer does not want to send (interested and choked)", - "Inspector -> peer -> status")]; - if ([flags rangeOfString: @"U"].location != NSNotFound) - [statusArray addObject: NSLocalizedString(@"Currently uploading (interested and not choked)", - "Inspector -> peer -> status")]; - if ([flags rangeOfString: @"u"].location != NSNotFound) - [statusArray addObject: NSLocalizedString(@"Peer wants you to upload, but you do not want to (interested and choked)", - "Inspector -> peer -> status")]; - if ([flags rangeOfString: @"K"].location != NSNotFound) - [statusArray addObject: NSLocalizedString(@"Peer is unchoking you, but you are not interested", - "Inspector -> peer -> status")]; - if ([flags rangeOfString: @"?"].location != NSNotFound) - [statusArray addObject: NSLocalizedString(@"You unchoked the peer, but the peer is not interested", - "Inspector -> peer -> status")]; + if ([flags rangeOfString:@"D"].location != NSNotFound) + { + [statusArray addObject:NSLocalizedString(@"Currently downloading (interested and not choked)", "Inspector -> peer -> status")]; + } + if ([flags rangeOfString:@"d"].location != NSNotFound) + { + [statusArray addObject:NSLocalizedString( + @"You want to download, but peer does not want to send (interested and choked)", + "Inspector -> peer -> status")]; + } + if ([flags rangeOfString:@"U"].location != NSNotFound) + { + [statusArray addObject:NSLocalizedString(@"Currently uploading (interested and not choked)", "Inspector -> peer -> status")]; + } + if ([flags rangeOfString:@"u"].location != NSNotFound) + { + [statusArray addObject:NSLocalizedString(@"Peer wants you to upload, but you do not want to (interested and choked)", "Inspector -> peer -> status")]; + } + if ([flags rangeOfString:@"K"].location != NSNotFound) + { + [statusArray addObject:NSLocalizedString(@"Peer is unchoking you, but you are not interested", "Inspector -> peer -> status")]; + } + if ([flags rangeOfString:@"?"].location != NSNotFound) + { + [statusArray addObject:NSLocalizedString(@"You unchoked the peer, but the peer is not interested", "Inspector -> peer -> status")]; + } if (statusArray.count > 0) { - NSString * statusStrings = [statusArray componentsJoinedByString: @"\n\n"]; - [components addObject: [@"\n" stringByAppendingString: statusStrings]]; + NSString* statusStrings = [statusArray componentsJoinedByString:@"\n\n"]; + [components addObject:[@"\n" stringByAppendingString:statusStrings]]; } - return [components componentsJoinedByString: @"\n"]; + return [components componentsJoinedByString:@"\n"]; } else { if (fTorrents.count > 1) + { return fWebSeeds[row][@"Name"]; + } } return nil; } -- (void) animationDidStart: (CAAnimation *) animation +- (void)animationDidStart:(CAAnimation*)animation { - if (![[animation valueForKey: ANIMATION_ID_KEY] isEqualToString: WEB_SEED_ANIMATION_ID]) + if (![[animation valueForKey:ANIMATION_ID_KEY] isEqualToString:WEB_SEED_ANIMATION_ID]) + { return; + } fWebSeedTable.enclosingScrollView.hidden = NO; } -- (void) animationDidStop: (CAAnimation *) animation finished: (BOOL) finished +- (void)animationDidStop:(CAAnimation*)animation finished:(BOOL)finished { - if (![[animation valueForKey: ANIMATION_ID_KEY] isEqualToString: WEB_SEED_ANIMATION_ID]) + if (![[animation valueForKey:ANIMATION_ID_KEY] isEqualToString:WEB_SEED_ANIMATION_ID]) + { return; + } fWebSeedTable.enclosingScrollView.hidden = finished && fWebSeedTableTopConstraint.constant < 0; } @@ -456,7 +528,7 @@ @implementation InfoPeersViewController (Private) -- (void) setupInfo +- (void)setupInfo { __block BOOL hasWebSeeds = NO; @@ -469,7 +541,7 @@ } else { - [fTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(Torrent * torrent, NSUInteger idx, BOOL *stop) { + [fTorrents enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(Torrent* torrent, NSUInteger idx, BOOL* stop) { if (torrent.webSeedCount > 0) { hasWebSeeds = YES; @@ -484,42 +556,49 @@ [fWebSeedTable reloadData]; } else - [fWebSeedTable deselectAll: self]; - [self setWebSeedTableHidden: !hasWebSeeds animate: YES]; + { + [fWebSeedTable deselectAll:self]; + } + [self setWebSeedTableHidden:!hasWebSeeds animate:YES]; fSet = YES; } -- (void) setWebSeedTableHidden: (BOOL) hide animate: (BOOL) animate +- (void)setWebSeedTableHidden:(BOOL)hide animate:(BOOL)animate { if (animate && (!self.view.window || !self.view.window.visible)) + { animate = NO; + } - const CGFloat webSeedTableTopMargin = hide ? -NSHeight(fWebSeedTable.enclosingScrollView.frame) : fViewTopMargin; + CGFloat const webSeedTableTopMargin = hide ? -NSHeight(fWebSeedTable.enclosingScrollView.frame) : fViewTopMargin; (animate ? [fWebSeedTableTopConstraint animator] : fWebSeedTableTopConstraint).constant = webSeedTableTopMargin; } -- (NSArray *) peerSortDescriptors +- (NSArray*)peerSortDescriptors { - NSMutableArray * descriptors = [NSMutableArray arrayWithCapacity: 2]; + NSMutableArray* descriptors = [NSMutableArray arrayWithCapacity:2]; - NSArray * oldDescriptors = fPeerTable.sortDescriptors; + NSArray* oldDescriptors = fPeerTable.sortDescriptors; BOOL useSecond = YES, asc = YES; if (oldDescriptors.count > 0) { - NSSortDescriptor * descriptor = oldDescriptors[0]; - [descriptors addObject: descriptor]; + NSSortDescriptor* descriptor = oldDescriptors[0]; + [descriptors addObject:descriptor]; - if ((useSecond = ![descriptor.key isEqualToString: @"IP"])) + if ((useSecond = ![descriptor.key isEqualToString:@"IP"])) + { asc = descriptor.ascending; + } } //sort by IP after primary sort if (useSecond) { - NSSortDescriptor * secondDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"IP" ascending: asc selector: @selector(compareNumeric:)]; - [descriptors addObject: secondDescriptor]; + NSSortDescriptor* secondDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"IP" ascending:asc + selector:@selector(compareNumeric:)]; + [descriptors addObject:secondDescriptor]; } return descriptors; diff --git a/macosx/InfoTabButtonBack.m b/macosx/InfoTabButtonBack.m index a76b4150c..8ef468caf 100644 --- a/macosx/InfoTabButtonBack.m +++ b/macosx/InfoTabButtonBack.m @@ -25,19 +25,22 @@ @implementation InfoTabButtonBack -- (void) drawRect: (NSRect) rect +- (void)drawRect:(NSRect)rect { NSInteger count = 0; NSRect gridRects[2]; - NSColor * colorRects[2]; + NSColor* colorRects[2]; NSRect lineBorderRect = NSMakeRect(NSMinX(rect), NSHeight(self.bounds) - 1.0, NSWidth(rect), 1.0); if (NSIntersectsRect(lineBorderRect, rect)) { gridRects[count] = lineBorderRect; - if (@available(macOS 10.14, *)) { + if (@available(macOS 10.14, *)) + { colorRects[count] = NSColor.separatorColor; - } else { + } + else + { colorRects[count] = NSColor.grayColor; } ++count; @@ -49,9 +52,12 @@ if (NSIntersectsRect(lineBorderRect, rect)) { gridRects[count] = lineBorderRect; - if (@available(macOS 10.14, *)) { + if (@available(macOS 10.14, *)) + { colorRects[count] = NSColor.separatorColor; - } else { + } + else + { colorRects[count] = NSColor.grayColor; } ++count; @@ -62,18 +68,21 @@ NSRectFillListWithColors(gridRects, colorRects, count); - NSGradient *gradient; + NSGradient* gradient; - if (NSApp.isDarkMode) { - NSColor * darkColor = [NSColor colorWithCalibratedRed: 60.0/255.0 green: 60.0/255.0 blue: 60.0/255.0 alpha: 1.0]; - NSColor * lightColor = [NSColor colorWithCalibratedRed: 90.0/255.0 green: 90.0/255.0 blue: 90.0/255.0 alpha: 1.0]; - gradient = [[NSGradient alloc] initWithStartingColor: lightColor endingColor: darkColor]; - } else { - NSColor * lightColor = [NSColor colorWithCalibratedRed: 245.0/255.0 green: 245.0/255.0 blue: 245.0/255.0 alpha: 1.0]; - NSColor * darkColor = [NSColor colorWithCalibratedRed: 215.0/255.0 green: 215.0/255.0 blue: 215.0/255.0 alpha: 1.0]; - gradient = [[NSGradient alloc] initWithStartingColor: lightColor endingColor: darkColor]; + if (NSApp.isDarkMode) + { + NSColor* darkColor = [NSColor colorWithCalibratedRed:60.0 / 255.0 green:60.0 / 255.0 blue:60.0 / 255.0 alpha:1.0]; + NSColor* lightColor = [NSColor colorWithCalibratedRed:90.0 / 255.0 green:90.0 / 255.0 blue:90.0 / 255.0 alpha:1.0]; + gradient = [[NSGradient alloc] initWithStartingColor:lightColor endingColor:darkColor]; } - [gradient drawInRect: rect angle: 270.0]; + else + { + NSColor* lightColor = [NSColor colorWithCalibratedRed:245.0 / 255.0 green:245.0 / 255.0 blue:245.0 / 255.0 alpha:1.0]; + NSColor* darkColor = [NSColor colorWithCalibratedRed:215.0 / 255.0 green:215.0 / 255.0 blue:215.0 / 255.0 alpha:1.0]; + gradient = [[NSGradient alloc] initWithStartingColor:lightColor endingColor:darkColor]; + } + [gradient drawInRect:rect angle:270.0]; } @end diff --git a/macosx/InfoTabButtonCell.h b/macosx/InfoTabButtonCell.h index fed93ef9b..588e73370 100644 --- a/macosx/InfoTabButtonCell.h +++ b/macosx/InfoTabButtonCell.h @@ -24,13 +24,13 @@ @interface InfoTabButtonCell : NSButtonCell { - NSImage * fIcon; + NSImage* fIcon; BOOL fSelected; } -- (void) setSelectedTab: (BOOL) selected; +- (void)setSelectedTab:(BOOL)selected; -- (void) reloadAppearance; +- (void)reloadAppearance; @end diff --git a/macosx/InfoTabButtonCell.m b/macosx/InfoTabButtonCell.m index 7f9f9b68c..06fa02de6 100644 --- a/macosx/InfoTabButtonCell.m +++ b/macosx/InfoTabButtonCell.m @@ -25,12 +25,12 @@ @implementation InfoTabButtonCell -- (void) awakeFromNib +- (void)awakeFromNib { - if (!NSApp.onMojaveOrBetter) { - NSNotificationCenter * nc = NSNotificationCenter.defaultCenter; - [nc addObserver: self selector: @selector(updateControlTint:) - name: NSControlTintDidChangeNotification object: NSApp]; + if (!NSApp.onMojaveOrBetter) + { + NSNotificationCenter* nc = NSNotificationCenter.defaultCenter; + [nc addObserver:self selector:@selector(updateControlTint:) name:NSControlTintDidChangeNotification object:NSApp]; } fSelected = NO; @@ -39,75 +39,86 @@ fIcon = self.image; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; } -- (void) setControlView: (NSView *) controlView +- (void)setControlView:(NSView*)controlView { - const BOOL hadControlView = self.controlView != nil; + BOOL const hadControlView = self.controlView != nil; super.controlView = controlView; if (!hadControlView) { - [(NSMatrix *)self.controlView setToolTip: self.title forCell: self]; - [self setSelectedTab: fSelected]; + [(NSMatrix*)self.controlView setToolTip:self.title forCell:self]; + [self setSelectedTab:fSelected]; } } -- (void) setSelectedTab: (BOOL) selected +- (void)setSelectedTab:(BOOL)selected { fSelected = selected; [self reloadAppearance]; } -- (void) reloadAppearance +- (void)reloadAppearance { if (self.controlView == nil) + { return; + } NSInteger row, col; - [(NSMatrix *)self.controlView getRow: &row column: &col ofCell: self]; - NSRect tabRect = [(NSMatrix *)self.controlView cellFrameAtRow: row column: col]; + [(NSMatrix*)self.controlView getRow:&row column:&col ofCell:self]; + NSRect tabRect = [(NSMatrix*)self.controlView cellFrameAtRow:row column:col]; tabRect.origin.x = 0.0; tabRect.origin.y = 0.0; - NSImage * tabImage = [[NSImage alloc] initWithSize: tabRect.size]; + NSImage* tabImage = [[NSImage alloc] initWithSize:tabRect.size]; [tabImage lockFocus]; - NSGradient * gradient; + NSGradient* gradient; if (fSelected) { - NSColor * lightColor, * darkColor; - if (@available(macOS 10.14, *)) { - lightColor = [NSColor.controlAccentColor blendedColorWithFraction: 0.35 ofColor: NSColor.whiteColor]; - darkColor = [NSColor.controlAccentColor blendedColorWithFraction: 0.15 ofColor: NSColor.whiteColor]; - } else { - lightColor = [NSColor colorForControlTint: NSColor.currentControlTint]; - darkColor = [lightColor blendedColorWithFraction: 0.2 ofColor: NSColor.blackColor]; + NSColor *lightColor, *darkColor; + if (@available(macOS 10.14, *)) + { + lightColor = [NSColor.controlAccentColor blendedColorWithFraction:0.35 ofColor:NSColor.whiteColor]; + darkColor = [NSColor.controlAccentColor blendedColorWithFraction:0.15 ofColor:NSColor.whiteColor]; } - gradient = [[NSGradient alloc] initWithStartingColor: lightColor endingColor: darkColor]; + else + { + lightColor = [NSColor colorForControlTint:NSColor.currentControlTint]; + darkColor = [lightColor blendedColorWithFraction:0.2 ofColor:NSColor.blackColor]; + } + gradient = [[NSGradient alloc] initWithStartingColor:lightColor endingColor:darkColor]; } else { - if (NSApp.isDarkMode) { - NSColor * darkColor = [NSColor colorWithCalibratedRed: 60.0/255.0 green: 60.0/255.0 blue: 60.0/255.0 alpha: 1.0]; - NSColor * lightColor = [NSColor colorWithCalibratedRed: 90.0/255.0 green: 90.0/255.0 blue: 90.0/255.0 alpha: 1.0]; - gradient = [[NSGradient alloc] initWithStartingColor: lightColor endingColor: darkColor]; - } else { - NSColor * lightColor = [NSColor colorWithCalibratedRed: 245.0/255.0 green: 245.0/255.0 blue: 245.0/255.0 alpha: 1.0]; - NSColor * darkColor = [NSColor colorWithCalibratedRed: 215.0/255.0 green: 215.0/255.0 blue: 215.0/255.0 alpha: 1.0]; - gradient = [[NSGradient alloc] initWithStartingColor: lightColor endingColor: darkColor]; + if (NSApp.isDarkMode) + { + NSColor* darkColor = [NSColor colorWithCalibratedRed:60.0 / 255.0 green:60.0 / 255.0 blue:60.0 / 255.0 alpha:1.0]; + NSColor* lightColor = [NSColor colorWithCalibratedRed:90.0 / 255.0 green:90.0 / 255.0 blue:90.0 / 255.0 alpha:1.0]; + gradient = [[NSGradient alloc] initWithStartingColor:lightColor endingColor:darkColor]; + } + else + { + NSColor* lightColor = [NSColor colorWithCalibratedRed:245.0 / 255.0 green:245.0 / 255.0 blue:245.0 / 255.0 alpha:1.0]; + NSColor* darkColor = [NSColor colorWithCalibratedRed:215.0 / 255.0 green:215.0 / 255.0 blue:215.0 / 255.0 alpha:1.0]; + gradient = [[NSGradient alloc] initWithStartingColor:lightColor endingColor:darkColor]; } } - if (@available(macOS 10.14, *)) { + if (@available(macOS 10.14, *)) + { [NSColor.separatorColor set]; - } else { + } + else + { [NSColor.grayColor set]; } NSRectFill(NSMakeRect(0.0, 0.0, NSWidth(tabRect), 1.0)); @@ -116,17 +127,19 @@ tabRect = NSMakeRect(0.0, 1.0, NSWidth(tabRect) - 1.0, NSHeight(tabRect) - 2.0); - [gradient drawInRect: tabRect angle: 270.0]; + [gradient drawInRect:tabRect angle:270.0]; if (fIcon) { - const NSSize iconSize = fIcon.size; + NSSize const iconSize = fIcon.size; - const NSRect iconRect = NSMakeRect(NSMinX(tabRect) + floor((NSWidth(tabRect) - iconSize.width) * 0.5), - NSMinY(tabRect) + floor((NSHeight(tabRect) - iconSize.height) * 0.5), - iconSize.width, iconSize.height); + NSRect const iconRect = NSMakeRect( + NSMinX(tabRect) + floor((NSWidth(tabRect) - iconSize.width) * 0.5), + NSMinY(tabRect) + floor((NSHeight(tabRect) - iconSize.height) * 0.5), + iconSize.width, + iconSize.height); - [fIcon drawInRect: iconRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0]; + [fIcon drawInRect:iconRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; } [tabImage unlockFocus]; @@ -134,12 +147,14 @@ self.image = tabImage; } -- (void) updateControlTint: (NSNotification *) notification +- (void)updateControlTint:(NSNotification*)notification { NSAssert(!NSApp.onMojaveOrBetter, @"should not be observing control tint color when accent color is available"); if (fSelected) - [self setSelectedTab: YES]; + { + [self setSelectedTab:YES]; + } } @end diff --git a/macosx/InfoTabMatrix.m b/macosx/InfoTabMatrix.m index a9c4bd8a7..c81301ec3 100644 --- a/macosx/InfoTabMatrix.m +++ b/macosx/InfoTabMatrix.m @@ -13,7 +13,8 @@ - (void)viewDidChangeEffectiveAppearance; { - for (InfoTabButtonCell *cell in self.cells) { + for (InfoTabButtonCell* cell in self.cells) + { [cell reloadAppearance]; } } diff --git a/macosx/InfoTextField.m b/macosx/InfoTextField.m index 573a4064a..f2c6e28ac 100644 --- a/macosx/InfoTextField.m +++ b/macosx/InfoTextField.m @@ -24,18 +24,18 @@ @implementation InfoTextField -- (void) setStringValue: (NSString *) string +- (void)setStringValue:(NSString*)string { super.stringValue = string; - self.selectable = ![self.stringValue isEqualToString: @""]; + self.selectable = ![self.stringValue isEqualToString:@""]; } -- (void) setObjectValue: (id ) object +- (void)setObjectValue:(id)object { super.objectValue = object; - self.selectable = ![self.stringValue isEqualToString: @""]; + self.selectable = ![self.stringValue isEqualToString:@""]; } @end diff --git a/macosx/InfoTrackersViewController.h b/macosx/InfoTrackersViewController.h index a46b6f24f..f3d40d23b 100644 --- a/macosx/InfoTrackersViewController.h +++ b/macosx/InfoTrackersViewController.h @@ -28,26 +28,26 @@ @class TrackerTableView; @class TrackerCell; -@interface InfoTrackersViewController : NSViewController +@interface InfoTrackersViewController : NSViewController { - NSArray * fTorrents; + NSArray* fTorrents; BOOL fSet; - NSMutableArray * fTrackers; + NSMutableArray* fTrackers; - IBOutlet TrackerTableView * fTrackerTable; - TrackerCell * fTrackerCell; + IBOutlet TrackerTableView* fTrackerTable; + TrackerCell* fTrackerCell; - IBOutlet NSSegmentedControl * fTrackerAddRemoveControl; + IBOutlet NSSegmentedControl* fTrackerAddRemoveControl; } -- (void) setInfoForTorrents: (NSArray *) torrents; -- (void) updateInfo; +- (void)setInfoForTorrents:(NSArray*)torrents; +- (void)updateInfo; -- (void) saveViewSize; -- (void) clearView; +- (void)saveViewSize; +- (void)clearView; -- (void) addRemoveTracker: (id) sender; +- (void)addRemoveTracker:(id)sender; @end diff --git a/macosx/InfoTrackersViewController.m b/macosx/InfoTrackersViewController.m index d5daf7ed3..667364002 100644 --- a/macosx/InfoTrackersViewController.m +++ b/macosx/InfoTrackersViewController.m @@ -32,21 +32,20 @@ #define TRACKER_ADD_TAG 0 #define TRACKER_REMOVE_TAG 1 - @interface InfoTrackersViewController (Private) -- (void) setupInfo; +- (void)setupInfo; -- (void) addTrackers; -- (void) removeTrackers; +- (void)addTrackers; +- (void)removeTrackers; @end @implementation InfoTrackersViewController -- (instancetype) init +- (instancetype)init { - if ((self = [super initWithNibName: @"InfoTrackersView" bundle: nil])) + if ((self = [super initWithNibName:@"InfoTrackersView" bundle:nil])) { self.title = NSLocalizedString(@"Trackers", "Inspector view -> title"); @@ -56,14 +55,14 @@ return self; } -- (void) awakeFromNib +- (void)awakeFromNib { - [fTrackerAddRemoveControl.cell setToolTip: NSLocalizedString(@"Add a tracker", "Inspector view -> tracker buttons") - forSegment: TRACKER_ADD_TAG]; - [fTrackerAddRemoveControl.cell setToolTip: NSLocalizedString(@"Remove selected trackers", "Inspector view -> tracker buttons") - forSegment: TRACKER_REMOVE_TAG]; + [fTrackerAddRemoveControl.cell setToolTip:NSLocalizedString(@"Add a tracker", "Inspector view -> tracker buttons") + forSegment:TRACKER_ADD_TAG]; + [fTrackerAddRemoveControl.cell setToolTip:NSLocalizedString(@"Remove selected trackers", "Inspector view -> tracker buttons") + forSegment:TRACKER_REMOVE_TAG]; - const CGFloat height = [NSUserDefaults.standardUserDefaults floatForKey: @"InspectorContentHeightTracker"]; + CGFloat const height = [NSUserDefaults.standardUserDefaults floatForKey:@"InspectorContentHeightTracker"]; if (height != 0.0) { NSRect viewRect = self.view.frame; @@ -72,8 +71,7 @@ } } - -- (void) setInfoForTorrents: (NSArray *) torrents +- (void)setInfoForTorrents:(NSArray*)torrents { //don't check if it's the same in case the metadata changed fTorrents = torrents; @@ -81,256 +79,302 @@ fSet = NO; } -- (void) updateInfo +- (void)updateInfo { if (!fSet) + { [self setupInfo]; + } if (fTorrents.count == 0) + { return; + } //get updated tracker stats if (fTrackerTable.editedRow == -1) { - NSArray * oldTrackers = fTrackers; + NSArray* oldTrackers = fTrackers; if (fTorrents.count == 1) - fTrackers = ((Torrent *)fTorrents[0]).allTrackerStats; + { + fTrackers = ((Torrent*)fTorrents[0]).allTrackerStats; + } else { fTrackers = [[NSMutableArray alloc] init]; - for (Torrent * torrent in fTorrents) - [fTrackers addObjectsFromArray: torrent.allTrackerStats]; + for (Torrent* torrent in fTorrents) + { + [fTrackers addObjectsFromArray:torrent.allTrackerStats]; + } } - [fTrackerTable setTrackers: fTrackers]; + [fTrackerTable setTrackers:fTrackers]; - if (oldTrackers && [fTrackers isEqualToArray: oldTrackers]) - fTrackerTable.needsDisplay = YES; + if (oldTrackers && [fTrackers isEqualToArray:oldTrackers]) + { + fTrackerTable.needsDisplay = YES; + } else + { [fTrackerTable reloadData]; - + } } else { NSAssert1(fTorrents.count == 1, @"Attempting to add tracker with %ld transfers selected", fTorrents.count); - NSIndexSet * addedIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(fTrackers.count-2, 2)]; - NSArray * tierAndTrackerBeingAdded = [fTrackers objectsAtIndexes: addedIndexes]; + NSIndexSet* addedIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(fTrackers.count - 2, 2)]; + NSArray* tierAndTrackerBeingAdded = [fTrackers objectsAtIndexes:addedIndexes]; - fTrackers = ((Torrent *)fTorrents[0]).allTrackerStats; - [fTrackers addObjectsFromArray: tierAndTrackerBeingAdded]; + fTrackers = ((Torrent*)fTorrents[0]).allTrackerStats; + [fTrackers addObjectsFromArray:tierAndTrackerBeingAdded]; - [fTrackerTable setTrackers: fTrackers]; + [fTrackerTable setTrackers:fTrackers]; - NSIndexSet * updateIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTrackers.count-2)], - * columnIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTrackerTable.tableColumns.count)]; - [fTrackerTable reloadDataForRowIndexes: updateIndexes columnIndexes: columnIndexes]; + NSIndexSet *updateIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fTrackers.count - 2)], + *columnIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fTrackerTable.tableColumns.count)]; + [fTrackerTable reloadDataForRowIndexes:updateIndexes columnIndexes:columnIndexes]; } } -- (void) saveViewSize +- (void)saveViewSize { - [NSUserDefaults.standardUserDefaults setFloat: NSHeight(self.view.frame) forKey: @"InspectorContentHeightTracker"]; + [NSUserDefaults.standardUserDefaults setFloat:NSHeight(self.view.frame) forKey:@"InspectorContentHeightTracker"]; } -- (void) clearView +- (void)clearView { fTrackers = nil; } -- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView +- (NSInteger)numberOfRowsInTableView:(NSTableView*)tableView { return fTrackers ? fTrackers.count : 0; } -- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (NSInteger) row +- (id)tableView:(NSTableView*)tableView objectValueForTableColumn:(NSTableColumn*)column row:(NSInteger)row { id item = fTrackers[row]; - if ([item isKindOfClass: [NSDictionary class]]) + if ([item isKindOfClass:[NSDictionary class]]) { - const NSInteger tier = [item[@"Tier"] integerValue]; - NSString * tierString = tier == -1 ? NSLocalizedString(@"New Tier", "Inspector -> tracker table") - : [NSString stringWithFormat: NSLocalizedString(@"Tier %d", "Inspector -> tracker table"), tier]; + NSInteger const tier = [item[@"Tier"] integerValue]; + NSString* tierString = tier == -1 ? + NSLocalizedString(@"New Tier", "Inspector -> tracker table") : + [NSString stringWithFormat:NSLocalizedString(@"Tier %d", "Inspector -> tracker table"), tier]; if (fTorrents.count > 1) - tierString = [tierString stringByAppendingFormat: @" - %@", item[@"Name"]]; + { + tierString = [tierString stringByAppendingFormat:@" - %@", item[@"Name"]]; + } return tierString; } else + { return item; //TrackerNode or NSString + } } -- (NSCell *) tableView: (NSTableView *) tableView dataCellForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row +- (NSCell*)tableView:(NSTableView*)tableView dataCellForTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row { - const BOOL tracker = [fTrackers[row] isKindOfClass: [TrackerNode class]]; - return tracker ? fTrackerCell : [tableColumn dataCellForRow: row]; + BOOL const tracker = [fTrackers[row] isKindOfClass:[TrackerNode class]]; + return tracker ? fTrackerCell : [tableColumn dataCellForRow:row]; } -- (CGFloat) tableView: (NSTableView *) tableView heightOfRow: (NSInteger) row +- (CGFloat)tableView:(NSTableView*)tableView heightOfRow:(NSInteger)row { //check for NSDictionay instead of TrackerNode because of display issue when adding a row - if ([fTrackers[row] isKindOfClass: [NSDictionary class]]) + if ([fTrackers[row] isKindOfClass:[NSDictionary class]]) + { return TRACKER_GROUP_SEPARATOR_HEIGHT; + } else + { return tableView.rowHeight; + } } -- (BOOL) tableView: (NSTableView *) tableView shouldEditTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row +- (BOOL)tableView:(NSTableView*)tableView shouldEditTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row { //don't allow tier row to be edited by double-click return NO; } -- (void) tableViewSelectionDidChange: (NSNotification *) notification +- (void)tableViewSelectionDidChange:(NSNotification*)notification { - [fTrackerAddRemoveControl setEnabled: fTrackerTable.numberOfSelectedRows > 0 forSegment: TRACKER_REMOVE_TAG]; + [fTrackerAddRemoveControl setEnabled:fTrackerTable.numberOfSelectedRows > 0 forSegment:TRACKER_REMOVE_TAG]; } -- (BOOL) tableView: (NSTableView *) tableView isGroupRow: (NSInteger) row +- (BOOL)tableView:(NSTableView*)tableView isGroupRow:(NSInteger)row { - return ![fTrackers[row] isKindOfClass: [TrackerNode class]] && tableView.editedRow != row; + return ![fTrackers[row] isKindOfClass:[TrackerNode class]] && tableView.editedRow != row; } -- (NSString *) tableView: (NSTableView *) tableView toolTipForCell: (NSCell *) cell rect: (NSRectPointer) rect - tableColumn: (NSTableColumn *) column row: (NSInteger) row mouseLocation: (NSPoint) mouseLocation +- (NSString*)tableView:(NSTableView*)tableView + toolTipForCell:(NSCell*)cell + rect:(NSRectPointer)rect + tableColumn:(NSTableColumn*)column + row:(NSInteger)row + mouseLocation:(NSPoint)mouseLocation { id node = fTrackers[row]; - if ([node isKindOfClass: [TrackerNode class]]) - return ((TrackerNode *)node).fullAnnounceAddress; + if ([node isKindOfClass:[TrackerNode class]]) + { + return ((TrackerNode*)node).fullAnnounceAddress; + } else + { return nil; + } } -- (void) tableView: (NSTableView *) tableView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn - row: (NSInteger) row +- (void)tableView:(NSTableView*)tableView + setObjectValue:(id)object + forTableColumn:(NSTableColumn*)tableColumn + row:(NSInteger)row { - Torrent * torrent= fTorrents[0]; + Torrent* torrent = fTorrents[0]; BOOL added = NO; - for (NSString * tracker in [object componentsSeparatedByString: @"\n"]) - if ([torrent addTrackerToNewTier: tracker]) + for (NSString* tracker in [object componentsSeparatedByString:@"\n"]) + { + if ([torrent addTrackerToNewTier:tracker]) + { added = YES; + } + } if (!added) + { NSBeep(); + } //reset table with either new or old value fTrackers = torrent.allTrackerStats; - [fTrackerTable setTrackers: fTrackers]; + [fTrackerTable setTrackers:fTrackers]; [fTrackerTable reloadData]; - [fTrackerTable deselectAll: self]; + [fTrackerTable deselectAll:self]; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; //incase sort by tracker + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; //incase sort by tracker } -- (void) addRemoveTracker: (id) sender +- (void)addRemoveTracker:(id)sender { //don't allow add/remove when currently adding - it leads to weird results if (fTrackerTable.editedRow != -1) + { return; + } [self updateInfo]; - if ([[sender cell] tagForSegment: [sender selectedSegment]] == TRACKER_REMOVE_TAG) + if ([[sender cell] tagForSegment:[sender selectedSegment]] == TRACKER_REMOVE_TAG) + { [self removeTrackers]; + } else + { [self addTrackers]; + } } @end @implementation InfoTrackersViewController (Private) -- (void) setupInfo +- (void)setupInfo { - const NSUInteger numberSelected = fTorrents.count; + NSUInteger const numberSelected = fTorrents.count; if (numberSelected != 1) { if (numberSelected == 0) { fTrackers = nil; - [fTrackerTable setTrackers: nil]; + [fTrackerTable setTrackers:nil]; [fTrackerTable reloadData]; } - [fTrackerTable setTorrent: nil]; + [fTrackerTable setTorrent:nil]; - [fTrackerAddRemoveControl setEnabled: NO forSegment: TRACKER_ADD_TAG]; - [fTrackerAddRemoveControl setEnabled: NO forSegment: TRACKER_REMOVE_TAG]; + [fTrackerAddRemoveControl setEnabled:NO forSegment:TRACKER_ADD_TAG]; + [fTrackerAddRemoveControl setEnabled:NO forSegment:TRACKER_REMOVE_TAG]; } else { - [fTrackerTable setTorrent: fTorrents[0]]; + [fTrackerTable setTorrent:fTorrents[0]]; - [fTrackerAddRemoveControl setEnabled: YES forSegment: TRACKER_ADD_TAG]; - [fTrackerAddRemoveControl setEnabled: NO forSegment: TRACKER_REMOVE_TAG]; + [fTrackerAddRemoveControl setEnabled:YES forSegment:TRACKER_ADD_TAG]; + [fTrackerAddRemoveControl setEnabled:NO forSegment:TRACKER_REMOVE_TAG]; } - [fTrackerTable deselectAll: self]; + [fTrackerTable deselectAll:self]; fSet = YES; } #warning doesn't like blank addresses -- (void) addTrackers +- (void)addTrackers { [self.view.window makeKeyWindow]; NSAssert1(fTorrents.count == 1, @"Attempting to add tracker with %ld transfers selected", fTorrents.count); - [fTrackers addObject: @{@"Tier": @-1}]; - [fTrackers addObject: @""]; + [fTrackers addObject:@{ @"Tier" : @-1 }]; + [fTrackers addObject:@""]; - [fTrackerTable setTrackers: fTrackers]; + [fTrackerTable setTrackers:fTrackers]; [fTrackerTable reloadData]; - [fTrackerTable selectRowIndexes: [NSIndexSet indexSetWithIndex: fTrackers.count-1] byExtendingSelection: NO]; - [fTrackerTable editColumn: [fTrackerTable columnWithIdentifier: @"Tracker"] row: fTrackers.count-1 withEvent: nil select: YES]; + [fTrackerTable selectRowIndexes:[NSIndexSet indexSetWithIndex:fTrackers.count - 1] byExtendingSelection:NO]; + [fTrackerTable editColumn:[fTrackerTable columnWithIdentifier:@"Tracker"] row:fTrackers.count - 1 withEvent:nil select:YES]; } -- (void) removeTrackers +- (void)removeTrackers { - NSMutableDictionary * removeIdentifiers = [NSMutableDictionary dictionaryWithCapacity: fTorrents.count]; + NSMutableDictionary* removeIdentifiers = [NSMutableDictionary dictionaryWithCapacity:fTorrents.count]; NSUInteger removeTrackerCount = 0; - NSIndexSet * selectedIndexes = fTrackerTable.selectedRowIndexes; + NSIndexSet* selectedIndexes = fTrackerTable.selectedRowIndexes; BOOL groupSelected = NO; NSUInteger groupRowIndex = NSNotFound; - NSMutableIndexSet * removeIndexes = [NSMutableIndexSet indexSet]; + NSMutableIndexSet* removeIndexes = [NSMutableIndexSet indexSet]; for (NSUInteger i = 0; i < fTrackers.count; ++i) { id object = fTrackers[i]; - if ([object isKindOfClass: [TrackerNode class]]) + if ([object isKindOfClass:[TrackerNode class]]) { - TrackerNode * node = (TrackerNode *)object; - if (groupSelected || [selectedIndexes containsIndex: i]) + TrackerNode* node = (TrackerNode*)object; + if (groupSelected || [selectedIndexes containsIndex:i]) { - Torrent * torrent = node.torrent; - NSMutableSet * removeSet; + Torrent* torrent = node.torrent; + NSMutableSet* removeSet; if (!(removeSet = removeIdentifiers[torrent])) { removeSet = [NSMutableSet set]; removeIdentifiers[torrent] = removeSet; } - [removeSet addObject: node.fullAnnounceAddress]; + [removeSet addObject:node.fullAnnounceAddress]; ++removeTrackerCount; - [removeIndexes addIndex: i]; + [removeIndexes addIndex:i]; } else + { groupRowIndex = NSNotFound; //don't remove the group row + } } else { //mark the previous group row for removal, if necessary if (groupRowIndex != NSNotFound) - [removeIndexes addIndex: groupRowIndex]; + { + [removeIndexes addIndex:groupRowIndex]; + } - groupSelected = [selectedIndexes containsIndex: i]; + groupSelected = [selectedIndexes containsIndex:i]; if (!groupSelected && i > selectedIndexes.lastIndex) { groupRowIndex = NSNotFound; @@ -343,64 +387,84 @@ //mark the last group for removal, too if (groupRowIndex != NSNotFound) - [removeIndexes addIndex: groupRowIndex]; - - NSAssert2(removeTrackerCount <= removeIndexes.count, @"Marked %ld trackers to remove, but only removing %ld rows", removeTrackerCount, removeIndexes.count); - - //we might have no trackers if remove right after a failed add (race condition ftw) - #warning look into having a failed add apply right away, so that this can become an assert - if (removeTrackerCount == 0) - return; - - if ([NSUserDefaults.standardUserDefaults boolForKey: @"WarningRemoveTrackers"]) { - NSAlert * alert = [[NSAlert alloc] init]; + [removeIndexes addIndex:groupRowIndex]; + } + + NSAssert2( + removeTrackerCount <= removeIndexes.count, + @"Marked %ld trackers to remove, but only removing %ld rows", + removeTrackerCount, + removeIndexes.count); + +//we might have no trackers if remove right after a failed add (race condition ftw) +#warning look into having a failed add apply right away, so that this can become an assert + if (removeTrackerCount == 0) + { + return; + } + + if ([NSUserDefaults.standardUserDefaults boolForKey:@"WarningRemoveTrackers"]) + { + NSAlert* alert = [[NSAlert alloc] init]; if (removeTrackerCount > 1) { - alert.messageText = [NSString stringWithFormat: NSLocalizedString(@"Are you sure you want to remove %d trackers?", - "Remove trackers alert -> title"), removeTrackerCount]; - alert.informativeText = NSLocalizedString(@"Once removed, Transmission will no longer attempt to contact them." - " This cannot be undone.", "Remove trackers alert -> message"); + alert.messageText = [NSString + stringWithFormat:NSLocalizedString(@"Are you sure you want to remove %d trackers?", "Remove trackers alert -> title"), + removeTrackerCount]; + alert.informativeText = NSLocalizedString( + @"Once removed, Transmission will no longer attempt to contact them." + " This cannot be undone.", + "Remove trackers alert -> message"); } else { alert.messageText = NSLocalizedString(@"Are you sure you want to remove this tracker?", "Remove trackers alert -> title"); - alert.informativeText = NSLocalizedString(@"Once removed, Transmission will no longer attempt to contact it." - " This cannot be undone.", "Remove trackers alert -> message"); + alert.informativeText = NSLocalizedString( + @"Once removed, Transmission will no longer attempt to contact it." + " This cannot be undone.", + "Remove trackers alert -> message"); } - [alert addButtonWithTitle: NSLocalizedString(@"Remove", "Remove trackers alert -> button")]; - [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Remove trackers alert -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Remove", "Remove trackers alert -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Cancel", "Remove trackers alert -> button")]; alert.showsSuppressionButton = YES; NSInteger result = [alert runModal]; if (alert.suppressionButton.state == NSOnState) - [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningRemoveTrackers"]; + { + [NSUserDefaults.standardUserDefaults setBool:NO forKey:@"WarningRemoveTrackers"]; + } if (result != NSAlertFirstButtonReturn) + { return; + } } - [fTrackerTable beginUpdates]; - for (Torrent * torrent in removeIdentifiers) - [torrent removeTrackers: removeIdentifiers[torrent]]; + for (Torrent* torrent in removeIdentifiers) + { + [torrent removeTrackers:removeIdentifiers[torrent]]; + } //reset table with either new or old value fTrackers = [[NSMutableArray alloc] init]; - for (Torrent * torrent in fTorrents) - [fTrackers addObjectsFromArray: torrent.allTrackerStats]; + for (Torrent* torrent in fTorrents) + { + [fTrackers addObjectsFromArray:torrent.allTrackerStats]; + } - [fTrackerTable removeRowsAtIndexes: removeIndexes withAnimation: NSTableViewAnimationSlideLeft]; + [fTrackerTable removeRowsAtIndexes:removeIndexes withAnimation:NSTableViewAnimationSlideLeft]; - [fTrackerTable setTrackers: fTrackers]; + [fTrackerTable setTrackers:fTrackers]; [fTrackerTable endUpdates]; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; //incase sort by tracker + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; //incase sort by tracker } @end diff --git a/macosx/InfoViewController.h b/macosx/InfoViewController.h index 2fdb3fdeb..165ac21dd 100644 --- a/macosx/InfoViewController.h +++ b/macosx/InfoViewController.h @@ -24,11 +24,11 @@ @protocol InfoViewController -- (void) setInfoForTorrents: (NSArray *) torrents; -- (void) updateInfo; +- (void)setInfoForTorrents:(NSArray*)torrents; +- (void)updateInfo; @optional -- (void) clearView; -- (void) saveViewSize; +- (void)clearView; +- (void)saveViewSize; @end diff --git a/macosx/InfoWindowController.h b/macosx/InfoWindowController.h index 2639e8ac9..1a0db31f1 100644 --- a/macosx/InfoWindowController.h +++ b/macosx/InfoWindowController.h @@ -33,36 +33,38 @@ @interface InfoWindowController : NSWindowController { - NSArray * fTorrents; + NSArray* fTorrents; CGFloat fMinWindowWidth; - NSViewController * fViewController; + NSViewController* fViewController; NSInteger fCurrentTabTag; - IBOutlet NSMatrix * fTabMatrix; + IBOutlet NSMatrix* fTabMatrix; - InfoGeneralViewController * fGeneralViewController; - InfoActivityViewController * fActivityViewController; - InfoTrackersViewController * fTrackersViewController; - InfoPeersViewController * fPeersViewController; - InfoFileViewController * fFileViewController; - InfoOptionsViewController * fOptionsViewController; + InfoGeneralViewController* fGeneralViewController; + InfoActivityViewController* fActivityViewController; + InfoTrackersViewController* fTrackersViewController; + InfoPeersViewController* fPeersViewController; + InfoFileViewController* fFileViewController; + InfoOptionsViewController* fOptionsViewController; - IBOutlet NSImageView * fImageView; - IBOutlet NSTextField * fNameField, * fBasicInfoField, * fNoneSelectedField; + IBOutlet NSImageView* fImageView; + IBOutlet NSTextField* fNameField; + IBOutlet NSTextField* fBasicInfoField; + IBOutlet NSTextField* fNoneSelectedField; } -- (void) setInfoForTorrents: (NSArray *) torrents; -- (void) updateInfoStats; -- (void) updateOptions; +- (void)setInfoForTorrents:(NSArray*)torrents; +- (void)updateInfoStats; +- (void)updateOptions; -- (void) setTab: (id) sender; +- (void)setTab:(id)sender; -- (void) setNextTab; -- (void) setPreviousTab; +- (void)setNextTab; +- (void)setPreviousTab; -@property (nonatomic, readonly) NSArray *quickLookURLs; -@property (nonatomic, readonly) BOOL canQuickLook; -- (NSRect) quickLookSourceFrameForPreviewItem: (id ) item; +@property(nonatomic, readonly) NSArray* quickLookURLs; +@property(nonatomic, readonly) BOOL canQuickLook; +- (NSRect)quickLookSourceFrameForPreviewItem:(id)item; @end diff --git a/macosx/InfoWindowController.m b/macosx/InfoWindowController.m index b58c463d4..00c0ee929 100644 --- a/macosx/InfoWindowController.m +++ b/macosx/InfoWindowController.m @@ -55,135 +55,159 @@ typedef NS_ENUM(unsigned int, tabTag) { @interface InfoWindowController (Private) -- (void) resetInfo; -- (void) resetInfoForTorrent: (NSNotification *) notification; +- (void)resetInfo; +- (void)resetInfoForTorrent:(NSNotification*)notification; @end @implementation InfoWindowController -- (instancetype) init +- (instancetype)init { - self = [super initWithWindowNibName: @"InfoWindow"]; + self = [super initWithWindowNibName:@"InfoWindow"]; return self; } -- (void) awakeFromNib +- (void)awakeFromNib { fNoneSelectedField.stringValue = NSLocalizedString(@"No Torrents Selected", "Inspector -> selected torrents"); //window location and size - NSPanel * window = (NSPanel *)self.window; + NSPanel* window = (NSPanel*)self.window; window.floatingPanel = NO; - const CGFloat windowHeight = NSHeight(window.frame); + CGFloat const windowHeight = NSHeight(window.frame); fMinWindowWidth = window.minSize.width; - [window setFrameAutosaveName: @"InspectorWindow"]; - [window setFrameUsingName: @"InspectorWindow"]; + [window setFrameAutosaveName:@"InspectorWindow"]; + [window setFrameUsingName:@"InspectorWindow"]; NSRect windowRect = window.frame; windowRect.origin.y -= windowHeight - NSHeight(windowRect); windowRect.size.height = windowHeight; - [window setFrame: windowRect display: NO]; + [window setFrame:windowRect display:NO]; window.becomesKeyOnlyIfNeeded = YES; //set tab tooltips - [fTabMatrix setToolTip: NSLocalizedString(@"General Info", "Inspector -> tab") forCell: [fTabMatrix cellWithTag: TAB_GENERAL_TAG]]; - [fTabMatrix setToolTip: NSLocalizedString(@"Activity", "Inspector -> tab") forCell: [fTabMatrix cellWithTag: TAB_ACTIVITY_TAG]]; - [fTabMatrix setToolTip: NSLocalizedString(@"Trackers", "Inspector -> tab") forCell: [fTabMatrix cellWithTag: TAB_TRACKERS_TAG]]; - [fTabMatrix setToolTip: NSLocalizedString(@"Peers", "Inspector -> tab") forCell: [fTabMatrix cellWithTag: TAB_PEERS_TAG]]; - [fTabMatrix setToolTip: NSLocalizedString(@"Files", "Inspector -> tab") forCell: [fTabMatrix cellWithTag: TAB_FILE_TAG]]; - [fTabMatrix setToolTip: NSLocalizedString(@"Options", "Inspector -> tab") forCell: [fTabMatrix cellWithTag: TAB_OPTIONS_TAG]]; + [fTabMatrix setToolTip:NSLocalizedString(@"General Info", "Inspector -> tab") forCell:[fTabMatrix cellWithTag:TAB_GENERAL_TAG]]; + [fTabMatrix setToolTip:NSLocalizedString(@"Activity", "Inspector -> tab") forCell:[fTabMatrix cellWithTag:TAB_ACTIVITY_TAG]]; + [fTabMatrix setToolTip:NSLocalizedString(@"Trackers", "Inspector -> tab") forCell:[fTabMatrix cellWithTag:TAB_TRACKERS_TAG]]; + [fTabMatrix setToolTip:NSLocalizedString(@"Peers", "Inspector -> tab") forCell:[fTabMatrix cellWithTag:TAB_PEERS_TAG]]; + [fTabMatrix setToolTip:NSLocalizedString(@"Files", "Inspector -> tab") forCell:[fTabMatrix cellWithTag:TAB_FILE_TAG]]; + [fTabMatrix setToolTip:NSLocalizedString(@"Options", "Inspector -> tab") forCell:[fTabMatrix cellWithTag:TAB_OPTIONS_TAG]]; //set selected tab fCurrentTabTag = INVALID; - NSString * identifier = [NSUserDefaults.standardUserDefaults stringForKey: @"InspectorSelected"]; + NSString* identifier = [NSUserDefaults.standardUserDefaults stringForKey:@"InspectorSelected"]; NSInteger tag; - if ([identifier isEqualToString: TAB_INFO_IDENT]) - tag = TAB_GENERAL_TAG; - else if ([identifier isEqualToString: TAB_ACTIVITY_IDENT]) - tag = TAB_ACTIVITY_TAG; - else if ([identifier isEqualToString: TAB_TRACKER_IDENT]) - tag = TAB_TRACKERS_TAG; - else if ([identifier isEqualToString: TAB_PEERS_IDENT]) - tag = TAB_PEERS_TAG; - else if ([identifier isEqualToString: TAB_FILES_IDENT]) - tag = TAB_FILE_TAG; - else if ([identifier isEqualToString: TAB_OPTIONS_IDENT]) - tag = TAB_OPTIONS_TAG; - else //safety + if ([identifier isEqualToString:TAB_INFO_IDENT]) { - [NSUserDefaults.standardUserDefaults setObject: TAB_INFO_IDENT forKey: @"InspectorSelected"]; tag = TAB_GENERAL_TAG; } - [fTabMatrix selectCellWithTag: tag]; - [self setTab: nil]; + else if ([identifier isEqualToString:TAB_ACTIVITY_IDENT]) + { + tag = TAB_ACTIVITY_TAG; + } + else if ([identifier isEqualToString:TAB_TRACKER_IDENT]) + { + tag = TAB_TRACKERS_TAG; + } + else if ([identifier isEqualToString:TAB_PEERS_IDENT]) + { + tag = TAB_PEERS_TAG; + } + else if ([identifier isEqualToString:TAB_FILES_IDENT]) + { + tag = TAB_FILE_TAG; + } + else if ([identifier isEqualToString:TAB_OPTIONS_IDENT]) + { + tag = TAB_OPTIONS_TAG; + } + else //safety + { + [NSUserDefaults.standardUserDefaults setObject:TAB_INFO_IDENT forKey:@"InspectorSelected"]; + tag = TAB_GENERAL_TAG; + } + [fTabMatrix selectCellWithTag:tag]; + [self setTab:nil]; //set blank inspector - [self setInfoForTorrents: @[]]; + [self setInfoForTorrents:@[]]; //allow for update notifications - NSNotificationCenter * nc = NSNotificationCenter.defaultCenter; - [nc addObserver: self selector: @selector(resetInfoForTorrent:) name: @"ResetInspector" object: nil]; - [nc addObserver: self selector: @selector(updateInfoStats) name: @"UpdateStats" object: nil]; - [nc addObserver: self selector: @selector(updateOptions) name: @"UpdateOptions" object: nil]; + NSNotificationCenter* nc = NSNotificationCenter.defaultCenter; + [nc addObserver:self selector:@selector(resetInfoForTorrent:) name:@"ResetInspector" object:nil]; + [nc addObserver:self selector:@selector(updateInfoStats) name:@"UpdateStats" object:nil]; + [nc addObserver:self selector:@selector(updateOptions) name:@"UpdateOptions" object:nil]; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; - if ([fViewController respondsToSelector: @selector(saveViewSize)]) + if ([fViewController respondsToSelector:@selector(saveViewSize)]) + { [fViewController saveViewSize]; + } } -- (void) setInfoForTorrents: (NSArray *) torrents +- (void)setInfoForTorrents:(NSArray*)torrents { - if (fTorrents && [fTorrents isEqualToArray: torrents]) + if (fTorrents && [fTorrents isEqualToArray:torrents]) + { return; + } fTorrents = torrents; [self resetInfo]; } -- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame +- (NSRect)windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)defaultFrame { NSRect windowRect = window.frame; windowRect.size.width = window.minSize.width; return windowRect; } -- (void) windowWillClose: (NSNotification *) notification +- (void)windowWillClose:(NSNotification*)notification { if (fCurrentTabTag == TAB_FILE_TAG && ([QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible)) + { [[QLPreviewPanel sharedPreviewPanel] reloadData]; + } } -- (void) setTab: (id) sender +- (void)setTab:(id)sender { - const NSInteger oldTabTag = fCurrentTabTag; + NSInteger const oldTabTag = fCurrentTabTag; fCurrentTabTag = [fTabMatrix selectedTag]; if (fCurrentTabTag == oldTabTag) + { return; + } //take care of old view CGFloat oldHeight = 0; if (oldTabTag != INVALID) { //deselect old tab item - [(InfoTabButtonCell *)[fTabMatrix cellWithTag: oldTabTag] setSelectedTab: NO]; + [(InfoTabButtonCell*)[fTabMatrix cellWithTag:oldTabTag] setSelectedTab:NO]; - if ([fViewController respondsToSelector: @selector(saveViewSize)]) + if ([fViewController respondsToSelector:@selector(saveViewSize)]) + { [fViewController saveViewSize]; + } - if ([fViewController respondsToSelector: @selector(clearView)]) + if ([fViewController respondsToSelector:@selector(clearView)]) + { [fViewController clearView]; + } - NSView * oldView = fViewController.view; + NSView* oldView = fViewController.view; oldHeight = NSHeight(oldView.frame); //remove old view @@ -191,105 +215,105 @@ typedef NS_ENUM(unsigned int, tabTag) { } //set new tab item - NSString * identifier; + NSString* identifier; switch (fCurrentTabTag) { - case TAB_GENERAL_TAG: - if (!fGeneralViewController) - { - fGeneralViewController = [[InfoGeneralViewController alloc] init]; - [fGeneralViewController setInfoForTorrents: fTorrents]; - } + case TAB_GENERAL_TAG: + if (!fGeneralViewController) + { + fGeneralViewController = [[InfoGeneralViewController alloc] init]; + [fGeneralViewController setInfoForTorrents:fTorrents]; + } - fViewController = fGeneralViewController; - identifier = TAB_INFO_IDENT; - break; - case TAB_ACTIVITY_TAG: - if (!fActivityViewController) - { - fActivityViewController = [[InfoActivityViewController alloc] init]; - [fActivityViewController setInfoForTorrents: fTorrents]; - } + fViewController = fGeneralViewController; + identifier = TAB_INFO_IDENT; + break; + case TAB_ACTIVITY_TAG: + if (!fActivityViewController) + { + fActivityViewController = [[InfoActivityViewController alloc] init]; + [fActivityViewController setInfoForTorrents:fTorrents]; + } - fViewController = fActivityViewController; - identifier = TAB_ACTIVITY_IDENT; - break; - case TAB_TRACKERS_TAG: - if (!fTrackersViewController) - { - fTrackersViewController = [[InfoTrackersViewController alloc] init]; - [fTrackersViewController setInfoForTorrents: fTorrents]; - } + fViewController = fActivityViewController; + identifier = TAB_ACTIVITY_IDENT; + break; + case TAB_TRACKERS_TAG: + if (!fTrackersViewController) + { + fTrackersViewController = [[InfoTrackersViewController alloc] init]; + [fTrackersViewController setInfoForTorrents:fTorrents]; + } - fViewController = fTrackersViewController; - identifier = TAB_TRACKER_IDENT; - break; - case TAB_PEERS_TAG: - if (!fPeersViewController) - { - fPeersViewController = [[InfoPeersViewController alloc] init]; - [fPeersViewController setInfoForTorrents: fTorrents]; - } + fViewController = fTrackersViewController; + identifier = TAB_TRACKER_IDENT; + break; + case TAB_PEERS_TAG: + if (!fPeersViewController) + { + fPeersViewController = [[InfoPeersViewController alloc] init]; + [fPeersViewController setInfoForTorrents:fTorrents]; + } - fViewController = fPeersViewController; - identifier = TAB_PEERS_IDENT; - break; - case TAB_FILE_TAG: - if (!fFileViewController) - { - fFileViewController = [[InfoFileViewController alloc] init]; - [fFileViewController setInfoForTorrents: fTorrents]; - } + fViewController = fPeersViewController; + identifier = TAB_PEERS_IDENT; + break; + case TAB_FILE_TAG: + if (!fFileViewController) + { + fFileViewController = [[InfoFileViewController alloc] init]; + [fFileViewController setInfoForTorrents:fTorrents]; + } - fViewController = fFileViewController; - identifier = TAB_FILES_IDENT; - break; - case TAB_OPTIONS_TAG: - if (!fOptionsViewController) - { - fOptionsViewController = [[InfoOptionsViewController alloc] init]; - [fOptionsViewController setInfoForTorrents: fTorrents]; - } + fViewController = fFileViewController; + identifier = TAB_FILES_IDENT; + break; + case TAB_OPTIONS_TAG: + if (!fOptionsViewController) + { + fOptionsViewController = [[InfoOptionsViewController alloc] init]; + [fOptionsViewController setInfoForTorrents:fTorrents]; + } - fViewController = fOptionsViewController; - identifier = TAB_OPTIONS_IDENT; - break; - default: - NSAssert1(NO, @"Unknown info tab selected: %ld", fCurrentTabTag); - return; + fViewController = fOptionsViewController; + identifier = TAB_OPTIONS_IDENT; + break; + default: + NSAssert1(NO, @"Unknown info tab selected: %ld", fCurrentTabTag); + return; } - [NSUserDefaults.standardUserDefaults setObject: identifier forKey: @"InspectorSelected"]; + [NSUserDefaults.standardUserDefaults setObject:identifier forKey:@"InspectorSelected"]; - NSWindow * window = self.window; + NSWindow* window = self.window; - window.title = [NSString stringWithFormat: @"%@ - %@", fViewController.title, - NSLocalizedString(@"Torrent Inspector", "Inspector -> title")]; + window.title = [NSString + stringWithFormat:@"%@ - %@", fViewController.title, NSLocalizedString(@"Torrent Inspector", "Inspector -> title")]; //selected tab item - [(InfoTabButtonCell *)fTabMatrix.selectedCell setSelectedTab: YES]; + [(InfoTabButtonCell*)fTabMatrix.selectedCell setSelectedTab:YES]; - NSView * view = fViewController.view; + NSView* view = fViewController.view; [fViewController updateInfo]; NSRect windowRect = window.frame, viewRect = view.frame; - const CGFloat difference = NSHeight(viewRect) - oldHeight; + CGFloat const difference = NSHeight(viewRect) - oldHeight; windowRect.origin.y -= difference; windowRect.size.height += difference; - const CGFloat minWindowWidth = MAX(fMinWindowWidth, view.fittingSize.width); + CGFloat const minWindowWidth = MAX(fMinWindowWidth, view.fittingSize.width); windowRect.size.width = MAX(NSWidth(windowRect), minWindowWidth); - if ([fViewController respondsToSelector: @selector(saveViewSize)]) //a little bit hacky, but avoids requiring an extra method + if ([fViewController respondsToSelector:@selector(saveViewSize)]) //a little bit hacky, but avoids requiring an extra method { if (window.screen) { - const CGFloat screenHeight = NSHeight(window.screen.visibleFrame); + CGFloat const screenHeight = NSHeight(window.screen.visibleFrame); if (NSHeight(windowRect) > screenHeight) { - const CGFloat difference = screenHeight - NSHeight(windowRect); + CGFloat const difference = screenHeight - NSHeight(windowRect); windowRect.origin.y -= difference; windowRect.size.height += difference; @@ -309,140 +333,160 @@ typedef NS_ENUM(unsigned int, tabTag) { viewRect.size.width = NSWidth(windowRect); view.frame = viewRect; - [window setFrame: windowRect display: YES animate: oldTabTag != INVALID]; - [window.contentView addSubview: view]; + [window setFrame:windowRect display:YES animate:oldTabTag != INVALID]; + [window.contentView addSubview:view]; - [window.contentView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"H:|-0-[view]-0-|" - options: 0 - metrics: nil - views: @{ @"view": view }]]; - [window.contentView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"V:[tabs]-0-[view]-0-|" - options: 0 - metrics: nil - views: @{ @"tabs": fTabMatrix, @"view": view }]]; + [window.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[view]-0-|" options:0 metrics:nil + views:@{ @"view" : view }]]; + [window.contentView + addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[tabs]-0-[view]-0-|" options:0 metrics:nil + views:@{ @"tabs" : fTabMatrix, @"view" : view }]]; - if ((fCurrentTabTag == TAB_FILE_TAG || oldTabTag == TAB_FILE_TAG) - && ([QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible)) + if ((fCurrentTabTag == TAB_FILE_TAG || oldTabTag == TAB_FILE_TAG) && + ([QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible)) + { [[QLPreviewPanel sharedPreviewPanel] reloadData]; + } } -- (void) setNextTab +- (void)setNextTab { - NSInteger tag = [fTabMatrix selectedTag]+1; + NSInteger tag = [fTabMatrix selectedTag] + 1; if (tag >= fTabMatrix.numberOfColumns) + { tag = 0; + } - [fTabMatrix selectCellWithTag: tag]; - [self setTab: nil]; + [fTabMatrix selectCellWithTag:tag]; + [self setTab:nil]; } -- (void) setPreviousTab +- (void)setPreviousTab { - NSInteger tag = [fTabMatrix selectedTag]-1; + NSInteger tag = [fTabMatrix selectedTag] - 1; if (tag < 0) - tag = fTabMatrix.numberOfColumns-1; + { + tag = fTabMatrix.numberOfColumns - 1; + } - [fTabMatrix selectCellWithTag: tag]; - [self setTab: nil]; + [fTabMatrix selectCellWithTag:tag]; + [self setTab:nil]; } -- (void) swipeWithEvent: (NSEvent *) event +- (void)swipeWithEvent:(NSEvent*)event { if (event.deltaX < 0.0) + { [self setNextTab]; + } else if (event.deltaX > 0.0) + { [self setPreviousTab]; + } } -- (void) updateInfoStats +- (void)updateInfoStats { [fViewController updateInfo]; } -- (void) updateOptions +- (void)updateOptions { [fOptionsViewController updateOptions]; } -- (NSArray *) quickLookURLs +- (NSArray*)quickLookURLs { return fFileViewController.quickLookURLs; } -- (BOOL) canQuickLook +- (BOOL)canQuickLook { if (fCurrentTabTag != TAB_FILE_TAG || !self.window.visible) + { return NO; + } return fFileViewController.canQuickLook; } -- (NSRect) quickLookSourceFrameForPreviewItem: (id ) item +- (NSRect)quickLookSourceFrameForPreviewItem:(id)item { - return [fFileViewController quickLookSourceFrameForPreviewItem: item]; + return [fFileViewController quickLookSourceFrameForPreviewItem:item]; } @end @implementation InfoWindowController (Private) -- (void) resetInfo +- (void)resetInfo { - const NSUInteger numberSelected = fTorrents.count; + NSUInteger const numberSelected = fTorrents.count; if (numberSelected != 1) { if (numberSelected > 0) { - fImageView.image = [NSImage imageNamed: NSImageNameMultipleDocuments]; + fImageView.image = [NSImage imageNamed:NSImageNameMultipleDocuments]; - fNameField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"%@ Torrents Selected", - "Inspector -> selected torrents"), - [NSString formattedUInteger: numberSelected]]; + fNameField.stringValue = [NSString stringWithFormat:NSLocalizedString(@"%@ Torrents Selected", "Inspector -> selected torrents"), + [NSString formattedUInteger:numberSelected]]; fNameField.hidden = NO; uint64_t size = 0; NSUInteger fileCount = 0, magnetCount = 0; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) { size += torrent.size; fileCount += torrent.fileCount; if (torrent.magnet) + { ++magnetCount; + } } - NSMutableArray * fileStrings = [NSMutableArray arrayWithCapacity: 2]; + NSMutableArray* fileStrings = [NSMutableArray arrayWithCapacity:2]; if (fileCount > 0) { - NSString * fileString; + NSString* fileString; if (fileCount == 1) + { fileString = NSLocalizedString(@"1 file", "Inspector -> selected torrents"); + } else - fileString = [NSString stringWithFormat: NSLocalizedString(@"%@ files", "Inspector -> selected torrents"), - [NSString formattedUInteger: fileCount]]; - [fileStrings addObject: fileString]; + { + fileString = [NSString stringWithFormat:NSLocalizedString(@"%@ files", "Inspector -> selected torrents"), + [NSString formattedUInteger:fileCount]]; + } + [fileStrings addObject:fileString]; } if (magnetCount > 0) { - NSString * magnetString; + NSString* magnetString; if (magnetCount == 1) + { magnetString = NSLocalizedString(@"1 magnetized transfer", "Inspector -> selected torrents"); + } else - magnetString = [NSString stringWithFormat: NSLocalizedString(@"%@ magnetized transfers", - "Inspector -> selected torrents"), [NSString formattedUInteger: magnetCount]]; - [fileStrings addObject: magnetString]; + { + magnetString = [NSString stringWithFormat:NSLocalizedString(@"%@ magnetized transfers", "Inspector -> selected torrents"), + [NSString formattedUInteger:magnetCount]]; + } + [fileStrings addObject:magnetString]; } - NSString * fileString = [fileStrings componentsJoinedByString: @" + "]; + NSString* fileString = [fileStrings componentsJoinedByString:@" + "]; if (magnetCount < numberSelected) { - fBasicInfoField.stringValue = [NSString stringWithFormat: @"%@, %@", fileString, - [NSString stringWithFormat: NSLocalizedString(@"%@ total", "Inspector -> selected torrents"), - [NSString stringForFileSize: size]]]; + fBasicInfoField.stringValue = [NSString + stringWithFormat:@"%@, %@", + fileString, + [NSString stringWithFormat:NSLocalizedString(@"%@ total", "Inspector -> selected torrents"), + [NSString stringForFileSize:size]]]; - NSByteCountFormatter * formatter = [[NSByteCountFormatter alloc] init]; + NSByteCountFormatter* formatter = [[NSByteCountFormatter alloc] init]; formatter.allowedUnits = NSByteCountFormatterUseBytes; - fBasicInfoField.toolTip = [formatter stringFromByteCount: size]; + fBasicInfoField.toolTip = [formatter stringFromByteCount:size]; } else { @@ -455,7 +499,7 @@ typedef NS_ENUM(unsigned int, tabTag) { } else { - fImageView.image = [NSImage imageNamed: NSImageNameApplicationIcon]; + fImageView.image = [NSImage imageNamed:NSImageNameApplicationIcon]; fNoneSelectedField.hidden = NO; fNameField.hidden = YES; @@ -466,34 +510,38 @@ typedef NS_ENUM(unsigned int, tabTag) { } else { - Torrent * torrent = fTorrents[0]; + Torrent* torrent = fTorrents[0]; fImageView.image = torrent.icon; - NSString * name = torrent.name; + NSString* name = torrent.name; fNameField.stringValue = name; fNameField.toolTip = name; fNameField.hidden = NO; if (!torrent.magnet) { - NSString * basicString = [NSString stringForFileSize: torrent.size]; + NSString* basicString = [NSString stringForFileSize:torrent.size]; if (torrent.folder) { - NSString * fileString; - const NSUInteger fileCount = torrent.fileCount; + NSString* fileString; + NSUInteger const fileCount = torrent.fileCount; if (fileCount == 1) + { fileString = NSLocalizedString(@"1 file", "Inspector -> selected torrents"); + } else - fileString= [NSString stringWithFormat: NSLocalizedString(@"%@ files", "Inspector -> selected torrents"), - [NSString formattedUInteger: fileCount]]; - basicString = [NSString stringWithFormat: @"%@, %@", fileString, basicString]; + { + fileString = [NSString stringWithFormat:NSLocalizedString(@"%@ files", "Inspector -> selected torrents"), + [NSString formattedUInteger:fileCount]]; + } + basicString = [NSString stringWithFormat:@"%@, %@", fileString, basicString]; } fBasicInfoField.stringValue = basicString; - NSByteCountFormatter * formatter = [[NSByteCountFormatter alloc] init]; + NSByteCountFormatter* formatter = [[NSByteCountFormatter alloc] init]; formatter.allowedUnits = NSByteCountFormatterUseBytes; - fBasicInfoField.toolTip = [formatter stringFromByteCount: torrent.size]; + fBasicInfoField.toolTip = [formatter stringFromByteCount:torrent.size]; } else { @@ -505,21 +553,23 @@ typedef NS_ENUM(unsigned int, tabTag) { fNoneSelectedField.hidden = YES; } - [fGeneralViewController setInfoForTorrents: fTorrents]; - [fActivityViewController setInfoForTorrents: fTorrents]; - [fTrackersViewController setInfoForTorrents: fTorrents]; - [fPeersViewController setInfoForTorrents: fTorrents]; - [fFileViewController setInfoForTorrents: fTorrents]; - [fOptionsViewController setInfoForTorrents: fTorrents]; + [fGeneralViewController setInfoForTorrents:fTorrents]; + [fActivityViewController setInfoForTorrents:fTorrents]; + [fTrackersViewController setInfoForTorrents:fTorrents]; + [fPeersViewController setInfoForTorrents:fTorrents]; + [fFileViewController setInfoForTorrents:fTorrents]; + [fOptionsViewController setInfoForTorrents:fTorrents]; [fViewController updateInfo]; } -- (void) resetInfoForTorrent: (NSNotification *) notification +- (void)resetInfoForTorrent:(NSNotification*)notification { - Torrent * torrent = notification.userInfo[@"Torrent"]; - if (fTorrents && (!torrent || [fTorrents containsObject: torrent])) + Torrent* torrent = notification.userInfo[@"Torrent"]; + if (fTorrents && (!torrent || [fTorrents containsObject:torrent])) + { [self resetInfo]; + } } @end diff --git a/macosx/MessageWindowController.h b/macosx/MessageWindowController.h index ebe1c7a49..a3b06f965 100644 --- a/macosx/MessageWindowController.h +++ b/macosx/MessageWindowController.h @@ -24,27 +24,29 @@ @interface MessageWindowController : NSWindowController { - IBOutlet NSTableView * fMessageTable; + IBOutlet NSTableView* fMessageTable; - IBOutlet NSPopUpButton * fLevelButton; - IBOutlet NSButton * fSaveButton, * fClearButton; - IBOutlet NSSearchField * fFilterField; + IBOutlet NSPopUpButton* fLevelButton; + IBOutlet NSButton* fSaveButton; + IBOutlet NSButton* fClearButton; + IBOutlet NSSearchField* fFilterField; - NSMutableArray * fMessages, * fDisplayedMessages; + NSMutableArray* fMessages; + NSMutableArray* fDisplayedMessages; - NSDictionary * fAttributes; + NSDictionary* fAttributes; - NSTimer * fTimer; + NSTimer* fTimer; - NSLock * fLock; + NSLock* fLock; } -- (void) updateLog: (NSTimer *) timer; +- (void)updateLog:(NSTimer*)timer; -- (void) changeLevel: (id) sender; -- (void) changeFilter: (id) sender; -- (void) clearLog: (id) sender; +- (void)changeLevel:(id)sender; +- (void)changeFilter:(id)sender; +- (void)clearLog:(id)sender; -- (void) writeToFile: (id) sender; +- (void)writeToFile:(id)sender; @end diff --git a/macosx/MessageWindowController.m b/macosx/MessageWindowController.m index 8cb8f5818..c610b8133 100644 --- a/macosx/MessageWindowController.m +++ b/macosx/MessageWindowController.m @@ -30,56 +30,54 @@ #import "NSStringAdditions.h" #define LEVEL_ERROR 0 -#define LEVEL_INFO 1 +#define LEVEL_INFO 1 #define LEVEL_DEBUG 2 -#define UPDATE_SECONDS 0.75 +#define UPDATE_SECONDS 0.75 @interface MessageWindowController (Private) -- (void) resizeColumn; -- (BOOL) shouldIncludeMessageForFilter: (NSString *) filterString message: (NSDictionary *) message; -- (void) updateListForFilter; -- (NSString *) stringForMessage: (NSDictionary *) message; +- (void)resizeColumn; +- (BOOL)shouldIncludeMessageForFilter:(NSString*)filterString message:(NSDictionary*)message; +- (void)updateListForFilter; +- (NSString*)stringForMessage:(NSDictionary*)message; @end @implementation MessageWindowController -- (instancetype) init +- (instancetype)init { - return [super initWithWindowNibName: @"MessageWindow"]; + return [super initWithWindowNibName:@"MessageWindow"]; } -- (void) awakeFromNib +- (void)awakeFromNib { - NSWindow * window = self.window; + NSWindow* window = self.window; window.frameAutosaveName = @"MessageWindowFrame"; - [window setFrameUsingName: @"MessageWindowFrame"]; + [window setFrameUsingName:@"MessageWindowFrame"]; window.restorationClass = [self class]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(resizeColumn) - name: NSTableViewColumnDidResizeNotification object: fMessageTable]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(resizeColumn) + name:NSTableViewColumnDidResizeNotification + object:fMessageTable]; - [window setContentBorderThickness: NSMinY(fMessageTable.enclosingScrollView.frame) forEdge: NSMinYEdge]; + [window setContentBorderThickness:NSMinY(fMessageTable.enclosingScrollView.frame) forEdge:NSMinYEdge]; self.window.title = NSLocalizedString(@"Message Log", "Message window -> title"); //set images and text for popup button items - [fLevelButton itemAtIndex: LEVEL_ERROR].title = NSLocalizedString(@"Error", "Message window -> level string"); - [fLevelButton itemAtIndex: LEVEL_INFO].title = NSLocalizedString(@"Info", "Message window -> level string"); - [fLevelButton itemAtIndex: LEVEL_DEBUG].title = NSLocalizedString(@"Debug", "Message window -> level string"); + [fLevelButton itemAtIndex:LEVEL_ERROR].title = NSLocalizedString(@"Error", "Message window -> level string"); + [fLevelButton itemAtIndex:LEVEL_INFO].title = NSLocalizedString(@"Info", "Message window -> level string"); + [fLevelButton itemAtIndex:LEVEL_DEBUG].title = NSLocalizedString(@"Debug", "Message window -> level string"); - const CGFloat levelButtonOldWidth = NSWidth(fLevelButton.frame); + CGFloat const levelButtonOldWidth = NSWidth(fLevelButton.frame); [fLevelButton sizeToFit]; //set table column text - [fMessageTable tableColumnWithIdentifier: @"Date"].headerCell.title = NSLocalizedString(@"Date", - "Message window -> table column"); - [fMessageTable tableColumnWithIdentifier: @"Name"].headerCell.title = NSLocalizedString(@"Process", - "Message window -> table column"); - [fMessageTable tableColumnWithIdentifier: @"Message"].headerCell.title = NSLocalizedString(@"Message", - "Message window -> table column"); + [fMessageTable tableColumnWithIdentifier:@"Date"].headerCell.title = NSLocalizedString(@"Date", "Message window -> table column"); + [fMessageTable tableColumnWithIdentifier:@"Name"].headerCell.title = NSLocalizedString(@"Process", "Message window -> table column"); + [fMessageTable tableColumnWithIdentifier:@"Message"].headerCell.title = NSLocalizedString(@"Message", "Message window -> table column"); //set and size buttons fSaveButton.title = [NSLocalizedString(@"Save", "Message window -> save button") stringByAppendingEllipsis]; @@ -90,7 +88,7 @@ saveButtonFrame.origin.x += NSWidth(fLevelButton.frame) - levelButtonOldWidth; fSaveButton.frame = saveButtonFrame; - const CGFloat oldClearButtonWidth = fClearButton.frame.size.width; + CGFloat const oldClearButtonWidth = fClearButton.frame.size.width; fClearButton.title = NSLocalizedString(@"Clear", "Message window -> save button"); [fClearButton sizeToFit]; @@ -100,29 +98,29 @@ clearButtonFrame.origin.x -= NSWidth(clearButtonFrame) - oldClearButtonWidth; fClearButton.frame = clearButtonFrame; - [fFilterField.cell setPlaceholderString: NSLocalizedString(@"Filter", "Message window -> filter field")]; + [fFilterField.cell setPlaceholderString:NSLocalizedString(@"Filter", "Message window -> filter field")]; NSRect filterButtonFrame = fFilterField.frame; filterButtonFrame.origin.x -= NSWidth(clearButtonFrame) - oldClearButtonWidth; fFilterField.frame = filterButtonFrame; - fAttributes = [[[fMessageTable tableColumnWithIdentifier: @"Message"].dataCell attributedStringValue] - attributesAtIndex: 0 effectiveRange: NULL]; + fAttributes = [[[fMessageTable tableColumnWithIdentifier:@"Message"].dataCell attributedStringValue] attributesAtIndex:0 + effectiveRange:NULL]; //select proper level in popup button - switch ([NSUserDefaults.standardUserDefaults integerForKey: @"MessageLevel"]) + switch ([NSUserDefaults.standardUserDefaults integerForKey:@"MessageLevel"]) { - case TR_LOG_ERROR: - [fLevelButton selectItemAtIndex: LEVEL_ERROR]; - break; - case TR_LOG_INFO: - [fLevelButton selectItemAtIndex: LEVEL_INFO]; - break; - case TR_LOG_DEBUG: - [fLevelButton selectItemAtIndex: LEVEL_DEBUG]; - break; - default: //safety - [NSUserDefaults.standardUserDefaults setInteger: TR_LOG_ERROR forKey: @"MessageLevel"]; - [fLevelButton selectItemAtIndex: LEVEL_ERROR]; + case TR_LOG_ERROR: + [fLevelButton selectItemAtIndex:LEVEL_ERROR]; + break; + case TR_LOG_INFO: + [fLevelButton selectItemAtIndex:LEVEL_INFO]; + break; + case TR_LOG_DEBUG: + [fLevelButton selectItemAtIndex:LEVEL_DEBUG]; + break; + default: //safety + [NSUserDefaults.standardUserDefaults setInteger:TR_LOG_ERROR forKey:@"MessageLevel"]; + [fLevelButton selectItemAtIndex:LEVEL_ERROR]; } fMessages = [[NSMutableArray alloc] init]; @@ -131,218 +129,238 @@ fLock = [[NSLock alloc] init]; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; [fTimer invalidate]; } -- (void) windowDidBecomeKey: (NSNotification *) notification +- (void)windowDidBecomeKey:(NSNotification*)notification { if (!fTimer) { - fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_SECONDS target: self selector: @selector(updateLog:) userInfo: nil repeats: YES]; - [self updateLog: nil]; + fTimer = [NSTimer scheduledTimerWithTimeInterval:UPDATE_SECONDS target:self selector:@selector(updateLog:) userInfo:nil + repeats:YES]; + [self updateLog:nil]; } } -- (void) windowWillClose: (id)sender +- (void)windowWillClose:(id)sender { [fTimer invalidate]; fTimer = nil; } -+ (void) restoreWindowWithIdentifier: (NSString *) identifier state: (NSCoder *) state completionHandler: (void (^)(NSWindow *, NSError *)) completionHandler ++ (void)restoreWindowWithIdentifier:(NSString*)identifier + state:(NSCoder*)state + completionHandler:(void (^)(NSWindow*, NSError*))completionHandler { - NSAssert1([identifier isEqualToString: @"MessageWindow"], @"Trying to restore unexpected identifier %@", identifier); + NSAssert1([identifier isEqualToString:@"MessageWindow"], @"Trying to restore unexpected identifier %@", identifier); - NSWindow * window = ((Controller *)NSApp.delegate).messageWindowController.window; + NSWindow* window = ((Controller*)NSApp.delegate).messageWindowController.window; completionHandler(window, nil); } -- (void) window: (NSWindow *) window didDecodeRestorableState: (NSCoder *) coder +- (void)window:(NSWindow*)window didDecodeRestorableState:(NSCoder*)coder { [fTimer invalidate]; - fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_SECONDS target: self selector: @selector(updateLog:) userInfo: nil repeats: YES]; - [self updateLog: nil]; + fTimer = [NSTimer scheduledTimerWithTimeInterval:UPDATE_SECONDS target:self selector:@selector(updateLog:) userInfo:nil + repeats:YES]; + [self updateLog:nil]; } -- (void) updateLog: (NSTimer *) timer +- (void)updateLog:(NSTimer*)timer { - tr_log_message * messages; + tr_log_message* messages; if ((messages = tr_logGetQueue()) == NULL) + { return; + } [fLock lock]; static NSUInteger currentIndex = 0; - NSScroller * scroller = fMessageTable.enclosingScrollView.verticalScroller; - const BOOL shouldScroll = currentIndex == 0 || scroller.floatValue == 1.0 || scroller.hidden - || scroller.knobProportion == 1.0; + NSScroller* scroller = fMessageTable.enclosingScrollView.verticalScroller; + BOOL const shouldScroll = currentIndex == 0 || scroller.floatValue == 1.0 || scroller.hidden || scroller.knobProportion == 1.0; - const NSInteger maxLevel = [NSUserDefaults.standardUserDefaults integerForKey: @"MessageLevel"]; - NSString * filterString = fFilterField.stringValue; + NSInteger const maxLevel = [NSUserDefaults.standardUserDefaults integerForKey:@"MessageLevel"]; + NSString* filterString = fFilterField.stringValue; BOOL changed = NO; - for (tr_log_message * currentMessage = messages; currentMessage != NULL; currentMessage = currentMessage->next) + for (tr_log_message* currentMessage = messages; currentMessage != NULL; currentMessage = currentMessage->next) { - NSString * name = currentMessage->name != NULL ? @(currentMessage->name) - : NSProcessInfo.processInfo.processName; + NSString* name = currentMessage->name != NULL ? @(currentMessage->name) : NSProcessInfo.processInfo.processName; - NSString * file = [(@(currentMessage->file)).lastPathComponent stringByAppendingFormat: @":%d", - currentMessage->line]; + NSString* file = [(@(currentMessage->file)).lastPathComponent stringByAppendingFormat:@":%d", currentMessage->line]; - NSDictionary * message = @{ - @"Message": @(currentMessage->message), - @"Date": [NSDate dateWithTimeIntervalSince1970: currentMessage->when], - @"Index": @(currentIndex++), //more accurate when sorting by date - @"Level": @(currentMessage->level), - @"Name": name, - @"File": file}; - [fMessages addObject: message]; + NSDictionary* message = @{ + @"Message" : @(currentMessage->message), + @"Date" : [NSDate dateWithTimeIntervalSince1970:currentMessage->when], + @"Index" : @(currentIndex++), //more accurate when sorting by date + @"Level" : @(currentMessage->level), + @"Name" : name, + @"File" : file + }; + [fMessages addObject:message]; - if (currentMessage->level <= maxLevel && [self shouldIncludeMessageForFilter: filterString message: message]) + if (currentMessage->level <= maxLevel && [self shouldIncludeMessageForFilter:filterString message:message]) { - [fDisplayedMessages addObject: message]; + [fDisplayedMessages addObject:message]; changed = YES; } } if (fMessages.count > TR_LOG_MAX_QUEUE_LENGTH) { - const NSUInteger oldCount = fDisplayedMessages.count; + NSUInteger const oldCount = fDisplayedMessages.count; - NSIndexSet * removeIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fMessages.count-TR_LOG_MAX_QUEUE_LENGTH)]; - NSArray * itemsToRemove = [fMessages objectsAtIndexes: removeIndexes]; + NSIndexSet* removeIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fMessages.count - TR_LOG_MAX_QUEUE_LENGTH)]; + NSArray* itemsToRemove = [fMessages objectsAtIndexes:removeIndexes]; - [fMessages removeObjectsAtIndexes: removeIndexes]; - [fDisplayedMessages removeObjectsInArray: itemsToRemove]; + [fMessages removeObjectsAtIndexes:removeIndexes]; + [fDisplayedMessages removeObjectsInArray:itemsToRemove]; changed |= oldCount > fDisplayedMessages.count; } if (changed) { - [fDisplayedMessages sortUsingDescriptors: fMessageTable.sortDescriptors]; + [fDisplayedMessages sortUsingDescriptors:fMessageTable.sortDescriptors]; [fMessageTable reloadData]; if (shouldScroll) - [fMessageTable scrollRowToVisible: fMessageTable.numberOfRows-1]; + [fMessageTable scrollRowToVisible:fMessageTable.numberOfRows - 1]; } [fLock unlock]; - tr_logFreeQueue (messages); + tr_logFreeQueue(messages); } -- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView +- (NSInteger)numberOfRowsInTableView:(NSTableView*)tableView { return fDisplayedMessages.count; } -- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (NSInteger) row +- (id)tableView:(NSTableView*)tableView objectValueForTableColumn:(NSTableColumn*)column row:(NSInteger)row { - NSString * ident = column.identifier; - NSDictionary * message = fDisplayedMessages[row]; + NSString* ident = column.identifier; + NSDictionary* message = fDisplayedMessages[row]; - if ([ident isEqualToString: @"Date"]) - return message[@"Date"]; - else if ([ident isEqualToString: @"Level"]) + if ([ident isEqualToString:@"Date"]) { - const NSInteger level = [message[@"Level"] integerValue]; + return message[@"Date"]; + } + else if ([ident isEqualToString:@"Level"]) + { + NSInteger const level = [message[@"Level"] integerValue]; switch (level) { - case TR_LOG_ERROR: - return [NSImage imageNamed: @"RedDotFlat"]; - case TR_LOG_INFO: - return [NSImage imageNamed: @"YellowDotFlat"]; - case TR_LOG_DEBUG: - return [NSImage imageNamed: @"PurpleDotFlat"]; - default: - NSAssert1(NO, @"Unknown message log level: %ld", level); - return nil; + case TR_LOG_ERROR: + return [NSImage imageNamed:@"RedDotFlat"]; + case TR_LOG_INFO: + return [NSImage imageNamed:@"YellowDotFlat"]; + case TR_LOG_DEBUG: + return [NSImage imageNamed:@"PurpleDotFlat"]; + default: + NSAssert1(NO, @"Unknown message log level: %ld", level); + return nil; } } - else if ([ident isEqualToString: @"Name"]) + else if ([ident isEqualToString:@"Name"]) + { return message[@"Name"]; + } else + { return message[@"Message"]; + } } #warning don't cut off end -- (CGFloat) tableView: (NSTableView *) tableView heightOfRow: (NSInteger) row +- (CGFloat)tableView:(NSTableView*)tableView heightOfRow:(NSInteger)row { - NSString * message = fDisplayedMessages[row][@"Message"]; + NSString* message = fDisplayedMessages[row][@"Message"]; - NSTableColumn * column = [tableView tableColumnWithIdentifier: @"Message"]; - const CGFloat count = floorf([message sizeWithAttributes: fAttributes].width / column.width); + NSTableColumn* column = [tableView tableColumnWithIdentifier:@"Message"]; + CGFloat const count = floorf([message sizeWithAttributes:fAttributes].width / column.width); return tableView.rowHeight * (count + 1.0); } -- (void) tableView: (NSTableView *) tableView sortDescriptorsDidChange: (NSArray *) oldDescriptors +- (void)tableView:(NSTableView*)tableView sortDescriptorsDidChange:(NSArray*)oldDescriptors { - [fDisplayedMessages sortUsingDescriptors: fMessageTable.sortDescriptors]; + [fDisplayedMessages sortUsingDescriptors:fMessageTable.sortDescriptors]; [fMessageTable reloadData]; } -- (NSString *) tableView: (NSTableView *) tableView toolTipForCell: (NSCell *) cell rect: (NSRectPointer) rect - tableColumn: (NSTableColumn *) column row: (NSInteger) row mouseLocation: (NSPoint) mouseLocation +- (NSString*)tableView:(NSTableView*)tableView + toolTipForCell:(NSCell*)cell + rect:(NSRectPointer)rect + tableColumn:(NSTableColumn*)column + row:(NSInteger)row + mouseLocation:(NSPoint)mouseLocation { - NSDictionary * message = fDisplayedMessages[row]; + NSDictionary* message = fDisplayedMessages[row]; return message[@"File"]; } -- (void) copy: (id) sender +- (void)copy:(id)sender { - NSIndexSet * indexes = fMessageTable.selectedRowIndexes; - NSMutableArray * messageStrings = [NSMutableArray arrayWithCapacity: indexes.count]; + NSIndexSet* indexes = fMessageTable.selectedRowIndexes; + NSMutableArray* messageStrings = [NSMutableArray arrayWithCapacity:indexes.count]; - for (NSDictionary * message in [fDisplayedMessages objectsAtIndexes: indexes]) - [messageStrings addObject: [self stringForMessage: message]]; + for (NSDictionary* message in [fDisplayedMessages objectsAtIndexes:indexes]) + { + [messageStrings addObject:[self stringForMessage:message]]; + } - NSString * messageString = [messageStrings componentsJoinedByString: @"\n"]; + NSString* messageString = [messageStrings componentsJoinedByString:@"\n"]; - NSPasteboard * pb = NSPasteboard.generalPasteboard; + NSPasteboard* pb = NSPasteboard.generalPasteboard; [pb clearContents]; - [pb writeObjects: @[messageString]]; + [pb writeObjects:@[ messageString ]]; } -- (BOOL) validateMenuItem: (NSMenuItem *) menuItem +- (BOOL)validateMenuItem:(NSMenuItem*)menuItem { SEL action = menuItem.action; if (action == @selector(copy:)) + { return fMessageTable.numberOfSelectedRows > 0; + } return YES; } -- (void) changeLevel: (id) sender +- (void)changeLevel:(id)sender { NSInteger level; switch (fLevelButton.indexOfSelectedItem) { - case LEVEL_ERROR: - level = TR_LOG_ERROR; - break; - case LEVEL_INFO: - level = TR_LOG_INFO; - break; - case LEVEL_DEBUG: - level = TR_LOG_DEBUG; - break; - default: - NSAssert1(NO, @"Unknown message log level: %ld", [fLevelButton indexOfSelectedItem]); - level = TR_LOG_INFO; + case LEVEL_ERROR: + level = TR_LOG_ERROR; + break; + case LEVEL_INFO: + level = TR_LOG_INFO; + break; + case LEVEL_DEBUG: + level = TR_LOG_DEBUG; + break; + default: + NSAssert1(NO, @"Unknown message log level: %ld", [fLevelButton indexOfSelectedItem]); + level = TR_LOG_INFO; } - if ([NSUserDefaults.standardUserDefaults integerForKey: @"MessageLevel"] == level) + if ([NSUserDefaults.standardUserDefaults integerForKey:@"MessageLevel"] == level) + { return; + } - [NSUserDefaults.standardUserDefaults setInteger: level forKey: @"MessageLevel"]; + [NSUserDefaults.standardUserDefaults setInteger:level forKey:@"MessageLevel"]; [fLock lock]; @@ -351,7 +369,7 @@ [fLock unlock]; } -- (void) changeFilter: (id) sender +- (void)changeFilter:(id)sender { [fLock lock]; @@ -360,14 +378,15 @@ [fLock unlock]; } -- (void) clearLog: (id) sender +- (void)clearLog:(id)sender { [fLock lock]; [fMessages removeAllObjects]; [fMessageTable beginUpdates]; - [fMessageTable removeRowsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fDisplayedMessages.count)] withAnimation: NSTableViewAnimationSlideLeft]; + [fMessageTable removeRowsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fDisplayedMessages.count)] + withAnimation:NSTableViewAnimationSlideLeft]; [fDisplayedMessages removeAllObjects]; @@ -376,37 +395,39 @@ [fLock unlock]; } -- (void) writeToFile: (id) sender +- (void)writeToFile:(id)sender { - NSSavePanel * panel = [NSSavePanel savePanel]; - panel.allowedFileTypes = @[@"txt"]; + NSSavePanel* panel = [NSSavePanel savePanel]; + panel.allowedFileTypes = @[ @"txt" ]; panel.canSelectHiddenExtension = YES; panel.nameFieldStringValue = NSLocalizedString(@"untitled", "Save log panel -> default file name"); - [panel beginSheetModalForWindow: self.window completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) { //make the array sorted by date - NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey: @"Index" ascending: YES]; - NSArray * descriptors = @[descriptor]; - NSArray * sortedMessages = [fDisplayedMessages sortedArrayUsingDescriptors: descriptors]; + NSSortDescriptor* descriptor = [NSSortDescriptor sortDescriptorWithKey:@"Index" ascending:YES]; + NSArray* descriptors = @[ descriptor ]; + NSArray* sortedMessages = [fDisplayedMessages sortedArrayUsingDescriptors:descriptors]; //create the text to output - NSMutableArray * messageStrings = [NSMutableArray arrayWithCapacity: sortedMessages.count]; - for (NSDictionary * message in sortedMessages) - [messageStrings addObject: [self stringForMessage: message]]; - - NSString * fileString = [messageStrings componentsJoinedByString: @"\n"]; - - if (![fileString writeToFile: panel.URL.path atomically: YES encoding: NSUTF8StringEncoding error: nil]) + NSMutableArray* messageStrings = [NSMutableArray arrayWithCapacity:sortedMessages.count]; + for (NSDictionary* message in sortedMessages) { - NSAlert * alert = [[NSAlert alloc] init]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Save log alert panel -> button")]; + [messageStrings addObject:[self stringForMessage:message]]; + } + + NSString* fileString = [messageStrings componentsJoinedByString:@"\n"]; + + if (![fileString writeToFile:panel.URL.path atomically:YES encoding:NSUTF8StringEncoding error:nil]) + { + NSAlert* alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Save log alert panel -> button")]; alert.messageText = NSLocalizedString(@"Log Could Not Be Saved", "Save log alert panel -> title"); - alert.informativeText = [NSString stringWithFormat: - NSLocalizedString(@"There was a problem creating the file \"%@\".", - "Save log alert panel -> message"), panel.URL.path.lastPathComponent]; + alert.informativeText = [NSString + stringWithFormat:NSLocalizedString(@"There was a problem creating the file \"%@\".", "Save log alert panel -> message"), + panel.URL.path.lastPathComponent]; alert.alertStyle = NSWarningAlertStyle; [alert runModal]; @@ -419,54 +440,59 @@ @implementation MessageWindowController (Private) -- (void) resizeColumn +- (void)resizeColumn { - [fMessageTable noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: - NSMakeRange(0, fMessageTable.numberOfRows)]]; + [fMessageTable noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, fMessageTable.numberOfRows)]]; } -- (BOOL) shouldIncludeMessageForFilter: (NSString *) filterString message: (NSDictionary *) message +- (BOOL)shouldIncludeMessageForFilter:(NSString*)filterString message:(NSDictionary*)message { - if ([filterString isEqualToString: @""]) + if ([filterString isEqualToString:@""]) + { return YES; + } - const NSStringCompareOptions searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch; - return [message[@"Name"] rangeOfString: filterString options: searchOptions].location != NSNotFound - || [message[@"Message"] rangeOfString: filterString options: searchOptions].location != NSNotFound; + NSStringCompareOptions const searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch; + return [message[@"Name"] rangeOfString:filterString options:searchOptions].location != NSNotFound || + [message[@"Message"] rangeOfString:filterString options:searchOptions].location != NSNotFound; } -- (void) updateListForFilter +- (void)updateListForFilter { - const NSInteger level = [NSUserDefaults.standardUserDefaults integerForKey: @"MessageLevel"]; - NSString * filterString = fFilterField.stringValue; + NSInteger const level = [NSUserDefaults.standardUserDefaults integerForKey:@"MessageLevel"]; + NSString* filterString = fFilterField.stringValue; - NSIndexSet * indexes = [fMessages indexesOfObjectsWithOptions: NSEnumerationConcurrent passingTest: ^BOOL(id message, NSUInteger idx, BOOL * stop) { - return [((NSDictionary *)message)[@"Level"] integerValue] <= level && [self shouldIncludeMessageForFilter: filterString message: message]; - }]; + NSIndexSet* indexes = [fMessages indexesOfObjectsWithOptions:NSEnumerationConcurrent + passingTest:^BOOL(id message, NSUInteger idx, BOOL* stop) { + return [((NSDictionary*)message)[@"Level"] integerValue] <= level && + [self shouldIncludeMessageForFilter:filterString message:message]; + }]; - NSArray * tempMessages = [[fMessages objectsAtIndexes: indexes] sortedArrayUsingDescriptors: fMessageTable.sortDescriptors]; + NSArray* tempMessages = [[fMessages objectsAtIndexes:indexes] sortedArrayUsingDescriptors:fMessageTable.sortDescriptors]; [fMessageTable beginUpdates]; //figure out which rows were added/moved NSUInteger currentIndex = 0, totalCount = 0; - NSMutableArray * itemsToAdd = [NSMutableArray array]; - NSMutableIndexSet * itemsToAddIndexes = [NSMutableIndexSet indexSet]; + NSMutableArray* itemsToAdd = [NSMutableArray array]; + NSMutableIndexSet* itemsToAddIndexes = [NSMutableIndexSet indexSet]; - for (NSDictionary * message in tempMessages) + for (NSDictionary* message in tempMessages) { - const NSUInteger previousIndex = [fDisplayedMessages indexOfObject: message inRange: NSMakeRange(currentIndex, fDisplayedMessages.count-currentIndex)]; + NSUInteger const previousIndex = [fDisplayedMessages + indexOfObject:message + inRange:NSMakeRange(currentIndex, fDisplayedMessages.count - currentIndex)]; if (previousIndex == NSNotFound) { - [itemsToAdd addObject: message]; - [itemsToAddIndexes addIndex: totalCount]; + [itemsToAdd addObject:message]; + [itemsToAddIndexes addIndex:totalCount]; } else { if (previousIndex != currentIndex) { - [fDisplayedMessages moveObjectAtIndex: previousIndex toIndex: currentIndex]; - [fMessageTable moveRowAtIndex: previousIndex toIndex: currentIndex]; + [fDisplayedMessages moveObjectAtIndex:previousIndex toIndex:currentIndex]; + [fMessageTable moveRowAtIndex:previousIndex toIndex:currentIndex]; } ++currentIndex; } @@ -477,43 +503,43 @@ //remove trailing items - those are the unused if (currentIndex < fDisplayedMessages.count) { - const NSRange removeRange = NSMakeRange(currentIndex, fDisplayedMessages.count-currentIndex); - [fDisplayedMessages removeObjectsInRange: removeRange]; - [fMessageTable removeRowsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: removeRange] withAnimation: NSTableViewAnimationSlideDown]; + NSRange const removeRange = NSMakeRange(currentIndex, fDisplayedMessages.count - currentIndex); + [fDisplayedMessages removeObjectsInRange:removeRange]; + [fMessageTable removeRowsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:removeRange] + withAnimation:NSTableViewAnimationSlideDown]; } //add new items - [fDisplayedMessages insertObjects: itemsToAdd atIndexes: itemsToAddIndexes]; - [fMessageTable insertRowsAtIndexes: itemsToAddIndexes withAnimation: NSTableViewAnimationSlideUp]; + [fDisplayedMessages insertObjects:itemsToAdd atIndexes:itemsToAddIndexes]; + [fMessageTable insertRowsAtIndexes:itemsToAddIndexes withAnimation:NSTableViewAnimationSlideUp]; [fMessageTable endUpdates]; - NSAssert2([fDisplayedMessages isEqualToArray: tempMessages], @"Inconsistency between message arrays! %@ %@", fDisplayedMessages, tempMessages); + NSAssert2([fDisplayedMessages isEqualToArray:tempMessages], @"Inconsistency between message arrays! %@ %@", fDisplayedMessages, tempMessages); } -- (NSString *) stringForMessage: (NSDictionary *) message +- (NSString*)stringForMessage:(NSDictionary*)message { - NSString * levelString; - const NSInteger level = [message[@"Level"] integerValue]; + NSString* levelString; + NSInteger const level = [message[@"Level"] integerValue]; switch (level) { - case TR_LOG_ERROR: - levelString = NSLocalizedString(@"Error", "Message window -> level"); - break; - case TR_LOG_INFO: - levelString = NSLocalizedString(@"Info", "Message window -> level"); - break; - case TR_LOG_DEBUG: - levelString = NSLocalizedString(@"Debug", "Message window -> level"); - break; - default: - NSAssert1(NO, @"Unknown message log level: %ld", level); - levelString = @"?"; + case TR_LOG_ERROR: + levelString = NSLocalizedString(@"Error", "Message window -> level"); + break; + case TR_LOG_INFO: + levelString = NSLocalizedString(@"Info", "Message window -> level"); + break; + case TR_LOG_DEBUG: + levelString = NSLocalizedString(@"Debug", "Message window -> level"); + break; + default: + NSAssert1(NO, @"Unknown message log level: %ld", level); + levelString = @"?"; } - return [NSString stringWithFormat: @"%@ %@ [%@] %@: %@", message[@"Date"], - message[@"File"], levelString, - message[@"Name"], message[@"Message"], nil]; + return [NSString + stringWithFormat:@"%@ %@ [%@] %@: %@", message[@"Date"], message[@"File"], levelString, message[@"Name"], message[@"Message"], nil]; } @end diff --git a/macosx/NSApplicationAdditions.h b/macosx/NSApplicationAdditions.h index 249f23527..bb0134a8a 100644 --- a/macosx/NSApplicationAdditions.h +++ b/macosx/NSApplicationAdditions.h @@ -24,7 +24,7 @@ @interface NSApplication (NSApplicationAdditions) -@property (nonatomic, getter=isOnMojaveOrBetter, readonly) BOOL onMojaveOrBetter; -@property (nonatomic, getter=isDarkMode, readonly) BOOL darkMode; +@property(nonatomic, getter=isOnMojaveOrBetter, readonly) BOOL onMojaveOrBetter; +@property(nonatomic, getter=isDarkMode, readonly) BOOL darkMode; @end diff --git a/macosx/NSApplicationAdditions.m b/macosx/NSApplicationAdditions.m index a4dfe899c..b683e029c 100644 --- a/macosx/NSApplicationAdditions.m +++ b/macosx/NSApplicationAdditions.m @@ -24,16 +24,19 @@ @implementation NSApplication (NSApplicationAdditions) -- (BOOL) isOnMojaveOrBetter +- (BOOL)isOnMojaveOrBetter { return floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_13; } -- (BOOL) isDarkMode +- (BOOL)isDarkMode { - if (@available(macOS 10.14, *)) { + if (@available(macOS 10.14, *)) + { return [self.effectiveAppearance.name isEqualToString:NSAppearanceNameDarkAqua]; - } else { + } + else + { return NO; } } diff --git a/macosx/NSImageAdditions.h b/macosx/NSImageAdditions.h index f858789fa..284dd878c 100644 --- a/macosx/NSImageAdditions.h +++ b/macosx/NSImageAdditions.h @@ -24,6 +24,6 @@ @interface NSImage (NSImageAdditions) -- (NSImage *) imageWithColor: (NSColor *) color; +- (NSImage*)imageWithColor:(NSColor*)color; @end diff --git a/macosx/NSImageAdditions.m b/macosx/NSImageAdditions.m index a38af25ee..521e3a83c 100644 --- a/macosx/NSImageAdditions.m +++ b/macosx/NSImageAdditions.m @@ -24,15 +24,15 @@ @implementation NSImage (NSImageAdditions) -- (NSImage *) imageWithColor: (NSColor *) color +- (NSImage*)imageWithColor:(NSColor*)color { - NSImage * coloredImage = [self copy]; + NSImage* coloredImage = [self copy]; [coloredImage lockFocus]; [color set]; - const NSSize size = coloredImage.size; + NSSize const size = coloredImage.size; NSRectFillUsingOperation(NSMakeRect(0.0, 0.0, size.width, size.height), NSCompositeSourceAtop); [coloredImage unlockFocus]; diff --git a/macosx/NSMutableArrayAdditions.h b/macosx/NSMutableArrayAdditions.h index e39fcb19a..7068381d0 100644 --- a/macosx/NSMutableArrayAdditions.h +++ b/macosx/NSMutableArrayAdditions.h @@ -24,6 +24,6 @@ @interface NSMutableArray (NSMutableArrayAdditions) -- (void) moveObjectAtIndex: (NSUInteger) fromIndex toIndex: (NSUInteger) toIndex; +- (void)moveObjectAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex; @end diff --git a/macosx/NSMutableArrayAdditions.m b/macosx/NSMutableArrayAdditions.m index 27602d5cc..338607d9c 100644 --- a/macosx/NSMutableArrayAdditions.m +++ b/macosx/NSMutableArrayAdditions.m @@ -29,10 +29,12 @@ If the underlying data structure is a linked-list, for example, then this might be less efficient than simply removing the object and re-adding it. */ -- (void) moveObjectAtIndex: (NSUInteger) fromIndex toIndex: (NSUInteger) toIndex +- (void)moveObjectAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex { if (fromIndex == toIndex) + { return; + } id object = self[fromIndex]; @@ -40,15 +42,18 @@ if (fromIndex < toIndex) { for (NSUInteger i = fromIndex; i < toIndex; ++i) - self[i] = self[i+1]; + { + self[i] = self[i + 1]; + } } else { for (NSUInteger i = fromIndex; i > toIndex; --i) - self[i] = self[i-1]; + { + self[i] = self[i - 1]; + } } self[toIndex] = object; - } @end diff --git a/macosx/NSStringAdditions.h b/macosx/NSStringAdditions.h index 36094d5a4..c568e8833 100644 --- a/macosx/NSStringAdditions.h +++ b/macosx/NSStringAdditions.h @@ -24,22 +24,24 @@ @interface NSString (NSStringAdditions) -@property (nonatomic, class, readonly) NSString * ellipsis; -- (NSString *) stringByAppendingEllipsis; +@property(nonatomic, class, readonly) NSString* ellipsis; +- (NSString*)stringByAppendingEllipsis; -+ (NSString *) formattedUInteger: (NSUInteger) value; ++ (NSString*)formattedUInteger:(NSUInteger)value; -+ (NSString *) stringForFileSize: (uint64_t) size; -+ (NSString *) stringForFilePartialSize: (uint64_t) partialSize fullSize: (uint64_t) fullSize; ++ (NSString*)stringForFileSize:(uint64_t)size; ++ (NSString*)stringForFilePartialSize:(uint64_t)partialSize fullSize:(uint64_t)fullSize; -+ (NSString *) stringForSpeed: (CGFloat) speed; -+ (NSString *) stringForSpeedAbbrev: (CGFloat) speed; -+ (NSString *) stringForRatio: (CGFloat) ratio; ++ (NSString*)stringForSpeed:(CGFloat)speed; ++ (NSString*)stringForSpeedAbbrev:(CGFloat)speed; ++ (NSString*)stringForRatio:(CGFloat)ratio; -+ (NSString *) percentString: (CGFloat) progress longDecimals: (BOOL) longDecimals; ++ (NSString*)percentString:(CGFloat)progress longDecimals:(BOOL)longDecimals; -- (NSComparisonResult) compareNumeric: (NSString *) string; //simple compare method for strings with numbers (works for IP addresses) +// simple compare method for strings with numbers (works for IP addresses) +- (NSComparisonResult)compareNumeric:(NSString*)string; -- (NSArray *) betterComponentsSeparatedByCharactersInSet: (NSCharacterSet *) separators; //like componentsSeparatedByCharactersInSet:, but excludes blank values +// like componentsSeparatedByCharactersInSet:, but excludes blank values +- (NSArray*)betterComponentsSeparatedByCharactersInSet:(NSCharacterSet*)separators; @end diff --git a/macosx/NSStringAdditions.m b/macosx/NSStringAdditions.m index 4d631353b..854ff2c5a 100644 --- a/macosx/NSStringAdditions.m +++ b/macosx/NSStringAdditions.m @@ -28,133 +28,153 @@ @interface NSString (Private) -+ (NSString *) stringForFileSizeLion: (uint64_t) size showUnitUnless: (NSString *) notAllowedUnit unitsUsed: (NSString **) unitUsed; ++ (NSString*)stringForFileSizeLion:(uint64_t)size showUnitUnless:(NSString*)notAllowedUnit unitsUsed:(NSString**)unitUsed; -+ (NSString *) stringForSpeed: (CGFloat) speed kb: (NSString *) kb mb: (NSString *) mb gb: (NSString *) gb; ++ (NSString*)stringForSpeed:(CGFloat)speed kb:(NSString*)kb mb:(NSString*)mb gb:(NSString*)gb; @end @implementation NSString (NSStringAdditions) -+ (NSString *) ellipsis ++ (NSString*)ellipsis { return @"\xE2\x80\xA6"; } -- (NSString *) stringByAppendingEllipsis +- (NSString*)stringByAppendingEllipsis { - return [self stringByAppendingString: NSString.ellipsis]; + return [self stringByAppendingString:NSString.ellipsis]; } #warning use localizedStringWithFormat: directly when 10.9-only and stringsdict translations are in place -+ (NSString *) formattedUInteger: (NSUInteger) value ++ (NSString*)formattedUInteger:(NSUInteger)value { - return [NSString localizedStringWithFormat: @"%lu", value]; + return [NSString localizedStringWithFormat:@"%lu", value]; } #warning should we take long long instead? -+ (NSString *) stringForFileSize: (uint64_t) size ++ (NSString*)stringForFileSize:(uint64_t)size { - return [NSByteCountFormatter stringFromByteCount: size countStyle: NSByteCountFormatterCountStyleFile]; + return [NSByteCountFormatter stringFromByteCount:size countStyle:NSByteCountFormatterCountStyleFile]; } #warning should we take long long instead? -+ (NSString *) stringForFilePartialSize: (uint64_t) partialSize fullSize: (uint64_t) fullSize ++ (NSString*)stringForFilePartialSize:(uint64_t)partialSize fullSize:(uint64_t)fullSize { - NSByteCountFormatter * fileSizeFormatter = [[NSByteCountFormatter alloc] init]; + NSByteCountFormatter* fileSizeFormatter = [[NSByteCountFormatter alloc] init]; - NSString * fullString = [fileSizeFormatter stringFromByteCount: fullSize]; + NSString* fullString = [fileSizeFormatter stringFromByteCount:fullSize]; //figure out the magniture of the two, since we can't rely on comparing the units because of localization and pluralization issues (for example, "1 byte of 2 bytes") BOOL partialUnitsSame; if (partialSize == 0) + { partialUnitsSame = YES; //we want to just show "0" when we have no partial data, so always set to the same units + } else { - const unsigned int magnitudePartial = log(partialSize)/log(1000); - const unsigned int magnitudeFull = fullSize < 1000 ? 0 : log(fullSize)/log(1000); //we have to catch 0 with a special case, so might as well avoid the math for all of magnitude 0 + unsigned int const magnitudePartial = log(partialSize) / log(1000); + // we have to catch 0 with a special case, so might as well avoid the math for all of magnitude 0 + unsigned int const magnitudeFull = fullSize < 1000 ? 0 : log(fullSize) / log(1000); partialUnitsSame = magnitudePartial == magnitudeFull; } fileSizeFormatter.includesUnit = !partialUnitsSame; - NSString * partialString = [fileSizeFormatter stringFromByteCount: partialSize]; + NSString* partialString = [fileSizeFormatter stringFromByteCount:partialSize]; - - return [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "file size string"), partialString, fullString]; + return [NSString stringWithFormat:NSLocalizedString(@"%@ of %@", "file size string"), partialString, fullString]; } -+ (NSString *) stringForSpeed: (CGFloat) speed ++ (NSString*)stringForSpeed:(CGFloat)speed { - return [self stringForSpeed: speed - kb: NSLocalizedString(@"KB/s", "Transfer speed (kilobytes per second)") - mb: NSLocalizedString(@"MB/s", "Transfer speed (megabytes per second)") - gb: NSLocalizedString(@"GB/s", "Transfer speed (gigabytes per second)")]; + return [self stringForSpeed:speed kb:NSLocalizedString(@"KB/s", "Transfer speed (kilobytes per second)") + mb:NSLocalizedString(@"MB/s", "Transfer speed (megabytes per second)") + gb:NSLocalizedString(@"GB/s", "Transfer speed (gigabytes per second)")]; } -+ (NSString *) stringForSpeedAbbrev: (CGFloat) speed ++ (NSString*)stringForSpeedAbbrev:(CGFloat)speed { - return [self stringForSpeed: speed kb: @"K" mb: @"M" gb: @"G"]; + return [self stringForSpeed:speed kb:@"K" mb:@"M" gb:@"G"]; } -+ (NSString *) stringForRatio: (CGFloat) ratio ++ (NSString*)stringForRatio:(CGFloat)ratio { //N/A is different than libtransmission's if ((int)ratio == TR_RATIO_NA) + { return NSLocalizedString(@"N/A", "No Ratio"); + } else if ((int)ratio == TR_RATIO_INF) + { return @"\xE2\x88\x9E"; + } else { if (ratio < 10.0) - return [NSString localizedStringWithFormat: @"%.2f", tr_truncd(ratio, 2)]; + { + return [NSString localizedStringWithFormat:@"%.2f", tr_truncd(ratio, 2)]; + } else if (ratio < 100.0) - return [NSString localizedStringWithFormat: @"%.1f", tr_truncd(ratio, 1)]; + { + return [NSString localizedStringWithFormat:@"%.1f", tr_truncd(ratio, 1)]; + } else - return [NSString localizedStringWithFormat: @"%.0f", tr_truncd(ratio, 0)]; + { + return [NSString localizedStringWithFormat:@"%.0f", tr_truncd(ratio, 0)]; + } } } -+ (NSString *) percentString: (CGFloat) progress longDecimals: (BOOL) longDecimals ++ (NSString*)percentString:(CGFloat)progress longDecimals:(BOOL)longDecimals { if (progress >= 1.0) - return [NSString localizedStringWithFormat: @"%d%%", 100]; + { + return [NSString localizedStringWithFormat:@"%d%%", 100]; + } else if (longDecimals) - return [NSString localizedStringWithFormat: @"%.2f%%", tr_truncd(progress * 100.0, 2)]; + { + return [NSString localizedStringWithFormat:@"%.2f%%", tr_truncd(progress * 100.0, 2)]; + } else - return [NSString localizedStringWithFormat: @"%.1f%%", tr_truncd(progress * 100.0, 1)]; + { + return [NSString localizedStringWithFormat:@"%.1f%%", tr_truncd(progress * 100.0, 1)]; + } } -- (NSComparisonResult) compareNumeric: (NSString *) string +- (NSComparisonResult)compareNumeric:(NSString*)string { - const NSStringCompareOptions comparisonOptions = NSNumericSearch | NSForcedOrderingSearch; - return [self compare: string options: comparisonOptions range: NSMakeRange(0, self.length) locale: NSLocale.currentLocale]; + NSStringCompareOptions const comparisonOptions = NSNumericSearch | NSForcedOrderingSearch; + return [self compare:string options:comparisonOptions range:NSMakeRange(0, self.length) locale:NSLocale.currentLocale]; } -- (NSArray *) betterComponentsSeparatedByCharactersInSet: (NSCharacterSet *) separators +- (NSArray*)betterComponentsSeparatedByCharactersInSet:(NSCharacterSet*)separators { - NSMutableArray * components = [NSMutableArray array]; + NSMutableArray* components = [NSMutableArray array]; - NSCharacterSet * includededCharSet = separators.invertedSet; + NSCharacterSet* includededCharSet = separators.invertedSet; NSUInteger index = 0; - const NSUInteger fullLength = self.length; + NSUInteger const fullLength = self.length; do { - const NSUInteger start = [self rangeOfCharacterFromSet: includededCharSet options: 0 range: NSMakeRange(index, fullLength - index)].location; + NSUInteger const start = [self rangeOfCharacterFromSet:includededCharSet options:0 + range:NSMakeRange(index, fullLength - index)] + .location; if (start == NSNotFound) - break; - - const NSRange endRange = [self rangeOfCharacterFromSet: separators options: 0 range: NSMakeRange(start, fullLength - start)]; - if (endRange.location == NSNotFound) { - [components addObject: [self substringFromIndex: start]]; break; } - [components addObject: [self substringWithRange: NSMakeRange(start, endRange.location - start)]]; + NSRange const endRange = [self rangeOfCharacterFromSet:separators options:0 range:NSMakeRange(start, fullLength - start)]; + if (endRange.location == NSNotFound) + { + [components addObject:[self substringFromIndex:start]]; + break; + } + + [components addObject:[self substringWithRange:NSMakeRange(start, endRange.location - start)]]; index = NSMaxRange(endRange); - } - while (YES); + } while (YES); return components; } @@ -163,10 +183,10 @@ @implementation NSString (Private) -+ (NSString *) stringForFileSizeLion: (uint64_t) size showUnitUnless: (NSString *) notAllowedUnit unitsUsed: (NSString **) unitUsed ++ (NSString*)stringForFileSizeLion:(uint64_t)size showUnitUnless:(NSString*)notAllowedUnit unitsUsed:(NSString**)unitUsed { double convertedSize; - NSString * unit; + NSString* unit; NSUInteger decimals; if (size < pow(1000, 2)) { @@ -194,35 +214,47 @@ } //match Finder's behavior - NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init]; + NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init]; numberFormatter.numberStyle = NSNumberFormatterDecimalStyle; numberFormatter.minimumFractionDigits = 0; numberFormatter.maximumFractionDigits = decimals; - NSString * fileSizeString = [numberFormatter stringFromNumber: @(convertedSize)]; + NSString* fileSizeString = [numberFormatter stringFromNumber:@(convertedSize)]; - if (!notAllowedUnit || ![unit isEqualToString: notAllowedUnit]) - fileSizeString = [fileSizeString stringByAppendingFormat: @" %@", unit]; + if (!notAllowedUnit || ![unit isEqualToString:notAllowedUnit]) + { + fileSizeString = [fileSizeString stringByAppendingFormat:@" %@", unit]; + } if (unitUsed) + { *unitUsed = unit; + } return fileSizeString; } -+ (NSString *) stringForSpeed: (CGFloat) speed kb: (NSString *) kb mb: (NSString *) mb gb: (NSString *) gb ++ (NSString*)stringForSpeed:(CGFloat)speed kb:(NSString*)kb mb:(NSString*)mb gb:(NSString*)gb { if (speed <= 999.95) //0.0 KB/s to 999.9 KB/s - return [NSString localizedStringWithFormat: @"%.1f %@", speed, kb]; + { + return [NSString localizedStringWithFormat:@"%.1f %@", speed, kb]; + } speed /= 1000.0; if (speed <= 99.995) //1.00 MB/s to 99.99 MB/s - return [NSString localizedStringWithFormat: @"%.2f %@", speed, mb]; + { + return [NSString localizedStringWithFormat:@"%.2f %@", speed, mb]; + } else if (speed <= 999.95) //100.0 MB/s to 999.9 MB/s - return [NSString localizedStringWithFormat: @"%.1f %@", speed, mb]; + { + return [NSString localizedStringWithFormat:@"%.1f %@", speed, mb]; + } else //insane speeds - return [NSString localizedStringWithFormat: @"%.2f %@", (speed / 1000.0), gb]; + { + return [NSString localizedStringWithFormat:@"%.2f %@", (speed / 1000.0), gb]; + } } @end diff --git a/macosx/PeerProgressIndicatorCell.h b/macosx/PeerProgressIndicatorCell.h index ecc703b52..49ee67602 100644 --- a/macosx/PeerProgressIndicatorCell.h +++ b/macosx/PeerProgressIndicatorCell.h @@ -24,10 +24,10 @@ @interface PeerProgressIndicatorCell : NSLevelIndicatorCell { - NSDictionary * fAttributes; + NSDictionary* fAttributes; BOOL fSeed; } -- (void) setSeed: (BOOL) seed; +- (void)setSeed:(BOOL)seed; @end diff --git a/macosx/PeerProgressIndicatorCell.m b/macosx/PeerProgressIndicatorCell.m index 2e396248b..5fd8206ad 100644 --- a/macosx/PeerProgressIndicatorCell.m +++ b/macosx/PeerProgressIndicatorCell.m @@ -25,35 +25,36 @@ @implementation PeerProgressIndicatorCell -- (id) copyWithZone: (NSZone *) zone +- (id)copyWithZone:(NSZone*)zone { - PeerProgressIndicatorCell * copy = [super copyWithZone: zone]; + PeerProgressIndicatorCell* copy = [super copyWithZone:zone]; copy->fAttributes = fAttributes; return copy; } - -- (void) setSeed: (BOOL) seed +- (void)setSeed:(BOOL)seed { fSeed = seed; } -- (void) drawWithFrame: (NSRect) cellFrame inView: (NSView *) controlView +- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView { - if ([NSUserDefaults.standardUserDefaults boolForKey: @"DisplayPeerProgressBarNumber"]) + if ([NSUserDefaults.standardUserDefaults boolForKey:@"DisplayPeerProgressBarNumber"]) { if (!fAttributes) { - NSMutableParagraphStyle * paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + NSMutableParagraphStyle* paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; paragraphStyle.alignment = NSRightTextAlignment; - fAttributes = @{NSFontAttributeName: [NSFont systemFontOfSize: 11.0], - NSForegroundColorAttributeName: NSColor.labelColor, - NSParagraphStyleAttributeName: paragraphStyle}; + fAttributes = @{ + NSFontAttributeName : [NSFont systemFontOfSize:11.0], + NSForegroundColorAttributeName : NSColor.labelColor, + NSParagraphStyleAttributeName : paragraphStyle + }; } - [[NSString percentString: self.floatValue longDecimals: NO] drawInRect: cellFrame withAttributes: fAttributes]; + [[NSString percentString:self.floatValue longDecimals:NO] drawInRect:cellFrame withAttributes:fAttributes]; } else { @@ -63,17 +64,20 @@ fAttributes = nil; } - [super drawWithFrame: cellFrame inView: controlView]; + [super drawWithFrame:cellFrame inView:controlView]; if (fSeed) { - NSImage * checkImage = [NSImage imageNamed: @"CompleteCheck"]; + NSImage* checkImage = [NSImage imageNamed:@"CompleteCheck"]; - const NSSize imageSize = checkImage.size; - const NSRect rect = NSMakeRect(floor(NSMidX(cellFrame) - imageSize.width * 0.5), - floor(NSMidY(cellFrame) - imageSize.height * 0.5), - imageSize.width, imageSize.height); + NSSize const imageSize = checkImage.size; + NSRect const rect = NSMakeRect( + floor(NSMidX(cellFrame) - imageSize.width * 0.5), + floor(NSMidY(cellFrame) - imageSize.height * 0.5), + imageSize.width, + imageSize.height); - [checkImage drawInRect: rect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; + [checkImage drawInRect:rect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 respectFlipped:YES + hints:nil]; } } } diff --git a/macosx/PeerTableView.m b/macosx/PeerTableView.m index 79e974531..295ccbdb0 100644 --- a/macosx/PeerTableView.m +++ b/macosx/PeerTableView.m @@ -24,17 +24,17 @@ @implementation PeerTableView -- (void) mouseDown: (NSEvent *) event +- (void)mouseDown:(NSEvent*)event { - NSPoint point = [self convertPoint: event.locationInWindow fromView: nil]; - if ([self rowAtPoint: point] != -1 && [self columnAtPoint: point] == [self columnWithIdentifier: @"Progress"]) + NSPoint point = [self convertPoint:event.locationInWindow fromView:nil]; + if ([self rowAtPoint:point] != -1 && [self columnAtPoint:point] == [self columnWithIdentifier:@"Progress"]) { - [NSUserDefaults.standardUserDefaults setBool: ![NSUserDefaults.standardUserDefaults - boolForKey: @"DisplayPeerProgressBarNumber"] forKey: @"DisplayPeerProgressBarNumber"]; + [NSUserDefaults.standardUserDefaults setBool:![NSUserDefaults.standardUserDefaults boolForKey:@"DisplayPeerProgressBarNumber"] + forKey:@"DisplayPeerProgressBarNumber"]; - NSIndexSet * rowIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, self.numberOfRows)], - * columnIndexes = [NSIndexSet indexSetWithIndex: [self columnAtPoint: point]]; - [self reloadDataForRowIndexes: rowIndexes columnIndexes: columnIndexes]; + NSIndexSet *rowIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.numberOfRows)], + *columnIndexes = [NSIndexSet indexSetWithIndex:[self columnAtPoint:point]]; + [self reloadDataForRowIndexes:rowIndexes columnIndexes:columnIndexes]; } } diff --git a/macosx/PiecesView.h b/macosx/PiecesView.h index c8280a79f..cbfad8fbe 100644 --- a/macosx/PiecesView.h +++ b/macosx/PiecesView.h @@ -26,17 +26,21 @@ @interface PiecesView : NSImageView { - int8_t * fPieces; + int8_t* fPieces; - NSColor * fGreenAvailabilityColor, * fBluePieceColor; + NSColor* fGreenAvailabilityColor; + NSColor* fBluePieceColor; - Torrent * fTorrent; - NSInteger fNumPieces, fAcross, fWidth, fExtraBorder; + Torrent* fTorrent; + NSInteger fNumPieces; + NSInteger fAcross; + NSInteger fWidth; + NSInteger fExtraBorder; } -- (void) setTorrent: (Torrent *) torrent; +- (void)setTorrent:(Torrent*)torrent; -- (void) clearView; -- (void) updateView; +- (void)clearView; +- (void)updateView; @end diff --git a/macosx/PiecesView.m b/macosx/PiecesView.m index 4602bbbb5..52b425dec 100644 --- a/macosx/PiecesView.m +++ b/macosx/PiecesView.m @@ -43,22 +43,22 @@ enum @implementation PiecesView -- (void) awakeFromNib +- (void)awakeFromNib { //store box colors - fGreenAvailabilityColor = [NSColor colorWithCalibratedRed: 0.0 green: 1.0 blue: 0.4 alpha: 1.0]; - fBluePieceColor = [NSColor colorWithCalibratedRed: 0.0 green: 0.4 blue: 0.8 alpha: 1.0]; + fGreenAvailabilityColor = [NSColor colorWithCalibratedRed:0.0 green:1.0 blue:0.4 alpha:1.0]; + fBluePieceColor = [NSColor colorWithCalibratedRed:0.0 green:0.4 blue:0.8 alpha:1.0]; //actually draw the box - [self setTorrent: nil]; + [self setTorrent:nil]; } -- (void) dealloc +- (void)dealloc { tr_free(fPieces); } -- (void) setTorrent: (Torrent *) torrent +- (void)setTorrent:(Torrent*)torrent { [self clearView]; @@ -69,17 +69,17 @@ enum fNumPieces = MIN(fTorrent.pieceCount, MAX_ACROSS * MAX_ACROSS); fAcross = ceil(sqrt(fNumPieces)); - const CGFloat width = self.bounds.size.width; + CGFloat const width = self.bounds.size.width; fWidth = (width - (fAcross + 1) * BETWEEN) / fAcross; fExtraBorder = (width - ((fWidth + BETWEEN) * fAcross + BETWEEN)) / 2; } - NSImage * back = [[NSImage alloc] initWithSize: self.bounds.size]; + NSImage* back = [[NSImage alloc] initWithSize:self.bounds.size]; [back lockFocus]; - NSGradient * gradient = [[NSGradient alloc] initWithStartingColor: [NSColor colorWithCalibratedWhite: 0.0 alpha: 0.4] - endingColor: [NSColor colorWithCalibratedWhite: 0.2 alpha: 0.4]]; - [gradient drawInRect: self.bounds angle: 90.0]; + NSGradient* gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.4] + endingColor:[NSColor colorWithCalibratedWhite:0.2 alpha:0.4]]; + [gradient drawInRect:self.bounds angle:90.0]; [back unlockFocus]; self.image = back; @@ -87,47 +87,51 @@ enum [self setNeedsDisplay]; } -- (void) clearView +- (void)clearView { tr_free(fPieces); fPieces = NULL; } -- (void) updateView +- (void)updateView { if (!fTorrent) + { return; + } //determine if first time - const BOOL first = fPieces == NULL; + BOOL const first = fPieces == NULL; if (first) - fPieces = (int8_t *)tr_malloc(fNumPieces * sizeof(int8_t)); + { + fPieces = (int8_t*)tr_malloc(fNumPieces * sizeof(int8_t)); + } - int8_t * pieces = NULL; - float * piecesPercent = NULL; + int8_t* pieces = NULL; + float* piecesPercent = NULL; - const BOOL showAvailablity = [NSUserDefaults.standardUserDefaults boolForKey: @"PiecesViewShowAvailability"]; + BOOL const showAvailablity = [NSUserDefaults.standardUserDefaults boolForKey:@"PiecesViewShowAvailability"]; if (showAvailablity) { - pieces = (int8_t *)tr_malloc(fNumPieces * sizeof(int8_t)); - [fTorrent getAvailability: pieces size: fNumPieces]; + pieces = (int8_t*)tr_malloc(fNumPieces * sizeof(int8_t)); + [fTorrent getAvailability:pieces size:fNumPieces]; } else { - piecesPercent = (float *)tr_malloc(fNumPieces * sizeof(float)); - [fTorrent getAmountFinished: piecesPercent size: fNumPieces]; + piecesPercent = (float*)tr_malloc(fNumPieces * sizeof(float)); + [fTorrent getAmountFinished:piecesPercent size:fNumPieces]; } - NSImage * image = self.image; + NSImage* image = self.image; NSRect fillRects[fNumPieces]; - NSColor * fillColors[fNumPieces]; + NSColor* fillColors[fNumPieces]; NSInteger usedCount = 0; for (NSInteger index = 0; index < fNumPieces; index++) { - NSColor * pieceColor = nil; + NSColor* pieceColor = nil; if (showAvailablity ? pieces[index] == -1 : piecesPercent[index] == 1.0) { @@ -164,19 +168,21 @@ enum else { //always redraw "mixed" - CGFloat percent = showAvailablity ? (CGFloat)pieces[index]/HIGH_PEERS : piecesPercent[index]; - NSColor * fullColor = showAvailablity ? fGreenAvailabilityColor : fBluePieceColor; - pieceColor = [NSColor.whiteColor blendedColorWithFraction: percent ofColor: fullColor]; + CGFloat percent = showAvailablity ? (CGFloat)pieces[index] / HIGH_PEERS : piecesPercent[index]; + NSColor* fullColor = showAvailablity ? fGreenAvailabilityColor : fBluePieceColor; + pieceColor = [NSColor.whiteColor blendedColorWithFraction:percent ofColor:fullColor]; fPieces[index] = PIECE_SOME; } if (pieceColor) { - const NSInteger across = index % fAcross, - down = index / fAcross; - fillRects[usedCount] = NSMakeRect(across * (fWidth + BETWEEN) + BETWEEN + fExtraBorder, - image.size.width - (down + 1) * (fWidth + BETWEEN) - fExtraBorder, - fWidth, fWidth); + NSInteger const across = index % fAcross; + NSInteger const down = index / fAcross; + fillRects[usedCount] = NSMakeRect( + across * (fWidth + BETWEEN) + BETWEEN + fExtraBorder, + image.size.width - (down + 1) * (fWidth + BETWEEN) - fExtraBorder, + fWidth, + fWidth); fillColors[usedCount] = pieceColor; usedCount++; @@ -195,22 +201,22 @@ enum tr_free(piecesPercent); } -- (BOOL) acceptsFirstMouse: (NSEvent *) event +- (BOOL)acceptsFirstMouse:(NSEvent*)event { return YES; } -- (void) mouseDown: (NSEvent *) event +- (void)mouseDown:(NSEvent*)event { if (fTorrent) { - const BOOL availability = ![NSUserDefaults.standardUserDefaults boolForKey: @"PiecesViewShowAvailability"]; - [NSUserDefaults.standardUserDefaults setBool: availability forKey: @"PiecesViewShowAvailability"]; + BOOL const availability = ![NSUserDefaults.standardUserDefaults boolForKey:@"PiecesViewShowAvailability"]; + [NSUserDefaults.standardUserDefaults setBool:availability forKey:@"PiecesViewShowAvailability"]; [self sendAction:self.action to:self.target]; } - [super mouseDown: event]; + [super mouseDown:event]; } @end diff --git a/macosx/PortChecker.h b/macosx/PortChecker.h index 2a56fb725..9db87b5e5 100644 --- a/macosx/PortChecker.h +++ b/macosx/PortChecker.h @@ -22,7 +22,7 @@ #import -typedef NS_ENUM(unsigned int, port_status_t) { +typedef NS_ENUM(unsigned int, port_status_t) { // PORT_STATUS_CHECKING, PORT_STATUS_OPEN, PORT_STATUS_CLOSED, @@ -34,15 +34,15 @@ typedef NS_ENUM(unsigned int, port_status_t) { id fDelegate; port_status_t fStatus; - NSURLConnection * fConnection; - NSMutableData * fPortProbeData; + NSURLConnection* fConnection; + NSMutableData* fPortProbeData; - NSTimer * fTimer; + NSTimer* fTimer; } -- (instancetype) initForPort: (NSInteger) portNumber delay: (BOOL) delay withDelegate: (id) delegate; -- (void) cancelProbe; +- (instancetype)initForPort:(NSInteger)portNumber delay:(BOOL)delay withDelegate:(id)delegate; +- (void)cancelProbe; -@property (nonatomic, readonly) port_status_t status; +@property(nonatomic, readonly) port_status_t status; @end diff --git a/macosx/PortChecker.m b/macosx/PortChecker.m index c95c1c6c9..4072b4725 100644 --- a/macosx/PortChecker.m +++ b/macosx/PortChecker.m @@ -22,20 +22,20 @@ #import "PortChecker.h" -#define CHECKER_URL(port) [NSString stringWithFormat: @"https://portcheck.transmissionbt.com/%ld", port] +#define CHECKER_URL(port) [NSString stringWithFormat:@"https://portcheck.transmissionbt.com/%ld", port] #define CHECK_FIRE 3.0 @interface PortChecker (Private) -- (void) startProbe: (NSTimer *) timer; +- (void)startProbe:(NSTimer*)timer; -- (void) callBackWithStatus: (port_status_t) status; +- (void)callBackWithStatus:(port_status_t)status; @end @implementation PortChecker -- (instancetype) initForPort: (NSInteger) portNumber delay: (BOOL) delay withDelegate: (id) delegate +- (instancetype)initForPort:(NSInteger)portNumber delay:(BOOL)delay withDelegate:(id)delegate { if ((self = [super init])) { @@ -43,25 +43,29 @@ fStatus = PORT_STATUS_CHECKING; - fTimer = [NSTimer scheduledTimerWithTimeInterval: CHECK_FIRE target: self selector: @selector(startProbe:) userInfo: @(portNumber) repeats: NO]; + fTimer = [NSTimer scheduledTimerWithTimeInterval:CHECK_FIRE target:self selector:@selector(startProbe:) + userInfo:@(portNumber) + repeats:NO]; if (!delay) + { [fTimer fire]; + } } return self; } -- (void) dealloc +- (void)dealloc { [fTimer invalidate]; } -- (port_status_t) status +- (port_status_t)status { return fStatus; } -- (void) cancelProbe +- (void)cancelProbe { [fTimer invalidate]; fTimer = nil; @@ -69,43 +73,47 @@ [fConnection cancel]; } -- (void) connection: (NSURLConnection *) connection didReceiveResponse: (NSURLResponse *) response +- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response { fPortProbeData.length = 0; } -- (void) connection: (NSURLConnection *) connection didReceiveData: (NSData *) data +- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data { - [fPortProbeData appendData: data]; + [fPortProbeData appendData:data]; } -- (void) connection: (NSURLConnection *) connection didFailWithError: (NSError *) error +- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error { NSLog(@"Unable to get port status: connection failed (%@)", error.localizedDescription); - [self callBackWithStatus: PORT_STATUS_ERROR]; + [self callBackWithStatus:PORT_STATUS_ERROR]; } -- (void) connectionDidFinishLoading: (NSURLConnection *) connection +- (void)connectionDidFinishLoading:(NSURLConnection*)connection { - NSString * probeString = [[NSString alloc] initWithData: fPortProbeData encoding: NSUTF8StringEncoding]; + NSString* probeString = [[NSString alloc] initWithData:fPortProbeData encoding:NSUTF8StringEncoding]; fPortProbeData = nil; if (probeString) { - if ([probeString isEqualToString: @"1"]) - [self callBackWithStatus: PORT_STATUS_OPEN]; - else if ([probeString isEqualToString: @"0"]) - [self callBackWithStatus: PORT_STATUS_CLOSED]; + if ([probeString isEqualToString:@"1"]) + { + [self callBackWithStatus:PORT_STATUS_OPEN]; + } + else if ([probeString isEqualToString:@"0"]) + { + [self callBackWithStatus:PORT_STATUS_CLOSED]; + } else { NSLog(@"Unable to get port status: invalid response (%@)", probeString); - [self callBackWithStatus: PORT_STATUS_ERROR]; + [self callBackWithStatus:PORT_STATUS_ERROR]; } } else { NSLog(@"Unable to get port status: invalid data received"); - [self callBackWithStatus: PORT_STATUS_ERROR]; + [self callBackWithStatus:PORT_STATUS_ERROR]; } } @@ -113,29 +121,33 @@ @implementation PortChecker (Private) -- (void) startProbe: (NSTimer *) timer +- (void)startProbe:(NSTimer*)timer { fTimer = nil; - NSURLRequest * portProbeRequest = [NSURLRequest requestWithURL: [NSURL URLWithString: CHECKER_URL([[timer userInfo] integerValue])] - cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval: 15.0]; + NSURLRequest* portProbeRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:CHECKER_URL([[timer userInfo] integerValue])] + cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData + timeoutInterval:15.0]; - if ((fConnection = [[NSURLConnection alloc] initWithRequest: portProbeRequest delegate: self])) + if ((fConnection = [[NSURLConnection alloc] initWithRequest:portProbeRequest delegate:self])) + { fPortProbeData = [[NSMutableData alloc] init]; + } else { NSLog(@"Unable to get port status: failed to initiate connection"); - [self callBackWithStatus: PORT_STATUS_ERROR]; + [self callBackWithStatus:PORT_STATUS_ERROR]; } } -- (void) callBackWithStatus: (port_status_t) status +- (void)callBackWithStatus:(port_status_t)status { fStatus = status; - if (fDelegate && [fDelegate respondsToSelector: @selector(portCheckerDidFinishProbing:)]) - [fDelegate performSelectorOnMainThread: @selector(portCheckerDidFinishProbing:) withObject: self waitUntilDone: NO]; + if (fDelegate && [fDelegate respondsToSelector:@selector(portCheckerDidFinishProbing:)]) + { + [fDelegate performSelectorOnMainThread:@selector(portCheckerDidFinishProbing:) withObject:self waitUntilDone:NO]; + } } @end - diff --git a/macosx/PredicateEditorRowTemplateAny.m b/macosx/PredicateEditorRowTemplateAny.m index 3eb6da78a..035eaf008 100644 --- a/macosx/PredicateEditorRowTemplateAny.m +++ b/macosx/PredicateEditorRowTemplateAny.m @@ -24,17 +24,16 @@ @implementation PredicateEditorRowTemplateAny -- (NSPredicate *) predicateWithSubpredicates: (NSArray *) subpredicates +- (NSPredicate*)predicateWithSubpredicates:(NSArray*)subpredicates { //we only make NSComparisonPredicates - NSComparisonPredicate * predicate = (NSComparisonPredicate *)[super predicateWithSubpredicates: subpredicates]; + NSComparisonPredicate* predicate = (NSComparisonPredicate*)[super predicateWithSubpredicates:subpredicates]; //construct a near-identical predicate - return [NSComparisonPredicate predicateWithLeftExpression: predicate.leftExpression - rightExpression: predicate.rightExpression - modifier: NSAnyPredicateModifier - type: predicate.predicateOperatorType - options: predicate.options]; + return [NSComparisonPredicate predicateWithLeftExpression:predicate.leftExpression rightExpression:predicate.rightExpression + modifier:NSAnyPredicateModifier + type:predicate.predicateOperatorType + options:predicate.options]; } @end diff --git a/macosx/PrefsController.h b/macosx/PrefsController.h index ea7ee1f47..b23d7aa8d 100644 --- a/macosx/PrefsController.h +++ b/macosx/PrefsController.h @@ -26,152 +26,173 @@ @class PortChecker; -@interface PrefsController : NSWindowController +@interface PrefsController : NSWindowController { - tr_session * fHandle; - NSUserDefaults * fDefaults; + tr_session* fHandle; + NSUserDefaults* fDefaults; BOOL fHasLoaded; - IBOutlet NSView * fGeneralView, * fTransfersView, * fBandwidthView, * fPeersView, * fNetworkView, * fRemoteView, * fGroupsView; + IBOutlet NSView* fGeneralView; + IBOutlet NSView* fTransfersView; + IBOutlet NSView* fBandwidthView; + IBOutlet NSView* fPeersView; + IBOutlet NSView* fNetworkView; + IBOutlet NSView* fRemoteView; + IBOutlet NSView* fGroupsView; - NSString * fInitialString; + NSString* fInitialString; - IBOutlet NSButton *fSystemPreferencesButton; - IBOutlet NSTextField * fCheckForUpdatesLabel; - IBOutlet NSButton * fCheckForUpdatesButton, * fCheckForUpdatesBetaButton; + IBOutlet NSButton* fSystemPreferencesButton; + IBOutlet NSTextField* fCheckForUpdatesLabel; + IBOutlet NSButton* fCheckForUpdatesButton; + IBOutlet NSButton* fCheckForUpdatesBetaButton; - IBOutlet NSPopUpButton * fFolderPopUp, * fIncompleteFolderPopUp, * fImportFolderPopUp, * fDoneScriptPopUp; - IBOutlet NSButton * fShowMagnetAddWindowCheck; - IBOutlet NSTextField * fRatioStopField, * fIdleStopField, * fQueueDownloadField, * fQueueSeedField, * fStalledField; + IBOutlet NSPopUpButton* fFolderPopUp; + IBOutlet NSPopUpButton* fIncompleteFolderPopUp; + IBOutlet NSPopUpButton* fImportFolderPopUp; + IBOutlet NSPopUpButton* fDoneScriptPopUp; + IBOutlet NSButton* fShowMagnetAddWindowCheck; + IBOutlet NSTextField* fRatioStopField; + IBOutlet NSTextField* fIdleStopField; + IBOutlet NSTextField* fQueueDownloadField; + IBOutlet NSTextField* fQueueSeedField; + IBOutlet NSTextField* fStalledField; - IBOutlet NSTextField * fUploadField, * fDownloadField, - * fSpeedLimitUploadField, * fSpeedLimitDownloadField; - IBOutlet NSPopUpButton * fAutoSpeedDayTypePopUp; + IBOutlet NSTextField* fUploadField; + IBOutlet NSTextField* fDownloadField; + IBOutlet NSTextField* fSpeedLimitUploadField; + IBOutlet NSTextField* fSpeedLimitDownloadField; + IBOutlet NSPopUpButton* fAutoSpeedDayTypePopUp; - IBOutlet NSTextField * fPeersGlobalField, * fPeersTorrentField, - * fBlocklistURLField, * fBlocklistMessageField, * fBlocklistDateField; - IBOutlet NSButton * fBlocklistButton; + IBOutlet NSTextField* fPeersGlobalField; + IBOutlet NSTextField* fPeersTorrentField; + IBOutlet NSTextField* fBlocklistURLField; + IBOutlet NSTextField* fBlocklistMessageField; + IBOutlet NSTextField* fBlocklistDateField; + IBOutlet NSButton* fBlocklistButton; - PortChecker * fPortChecker; - IBOutlet NSTextField * fPortField, * fPortStatusField; - IBOutlet NSButton * fNatCheck; - IBOutlet NSImageView * fPortStatusImage; - IBOutlet NSProgressIndicator * fPortStatusProgress; - NSTimer * fPortStatusTimer; + PortChecker* fPortChecker; + IBOutlet NSTextField* fPortField; + IBOutlet NSTextField* fPortStatusField; + IBOutlet NSButton* fNatCheck; + IBOutlet NSImageView* fPortStatusImage; + IBOutlet NSProgressIndicator* fPortStatusProgress; + NSTimer* fPortStatusTimer; int fPeerPort, fNatStatus; - IBOutlet NSTextField * fRPCPortField, * fRPCPasswordField; - IBOutlet NSTableView * fRPCWhitelistTable; - NSMutableArray * fRPCWhitelistArray; - IBOutlet NSSegmentedControl * fRPCAddRemoveControl; - NSString * fRPCPassword; + IBOutlet NSTextField* fRPCPortField; + IBOutlet NSTextField* fRPCPasswordField; + IBOutlet NSTableView* fRPCWhitelistTable; + NSMutableArray* fRPCWhitelistArray; + IBOutlet NSSegmentedControl* fRPCAddRemoveControl; + NSString* fRPCPassword; } -- (instancetype) initWithHandle: (tr_session *) handle; +- (instancetype)initWithHandle:(tr_session*)handle; -- (void) setAutoUpdateToBeta: (id) sender; +- (void)setAutoUpdateToBeta:(id)sender; -- (void) setPort: (id) sender; -- (void) randomPort: (id) sender; -- (void) setRandomPortOnStart: (id) sender; -- (void) setNat: (id) sender; -- (void) updatePortStatus; -- (void) portCheckerDidFinishProbing: (PortChecker *) portChecker; +- (void)setPort:(id)sender; +- (void)randomPort:(id)sender; +- (void)setRandomPortOnStart:(id)sender; +- (void)setNat:(id)sender; +- (void)updatePortStatus; +- (void)portCheckerDidFinishProbing:(PortChecker*)portChecker; -@property (nonatomic, readonly) NSArray *sounds; -- (void) setSound: (id) sender; +@property(nonatomic, readonly) NSArray* sounds; +- (void)setSound:(id)sender; -- (void) setUTP: (id) sender; +- (void)setUTP:(id)sender; -- (void) setPeersGlobal: (id) sender; -- (void) setPeersTorrent: (id) sender; +- (void)setPeersGlobal:(id)sender; +- (void)setPeersTorrent:(id)sender; -- (void) setPEX: (id) sender; -- (void) setDHT: (id) sender; -- (void) setLPD: (id) sender; +- (void)setPEX:(id)sender; +- (void)setDHT:(id)sender; +- (void)setLPD:(id)sender; -- (void) setEncryptionMode: (id) sender; +- (void)setEncryptionMode:(id)sender; -- (void) setBlocklistEnabled: (id) sender; -- (void) updateBlocklist: (id) sender; -- (void) setBlocklistAutoUpdate: (id) sender; -- (void) updateBlocklistFields; -- (void) updateBlocklistURLField; -- (void) updateBlocklistButton; +- (void)setBlocklistEnabled:(id)sender; +- (void)updateBlocklist:(id)sender; +- (void)setBlocklistAutoUpdate:(id)sender; +- (void)updateBlocklistFields; +- (void)updateBlocklistURLField; +- (void)updateBlocklistButton; -- (void) setAutoStartDownloads: (id) sender; +- (void)setAutoStartDownloads:(id)sender; -- (void) setBadge: (id) sender; +- (void)setBadge:(id)sender; -- (IBAction) openNotificationSystemPrefs: (NSButton *) sender; +- (IBAction)openNotificationSystemPrefs:(NSButton*)sender; -- (void) resetWarnings: (id) sender; +- (void)resetWarnings:(id)sender; -- (void) setDefaultForMagnets: (id) sender; +- (void)setDefaultForMagnets:(id)sender; -- (void) setQueue: (id) sender; -- (void) setQueueNumber: (id) sender; +- (void)setQueue:(id)sender; +- (void)setQueueNumber:(id)sender; -- (void) setStalled: (id) sender; -- (void) setStalledMinutes: (id) sender; +- (void)setStalled:(id)sender; +- (void)setStalledMinutes:(id)sender; -- (void) setDownloadLocation: (id) sender; -- (void) folderSheetShow: (id) sender; -- (void) incompleteFolderSheetShow: (id) sender; -- (void) setUseIncompleteFolder: (id) sender; +- (void)setDownloadLocation:(id)sender; +- (void)folderSheetShow:(id)sender; +- (void)incompleteFolderSheetShow:(id)sender; +- (void)setUseIncompleteFolder:(id)sender; -- (void) setRenamePartialFiles: (id) sender; +- (void)setRenamePartialFiles:(id)sender; -- (IBAction) setShowAddMagnetWindow: (id) sender; -- (void) updateShowAddMagnetWindowField; +- (IBAction)setShowAddMagnetWindow:(id)sender; +- (void)updateShowAddMagnetWindowField; -- (void) setDoneScriptEnabled: (id) sender; -- (void) doneScriptSheetShow: (id) sender; +- (void)setDoneScriptEnabled:(id)sender; +- (void)doneScriptSheetShow:(id)sender; -- (void) applyRatioSetting: (id) sender; -- (void) setRatioStop: (id) sender; -- (void) updateRatioStopField; -- (void) updateRatioStopFieldOld; +- (void)applyRatioSetting:(id)sender; +- (void)setRatioStop:(id)sender; +- (void)updateRatioStopField; +- (void)updateRatioStopFieldOld; -- (void) applyIdleStopSetting: (id) sender; -- (void) setIdleStop: (id) sender; -- (void) updateLimitStopField; +- (void)applyIdleStopSetting:(id)sender; +- (void)setIdleStop:(id)sender; +- (void)updateLimitStopField; -- (void) applySpeedSettings: (id) sender; -- (void) applyAltSpeedSettings; +- (void)applySpeedSettings:(id)sender; +- (void)applyAltSpeedSettings; -- (void) updateLimitFields; -- (void) setGlobalLimit: (id) sender; +- (void)updateLimitFields; +- (void)setGlobalLimit:(id)sender; -- (void) setSpeedLimit: (id) sender; -- (void) setAutoSpeedLimit: (id) sender; -- (void) setAutoSpeedLimitTime: (id) sender; -- (void) setAutoSpeedLimitDay: (id) sender; -+ (NSInteger) dateToTimeSum: (NSDate *) date; -+ (NSDate *) timeSumToDate: (NSInteger) sum; +- (void)setSpeedLimit:(id)sender; +- (void)setAutoSpeedLimit:(id)sender; +- (void)setAutoSpeedLimitTime:(id)sender; +- (void)setAutoSpeedLimitDay:(id)sender; ++ (NSInteger)dateToTimeSum:(NSDate*)date; ++ (NSDate*)timeSumToDate:(NSInteger)sum; -- (void) setAutoImport: (id) sender; -- (void) importFolderSheetShow: (id) sender; +- (void)setAutoImport:(id)sender; +- (void)importFolderSheetShow:(id)sender; -- (void) setAutoSize: (id) sender; +- (void)setAutoSize:(id)sender; -- (void) setRPCEnabled: (id) sender; -- (void) linkWebUI: (id) sender; -- (void) setRPCAuthorize: (id) sender; -- (void) setRPCUsername: (id) sender; -- (void) setRPCPassword: (id) sender; -- (void) updateRPCPassword; -- (void) setRPCPort: (id) sender; -- (void) setRPCUseWhitelist: (id) sender; -- (void) setRPCWebUIDiscovery: (id) sender; -- (void) updateRPCWhitelist; -- (void) addRemoveRPCIP: (id) sender; +- (void)setRPCEnabled:(id)sender; +- (void)linkWebUI:(id)sender; +- (void)setRPCAuthorize:(id)sender; +- (void)setRPCUsername:(id)sender; +- (void)setRPCPassword:(id)sender; +- (void)updateRPCPassword; +- (void)setRPCPort:(id)sender; +- (void)setRPCUseWhitelist:(id)sender; +- (void)setRPCWebUIDiscovery:(id)sender; +- (void)updateRPCWhitelist; +- (void)addRemoveRPCIP:(id)sender; -- (void) helpForScript: (id) sender; -- (void) helpForPeers: (id) sender; -- (void) helpForNetwork: (id) sender; -- (void) helpForRemote: (id) sender; +- (void)helpForScript:(id)sender; +- (void)helpForPeers:(id)sender; +- (void)helpForNetwork:(id)sender; +- (void)helpForRemote:(id)sender; -- (void) rpcUpdatePrefs; +- (void)rpcUpdatePrefs; @end diff --git a/macosx/PrefsController.m b/macosx/PrefsController.m index 145e4976a..01ff8de13 100644 --- a/macosx/PrefsController.m +++ b/macosx/PrefsController.m @@ -38,76 +38,82 @@ #import "NSApplicationAdditions.h" #import "NSStringAdditions.h" -#define DOWNLOAD_FOLDER 0 -#define DOWNLOAD_TORRENT 2 +#define DOWNLOAD_FOLDER 0 +#define DOWNLOAD_TORRENT 2 -#define RPC_IP_ADD_TAG 0 -#define RPC_IP_REMOVE_TAG 1 +#define RPC_IP_ADD_TAG 0 +#define RPC_IP_REMOVE_TAG 1 -#define TOOLBAR_GENERAL @"TOOLBAR_GENERAL" -#define TOOLBAR_TRANSFERS @"TOOLBAR_TRANSFERS" -#define TOOLBAR_GROUPS @"TOOLBAR_GROUPS" -#define TOOLBAR_BANDWIDTH @"TOOLBAR_BANDWIDTH" -#define TOOLBAR_PEERS @"TOOLBAR_PEERS" -#define TOOLBAR_NETWORK @"TOOLBAR_NETWORK" -#define TOOLBAR_REMOTE @"TOOLBAR_REMOTE" +#define TOOLBAR_GENERAL @"TOOLBAR_GENERAL" +#define TOOLBAR_TRANSFERS @"TOOLBAR_TRANSFERS" +#define TOOLBAR_GROUPS @"TOOLBAR_GROUPS" +#define TOOLBAR_BANDWIDTH @"TOOLBAR_BANDWIDTH" +#define TOOLBAR_PEERS @"TOOLBAR_PEERS" +#define TOOLBAR_NETWORK @"TOOLBAR_NETWORK" +#define TOOLBAR_REMOTE @"TOOLBAR_REMOTE" -#define RPC_KEYCHAIN_SERVICE "Transmission:Remote" -#define RPC_KEYCHAIN_NAME "Remote" +#define RPC_KEYCHAIN_SERVICE "Transmission:Remote" +#define RPC_KEYCHAIN_NAME "Remote" -#define WEBUI_URL @"http://localhost:%ld/" +#define WEBUI_URL @"http://localhost:%ld/" @interface PrefsController (Private) -- (void) setPrefView: (id) sender; +- (void)setPrefView:(id)sender; -- (void) setKeychainPassword: (const char *) password forService: (const char *) service username: (const char *) username; +- (void)setKeychainPassword:(char const*)password forService:(char const*)service username:(char const*)username; @end @implementation PrefsController -- (instancetype) initWithHandle: (tr_session *) handle +- (instancetype)initWithHandle:(tr_session*)handle { - if ((self = [super initWithWindowNibName: @"PrefsWindow"])) + if ((self = [super initWithWindowNibName:@"PrefsWindow"])) { fHandle = handle; fDefaults = NSUserDefaults.standardUserDefaults; //check for old version download location (before 1.1) - NSString * choice; - if ((choice = [fDefaults stringForKey: @"DownloadChoice"])) + NSString* choice; + if ((choice = [fDefaults stringForKey:@"DownloadChoice"])) { - [fDefaults setBool: [choice isEqualToString: @"Constant"] forKey: @"DownloadLocationConstant"]; - [fDefaults setBool: YES forKey: @"DownloadAsk"]; + [fDefaults setBool:[choice isEqualToString:@"Constant"] forKey:@"DownloadLocationConstant"]; + [fDefaults setBool:YES forKey:@"DownloadAsk"]; - [fDefaults removeObjectForKey: @"DownloadChoice"]; + [fDefaults removeObjectForKey:@"DownloadChoice"]; } //check for old version blocklist (before 2.12) - NSDate * blocklistDate; - if ((blocklistDate = [fDefaults objectForKey: @"BlocklistLastUpdate"])) + NSDate* blocklistDate; + if ((blocklistDate = [fDefaults objectForKey:@"BlocklistLastUpdate"])) { - [fDefaults setObject: blocklistDate forKey: @"BlocklistNewLastUpdateSuccess"]; - [fDefaults setObject: blocklistDate forKey: @"BlocklistNewLastUpdate"]; - [fDefaults removeObjectForKey: @"BlocklistLastUpdate"]; + [fDefaults setObject:blocklistDate forKey:@"BlocklistNewLastUpdateSuccess"]; + [fDefaults setObject:blocklistDate forKey:@"BlocklistNewLastUpdate"]; + [fDefaults removeObjectForKey:@"BlocklistLastUpdate"]; - NSURL * blocklistDir = [[NSFileManager.defaultManager URLsForDirectory: NSApplicationDirectory inDomains: NSUserDomainMask][0] URLByAppendingPathComponent: @"Transmission/blocklists/"]; - [NSFileManager.defaultManager moveItemAtURL: [blocklistDir URLByAppendingPathComponent: @"level1.bin"] - toURL: [blocklistDir URLByAppendingPathComponent: @DEFAULT_BLOCKLIST_FILENAME] - error: nil]; + NSURL* blocklistDir = [[NSFileManager.defaultManager URLsForDirectory:NSApplicationDirectory inDomains:NSUserDomainMask][0] + URLByAppendingPathComponent:@"Transmission/blocklists/"]; + [NSFileManager.defaultManager moveItemAtURL:[blocklistDir URLByAppendingPathComponent:@"level1.bin"] + toURL:[blocklistDir URLByAppendingPathComponent:@DEFAULT_BLOCKLIST_FILENAME] + error:nil]; } //save a new random port - if ([fDefaults boolForKey: @"RandomPort"]) - [fDefaults setInteger: tr_sessionGetPeerPort(fHandle) forKey: @"BindPort"]; + if ([fDefaults boolForKey:@"RandomPort"]) + { + [fDefaults setInteger:tr_sessionGetPeerPort(fHandle) forKey:@"BindPort"]; + } //set auto import - NSString * autoPath; - VDKQueue* x = [(Controller *)[NSApp delegate] fileWatcherQueue]; - if ([fDefaults boolForKey: @"AutoImport"] && (autoPath = [fDefaults stringForKey: @"AutoImportDirectory"])) - [((Controller *)NSApp.delegate).fileWatcherQueue addPath: autoPath.stringByExpandingTildeInPath notifyingAbout: VDKQueueNotifyAboutWrite]; + NSString* autoPath; + VDKQueue* x = [(Controller*)[NSApp delegate] fileWatcherQueue]; + if ([fDefaults boolForKey:@"AutoImport"] && (autoPath = [fDefaults stringForKey:@"AutoImportDirectory"])) + { + [((Controller*)NSApp.delegate).fileWatcherQueue addPath:autoPath.stringByExpandingTildeInPath + notifyingAbout:VDKQueueNotifyAboutWrite]; + } //set special-handling of magnet link add window checkbox [self updateShowAddMagnetWindowField]; @@ -116,33 +122,35 @@ [BlocklistScheduler.scheduler updateSchedule]; //set encryption - [self setEncryptionMode: nil]; + [self setEncryptionMode:nil]; //update rpc whitelist [self updateRPCPassword]; - fRPCWhitelistArray = [[fDefaults arrayForKey: @"RPCWhitelist"] mutableCopy]; + fRPCWhitelistArray = [[fDefaults arrayForKey:@"RPCWhitelist"] mutableCopy]; if (!fRPCWhitelistArray) - fRPCWhitelistArray = [NSMutableArray arrayWithObject: @"127.0.0.1"]; + { + fRPCWhitelistArray = [NSMutableArray arrayWithObject:@"127.0.0.1"]; + } [self updateRPCWhitelist]; //reset old Sparkle settings from previous versions - [fDefaults removeObjectForKey: @"SUScheduledCheckInterval"]; - if ([fDefaults objectForKey: @"CheckForUpdates"]) + [fDefaults removeObjectForKey:@"SUScheduledCheckInterval"]; + if ([fDefaults objectForKey:@"CheckForUpdates"]) { - [[SUUpdater sharedUpdater] setAutomaticallyChecksForUpdates: [fDefaults boolForKey: @"CheckForUpdates"]]; - [fDefaults removeObjectForKey: @"CheckForUpdates"]; + [[SUUpdater sharedUpdater] setAutomaticallyChecksForUpdates:[fDefaults boolForKey:@"CheckForUpdates"]]; + [fDefaults removeObjectForKey:@"CheckForUpdates"]; } - [self setAutoUpdateToBeta: nil]; + [self setAutoUpdateToBeta:nil]; } return self; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; [fPortStatusTimer invalidate]; if (fPortChecker) @@ -151,13 +159,13 @@ } } -- (void) awakeFromNib +- (void)awakeFromNib { fHasLoaded = YES; self.window.restorationClass = [self class]; - NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"Preferences Toolbar"]; + NSToolbar* toolbar = [[NSToolbar alloc] initWithIdentifier:@"Preferences Toolbar"]; toolbar.delegate = self; toolbar.allowsUserCustomization = NO; toolbar.displayMode = NSToolbarDisplayModeIconAndLabel; @@ -165,154 +173,184 @@ toolbar.selectedItemIdentifier = TOOLBAR_GENERAL; self.window.toolbar = toolbar; - [self setPrefView: nil]; + [self setPrefView:nil]; //set download folder - [fFolderPopUp selectItemAtIndex: [fDefaults boolForKey: @"DownloadLocationConstant"] ? DOWNLOAD_FOLDER : DOWNLOAD_TORRENT]; + [fFolderPopUp selectItemAtIndex:[fDefaults boolForKey:@"DownloadLocationConstant"] ? DOWNLOAD_FOLDER : DOWNLOAD_TORRENT]; //set stop ratio - fRatioStopField.floatValue = [fDefaults floatForKey: @"RatioLimit"]; + fRatioStopField.floatValue = [fDefaults floatForKey:@"RatioLimit"]; //set idle seeding minutes - fIdleStopField.integerValue = [fDefaults integerForKey: @"IdleLimitMinutes"]; + fIdleStopField.integerValue = [fDefaults integerForKey:@"IdleLimitMinutes"]; //set limits [self updateLimitFields]; //set speed limit - fSpeedLimitUploadField.intValue = [fDefaults integerForKey: @"SpeedLimitUploadLimit"]; - fSpeedLimitDownloadField.intValue = [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]; + fSpeedLimitUploadField.intValue = [fDefaults integerForKey:@"SpeedLimitUploadLimit"]; + fSpeedLimitDownloadField.intValue = [fDefaults integerForKey:@"SpeedLimitDownloadLimit"]; //set port - fPortField.intValue = [fDefaults integerForKey: @"BindPort"]; + fPortField.intValue = [fDefaults integerForKey:@"BindPort"]; fNatStatus = -1; [self updatePortStatus]; - fPortStatusTimer = [NSTimer scheduledTimerWithTimeInterval: 5.0 target: self selector: @selector(updatePortStatus) userInfo: nil repeats: YES]; + fPortStatusTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(updatePortStatus) userInfo:nil + repeats:YES]; //set peer connections - fPeersGlobalField.intValue = [fDefaults integerForKey: @"PeersTotal"]; - fPeersTorrentField.intValue = [fDefaults integerForKey: @"PeersTorrent"]; + fPeersGlobalField.intValue = [fDefaults integerForKey:@"PeersTotal"]; + fPeersTorrentField.intValue = [fDefaults integerForKey:@"PeersTorrent"]; //set queue values - fQueueDownloadField.intValue = [fDefaults integerForKey: @"QueueDownloadNumber"]; - fQueueSeedField.intValue = [fDefaults integerForKey: @"QueueSeedNumber"]; - fStalledField.intValue = [fDefaults integerForKey: @"StalledMinutes"]; + fQueueDownloadField.intValue = [fDefaults integerForKey:@"QueueDownloadNumber"]; + fQueueSeedField.intValue = [fDefaults integerForKey:@"QueueSeedNumber"]; + fStalledField.intValue = [fDefaults integerForKey:@"StalledMinutes"]; //set blocklist - NSString * blocklistURL = [fDefaults stringForKey: @"BlocklistURL"]; + NSString* blocklistURL = [fDefaults stringForKey:@"BlocklistURL"]; if (blocklistURL) + { fBlocklistURLField.stringValue = blocklistURL; + } [self updateBlocklistButton]; [self updateBlocklistFields]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateLimitFields) - name: @"UpdateSpeedLimitValuesOutsidePrefs" object: nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateLimitFields) + name:@"UpdateSpeedLimitValuesOutsidePrefs" + object:nil]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateRatioStopField) - name: @"UpdateRatioStopValueOutsidePrefs" object: nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateRatioStopField) + name:@"UpdateRatioStopValueOutsidePrefs" + object:nil]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateLimitStopField) - name: @"UpdateIdleStopValueOutsidePrefs" object: nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateLimitStopField) + name:@"UpdateIdleStopValueOutsidePrefs" + object:nil]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateBlocklistFields) - name: @"BlocklistUpdated" object: nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateBlocklistFields) name:@"BlocklistUpdated" + object:nil]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateBlocklistURLField) - name: NSControlTextDidChangeNotification object: fBlocklistURLField]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateBlocklistURLField) + name:NSControlTextDidChangeNotification + object:fBlocklistURLField]; //set rpc port - fRPCPortField.intValue = [fDefaults integerForKey: @"RPCPort"]; + fRPCPortField.intValue = [fDefaults integerForKey:@"RPCPort"]; //set rpc password if (fRPCPassword) + { fRPCPasswordField.stringValue = fRPCPassword; + } } -- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag +- (NSToolbarItem*)toolbar:(NSToolbar*)toolbar itemForItemIdentifier:(NSString*)ident willBeInsertedIntoToolbar:(BOOL)flag { - NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident]; + NSToolbarItem* item = [[NSToolbarItem alloc] initWithItemIdentifier:ident]; - if ([ident isEqualToString: TOOLBAR_GENERAL]) + if ([ident isEqualToString:TOOLBAR_GENERAL]) { item.label = NSLocalizedString(@"General", "Preferences -> toolbar item title"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"gearshape" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: NSImageNamePreferencesGeneral]; + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"gearshape" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:NSImageNamePreferencesGeneral]; } item.target = self; item.action = @selector(setPrefView:); item.autovalidates = NO; } - else if ([ident isEqualToString: TOOLBAR_TRANSFERS]) + else if ([ident isEqualToString:TOOLBAR_TRANSFERS]) { item.label = NSLocalizedString(@"Transfers", "Preferences -> toolbar item title"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"arrow.up.arrow.down" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: @"Transfers"]; + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"arrow.up.arrow.down" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:@"Transfers"]; } item.target = self; item.action = @selector(setPrefView:); item.autovalidates = NO; } - else if ([ident isEqualToString: TOOLBAR_GROUPS]) + else if ([ident isEqualToString:TOOLBAR_GROUPS]) { item.label = NSLocalizedString(@"Groups", "Preferences -> toolbar item title"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"pin" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: @"Groups"]; + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"pin" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:@"Groups"]; } item.target = self; item.action = @selector(setPrefView:); item.autovalidates = NO; } - else if ([ident isEqualToString: TOOLBAR_BANDWIDTH]) + else if ([ident isEqualToString:TOOLBAR_BANDWIDTH]) { item.label = NSLocalizedString(@"Bandwidth", "Preferences -> toolbar item title"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"speedometer" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: @"Bandwidth"]; + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"speedometer" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:@"Bandwidth"]; } item.target = self; item.action = @selector(setPrefView:); item.autovalidates = NO; } - else if ([ident isEqualToString: TOOLBAR_PEERS]) + else if ([ident isEqualToString:TOOLBAR_PEERS]) { item.label = NSLocalizedString(@"Peers", "Preferences -> toolbar item title"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"person.2" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: NSImageNameUserGroup]; + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"person.2" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:NSImageNameUserGroup]; } item.target = self; item.action = @selector(setPrefView:); item.autovalidates = NO; } - else if ([ident isEqualToString: TOOLBAR_NETWORK]) + else if ([ident isEqualToString:TOOLBAR_NETWORK]) { item.label = NSLocalizedString(@"Network", "Preferences -> toolbar item title"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"network" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: NSImageNameNetwork]; + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"network" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:NSImageNameNetwork]; } item.target = self; item.action = @selector(setPrefView:); item.autovalidates = NO; } - else if ([ident isEqualToString: TOOLBAR_REMOTE]) + else if ([ident isEqualToString:TOOLBAR_REMOTE]) { item.label = NSLocalizedString(@"Remote", "Preferences -> toolbar item title"); - if (@available(macOS 11.0, *)) { - item.image = [NSImage imageWithSystemSymbolName: @"antenna.radiowaves.left.and.right" accessibilityDescription: nil]; - } else { - item.image = [NSImage imageNamed: @"Remote"]; + if (@available(macOS 11.0, *)) + { + item.image = [NSImage imageWithSystemSymbolName:@"antenna.radiowaves.left.and.right" accessibilityDescription:nil]; + } + else + { + item.image = [NSImage imageNamed:@"Remote"]; } item.target = self; item.action = @selector(setPrefView:); @@ -326,25 +364,34 @@ return item; } -- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar +- (NSArray*)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar { - return @[TOOLBAR_GENERAL, TOOLBAR_TRANSFERS, TOOLBAR_GROUPS, TOOLBAR_BANDWIDTH, - TOOLBAR_PEERS, TOOLBAR_NETWORK, TOOLBAR_REMOTE]; + return @[ + TOOLBAR_GENERAL, + TOOLBAR_TRANSFERS, + TOOLBAR_GROUPS, + TOOLBAR_BANDWIDTH, + TOOLBAR_PEERS, + TOOLBAR_NETWORK, + TOOLBAR_REMOTE + ]; } -- (NSArray *) toolbarSelectableItemIdentifiers: (NSToolbar *) toolbar +- (NSArray*)toolbarSelectableItemIdentifiers:(NSToolbar*)toolbar { - return [self toolbarAllowedItemIdentifiers: toolbar]; + return [self toolbarAllowedItemIdentifiers:toolbar]; } -- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar +- (NSArray*)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar { - return [self toolbarAllowedItemIdentifiers: toolbar]; + return [self toolbarAllowedItemIdentifiers:toolbar]; } -+ (void) restoreWindowWithIdentifier: (NSString *) identifier state: (NSCoder *) state completionHandler: (void (^)(NSWindow *, NSError *)) completionHandler ++ (void)restoreWindowWithIdentifier:(NSString*)identifier + state:(NSCoder*)state + completionHandler:(void (^)(NSWindow*, NSError*))completionHandler { - NSWindow * window = ((Controller *)NSApp.delegate).prefsController.window; + NSWindow* window = ((Controller*)NSApp.delegate).prefsController.window; completionHandler(window, nil); } @@ -352,50 +399,50 @@ #if defined(TR_BETA_RELEASE) #define SPARKLE_TAG YES #else -#define SPARKLE_TAG [fDefaults boolForKey: @"AutoUpdateBeta"] +#define SPARKLE_TAG [fDefaults boolForKey:@"AutoUpdateBeta"] #endif -- (void) setAutoUpdateToBeta: (id) sender +- (void)setAutoUpdateToBeta:(id)sender { // TODO: Support beta releases (if/when necessary) } -- (void) setPort: (id) sender +- (void)setPort:(id)sender { - const tr_port port = [sender intValue]; - [fDefaults setInteger: port forKey: @"BindPort"]; + tr_port const port = [sender intValue]; + [fDefaults setInteger:port forKey:@"BindPort"]; tr_sessionSetPeerPort(fHandle, port); fPeerPort = -1; [self updatePortStatus]; } -- (void) randomPort: (id) sender +- (void)randomPort:(id)sender { - const tr_port port = tr_sessionSetPeerPortRandom(fHandle); - [fDefaults setInteger: port forKey: @"BindPort"]; + tr_port const port = tr_sessionSetPeerPortRandom(fHandle); + [fDefaults setInteger:port forKey:@"BindPort"]; fPortField.intValue = port; fPeerPort = -1; [self updatePortStatus]; } -- (void) setRandomPortOnStart: (id) sender +- (void)setRandomPortOnStart:(id)sender { - tr_sessionSetPeerPortRandomOnStart(fHandle, ((NSButton *)sender).state == NSOnState); + tr_sessionSetPeerPortRandomOnStart(fHandle, ((NSButton*)sender).state == NSOnState); } -- (void) setNat: (id) sender +- (void)setNat:(id)sender { - tr_sessionSetPortForwardingEnabled(fHandle, [fDefaults boolForKey: @"NatTraversal"]); + tr_sessionSetPortForwardingEnabled(fHandle, [fDefaults boolForKey:@"NatTraversal"]); fNatStatus = -1; [self updatePortStatus]; } -- (void) updatePortStatus +- (void)updatePortStatus { - const tr_port_forwarding fwd = tr_sessionGetPortForwarding(fHandle); - const int port = tr_sessionGetPeerPort(fHandle); + tr_port_forwarding const fwd = tr_sessionGetPortForwarding(fHandle); + int const port = tr_sessionGetPeerPort(fHandle); BOOL natStatusChanged = (fNatStatus != fwd); BOOL peerPortChanged = (fPeerPort != port); @@ -406,60 +453,62 @@ fPortStatusField.stringValue = @""; fPortStatusImage.image = nil; - [fPortStatusProgress startAnimation: self]; + [fPortStatusProgress startAnimation:self]; if (fPortChecker) { [fPortChecker cancelProbe]; } BOOL delay = natStatusChanged || tr_sessionIsPortForwardingEnabled(fHandle); - fPortChecker = [[PortChecker alloc] initForPort: fPeerPort delay: delay withDelegate: self]; + fPortChecker = [[PortChecker alloc] initForPort:fPeerPort delay:delay withDelegate:self]; } } -- (void) portCheckerDidFinishProbing: (PortChecker *) portChecker +- (void)portCheckerDidFinishProbing:(PortChecker*)portChecker { - [fPortStatusProgress stopAnimation: self]; + [fPortStatusProgress stopAnimation:self]; switch (fPortChecker.status) { - case PORT_STATUS_OPEN: - fPortStatusField.stringValue = NSLocalizedString(@"Port is open", "Preferences -> Network -> port status"); - fPortStatusImage.image = [NSImage imageNamed: NSImageNameStatusAvailable]; - break; - case PORT_STATUS_CLOSED: - fPortStatusField.stringValue = NSLocalizedString(@"Port is closed", "Preferences -> Network -> port status"); - fPortStatusImage.image = [NSImage imageNamed: NSImageNameStatusUnavailable]; - break; - case PORT_STATUS_ERROR: - fPortStatusField.stringValue = NSLocalizedString(@"Port check site is down", "Preferences -> Network -> port status"); - fPortStatusImage.image = [NSImage imageNamed: NSImageNameStatusPartiallyAvailable]; - break; - default: - NSAssert1(NO, @"Port checker returned invalid status: %d", fPortChecker.status); - break; + case PORT_STATUS_OPEN: + fPortStatusField.stringValue = NSLocalizedString(@"Port is open", "Preferences -> Network -> port status"); + fPortStatusImage.image = [NSImage imageNamed:NSImageNameStatusAvailable]; + break; + case PORT_STATUS_CLOSED: + fPortStatusField.stringValue = NSLocalizedString(@"Port is closed", "Preferences -> Network -> port status"); + fPortStatusImage.image = [NSImage imageNamed:NSImageNameStatusUnavailable]; + break; + case PORT_STATUS_ERROR: + fPortStatusField.stringValue = NSLocalizedString(@"Port check site is down", "Preferences -> Network -> port status"); + fPortStatusImage.image = [NSImage imageNamed:NSImageNameStatusPartiallyAvailable]; + break; + default: + NSAssert1(NO, @"Port checker returned invalid status: %d", fPortChecker.status); + break; } fPortChecker = nil; } -- (NSArray *) sounds +- (NSArray*)sounds { - NSMutableArray * sounds = [NSMutableArray array]; + NSMutableArray* sounds = [NSMutableArray array]; - NSArray * directories = NSSearchPathForDirectoriesInDomains(NSAllLibrariesDirectory, NSUserDomainMask | NSLocalDomainMask | NSSystemDomainMask, YES); + NSArray* directories = NSSearchPathForDirectoriesInDomains(NSAllLibrariesDirectory, NSUserDomainMask | NSLocalDomainMask | NSSystemDomainMask, YES); - for (__strong NSString * directory in directories) + for (__strong NSString* directory in directories) { - directory = [directory stringByAppendingPathComponent: @"Sounds"]; + directory = [directory stringByAppendingPathComponent:@"Sounds"]; BOOL isDirectory; - if ([NSFileManager.defaultManager fileExistsAtPath: directory isDirectory: &isDirectory] && isDirectory) + if ([NSFileManager.defaultManager fileExistsAtPath:directory isDirectory:&isDirectory] && isDirectory) { - NSArray * directoryContents = [NSFileManager.defaultManager contentsOfDirectoryAtPath: directory error: NULL]; - for (__strong NSString * sound in directoryContents) + NSArray* directoryContents = [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:NULL]; + for (__strong NSString* sound in directoryContents) { sound = sound.stringByDeletingPathExtension; - if ([NSSound soundNamed: sound]) - [sounds addObject: sound]; + if ([NSSound soundNamed:sound]) + { + [sounds addObject:sound]; + } } } } @@ -467,266 +516,282 @@ return sounds; } -- (void) setSound: (id) sender +- (void)setSound:(id)sender { //play sound when selecting - NSSound * sound; - if ((sound = [NSSound soundNamed: [sender titleOfSelectedItem]])) + NSSound* sound; + if ((sound = [NSSound soundNamed:[sender titleOfSelectedItem]])) + { [sound play]; + } } -- (void) setUTP: (id) sender +- (void)setUTP:(id)sender { - tr_sessionSetUTPEnabled(fHandle, [fDefaults boolForKey: @"UTPGlobal"]); + tr_sessionSetUTPEnabled(fHandle, [fDefaults boolForKey:@"UTPGlobal"]); } -- (void) setPeersGlobal: (id) sender +- (void)setPeersGlobal:(id)sender { - const int count = [sender intValue]; - [fDefaults setInteger: count forKey: @"PeersTotal"]; + int const count = [sender intValue]; + [fDefaults setInteger:count forKey:@"PeersTotal"]; tr_sessionSetPeerLimit(fHandle, count); } -- (void) setPeersTorrent: (id) sender +- (void)setPeersTorrent:(id)sender { - const int count = [sender intValue]; - [fDefaults setInteger: count forKey: @"PeersTorrent"]; + int const count = [sender intValue]; + [fDefaults setInteger:count forKey:@"PeersTorrent"]; tr_sessionSetPeerLimitPerTorrent(fHandle, count); } -- (void) setPEX: (id) sender +- (void)setPEX:(id)sender { - tr_sessionSetPexEnabled(fHandle, [fDefaults boolForKey: @"PEXGlobal"]); + tr_sessionSetPexEnabled(fHandle, [fDefaults boolForKey:@"PEXGlobal"]); } -- (void) setDHT: (id) sender +- (void)setDHT:(id)sender { - tr_sessionSetDHTEnabled(fHandle, [fDefaults boolForKey: @"DHTGlobal"]); + tr_sessionSetDHTEnabled(fHandle, [fDefaults boolForKey:@"DHTGlobal"]); } -- (void) setLPD: (id) sender +- (void)setLPD:(id)sender { - tr_sessionSetLPDEnabled(fHandle, [fDefaults boolForKey: @"LocalPeerDiscoveryGlobal"]); + tr_sessionSetLPDEnabled(fHandle, [fDefaults boolForKey:@"LocalPeerDiscoveryGlobal"]); } -- (void) setEncryptionMode: (id) sender +- (void)setEncryptionMode:(id)sender { - const tr_encryption_mode mode = [fDefaults boolForKey: @"EncryptionPrefer"] ? - ([fDefaults boolForKey: @"EncryptionRequire"] ? TR_ENCRYPTION_REQUIRED : TR_ENCRYPTION_PREFERRED) : TR_CLEAR_PREFERRED; + tr_encryption_mode const mode = [fDefaults boolForKey:@"EncryptionPrefer"] ? + ([fDefaults boolForKey:@"EncryptionRequire"] ? TR_ENCRYPTION_REQUIRED : TR_ENCRYPTION_PREFERRED) : + TR_CLEAR_PREFERRED; tr_sessionSetEncryption(fHandle, mode); } -- (void) setBlocklistEnabled: (id) sender +- (void)setBlocklistEnabled:(id)sender { - tr_blocklistSetEnabled(fHandle, [fDefaults boolForKey: @"BlocklistNew"]); + tr_blocklistSetEnabled(fHandle, [fDefaults boolForKey:@"BlocklistNew"]); [BlocklistScheduler.scheduler updateSchedule]; [self updateBlocklistButton]; } -- (void) updateBlocklist: (id) sender +- (void)updateBlocklist:(id)sender { - [BlocklistDownloaderViewController downloadWithPrefsController: self]; + [BlocklistDownloaderViewController downloadWithPrefsController:self]; } -- (void) setBlocklistAutoUpdate: (id) sender +- (void)setBlocklistAutoUpdate:(id)sender { [BlocklistScheduler.scheduler updateSchedule]; } -- (void) updateBlocklistFields +- (void)updateBlocklistFields { - const BOOL exists = tr_blocklistExists(fHandle); + BOOL const exists = tr_blocklistExists(fHandle); if (exists) { - NSString * countString = [NSString formattedUInteger: tr_blocklistGetRuleCount(fHandle)]; - fBlocklistMessageField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"%@ IP address rules in list", - "Prefs -> blocklist -> message"), countString]; + NSString* countString = [NSString formattedUInteger:tr_blocklistGetRuleCount(fHandle)]; + fBlocklistMessageField.stringValue = [NSString + stringWithFormat:NSLocalizedString(@"%@ IP address rules in list", "Prefs -> blocklist -> message"), countString]; } else - fBlocklistMessageField.stringValue = NSLocalizedString(@"A blocklist must first be downloaded", - "Prefs -> blocklist -> message"); + { + fBlocklistMessageField.stringValue = NSLocalizedString(@"A blocklist must first be downloaded", "Prefs -> blocklist -> message"); + } - NSString * updatedDateString; + NSString* updatedDateString; if (exists) { - NSDate * updatedDate = [fDefaults objectForKey: @"BlocklistNewLastUpdateSuccess"]; + NSDate* updatedDate = [fDefaults objectForKey:@"BlocklistNewLastUpdateSuccess"]; if (updatedDate) - updatedDateString = [NSDateFormatter localizedStringFromDate: updatedDate dateStyle: NSDateFormatterFullStyle timeStyle: NSDateFormatterShortStyle]; + { + updatedDateString = [NSDateFormatter localizedStringFromDate:updatedDate dateStyle:NSDateFormatterFullStyle + timeStyle:NSDateFormatterShortStyle]; + } else + { updatedDateString = NSLocalizedString(@"N/A", "Prefs -> blocklist -> message"); + } } else + { updatedDateString = NSLocalizedString(@"Never", "Prefs -> blocklist -> message"); + } - fBlocklistDateField.stringValue = [NSString stringWithFormat: @"%@: %@", - NSLocalizedString(@"Last updated", "Prefs -> blocklist -> message"), updatedDateString]; + fBlocklistDateField.stringValue = [NSString + stringWithFormat:@"%@: %@", NSLocalizedString(@"Last updated", "Prefs -> blocklist -> message"), updatedDateString]; } -- (void) updateBlocklistURLField +- (void)updateBlocklistURLField { - NSString * blocklistString = fBlocklistURLField.stringValue; + NSString* blocklistString = fBlocklistURLField.stringValue; - [fDefaults setObject: blocklistString forKey: @"BlocklistURL"]; + [fDefaults setObject:blocklistString forKey:@"BlocklistURL"]; tr_blocklistSetURL(fHandle, blocklistString.UTF8String); [self updateBlocklistButton]; } -- (void) updateBlocklistButton +- (void)updateBlocklistButton { - NSString * blocklistString = [fDefaults objectForKey: @"BlocklistURL"]; - const BOOL enable = (blocklistString && ![blocklistString isEqualToString: @""]) - && [fDefaults boolForKey: @"BlocklistNew"]; + NSString* blocklistString = [fDefaults objectForKey:@"BlocklistURL"]; + BOOL const enable = (blocklistString && ![blocklistString isEqualToString:@""]) && [fDefaults boolForKey:@"BlocklistNew"]; fBlocklistButton.enabled = enable; } -- (void) setAutoStartDownloads: (id) sender +- (void)setAutoStartDownloads:(id)sender { - tr_sessionSetPaused(fHandle, ![fDefaults boolForKey: @"AutoStartDownload"]); + tr_sessionSetPaused(fHandle, ![fDefaults boolForKey:@"AutoStartDownload"]); } -- (void) applySpeedSettings: (id) sender +- (void)applySpeedSettings:(id)sender { - tr_sessionLimitSpeed(fHandle, TR_UP, [fDefaults boolForKey: @"CheckUpload"]); - tr_sessionSetSpeedLimit_KBps(fHandle, TR_UP, [fDefaults integerForKey: @"UploadLimit"]); + tr_sessionLimitSpeed(fHandle, TR_UP, [fDefaults boolForKey:@"CheckUpload"]); + tr_sessionSetSpeedLimit_KBps(fHandle, TR_UP, [fDefaults integerForKey:@"UploadLimit"]); - tr_sessionLimitSpeed(fHandle, TR_DOWN, [fDefaults boolForKey: @"CheckDownload"]); - tr_sessionSetSpeedLimit_KBps(fHandle, TR_DOWN, [fDefaults integerForKey: @"DownloadLimit"]); + tr_sessionLimitSpeed(fHandle, TR_DOWN, [fDefaults boolForKey:@"CheckDownload"]); + tr_sessionSetSpeedLimit_KBps(fHandle, TR_DOWN, [fDefaults integerForKey:@"DownloadLimit"]); - [NSNotificationCenter.defaultCenter postNotificationName: @"SpeedLimitUpdate" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"SpeedLimitUpdate" object:nil]; } -- (void) applyAltSpeedSettings +- (void)applyAltSpeedSettings { - tr_sessionSetAltSpeed_KBps(fHandle, TR_UP, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]); - tr_sessionSetAltSpeed_KBps(fHandle, TR_DOWN, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]); + tr_sessionSetAltSpeed_KBps(fHandle, TR_UP, [fDefaults integerForKey:@"SpeedLimitUploadLimit"]); + tr_sessionSetAltSpeed_KBps(fHandle, TR_DOWN, [fDefaults integerForKey:@"SpeedLimitDownloadLimit"]); - [NSNotificationCenter.defaultCenter postNotificationName: @"SpeedLimitUpdate" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"SpeedLimitUpdate" object:nil]; } -- (void) applyRatioSetting: (id) sender +- (void)applyRatioSetting:(id)sender { - tr_sessionSetRatioLimited(fHandle, [fDefaults boolForKey: @"RatioCheck"]); - tr_sessionSetRatioLimit(fHandle, [fDefaults floatForKey: @"RatioLimit"]); + tr_sessionSetRatioLimited(fHandle, [fDefaults boolForKey:@"RatioCheck"]); + tr_sessionSetRatioLimit(fHandle, [fDefaults floatForKey:@"RatioLimit"]); //reload main table for seeding progress - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; //reload global settings in inspector - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGlobalOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGlobalOptions" object:nil]; } -- (void) setRatioStop: (id) sender +- (void)setRatioStop:(id)sender { - [fDefaults setFloat: [sender floatValue] forKey: @"RatioLimit"]; + [fDefaults setFloat:[sender floatValue] forKey:@"RatioLimit"]; - [self applyRatioSetting: nil]; + [self applyRatioSetting:nil]; } -- (void) updateRatioStopField +- (void)updateRatioStopField { if (fHasLoaded) - fRatioStopField.floatValue = [fDefaults floatForKey: @"RatioLimit"]; + { + fRatioStopField.floatValue = [fDefaults floatForKey:@"RatioLimit"]; + } } -- (void) updateRatioStopFieldOld +- (void)updateRatioStopFieldOld { [self updateRatioStopField]; - [self applyRatioSetting: nil]; + [self applyRatioSetting:nil]; } -- (void) applyIdleStopSetting: (id) sender +- (void)applyIdleStopSetting:(id)sender { - tr_sessionSetIdleLimited(fHandle, [fDefaults boolForKey: @"IdleLimitCheck"]); - tr_sessionSetIdleLimit(fHandle, [fDefaults integerForKey: @"IdleLimitMinutes"]); + tr_sessionSetIdleLimited(fHandle, [fDefaults boolForKey:@"IdleLimitCheck"]); + tr_sessionSetIdleLimit(fHandle, [fDefaults integerForKey:@"IdleLimitMinutes"]); //reload main table for remaining seeding time - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; //reload global settings in inspector - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGlobalOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGlobalOptions" object:nil]; } -- (void) setIdleStop: (id) sender +- (void)setIdleStop:(id)sender { - [fDefaults setInteger: [sender integerValue] forKey: @"IdleLimitMinutes"]; + [fDefaults setInteger:[sender integerValue] forKey:@"IdleLimitMinutes"]; - [self applyIdleStopSetting: nil]; + [self applyIdleStopSetting:nil]; } -- (void) updateLimitStopField +- (void)updateLimitStopField { if (fHasLoaded) - fIdleStopField.integerValue = [fDefaults integerForKey: @"IdleLimitMinutes"]; + { + fIdleStopField.integerValue = [fDefaults integerForKey:@"IdleLimitMinutes"]; + } } -- (void) updateLimitFields +- (void)updateLimitFields { if (!fHasLoaded) + { return; + } - fUploadField.intValue = [fDefaults integerForKey: @"UploadLimit"]; - fDownloadField.intValue = [fDefaults integerForKey: @"DownloadLimit"]; + fUploadField.intValue = [fDefaults integerForKey:@"UploadLimit"]; + fDownloadField.intValue = [fDefaults integerForKey:@"DownloadLimit"]; } -- (void) setGlobalLimit: (id) sender +- (void)setGlobalLimit:(id)sender { - [fDefaults setInteger: [sender intValue] forKey: sender == fUploadField ? @"UploadLimit" : @"DownloadLimit"]; - [self applySpeedSettings: self]; + [fDefaults setInteger:[sender intValue] forKey:sender == fUploadField ? @"UploadLimit" : @"DownloadLimit"]; + [self applySpeedSettings:self]; } -- (void) setSpeedLimit: (id) sender +- (void)setSpeedLimit:(id)sender { - [fDefaults setInteger: [sender intValue] forKey: sender == fSpeedLimitUploadField - ? @"SpeedLimitUploadLimit" : @"SpeedLimitDownloadLimit"]; + [fDefaults setInteger:[sender intValue] + forKey:sender == fSpeedLimitUploadField ? @"SpeedLimitUploadLimit" : @"SpeedLimitDownloadLimit"]; [self applyAltSpeedSettings]; } -- (void) setAutoSpeedLimit: (id) sender +- (void)setAutoSpeedLimit:(id)sender { - tr_sessionUseAltSpeedTime(fHandle, [fDefaults boolForKey: @"SpeedLimitAuto"]); + tr_sessionUseAltSpeedTime(fHandle, [fDefaults boolForKey:@"SpeedLimitAuto"]); } -- (void) setAutoSpeedLimitTime: (id) sender +- (void)setAutoSpeedLimitTime:(id)sender { - tr_sessionSetAltSpeedBegin(fHandle, [PrefsController dateToTimeSum: [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]]); - tr_sessionSetAltSpeedEnd(fHandle, [PrefsController dateToTimeSum: [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]]); + tr_sessionSetAltSpeedBegin(fHandle, [PrefsController dateToTimeSum:[fDefaults objectForKey:@"SpeedLimitAutoOnDate"]]); + tr_sessionSetAltSpeedEnd(fHandle, [PrefsController dateToTimeSum:[fDefaults objectForKey:@"SpeedLimitAutoOffDate"]]); } -- (void) setAutoSpeedLimitDay: (id) sender +- (void)setAutoSpeedLimitDay:(id)sender { tr_sessionSetAltSpeedDay(fHandle, [sender selectedItem].tag); } -+ (NSInteger) dateToTimeSum: (NSDate *) date ++ (NSInteger)dateToTimeSum:(NSDate*)date { - NSCalendar * calendar = NSCalendar.currentCalendar; - NSDateComponents * components = [calendar components: NSCalendarUnitHour | NSCalendarUnitMinute fromDate: date]; + NSCalendar* calendar = NSCalendar.currentCalendar; + NSDateComponents* components = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute fromDate:date]; return components.hour * 60 + components.minute; } -+ (NSDate *) timeSumToDate: (NSInteger) sum ++ (NSDate*)timeSumToDate:(NSInteger)sum { - NSDateComponents * comps = [[NSDateComponents alloc] init]; + NSDateComponents* comps = [[NSDateComponents alloc] init]; comps.hour = sum / 60; comps.minute = sum % 60; - return [NSCalendar.currentCalendar dateFromComponents: comps]; + return [NSCalendar.currentCalendar dateFromComponents:comps]; } -- (BOOL) control: (NSControl *) control textShouldBeginEditing: (NSText *) fieldEditor +- (BOOL)control:(NSControl*)control textShouldBeginEditing:(NSText*)fieldEditor { fInitialString = control.stringValue; return YES; } -- (BOOL) control: (NSControl *) control didFailToFormatString: (NSString *) string errorDescription: (NSString *) error +- (BOOL)control:(NSControl*)control didFailToFormatString:(NSString*)string errorDescription:(NSString*)error { NSBeep(); if (fInitialString) @@ -737,86 +802,88 @@ return NO; } -- (void) setBadge: (id) sender +- (void)setBadge:(id)sender { - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:self]; } -- (IBAction) openNotificationSystemPrefs: (NSButton *) sender +- (IBAction)openNotificationSystemPrefs:(NSButton*)sender { - [NSWorkspace.sharedWorkspace openURL: [NSURL fileURLWithPath:@"/System/Library/PreferencePanes/Notifications.prefPane"]]; + [NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:@"/System/Library/PreferencePanes/Notifications.prefPane"]]; } -- (void) resetWarnings: (id) sender +- (void)resetWarnings:(id)sender { - [fDefaults removeObjectForKey: @"WarningDuplicate"]; - [fDefaults removeObjectForKey: @"WarningRemainingSpace"]; - [fDefaults removeObjectForKey: @"WarningFolderDataSameName"]; - [fDefaults removeObjectForKey: @"WarningResetStats"]; - [fDefaults removeObjectForKey: @"WarningCreatorBlankAddress"]; - [fDefaults removeObjectForKey: @"WarningCreatorPrivateBlankAddress"]; - [fDefaults removeObjectForKey: @"WarningRemoveTrackers"]; - [fDefaults removeObjectForKey: @"WarningInvalidOpen"]; - [fDefaults removeObjectForKey: @"WarningRemoveCompleted"]; - [fDefaults removeObjectForKey: @"WarningDonate"]; + [fDefaults removeObjectForKey:@"WarningDuplicate"]; + [fDefaults removeObjectForKey:@"WarningRemainingSpace"]; + [fDefaults removeObjectForKey:@"WarningFolderDataSameName"]; + [fDefaults removeObjectForKey:@"WarningResetStats"]; + [fDefaults removeObjectForKey:@"WarningCreatorBlankAddress"]; + [fDefaults removeObjectForKey:@"WarningCreatorPrivateBlankAddress"]; + [fDefaults removeObjectForKey:@"WarningRemoveTrackers"]; + [fDefaults removeObjectForKey:@"WarningInvalidOpen"]; + [fDefaults removeObjectForKey:@"WarningRemoveCompleted"]; + [fDefaults removeObjectForKey:@"WarningDonate"]; //[fDefaults removeObjectForKey: @"WarningLegal"]; } -- (void) setDefaultForMagnets: (id) sender +- (void)setDefaultForMagnets:(id)sender { - NSString * bundleID = NSBundle.mainBundle.bundleIdentifier; - const OSStatus result = LSSetDefaultHandlerForURLScheme((CFStringRef)@"magnet", (__bridge CFStringRef)bundleID); + NSString* bundleID = NSBundle.mainBundle.bundleIdentifier; + OSStatus const result = LSSetDefaultHandlerForURLScheme((CFStringRef) @"magnet", (__bridge CFStringRef)bundleID); if (result != noErr) + { NSLog(@"Failed setting default magnet link handler"); + } } -- (void) setQueue: (id) sender +- (void)setQueue:(id)sender { //let's just do both - easier that way - tr_sessionSetQueueEnabled(fHandle, TR_DOWN, [fDefaults boolForKey: @"Queue"]); - tr_sessionSetQueueEnabled(fHandle, TR_UP, [fDefaults boolForKey: @"QueueSeed"]); + tr_sessionSetQueueEnabled(fHandle, TR_DOWN, [fDefaults boolForKey:@"Queue"]); + tr_sessionSetQueueEnabled(fHandle, TR_UP, [fDefaults boolForKey:@"QueueSeed"]); //handle if any transfers switch from queued to paused - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateQueue" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateQueue" object:self]; } -- (void) setQueueNumber: (id) sender +- (void)setQueueNumber:(id)sender { - const NSInteger number = [sender intValue]; - const BOOL seed = sender == fQueueSeedField; + NSInteger const number = [sender intValue]; + BOOL const seed = sender == fQueueSeedField; - [fDefaults setInteger: number forKey: seed ? @"QueueSeedNumber" : @"QueueDownloadNumber"]; + [fDefaults setInteger:number forKey:seed ? @"QueueSeedNumber" : @"QueueDownloadNumber"]; tr_sessionSetQueueSize(fHandle, seed ? TR_UP : TR_DOWN, number); } -- (void) setStalled: (id) sender +- (void)setStalled:(id)sender { - tr_sessionSetQueueStalledEnabled(fHandle, [fDefaults boolForKey: @"CheckStalled"]); + tr_sessionSetQueueStalledEnabled(fHandle, [fDefaults boolForKey:@"CheckStalled"]); //reload main table for stalled status - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; } -- (void) setStalledMinutes: (id) sender +- (void)setStalledMinutes:(id)sender { - const NSInteger min = [sender intValue]; - [fDefaults setInteger: min forKey: @"StalledMinutes"]; + NSInteger const min = [sender intValue]; + [fDefaults setInteger:min forKey:@"StalledMinutes"]; tr_sessionSetQueueStalledMinutes(fHandle, min); //reload main table for stalled status - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:self]; } -- (void) setDownloadLocation: (id) sender +- (void)setDownloadLocation:(id)sender { - [fDefaults setBool: fFolderPopUp.indexOfSelectedItem == DOWNLOAD_FOLDER forKey: @"DownloadLocationConstant"]; + [fDefaults setBool:fFolderPopUp.indexOfSelectedItem == DOWNLOAD_FOLDER forKey:@"DownloadLocationConstant"]; [self updateShowAddMagnetWindowField]; } -- (void) folderSheetShow: (id) sender +- (void)folderSheetShow:(id)sender { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; panel.prompt = NSLocalizedString(@"Select", "Preferences -> Open panel prompt"); panel.allowsMultipleSelection = NO; @@ -824,14 +891,14 @@ panel.canChooseDirectories = YES; panel.canCreateDirectories = YES; - [panel beginSheetModalForWindow: self.window completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) { - [fFolderPopUp selectItemAtIndex: DOWNLOAD_FOLDER]; + [fFolderPopUp selectItemAtIndex:DOWNLOAD_FOLDER]; - NSString * folder = panel.URLs[0].path; - [fDefaults setObject: folder forKey: @"DownloadFolder"]; - [fDefaults setBool: YES forKey: @"DownloadLocationConstant"]; + NSString* folder = panel.URLs[0].path; + [fDefaults setObject:folder forKey:@"DownloadFolder"]; + [fDefaults setBool:YES forKey:@"DownloadLocationConstant"]; [self updateShowAddMagnetWindowField]; assert(folder.length > 0); @@ -840,14 +907,14 @@ else { //reset if cancelled - [fFolderPopUp selectItemAtIndex: [fDefaults boolForKey: @"DownloadLocationConstant"] ? DOWNLOAD_FOLDER : DOWNLOAD_TORRENT]; + [fFolderPopUp selectItemAtIndex:[fDefaults boolForKey:@"DownloadLocationConstant"] ? DOWNLOAD_FOLDER : DOWNLOAD_TORRENT]; } }]; } -- (void) incompleteFolderSheetShow: (id) sender +- (void)incompleteFolderSheetShow:(id)sender { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; panel.prompt = NSLocalizedString(@"Select", "Preferences -> Open panel prompt"); panel.allowsMultipleSelection = NO; @@ -855,22 +922,22 @@ panel.canChooseDirectories = YES; panel.canCreateDirectories = YES; - [panel beginSheetModalForWindow: self.window completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) { - NSString * folder = panel.URLs[0].path; - [fDefaults setObject: folder forKey: @"IncompleteDownloadFolder"]; + NSString* folder = panel.URLs[0].path; + [fDefaults setObject:folder forKey:@"IncompleteDownloadFolder"]; assert(folder.length > 0); tr_sessionSetIncompleteDir(fHandle, folder.fileSystemRepresentation); } - [fIncompleteFolderPopUp selectItemAtIndex: 0]; + [fIncompleteFolderPopUp selectItemAtIndex:0]; }]; } -- (void) doneScriptSheetShow:(id)sender +- (void)doneScriptSheetShow:(id)sender { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; panel.prompt = NSLocalizedString(@"Select", "Preferences -> Open panel prompt"); panel.allowsMultipleSelection = NO; @@ -878,41 +945,41 @@ panel.canChooseDirectories = NO; panel.canCreateDirectories = NO; - [panel beginSheetModalForWindow: self.window completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) { - NSString * filePath = panel.URLs[0].path; + NSString* filePath = panel.URLs[0].path; assert(filePath.length > 0); - [fDefaults setObject: filePath forKey: @"DoneScriptPath"]; + [fDefaults setObject:filePath forKey:@"DoneScriptPath"]; tr_sessionSetTorrentDoneScript(fHandle, filePath.fileSystemRepresentation); - [fDefaults setBool: YES forKey: @"DoneScriptEnabled"]; + [fDefaults setBool:YES forKey:@"DoneScriptEnabled"]; tr_sessionSetTorrentDoneScriptEnabled(fHandle, YES); } - [fDoneScriptPopUp selectItemAtIndex: 0]; + [fDoneScriptPopUp selectItemAtIndex:0]; }]; } -- (void) setUseIncompleteFolder: (id) sender +- (void)setUseIncompleteFolder:(id)sender { - tr_sessionSetIncompleteDirEnabled(fHandle, [fDefaults boolForKey: @"UseIncompleteDownloadFolder"]); + tr_sessionSetIncompleteDirEnabled(fHandle, [fDefaults boolForKey:@"UseIncompleteDownloadFolder"]); } -- (void) setRenamePartialFiles: (id) sender +- (void)setRenamePartialFiles:(id)sender { - tr_sessionSetIncompleteFileNamingEnabled(fHandle, [fDefaults boolForKey: @"RenamePartialFiles"]); + tr_sessionSetIncompleteFileNamingEnabled(fHandle, [fDefaults boolForKey:@"RenamePartialFiles"]); } -- (void) setShowAddMagnetWindow: (id) sender +- (void)setShowAddMagnetWindow:(id)sender { - [fDefaults setBool: (fShowMagnetAddWindowCheck.state == NSOnState) forKey: @"MagnetOpenAsk"]; + [fDefaults setBool:(fShowMagnetAddWindowCheck.state == NSOnState) forKey:@"MagnetOpenAsk"]; } -- (void) updateShowAddMagnetWindowField +- (void)updateShowAddMagnetWindowField { - if (![fDefaults boolForKey: @"DownloadLocationConstant"]) + if (![fDefaults boolForKey:@"DownloadLocationConstant"]) { //always show the add window for magnet links when the download location is the same as the torrent file fShowMagnetAddWindowCheck.state = NSOnState; @@ -920,45 +987,50 @@ } else { - fShowMagnetAddWindowCheck.state = [fDefaults boolForKey: @"MagnetOpenAsk"]; + fShowMagnetAddWindowCheck.state = [fDefaults boolForKey:@"MagnetOpenAsk"]; fShowMagnetAddWindowCheck.enabled = YES; } } -- (void) setDoneScriptEnabled: (id) sender +- (void)setDoneScriptEnabled:(id)sender { - if ([fDefaults boolForKey: @"DoneScriptEnabled"] && ![NSFileManager.defaultManager fileExistsAtPath: [fDefaults stringForKey:@"DoneScriptPath"]]) + if ([fDefaults boolForKey:@"DoneScriptEnabled"] && + ![NSFileManager.defaultManager fileExistsAtPath:[fDefaults stringForKey:@"DoneScriptPath"]]) { // enabled is set but script file doesn't exist, so prompt for one and disable until they pick one - [fDefaults setBool: NO forKey: @"DoneScriptEnabled"]; - [self doneScriptSheetShow: sender]; + [fDefaults setBool:NO forKey:@"DoneScriptEnabled"]; + [self doneScriptSheetShow:sender]; } - tr_sessionSetTorrentDoneScriptEnabled(fHandle, [fDefaults boolForKey: @"DoneScriptEnabled"]); + tr_sessionSetTorrentDoneScriptEnabled(fHandle, [fDefaults boolForKey:@"DoneScriptEnabled"]); } -- (void) setAutoImport: (id) sender +- (void)setAutoImport:(id)sender { - NSString * path; - if ((path = [fDefaults stringForKey: @"AutoImportDirectory"])) + NSString* path; + if ((path = [fDefaults stringForKey:@"AutoImportDirectory"])) { - VDKQueue * watcherQueue = ((Controller *)NSApp.delegate).fileWatcherQueue; - if ([fDefaults boolForKey: @"AutoImport"]) + VDKQueue* watcherQueue = ((Controller*)NSApp.delegate).fileWatcherQueue; + if ([fDefaults boolForKey:@"AutoImport"]) { path = path.stringByExpandingTildeInPath; - [watcherQueue addPath: path notifyingAbout: VDKQueueNotifyAboutWrite]; + [watcherQueue addPath:path notifyingAbout:VDKQueueNotifyAboutWrite]; } else + { [watcherQueue removeAllPaths]; + } - [NSNotificationCenter.defaultCenter postNotificationName: @"AutoImportSettingChange" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"AutoImportSettingChange" object:self]; } else - [self importFolderSheetShow: nil]; + { + [self importFolderSheetShow:nil]; + } } -- (void) importFolderSheetShow: (id) sender +- (void)importFolderSheetShow:(id)sender { - NSOpenPanel * panel = [NSOpenPanel openPanel]; + NSOpenPanel* panel = [NSOpenPanel openPanel]; panel.prompt = NSLocalizedString(@"Select", "Preferences -> Open panel prompt"); panel.allowsMultipleSelection = NO; @@ -966,178 +1038,199 @@ panel.canChooseDirectories = YES; panel.canCreateDirectories = YES; - [panel beginSheetModalForWindow: self.window completionHandler: ^(NSInteger result) { + [panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { if (result == NSFileHandlingPanelOKButton) { - VDKQueue * watcherQueue = ((Controller *)NSApp.delegate).fileWatcherQueue; + VDKQueue* watcherQueue = ((Controller*)NSApp.delegate).fileWatcherQueue; [watcherQueue removeAllPaths]; - NSString * path = (panel.URLs[0]).path; - [fDefaults setObject: path forKey: @"AutoImportDirectory"]; - [watcherQueue addPath: path.stringByExpandingTildeInPath notifyingAbout: VDKQueueNotifyAboutWrite]; + NSString* path = (panel.URLs[0]).path; + [fDefaults setObject:path forKey:@"AutoImportDirectory"]; + [watcherQueue addPath:path.stringByExpandingTildeInPath notifyingAbout:VDKQueueNotifyAboutWrite]; - [NSNotificationCenter.defaultCenter postNotificationName: @"AutoImportSettingChange" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"AutoImportSettingChange" object:self]; } else { - NSString * path = [fDefaults stringForKey: @"AutoImportDirectory"]; + NSString* path = [fDefaults stringForKey:@"AutoImportDirectory"]; if (!path) - [fDefaults setBool: NO forKey: @"AutoImport"]; + [fDefaults setBool:NO forKey:@"AutoImport"]; } - [fImportFolderPopUp selectItemAtIndex: 0]; + [fImportFolderPopUp selectItemAtIndex:0]; }]; } -- (void) setAutoSize: (id) sender +- (void)setAutoSize:(id)sender { - [NSNotificationCenter.defaultCenter postNotificationName: @"AutoSizeSettingChange" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"AutoSizeSettingChange" object:self]; } -- (void) setRPCEnabled: (id) sender +- (void)setRPCEnabled:(id)sender { - BOOL enable = [fDefaults boolForKey: @"RPC"]; + BOOL enable = [fDefaults boolForKey:@"RPC"]; tr_sessionSetRPCEnabled(fHandle, enable); - [self setRPCWebUIDiscovery: nil]; + [self setRPCWebUIDiscovery:nil]; } -- (void) linkWebUI: (id) sender +- (void)linkWebUI:(id)sender { - NSString * urlString = [NSString stringWithFormat: WEBUI_URL, [fDefaults integerForKey: @"RPCPort"]]; - [NSWorkspace.sharedWorkspace openURL: [NSURL URLWithString: urlString]]; + NSString* urlString = [NSString stringWithFormat:WEBUI_URL, [fDefaults integerForKey:@"RPCPort"]]; + [NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:urlString]]; } -- (void) setRPCAuthorize: (id) sender +- (void)setRPCAuthorize:(id)sender { - tr_sessionSetRPCPasswordEnabled(fHandle, [fDefaults boolForKey: @"RPCAuthorize"]); + tr_sessionSetRPCPasswordEnabled(fHandle, [fDefaults boolForKey:@"RPCAuthorize"]); } -- (void) setRPCUsername: (id) sender +- (void)setRPCUsername:(id)sender { - tr_sessionSetRPCUsername(fHandle, [fDefaults stringForKey: @"RPCUsername"].UTF8String); + tr_sessionSetRPCUsername(fHandle, [fDefaults stringForKey:@"RPCUsername"].UTF8String); } -- (void) setRPCPassword: (id) sender +- (void)setRPCPassword:(id)sender { fRPCPassword = [[sender stringValue] copy]; - const char * password = [sender stringValue].UTF8String; - [self setKeychainPassword: password forService: RPC_KEYCHAIN_SERVICE username: RPC_KEYCHAIN_NAME]; + char const* password = [sender stringValue].UTF8String; + [self setKeychainPassword:password forService:RPC_KEYCHAIN_SERVICE username:RPC_KEYCHAIN_NAME]; tr_sessionSetRPCPassword(fHandle, password); } -- (void) updateRPCPassword +- (void)updateRPCPassword { UInt32 passwordLength; - const char * password = nil; - SecKeychainFindGenericPassword(NULL, strlen(RPC_KEYCHAIN_SERVICE), RPC_KEYCHAIN_SERVICE, - strlen(RPC_KEYCHAIN_NAME), RPC_KEYCHAIN_NAME, &passwordLength, (void **)&password, NULL); + char const* password = nil; + SecKeychainFindGenericPassword( + NULL, + strlen(RPC_KEYCHAIN_SERVICE), + RPC_KEYCHAIN_SERVICE, + strlen(RPC_KEYCHAIN_NAME), + RPC_KEYCHAIN_NAME, + &passwordLength, + (void**)&password, + NULL); if (password != NULL) { - char fullPassword[passwordLength+1]; + char fullPassword[passwordLength + 1]; strncpy(fullPassword, password, passwordLength); fullPassword[passwordLength] = '\0'; - SecKeychainItemFreeContent(NULL, (void *)password); + SecKeychainItemFreeContent(NULL, (void*)password); tr_sessionSetRPCPassword(fHandle, fullPassword); - fRPCPassword = [[NSString alloc] initWithUTF8String: fullPassword]; + fRPCPassword = [[NSString alloc] initWithUTF8String:fullPassword]; fRPCPasswordField.stringValue = fRPCPassword; } - else - fRPCPassword = nil; -} - -- (void) setRPCPort: (id) sender -{ - int port = [sender intValue]; - [fDefaults setInteger: port forKey: @"RPCPort"]; - tr_sessionSetRPCPort(fHandle, port); - - [self setRPCWebUIDiscovery: nil]; -} - -- (void) setRPCUseWhitelist: (id) sender -{ - tr_sessionSetRPCWhitelistEnabled(fHandle, [fDefaults boolForKey: @"RPCUseWhitelist"]); -} - -- (void) setRPCWebUIDiscovery: (id) sender -{ - if ([fDefaults boolForKey:@"RPC"] && [fDefaults boolForKey: @"RPCWebDiscovery"]) - [BonjourController.defaultController startWithPort: [fDefaults integerForKey: @"RPCPort"]]; else { - if (BonjourController.defaultControllerExists) - [BonjourController.defaultController stop]; + fRPCPassword = nil; } } -- (void) updateRPCWhitelist +- (void)setRPCPort:(id)sender { - NSString * string = [fRPCWhitelistArray componentsJoinedByString: @","]; + int port = [sender intValue]; + [fDefaults setInteger:port forKey:@"RPCPort"]; + tr_sessionSetRPCPort(fHandle, port); + + [self setRPCWebUIDiscovery:nil]; +} + +- (void)setRPCUseWhitelist:(id)sender +{ + tr_sessionSetRPCWhitelistEnabled(fHandle, [fDefaults boolForKey:@"RPCUseWhitelist"]); +} + +- (void)setRPCWebUIDiscovery:(id)sender +{ + if ([fDefaults boolForKey:@"RPC"] && [fDefaults boolForKey:@"RPCWebDiscovery"]) + { + [BonjourController.defaultController startWithPort:[fDefaults integerForKey:@"RPCPort"]]; + } + else + { + if (BonjourController.defaultControllerExists) + { + [BonjourController.defaultController stop]; + } + } +} + +- (void)updateRPCWhitelist +{ + NSString* string = [fRPCWhitelistArray componentsJoinedByString:@","]; tr_sessionSetRPCWhitelist(fHandle, string.UTF8String); } -- (void) addRemoveRPCIP: (id) sender +- (void)addRemoveRPCIP:(id)sender { //don't allow add/remove when currently adding - it leads to weird results if (fRPCWhitelistTable.editedRow != -1) - return; - - if ([[sender cell] tagForSegment: [sender selectedSegment]] == RPC_IP_REMOVE_TAG) { - [fRPCWhitelistArray removeObjectsAtIndexes: fRPCWhitelistTable.selectedRowIndexes]; - [fRPCWhitelistTable deselectAll: self]; + return; + } + + if ([[sender cell] tagForSegment:[sender selectedSegment]] == RPC_IP_REMOVE_TAG) + { + [fRPCWhitelistArray removeObjectsAtIndexes:fRPCWhitelistTable.selectedRowIndexes]; + [fRPCWhitelistTable deselectAll:self]; [fRPCWhitelistTable reloadData]; - [fDefaults setObject: fRPCWhitelistArray forKey: @"RPCWhitelist"]; + [fDefaults setObject:fRPCWhitelistArray forKey:@"RPCWhitelist"]; [self updateRPCWhitelist]; } else { - [fRPCWhitelistArray addObject: @""]; + [fRPCWhitelistArray addObject:@""]; [fRPCWhitelistTable reloadData]; - const int row = fRPCWhitelistArray.count - 1; - [fRPCWhitelistTable selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; - [fRPCWhitelistTable editColumn: 0 row: row withEvent: nil select: YES]; + int const row = fRPCWhitelistArray.count - 1; + [fRPCWhitelistTable selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO]; + [fRPCWhitelistTable editColumn:0 row:row withEvent:nil select:YES]; } } -- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView +- (NSInteger)numberOfRowsInTableView:(NSTableView*)tableView { return fRPCWhitelistArray.count; } -- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row +- (id)tableView:(NSTableView*)tableView objectValueForTableColumn:(NSTableColumn*)tableColumn row:(NSInteger)row { return fRPCWhitelistArray[row]; } -- (void) tableView: (NSTableView *) tableView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn - row: (NSInteger) row +- (void)tableView:(NSTableView*)tableView + setObjectValue:(id)object + forTableColumn:(NSTableColumn*)tableColumn + row:(NSInteger)row { - NSArray * components = [object componentsSeparatedByString: @"."]; - NSMutableArray * newComponents = [NSMutableArray arrayWithCapacity: 4]; + NSArray* components = [object componentsSeparatedByString:@"."]; + NSMutableArray* newComponents = [NSMutableArray arrayWithCapacity:4]; //create better-formatted ip string BOOL valid = false; if (components.count == 4) { valid = true; - for (NSString * component in components) + for (NSString* component in components) { - if ([component isEqualToString: @"*"]) - [newComponents addObject: component]; + if ([component isEqualToString:@"*"]) + { + [newComponents addObject:component]; + } else { int num = component.intValue; if (num >= 0 && num < 256) - [newComponents addObject: @(num).stringValue]; + { + [newComponents addObject:@(num).stringValue]; + } else { valid = false; @@ -1147,210 +1240,214 @@ } } - NSString * newIP; + NSString* newIP; if (valid) { - newIP = [newComponents componentsJoinedByString: @"."]; + newIP = [newComponents componentsJoinedByString:@"."]; //don't allow the same ip address - if ([fRPCWhitelistArray containsObject: newIP] && ![fRPCWhitelistArray[row] isEqualToString: newIP]) + if ([fRPCWhitelistArray containsObject:newIP] && ![fRPCWhitelistArray[row] isEqualToString:newIP]) + { valid = false; + } } if (valid) { fRPCWhitelistArray[row] = newIP; - [fRPCWhitelistArray sortUsingSelector: @selector(compareNumeric:)]; + [fRPCWhitelistArray sortUsingSelector:@selector(compareNumeric:)]; } else { NSBeep(); - if ([fRPCWhitelistArray[row] isEqualToString: @""]) - [fRPCWhitelistArray removeObjectAtIndex: row]; + if ([fRPCWhitelistArray[row] isEqualToString:@""]) + { + [fRPCWhitelistArray removeObjectAtIndex:row]; + } } - [fRPCWhitelistTable deselectAll: self]; + [fRPCWhitelistTable deselectAll:self]; [fRPCWhitelistTable reloadData]; - [fDefaults setObject: fRPCWhitelistArray forKey: @"RPCWhitelist"]; + [fDefaults setObject:fRPCWhitelistArray forKey:@"RPCWhitelist"]; [self updateRPCWhitelist]; } -- (void) tableViewSelectionDidChange: (NSNotification *) notification +- (void)tableViewSelectionDidChange:(NSNotification*)notification { - [fRPCAddRemoveControl setEnabled: fRPCWhitelistTable.numberOfSelectedRows > 0 forSegment: RPC_IP_REMOVE_TAG]; + [fRPCAddRemoveControl setEnabled:fRPCWhitelistTable.numberOfSelectedRows > 0 forSegment:RPC_IP_REMOVE_TAG]; } -- (void) helpForScript: (id) sender +- (void)helpForScript:(id)sender { - [NSHelpManager.sharedHelpManager openHelpAnchor: @"script" - inBook: [NSBundle.mainBundle objectForInfoDictionaryKey: @"CFBundleHelpBookName"]]; + [NSHelpManager.sharedHelpManager openHelpAnchor:@"script" + inBook:[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleHelpBookName"]]; } -- (void) helpForPeers: (id) sender +- (void)helpForPeers:(id)sender { - [NSHelpManager.sharedHelpManager openHelpAnchor: @"peers" - inBook: [NSBundle.mainBundle objectForInfoDictionaryKey: @"CFBundleHelpBookName"]]; + [NSHelpManager.sharedHelpManager openHelpAnchor:@"peers" + inBook:[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleHelpBookName"]]; } -- (void) helpForNetwork: (id) sender +- (void)helpForNetwork:(id)sender { - [NSHelpManager.sharedHelpManager openHelpAnchor: @"network" - inBook: [NSBundle.mainBundle objectForInfoDictionaryKey: @"CFBundleHelpBookName"]]; + [NSHelpManager.sharedHelpManager openHelpAnchor:@"network" + inBook:[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleHelpBookName"]]; } -- (void) helpForRemote: (id) sender +- (void)helpForRemote:(id)sender { - [NSHelpManager.sharedHelpManager openHelpAnchor: @"remote" - inBook: [NSBundle.mainBundle objectForInfoDictionaryKey: @"CFBundleHelpBookName"]]; + [NSHelpManager.sharedHelpManager openHelpAnchor:@"remote" + inBook:[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleHelpBookName"]]; } -- (void) rpcUpdatePrefs +- (void)rpcUpdatePrefs { //encryption - const tr_encryption_mode encryptionMode = tr_sessionGetEncryption(fHandle); - [fDefaults setBool: encryptionMode != TR_CLEAR_PREFERRED forKey: @"EncryptionPrefer"]; - [fDefaults setBool: encryptionMode == TR_ENCRYPTION_REQUIRED forKey: @"EncryptionRequire"]; + tr_encryption_mode const encryptionMode = tr_sessionGetEncryption(fHandle); + [fDefaults setBool:encryptionMode != TR_CLEAR_PREFERRED forKey:@"EncryptionPrefer"]; + [fDefaults setBool:encryptionMode == TR_ENCRYPTION_REQUIRED forKey:@"EncryptionRequire"]; //download directory - NSString * downloadLocation = @(tr_sessionGetDownloadDir(fHandle)).stringByStandardizingPath; - [fDefaults setObject: downloadLocation forKey: @"DownloadFolder"]; + NSString* downloadLocation = @(tr_sessionGetDownloadDir(fHandle)).stringByStandardizingPath; + [fDefaults setObject:downloadLocation forKey:@"DownloadFolder"]; - NSString * incompleteLocation = @(tr_sessionGetIncompleteDir(fHandle)).stringByStandardizingPath; - [fDefaults setObject: incompleteLocation forKey: @"IncompleteDownloadFolder"]; + NSString* incompleteLocation = @(tr_sessionGetIncompleteDir(fHandle)).stringByStandardizingPath; + [fDefaults setObject:incompleteLocation forKey:@"IncompleteDownloadFolder"]; - const BOOL useIncomplete = tr_sessionIsIncompleteDirEnabled(fHandle); - [fDefaults setBool: useIncomplete forKey: @"UseIncompleteDownloadFolder"]; + BOOL const useIncomplete = tr_sessionIsIncompleteDirEnabled(fHandle); + [fDefaults setBool:useIncomplete forKey:@"UseIncompleteDownloadFolder"]; - const BOOL usePartialFileRanaming = tr_sessionIsIncompleteFileNamingEnabled(fHandle); - [fDefaults setBool: usePartialFileRanaming forKey: @"RenamePartialFiles"]; + BOOL const usePartialFileRanaming = tr_sessionIsIncompleteFileNamingEnabled(fHandle); + [fDefaults setBool:usePartialFileRanaming forKey:@"RenamePartialFiles"]; //utp - const BOOL utp = tr_sessionIsUTPEnabled(fHandle); - [fDefaults setBool: utp forKey: @"UTPGlobal"]; + BOOL const utp = tr_sessionIsUTPEnabled(fHandle); + [fDefaults setBool:utp forKey:@"UTPGlobal"]; //peers - const uint16_t peersTotal = tr_sessionGetPeerLimit(fHandle); - [fDefaults setInteger: peersTotal forKey: @"PeersTotal"]; + uint16_t const peersTotal = tr_sessionGetPeerLimit(fHandle); + [fDefaults setInteger:peersTotal forKey:@"PeersTotal"]; - const uint16_t peersTorrent = tr_sessionGetPeerLimitPerTorrent(fHandle); - [fDefaults setInteger: peersTorrent forKey: @"PeersTorrent"]; + uint16_t const peersTorrent = tr_sessionGetPeerLimitPerTorrent(fHandle); + [fDefaults setInteger:peersTorrent forKey:@"PeersTorrent"]; //pex - const BOOL pex = tr_sessionIsPexEnabled(fHandle); - [fDefaults setBool: pex forKey: @"PEXGlobal"]; + BOOL const pex = tr_sessionIsPexEnabled(fHandle); + [fDefaults setBool:pex forKey:@"PEXGlobal"]; //dht - const BOOL dht = tr_sessionIsDHTEnabled(fHandle); - [fDefaults setBool: dht forKey: @"DHTGlobal"]; + BOOL const dht = tr_sessionIsDHTEnabled(fHandle); + [fDefaults setBool:dht forKey:@"DHTGlobal"]; //lpd - const BOOL lpd = tr_sessionIsLPDEnabled(fHandle); - [fDefaults setBool: lpd forKey: @"LocalPeerDiscoveryGlobal"]; + BOOL const lpd = tr_sessionIsLPDEnabled(fHandle); + [fDefaults setBool:lpd forKey:@"LocalPeerDiscoveryGlobal"]; //auto start - const BOOL autoStart = !tr_sessionGetPaused(fHandle); - [fDefaults setBool: autoStart forKey: @"AutoStartDownload"]; + BOOL const autoStart = !tr_sessionGetPaused(fHandle); + [fDefaults setBool:autoStart forKey:@"AutoStartDownload"]; //port - const tr_port port = tr_sessionGetPeerPort(fHandle); - [fDefaults setInteger: port forKey: @"BindPort"]; + tr_port const port = tr_sessionGetPeerPort(fHandle); + [fDefaults setInteger:port forKey:@"BindPort"]; - const BOOL nat = tr_sessionIsPortForwardingEnabled(fHandle); - [fDefaults setBool: nat forKey: @"NatTraversal"]; + BOOL const nat = tr_sessionIsPortForwardingEnabled(fHandle); + [fDefaults setBool:nat forKey:@"NatTraversal"]; fPeerPort = -1; fNatStatus = -1; [self updatePortStatus]; - const BOOL randomPort = tr_sessionGetPeerPortRandomOnStart(fHandle); - [fDefaults setBool: randomPort forKey: @"RandomPort"]; + BOOL const randomPort = tr_sessionGetPeerPortRandomOnStart(fHandle); + [fDefaults setBool:randomPort forKey:@"RandomPort"]; //speed limit - down - const BOOL downLimitEnabled = tr_sessionIsSpeedLimited(fHandle, TR_DOWN); - [fDefaults setBool: downLimitEnabled forKey: @"CheckDownload"]; + BOOL const downLimitEnabled = tr_sessionIsSpeedLimited(fHandle, TR_DOWN); + [fDefaults setBool:downLimitEnabled forKey:@"CheckDownload"]; - const int downLimit = tr_sessionGetSpeedLimit_KBps(fHandle, TR_DOWN); - [fDefaults setInteger: downLimit forKey: @"DownloadLimit"]; + int const downLimit = tr_sessionGetSpeedLimit_KBps(fHandle, TR_DOWN); + [fDefaults setInteger:downLimit forKey:@"DownloadLimit"]; //speed limit - up - const BOOL upLimitEnabled = tr_sessionIsSpeedLimited(fHandle, TR_UP); - [fDefaults setBool: upLimitEnabled forKey: @"CheckUpload"]; + BOOL const upLimitEnabled = tr_sessionIsSpeedLimited(fHandle, TR_UP); + [fDefaults setBool:upLimitEnabled forKey:@"CheckUpload"]; - const int upLimit = tr_sessionGetSpeedLimit_KBps(fHandle, TR_UP); - [fDefaults setInteger: upLimit forKey: @"UploadLimit"]; + int const upLimit = tr_sessionGetSpeedLimit_KBps(fHandle, TR_UP); + [fDefaults setInteger:upLimit forKey:@"UploadLimit"]; //alt speed limit enabled - const BOOL useAltSpeed = tr_sessionUsesAltSpeed(fHandle); - [fDefaults setBool: useAltSpeed forKey: @"SpeedLimit"]; + BOOL const useAltSpeed = tr_sessionUsesAltSpeed(fHandle); + [fDefaults setBool:useAltSpeed forKey:@"SpeedLimit"]; //alt speed limit - down - const int downLimitAlt = tr_sessionGetAltSpeed_KBps(fHandle, TR_DOWN); - [fDefaults setInteger: downLimitAlt forKey: @"SpeedLimitDownloadLimit"]; + int const downLimitAlt = tr_sessionGetAltSpeed_KBps(fHandle, TR_DOWN); + [fDefaults setInteger:downLimitAlt forKey:@"SpeedLimitDownloadLimit"]; //alt speed limit - up - const int upLimitAlt = tr_sessionGetAltSpeed_KBps(fHandle, TR_UP); - [fDefaults setInteger: upLimitAlt forKey: @"SpeedLimitUploadLimit"]; + int const upLimitAlt = tr_sessionGetAltSpeed_KBps(fHandle, TR_UP); + [fDefaults setInteger:upLimitAlt forKey:@"SpeedLimitUploadLimit"]; //alt speed limit schedule - const BOOL useAltSpeedSched = tr_sessionUsesAltSpeedTime(fHandle); - [fDefaults setBool: useAltSpeedSched forKey: @"SpeedLimitAuto"]; + BOOL const useAltSpeedSched = tr_sessionUsesAltSpeedTime(fHandle); + [fDefaults setBool:useAltSpeedSched forKey:@"SpeedLimitAuto"]; - NSDate * limitStartDate = [PrefsController timeSumToDate: tr_sessionGetAltSpeedBegin(fHandle)]; - [fDefaults setObject: limitStartDate forKey: @"SpeedLimitAutoOnDate"]; + NSDate* limitStartDate = [PrefsController timeSumToDate:tr_sessionGetAltSpeedBegin(fHandle)]; + [fDefaults setObject:limitStartDate forKey:@"SpeedLimitAutoOnDate"]; - NSDate * limitEndDate = [PrefsController timeSumToDate: tr_sessionGetAltSpeedEnd(fHandle)]; - [fDefaults setObject: limitEndDate forKey: @"SpeedLimitAutoOffDate"]; + NSDate* limitEndDate = [PrefsController timeSumToDate:tr_sessionGetAltSpeedEnd(fHandle)]; + [fDefaults setObject:limitEndDate forKey:@"SpeedLimitAutoOffDate"]; - const int limitDay = tr_sessionGetAltSpeedDay(fHandle); - [fDefaults setInteger: limitDay forKey: @"SpeedLimitAutoDay"]; + int const limitDay = tr_sessionGetAltSpeedDay(fHandle); + [fDefaults setInteger:limitDay forKey:@"SpeedLimitAutoDay"]; //blocklist - const BOOL blocklist = tr_blocklistIsEnabled(fHandle); - [fDefaults setBool: blocklist forKey: @"BlocklistNew"]; + BOOL const blocklist = tr_blocklistIsEnabled(fHandle); + [fDefaults setBool:blocklist forKey:@"BlocklistNew"]; - NSString * blocklistURL = @(tr_blocklistGetURL(fHandle)); - [fDefaults setObject: blocklistURL forKey: @"BlocklistURL"]; + NSString* blocklistURL = @(tr_blocklistGetURL(fHandle)); + [fDefaults setObject:blocklistURL forKey:@"BlocklistURL"]; //seed ratio - const BOOL ratioLimited = tr_sessionIsRatioLimited(fHandle); - [fDefaults setBool: ratioLimited forKey: @"RatioCheck"]; + BOOL const ratioLimited = tr_sessionIsRatioLimited(fHandle); + [fDefaults setBool:ratioLimited forKey:@"RatioCheck"]; - const float ratioLimit = tr_sessionGetRatioLimit(fHandle); - [fDefaults setFloat: ratioLimit forKey: @"RatioLimit"]; + float const ratioLimit = tr_sessionGetRatioLimit(fHandle); + [fDefaults setFloat:ratioLimit forKey:@"RatioLimit"]; //idle seed limit - const BOOL idleLimited = tr_sessionIsIdleLimited(fHandle); - [fDefaults setBool: idleLimited forKey: @"IdleLimitCheck"]; + BOOL const idleLimited = tr_sessionIsIdleLimited(fHandle); + [fDefaults setBool:idleLimited forKey:@"IdleLimitCheck"]; - const NSUInteger idleLimitMin = tr_sessionGetIdleLimit(fHandle); - [fDefaults setInteger: idleLimitMin forKey: @"IdleLimitMinutes"]; + NSUInteger const idleLimitMin = tr_sessionGetIdleLimit(fHandle); + [fDefaults setInteger:idleLimitMin forKey:@"IdleLimitMinutes"]; //queue - const BOOL downloadQueue = tr_sessionGetQueueEnabled(fHandle, TR_DOWN); - [fDefaults setBool: downloadQueue forKey: @"Queue"]; + BOOL const downloadQueue = tr_sessionGetQueueEnabled(fHandle, TR_DOWN); + [fDefaults setBool:downloadQueue forKey:@"Queue"]; - const int downloadQueueNum = tr_sessionGetQueueSize(fHandle, TR_DOWN); - [fDefaults setInteger: downloadQueueNum forKey: @"QueueDownloadNumber"]; + int const downloadQueueNum = tr_sessionGetQueueSize(fHandle, TR_DOWN); + [fDefaults setInteger:downloadQueueNum forKey:@"QueueDownloadNumber"]; - const BOOL seedQueue = tr_sessionGetQueueEnabled(fHandle, TR_UP); - [fDefaults setBool: seedQueue forKey: @"QueueSeed"]; + BOOL const seedQueue = tr_sessionGetQueueEnabled(fHandle, TR_UP); + [fDefaults setBool:seedQueue forKey:@"QueueSeed"]; - const int seedQueueNum = tr_sessionGetQueueSize(fHandle, TR_UP); - [fDefaults setInteger: seedQueueNum forKey: @"QueueSeedNumber"]; + int const seedQueueNum = tr_sessionGetQueueSize(fHandle, TR_UP); + [fDefaults setInteger:seedQueueNum forKey:@"QueueSeedNumber"]; - const BOOL checkStalled = tr_sessionGetQueueStalledEnabled(fHandle); - [fDefaults setBool: checkStalled forKey: @"CheckStalled"]; + BOOL const checkStalled = tr_sessionGetQueueStalledEnabled(fHandle); + [fDefaults setBool:checkStalled forKey:@"CheckStalled"]; - const int stalledMinutes = tr_sessionGetQueueStalledMinutes(fHandle); - [fDefaults setInteger: stalledMinutes forKey: @"StalledMinutes"]; + int const stalledMinutes = tr_sessionGetQueueStalledMinutes(fHandle); + [fDefaults setInteger:stalledMinutes forKey:@"StalledMinutes"]; //done script - const BOOL doneScriptEnabled = tr_sessionIsTorrentDoneScriptEnabled(fHandle); - [fDefaults setBool: doneScriptEnabled forKey: @"DoneScriptEnabled"]; + BOOL const doneScriptEnabled = tr_sessionIsTorrentDoneScriptEnabled(fHandle); + [fDefaults setBool:doneScriptEnabled forKey:@"DoneScriptEnabled"]; - NSString * doneScriptPath = @(tr_sessionGetTorrentDoneScript(fHandle)); - [fDefaults setObject: doneScriptPath forKey: @"DoneScriptPath"]; + NSString* doneScriptPath = @(tr_sessionGetTorrentDoneScript(fHandle)); + [fDefaults setObject:doneScriptPath forKey:@"DoneScriptPath"]; //update gui if loaded if (fHasLoaded) @@ -1406,40 +1503,54 @@ fStalledField.intValue = stalledMinutes; } - [NSNotificationCenter.defaultCenter postNotificationName: @"SpeedLimitUpdate" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"SpeedLimitUpdate" object:nil]; //reload global settings in inspector - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGlobalOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateGlobalOptions" object:nil]; } @end @implementation PrefsController (Private) -- (void) setPrefView: (id) sender +- (void)setPrefView:(id)sender { - NSString * identifier; + NSString* identifier; if (sender) { identifier = [sender itemIdentifier]; - [NSUserDefaults.standardUserDefaults setObject: identifier forKey: @"SelectedPrefView"]; + [NSUserDefaults.standardUserDefaults setObject:identifier forKey:@"SelectedPrefView"]; } else - identifier = [NSUserDefaults.standardUserDefaults stringForKey: @"SelectedPrefView"]; + { + identifier = [NSUserDefaults.standardUserDefaults stringForKey:@"SelectedPrefView"]; + } - NSView * view; - if ([identifier isEqualToString: TOOLBAR_TRANSFERS]) + NSView* view; + if ([identifier isEqualToString:TOOLBAR_TRANSFERS]) + { view = fTransfersView; - else if ([identifier isEqualToString: TOOLBAR_GROUPS]) + } + else if ([identifier isEqualToString:TOOLBAR_GROUPS]) + { view = fGroupsView; - else if ([identifier isEqualToString: TOOLBAR_BANDWIDTH]) + } + else if ([identifier isEqualToString:TOOLBAR_BANDWIDTH]) + { view = fBandwidthView; - else if ([identifier isEqualToString: TOOLBAR_PEERS]) + } + else if ([identifier isEqualToString:TOOLBAR_PEERS]) + { view = fPeersView; - else if ([identifier isEqualToString: TOOLBAR_NETWORK]) + } + else if ([identifier isEqualToString:TOOLBAR_NETWORK]) + { view = fNetworkView; - else if ([identifier isEqualToString: TOOLBAR_REMOTE]) + } + else if ([identifier isEqualToString:TOOLBAR_REMOTE]) + { view = fRemoteView; + } else { identifier = TOOLBAR_GENERAL; //general view is the default selected @@ -1448,42 +1559,48 @@ self.window.toolbar.selectedItemIdentifier = identifier; - NSWindow * window = self.window; + NSWindow* window = self.window; if (window.contentView == view) + { return; + } NSRect windowRect = window.frame; - const CGFloat difference = NSHeight(view.frame) - NSHeight(window.contentView.frame); + CGFloat const difference = NSHeight(view.frame) - NSHeight(window.contentView.frame); windowRect.origin.y -= difference; windowRect.size.height += difference; view.hidden = YES; window.contentView = view; - [window setFrame: windowRect display: YES animate: YES]; + [window setFrame:windowRect display:YES animate:YES]; view.hidden = NO; //set title label if (sender) + { window.title = [sender label]; + } else { - NSToolbar * toolbar = window.toolbar; - NSString * itemIdentifier = toolbar.selectedItemIdentifier; - for (NSToolbarItem * item in toolbar.items) - if ([item.itemIdentifier isEqualToString: itemIdentifier]) + NSToolbar* toolbar = window.toolbar; + NSString* itemIdentifier = toolbar.selectedItemIdentifier; + for (NSToolbarItem* item in toolbar.items) + { + if ([item.itemIdentifier isEqualToString:itemIdentifier]) { window.title = item.label; break; } + } } } -static NSString * getOSStatusDescription(OSStatus errorCode) +static NSString* getOSStatusDescription(OSStatus errorCode) { - return [NSError errorWithDomain: NSOSStatusErrorDomain code: errorCode userInfo: NULL].description; + return [NSError errorWithDomain:NSOSStatusErrorDomain code:errorCode userInfo:NULL].description; } -- (void) setKeychainPassword: (const char *) password forService: (const char *) service username: (const char *) username +- (void)setKeychainPassword:(char const*)password forService:(char const*)service username:(char const*)username { SecKeychainItemRef item = NULL; NSUInteger passwordLength = strlen(password); @@ -1493,9 +1610,11 @@ static NSString * getOSStatusDescription(OSStatus errorCode) { if (passwordLength > 0) //found, so update { - result = SecKeychainItemModifyAttributesAndData(item, NULL, passwordLength, (const void *)password); + result = SecKeychainItemModifyAttributesAndData(item, NULL, passwordLength, (void const*)password); if (result != noErr) + { NSLog(@"Problem updating Keychain item: %@", getOSStatusDescription(result)); + } } else //remove the item { @@ -1510,14 +1629,17 @@ static NSString * getOSStatusDescription(OSStatus errorCode) { if (passwordLength > 0) { - result = SecKeychainAddGenericPassword(NULL, strlen(service), service, strlen(username), username, - passwordLength, (const void *)password, NULL); + result = SecKeychainAddGenericPassword(NULL, strlen(service), service, strlen(username), username, passwordLength, (void const*)password, NULL); if (result != noErr) + { NSLog(@"Problem adding Keychain item: %@", getOSStatusDescription(result)); + } } } else + { NSLog(@"Problem accessing Keychain: %@", getOSStatusDescription(result)); + } } @end diff --git a/macosx/PrefsWindow.m b/macosx/PrefsWindow.m index 9e84ff4f0..c203cec85 100644 --- a/macosx/PrefsWindow.m +++ b/macosx/PrefsWindow.m @@ -24,25 +24,31 @@ @implementation PrefsWindow -- (void)awakeFromNib { +- (void)awakeFromNib +{ [super awakeFromNib]; - - if (@available(macOS 11.0, *)) { + + if (@available(macOS 11.0, *)) + { self.toolbarStyle = NSWindowToolbarStylePreference; } } -- (void) keyDown: (NSEvent *) event +- (void)keyDown:(NSEvent*)event { if (event.keyCode == 53) //esc key + { [self close]; + } else - [super keyDown: event]; + { + [super keyDown:event]; + } } -- (void) close +- (void)close { - [self makeFirstResponder: nil]; //essentially saves pref changes on window close + [self makeFirstResponder:nil]; //essentially saves pref changes on window close [super close]; } diff --git a/macosx/ProgressGradients.h b/macosx/ProgressGradients.h index 5b8c069e0..c2a2ecac9 100644 --- a/macosx/ProgressGradients.h +++ b/macosx/ProgressGradients.h @@ -25,15 +25,15 @@ @interface ProgressGradients : NSObject -@property (nonatomic, class, readonly) NSGradient * progressWhiteGradient; -@property (nonatomic, class, readonly) NSGradient * progressGrayGradient; -@property (nonatomic, class, readonly) NSGradient * progressLightGrayGradient; -@property (nonatomic, class, readonly) NSGradient * progressBlueGradient; -@property (nonatomic, class, readonly) NSGradient * progressDarkBlueGradient; -@property (nonatomic, class, readonly) NSGradient * progressGreenGradient; -@property (nonatomic, class, readonly) NSGradient * progressLightGreenGradient; -@property (nonatomic, class, readonly) NSGradient * progressDarkGreenGradient; -@property (nonatomic, class, readonly) NSGradient * progressRedGradient; -@property (nonatomic, class, readonly) NSGradient * progressYellowGradient; +@property(nonatomic, class, readonly) NSGradient* progressWhiteGradient; +@property(nonatomic, class, readonly) NSGradient* progressGrayGradient; +@property(nonatomic, class, readonly) NSGradient* progressLightGrayGradient; +@property(nonatomic, class, readonly) NSGradient* progressBlueGradient; +@property(nonatomic, class, readonly) NSGradient* progressDarkBlueGradient; +@property(nonatomic, class, readonly) NSGradient* progressGreenGradient; +@property(nonatomic, class, readonly) NSGradient* progressLightGreenGradient; +@property(nonatomic, class, readonly) NSGradient* progressDarkGreenGradient; +@property(nonatomic, class, readonly) NSGradient* progressRedGradient; +@property(nonatomic, class, readonly) NSGradient* progressYellowGradient; @end diff --git a/macosx/ProgressGradients.m b/macosx/ProgressGradients.m index 597bd39d6..5a72baa88 100644 --- a/macosx/ProgressGradients.m +++ b/macosx/ProgressGradients.m @@ -25,112 +25,142 @@ @implementation ProgressGradients (Private) -+ (NSGradient *) progressGradientForRed: (CGFloat) redComponent green: (CGFloat) greenComponent blue: (CGFloat) blueComponent ++ (NSGradient*)progressGradientForRed:(CGFloat)redComponent green:(CGFloat)greenComponent blue:(CGFloat)blueComponent { - const CGFloat alpha = [NSUserDefaults.standardUserDefaults boolForKey: @"SmallView"] ? 0.27 : 1.0; + CGFloat const alpha = [NSUserDefaults.standardUserDefaults boolForKey:@"SmallView"] ? 0.27 : 1.0; - NSColor * baseColor = [NSColor colorWithCalibratedRed: redComponent green: greenComponent blue: blueComponent alpha: alpha]; + NSColor* baseColor = [NSColor colorWithCalibratedRed:redComponent green:greenComponent blue:blueComponent alpha:alpha]; - NSColor * color2 = [NSColor colorWithCalibratedRed: redComponent * 0.95 green: greenComponent * 0.95 blue: blueComponent * 0.95 - alpha: alpha]; + NSColor* color2 = [NSColor colorWithCalibratedRed:redComponent * 0.95 green:greenComponent * 0.95 blue:blueComponent * 0.95 + alpha:alpha]; - NSColor * color3 = [NSColor colorWithCalibratedRed: redComponent * 0.85 green: greenComponent * 0.85 blue: blueComponent * 0.85 - alpha: alpha]; + NSColor* color3 = [NSColor colorWithCalibratedRed:redComponent * 0.85 green:greenComponent * 0.85 blue:blueComponent * 0.85 + alpha:alpha]; - return [[NSGradient alloc] initWithColorsAndLocations: baseColor, 0.0, color2, 0.5, color3, 0.5, baseColor, 1.0, nil]; + return [[NSGradient alloc] initWithColorsAndLocations:baseColor, 0.0, color2, 0.5, color3, 0.5, baseColor, 1.0, nil]; } @end @implementation ProgressGradients -+ (NSGradient *) progressWhiteGradient ++ (NSGradient*)progressWhiteGradient { - if ([NSApp isDarkMode]) { - return [[self class] progressGradientForRed: 0.1 green: 0.1 blue: 0.1]; - } else { - return [[self class] progressGradientForRed: 0.95 green: 0.95 blue: 0.95]; + if ([NSApp isDarkMode]) + { + return [[self class] progressGradientForRed:0.1 green:0.1 blue:0.1]; + } + else + { + return [[self class] progressGradientForRed:0.95 green:0.95 blue:0.95]; } } -+ (NSGradient *) progressGrayGradient ++ (NSGradient*)progressGrayGradient { - if ([NSApp isDarkMode]) { - return [[self class] progressGradientForRed: 0.35 green: 0.35 blue: 0.35]; - } else { - return [[self class] progressGradientForRed: 0.7 green: 0.7 blue: 0.7]; + if ([NSApp isDarkMode]) + { + return [[self class] progressGradientForRed:0.35 green:0.35 blue:0.35]; + } + else + { + return [[self class] progressGradientForRed:0.7 green:0.7 blue:0.7]; } } -+ (NSGradient *) progressLightGrayGradient ++ (NSGradient*)progressLightGrayGradient { - if ([NSApp isDarkMode]) { - return [[self class] progressGradientForRed: 0.2 green: 0.2 blue: 0.2]; - } else { - return [[self class] progressGradientForRed: 0.87 green: 0.87 blue: 0.87]; + if ([NSApp isDarkMode]) + { + return [[self class] progressGradientForRed:0.2 green:0.2 blue:0.2]; + } + else + { + return [[self class] progressGradientForRed:0.87 green:0.87 blue:0.87]; } } -+ (NSGradient *) progressBlueGradient ++ (NSGradient*)progressBlueGradient { - if ([NSApp isDarkMode]) { - return [[self class] progressGradientForRed: 0.35 * 2.0/3.0 green: 0.67 * 2.0/3.0 blue: 0.98 * 2.0/3.0]; - } else { - return [[self class] progressGradientForRed: 0.35 green: 0.67 blue: 0.98]; + if ([NSApp isDarkMode]) + { + return [[self class] progressGradientForRed:0.35 * 2.0 / 3.0 green:0.67 * 2.0 / 3.0 blue:0.98 * 2.0 / 3.0]; + } + else + { + return [[self class] progressGradientForRed:0.35 green:0.67 blue:0.98]; } } -+ (NSGradient *) progressDarkBlueGradient ++ (NSGradient*)progressDarkBlueGradient { - if ([NSApp isDarkMode]) { - return [[self class] progressGradientForRed: 0.616 * 2.0/3.0 green: 0.722 * 2.0/3.0 blue: 0.776 * 2.0/3.0]; - } else { - return [[self class] progressGradientForRed: 0.616 green: 0.722 blue: 0.776]; + if ([NSApp isDarkMode]) + { + return [[self class] progressGradientForRed:0.616 * 2.0 / 3.0 green:0.722 * 2.0 / 3.0 blue:0.776 * 2.0 / 3.0]; + } + else + { + return [[self class] progressGradientForRed:0.616 green:0.722 blue:0.776]; } } -+ (NSGradient *) progressGreenGradient ++ (NSGradient*)progressGreenGradient { - if ([NSApp isDarkMode]) { - return [[self class] progressGradientForRed: 0.44 * 2.0/3.0 green: 0.89 * 2.0/3.0 blue: 0.40 * 2.0/3.0]; - } else { - return [[self class] progressGradientForRed: 0.44 green: 0.89 blue: 0.40]; + if ([NSApp isDarkMode]) + { + return [[self class] progressGradientForRed:0.44 * 2.0 / 3.0 green:0.89 * 2.0 / 3.0 blue:0.40 * 2.0 / 3.0]; + } + else + { + return [[self class] progressGradientForRed:0.44 green:0.89 blue:0.40]; } } -+ (NSGradient *) progressLightGreenGradient ++ (NSGradient*)progressLightGreenGradient { - if ([NSApp isDarkMode]) { - return [[self class] progressGradientForRed: 0.62 * 3.0/4.0 green: 0.99 * 3.0/4.0 blue: 0.58 * 3.0/4.0]; - } else { - return [[self class] progressGradientForRed: 0.62 green: 0.99 blue: 0.58]; + if ([NSApp isDarkMode]) + { + return [[self class] progressGradientForRed:0.62 * 3.0 / 4.0 green:0.99 * 3.0 / 4.0 blue:0.58 * 3.0 / 4.0]; + } + else + { + return [[self class] progressGradientForRed:0.62 green:0.99 blue:0.58]; } } -+ (NSGradient *) progressDarkGreenGradient ++ (NSGradient*)progressDarkGreenGradient { - if ([NSApp isDarkMode]) { - return [[self class] progressGradientForRed: 0.627 * 2.0/3.0 green: 0.714 * 2.0/3.0 blue: 0.639 * 2.0/3.0]; - } else { - return [[self class] progressGradientForRed: 0.627 green: 0.714 blue: 0.639]; + if ([NSApp isDarkMode]) + { + return [[self class] progressGradientForRed:0.627 * 2.0 / 3.0 green:0.714 * 2.0 / 3.0 blue:0.639 * 2.0 / 3.0]; + } + else + { + return [[self class] progressGradientForRed:0.627 green:0.714 blue:0.639]; } } -+ (NSGradient *) progressRedGradient ++ (NSGradient*)progressRedGradient { - if ([NSApp isDarkMode]) { - return [[self class] progressGradientForRed: 0.902 * 2.0/3.0 green: 0.439 * 2.0/3.0 blue: 0.451 * 2.0/3.0]; - } else { - return [[self class] progressGradientForRed: 0.902 green: 0.439 blue: 0.451]; + if ([NSApp isDarkMode]) + { + return [[self class] progressGradientForRed:0.902 * 2.0 / 3.0 green:0.439 * 2.0 / 3.0 blue:0.451 * 2.0 / 3.0]; + } + else + { + return [[self class] progressGradientForRed:0.902 green:0.439 blue:0.451]; } } -+ (NSGradient *) progressYellowGradient ++ (NSGradient*)progressYellowGradient { - if ([NSApp isDarkMode]) { - return [[self class] progressGradientForRed: 0.933 * 0.8 green: 0.890 * 0.8 blue: 0.243 * 0.8]; - } else { - return [[self class] progressGradientForRed: 0.933 green: 0.890 blue: 0.243]; + if ([NSApp isDarkMode]) + { + return [[self class] progressGradientForRed:0.933 * 0.8 green:0.890 * 0.8 blue:0.243 * 0.8]; + } + else + { + return [[self class] progressGradientForRed:0.933 green:0.890 blue:0.243]; } } diff --git a/macosx/QuickLookPlugin/GeneratePreviewForURL.m b/macosx/QuickLookPlugin/GeneratePreviewForURL.m index 461617cbb..8fab60af7 100644 --- a/macosx/QuickLookPlugin/GeneratePreviewForURL.m +++ b/macosx/QuickLookPlugin/GeneratePreviewForURL.m @@ -4,179 +4,238 @@ #import "NSStringAdditions.h" -OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options); -void CancelPreviewGeneration(void *thisInterface, QLPreviewRequestRef preview); +OSStatus GeneratePreviewForURL(void* thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options); +void CancelPreviewGeneration(void* thisInterface, QLPreviewRequestRef preview); -NSString * generateIconData(NSString * fileExtension, NSUInteger width, NSMutableDictionary * allImgProps) +NSString* generateIconData(NSString* fileExtension, NSUInteger width, NSMutableDictionary* allImgProps) { - NSString * rawFilename = ![fileExtension isEqualToString: @""] ? fileExtension : @"blank_file_name_transmission"; - NSString * iconFileName = [NSString stringWithFormat: @"%ldx%@.tiff", width, rawFilename]; //we need to do this once per file extension, per size + NSString* rawFilename = ![fileExtension isEqualToString:@""] ? fileExtension : @"blank_file_name_transmission"; + // we need to do this once per file extension, per size + NSString* iconFileName = [NSString stringWithFormat:@"%ldx%@.tiff", width, rawFilename]; - if (![allImgProps objectForKey: iconFileName]) + if (![allImgProps objectForKey:iconFileName]) { - NSImage * icon = [[NSWorkspace sharedWorkspace] iconForFileType: fileExtension]; + NSImage* icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileExtension]; - const NSRect iconFrame = NSMakeRect(0.0, 0.0, width, width); - NSImage * renderedIcon = [[NSImage alloc] initWithSize: iconFrame.size]; + NSRect const iconFrame = NSMakeRect(0.0, 0.0, width, width); + NSImage* renderedIcon = [[NSImage alloc] initWithSize:iconFrame.size]; [renderedIcon lockFocus]; - [icon drawInRect: iconFrame fromRect: NSZeroRect operation: NSCompositeCopy fraction: 1.0]; + [icon drawInRect:iconFrame fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0]; [renderedIcon unlockFocus]; - NSData * iconData = [renderedIcon TIFFRepresentation]; + NSData* iconData = [renderedIcon TIFFRepresentation]; - NSDictionary * imgProps = @{ - (NSString *)kQLPreviewPropertyMIMETypeKey : @"image/png", - (NSString *)kQLPreviewPropertyAttachmentDataKey : iconData }; - [allImgProps setObject: imgProps forKey: iconFileName]; + NSDictionary* imgProps = @{ + (NSString*)kQLPreviewPropertyMIMETypeKey : @"image/png", + (NSString*)kQLPreviewPropertyAttachmentDataKey : iconData + }; + [allImgProps setObject:imgProps forKey:iconFileName]; } - return [@"cid:" stringByAppendingString: iconFileName]; + return [@"cid:" stringByAppendingString:iconFileName]; } -OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options) +OSStatus GeneratePreviewForURL(void* thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options) { // Before proceeding make sure the user didn't cancel the request if (QLPreviewRequestIsCancelled(preview)) + { return noErr; + } //we need this call to ensure NSApp is initialized (not done automatically for plugins) [NSApplication sharedApplication]; //try to parse the torrent file tr_info inf; - tr_ctor * ctor = tr_ctorNew(NULL); - tr_ctorSetMetainfoFromFile(ctor, [[(__bridge NSURL *)url path] UTF8String]); - const int err = tr_torrentParse(ctor, &inf); + tr_ctor* ctor = tr_ctorNew(NULL); + tr_ctorSetMetainfoFromFile(ctor, [[(__bridge NSURL*)url path] UTF8String]); + int const err = tr_torrentParse(ctor, &inf); tr_ctorFree(ctor); if (err) + { return noErr; + } - NSBundle * bundle = [NSBundle bundleWithIdentifier: @"org.m0k.transmission.QuickLookPlugin"]; + NSBundle* bundle = [NSBundle bundleWithIdentifier:@"org.m0k.transmission.QuickLookPlugin"]; - NSURL * styleURL = [bundle URLForResource: @"style" withExtension: @"css"]; - NSString * styleContents = [NSString stringWithContentsOfURL: styleURL encoding: NSUTF8StringEncoding error: NULL]; + NSURL* styleURL = [bundle URLForResource:@"style" withExtension:@"css"]; + NSString* styleContents = [NSString stringWithContentsOfURL:styleURL encoding:NSUTF8StringEncoding error:NULL]; - NSMutableString * htmlString = [NSMutableString string]; - [htmlString appendFormat: @"", styleContents]; + NSMutableString* htmlString = [NSMutableString string]; + [htmlString appendFormat:@"", styleContents]; - NSMutableDictionary * allImgProps = [NSMutableDictionary dictionary]; + NSMutableDictionary* allImgProps = [NSMutableDictionary dictionary]; - NSString * name = [NSString stringWithUTF8String: inf.name]; - NSString * fileTypeString = inf.isFolder ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) : [name pathExtension]; + NSString* name = [NSString stringWithUTF8String:inf.name]; + NSString* fileTypeString = inf.isFolder ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) : [name pathExtension]; - const NSUInteger width = 32; - [htmlString appendFormat: @"

%@

", generateIconData(fileTypeString, width, allImgProps), width, width, name]; + NSUInteger const width = 32; + [htmlString appendFormat:@"

%@

", + generateIconData(fileTypeString, width, allImgProps), + width, + width, + name]; - NSString * fileSizeString = [NSString stringForFileSize: inf.totalSize]; + NSString* fileSizeString = [NSString stringForFileSize:inf.totalSize]; if (inf.isFolder) { - NSString * fileCountString; + NSString* fileCountString; if (inf.fileCount == 1) + { fileCountString = NSLocalizedStringFromTableInBundle(@"1 file", nil, bundle, "quicklook file count"); + } else - fileCountString= [NSString stringWithFormat: NSLocalizedStringFromTableInBundle(@"%@ files", nil, bundle, "quicklook file count"), [NSString formattedUInteger: inf.fileCount]]; - fileSizeString = [NSString stringWithFormat: @"%@, %@", fileCountString, fileSizeString]; + { + fileCountString = [NSString stringWithFormat:NSLocalizedStringFromTableInBundle(@"%@ files", nil, bundle, "quicklook file count"), + [NSString formattedUInteger:inf.fileCount]]; + } + fileSizeString = [NSString stringWithFormat:@"%@, %@", fileCountString, fileSizeString]; } - [htmlString appendFormat: @"

%@

", fileSizeString]; + [htmlString appendFormat:@"

%@

", fileSizeString]; - NSString * dateCreatedString = inf.dateCreated > 0 ? [NSDateFormatter localizedStringFromDate: [NSDate dateWithTimeIntervalSince1970: inf.dateCreated] dateStyle: NSDateFormatterLongStyle timeStyle: NSDateFormatterShortStyle] : nil; - NSString * creatorString = inf.creator ? [NSString stringWithUTF8String: inf.creator] : nil; - if ([creatorString isEqualToString: @""]) creatorString = nil; - NSString * creationString = nil; + NSString* dateCreatedString = inf.dateCreated > 0 ? + [NSDateFormatter localizedStringFromDate:[NSDate dateWithTimeIntervalSince1970:inf.dateCreated] dateStyle:NSDateFormatterLongStyle + timeStyle:NSDateFormatterShortStyle] : + nil; + NSString* creatorString = inf.creator ? [NSString stringWithUTF8String:inf.creator] : nil; + if ([creatorString isEqualToString:@""]) + { + creatorString = nil; + } + NSString* creationString = nil; if (dateCreatedString && creatorString) - creationString = [NSString stringWithFormat: NSLocalizedStringFromTableInBundle(@"Created on %@ with %@", nil, bundle, "quicklook creation info"), dateCreatedString, creatorString]; + { + creationString = [NSString + stringWithFormat:NSLocalizedStringFromTableInBundle(@"Created on %@ with %@", nil, bundle, "quicklook creation info"), + dateCreatedString, + creatorString]; + } else if (dateCreatedString) - creationString = [NSString stringWithFormat: NSLocalizedStringFromTableInBundle(@"Created on %@", nil, bundle, "quicklook creation info"), dateCreatedString]; + { + creationString = [NSString + stringWithFormat:NSLocalizedStringFromTableInBundle(@"Created on %@", nil, bundle, "quicklook creation info"), dateCreatedString]; + } else if (creatorString) - creationString = [NSString stringWithFormat: NSLocalizedStringFromTableInBundle(@"Created with %@", nil, bundle, "quicklook creation info"), creatorString]; + { + creationString = [NSString + stringWithFormat:NSLocalizedStringFromTableInBundle(@"Created with %@", nil, bundle, "quicklook creation info"), creatorString]; + } if (creationString) - [htmlString appendFormat: @"

%@

", creationString]; + { + [htmlString appendFormat:@"

%@

", creationString]; + } if (inf.comment) { - NSString * comment = [NSString stringWithUTF8String: inf.comment]; - if (![comment isEqualToString: @""]) - [htmlString appendFormat: @"

%@

", comment]; + NSString* comment = [NSString stringWithUTF8String:inf.comment]; + if (![comment isEqualToString:@""]) + [htmlString appendFormat:@"

%@

", comment]; } - NSMutableArray * lists = [NSMutableArray array]; + NSMutableArray* lists = [NSMutableArray array]; if (inf.webseedCount > 0) { - NSMutableString * listSection = [NSMutableString string]; - [listSection appendString: @""]; + NSMutableString* listSection = [NSMutableString string]; + [listSection appendString:@"
"]; - NSString * headerTitleString = inf.webseedCount == 1 ? NSLocalizedStringFromTableInBundle(@"1 Web Seed", nil, bundle, "quicklook web seed header") : [NSString stringWithFormat: NSLocalizedStringFromTableInBundle(@"%@ Web Seeds", nil, bundle, "quicklook web seed header"), [NSString formattedUInteger: inf.webseedCount]]; - [listSection appendFormat: @"", headerTitleString]; + NSString* headerTitleString = inf.webseedCount == 1 ? + NSLocalizedStringFromTableInBundle(@"1 Web Seed", nil, bundle, "quicklook web seed header") : + [NSString stringWithFormat:NSLocalizedStringFromTableInBundle(@"%@ Web Seeds", nil, bundle, "quicklook web seed header"), + [NSString formattedUInteger:inf.webseedCount]]; + [listSection appendFormat:@"", headerTitleString]; for (int i = 0; i < inf.webseedCount; ++i) - [listSection appendFormat: @"", inf.webseeds[i]]; + { + [listSection appendFormat:@"", inf.webseeds[i]]; + } [listSection appendString:@"
%@
%@
%s
%s
"]; - [lists addObject: listSection]; + [lists addObject:listSection]; } if (inf.trackerCount > 0) { - NSMutableString * listSection = [NSMutableString string]; - [listSection appendString: @""]; + NSMutableString* listSection = [NSMutableString string]; + [listSection appendString:@"
"]; - NSString * headerTitleString = inf.trackerCount == 1 ? NSLocalizedStringFromTableInBundle(@"1 Tracker", nil, bundle, "quicklook tracker header") : [NSString stringWithFormat: NSLocalizedStringFromTableInBundle(@"%@ Trackers", nil, bundle, "quicklook tracker header"), [NSString formattedUInteger: inf.trackerCount]]; - [listSection appendFormat: @"", headerTitleString]; + NSString* headerTitleString = inf.trackerCount == 1 ? + NSLocalizedStringFromTableInBundle(@"1 Tracker", nil, bundle, "quicklook tracker header") : + [NSString stringWithFormat:NSLocalizedStringFromTableInBundle(@"%@ Trackers", nil, bundle, "quicklook tracker header"), + [NSString formattedUInteger:inf.trackerCount]]; + [listSection appendFormat:@"", headerTitleString]; #warning handle tiers? for (int i = 0; i < inf.trackerCount; ++i) - [listSection appendFormat: @"", inf.trackers[i].announce]; + { + [listSection appendFormat:@"", inf.trackers[i].announce]; + } [listSection appendString:@"
%@
%@
%s
%s
"]; - [lists addObject: listSection]; + [lists addObject:listSection]; } if (inf.isFolder) { - NSMutableString * listSection = [NSMutableString string]; - [listSection appendString: @""]; + NSMutableString* listSection = [NSMutableString string]; + [listSection appendString:@"
"]; - NSString * fileTitleString = inf.fileCount == 1 ? NSLocalizedStringFromTableInBundle(@"1 File", nil, bundle, "quicklook file header") : [NSString stringWithFormat: NSLocalizedStringFromTableInBundle(@"%@ Files", nil, bundle, "quicklook file header"), [NSString formattedUInteger: inf.fileCount]]; - [listSection appendFormat: @"", fileTitleString]; + NSString* fileTitleString = inf.fileCount == 1 ? + NSLocalizedStringFromTableInBundle(@"1 File", nil, bundle, "quicklook file header") : + [NSString stringWithFormat:NSLocalizedStringFromTableInBundle(@"%@ Files", nil, bundle, "quicklook file header"), + [NSString formattedUInteger:inf.fileCount]]; + [listSection appendFormat:@"", fileTitleString]; #warning display size? #warning display folders? for (int i = 0; i < inf.fileCount; ++i) { - NSString * fullFilePath = [NSString stringWithUTF8String: inf.files[i].name]; - NSCAssert([fullFilePath hasPrefix: [name stringByAppendingString: @"/"]], @"Expected file path %@ to begin with %@/", fullFilePath, name); + NSString* fullFilePath = [NSString stringWithUTF8String:inf.files[i].name]; + NSCAssert([fullFilePath hasPrefix:[name stringByAppendingString:@"/"]], @"Expected file path %@ to begin with %@/", fullFilePath, name); - NSString * shortenedFilePath = [fullFilePath substringFromIndex: [name length]+1]; + NSString* shortenedFilePath = [fullFilePath substringFromIndex:[name length] + 1]; - const NSUInteger width = 16; - [listSection appendFormat: @"", generateIconData([shortenedFilePath pathExtension], width, allImgProps), width, width, shortenedFilePath]; + NSUInteger const width = 16; + [listSection appendFormat:@"", + generateIconData([shortenedFilePath pathExtension], width, allImgProps), + width, + width, + shortenedFilePath]; } [listSection appendString:@"
%@
%@
%@
%@
"]; - [lists addObject: listSection]; + [lists addObject:listSection]; } if ([lists count] > 0) - [htmlString appendFormat: @"

%@", [lists componentsJoinedByString: @"
"]]; + { + [htmlString appendFormat:@"

%@", [lists componentsJoinedByString:@"
"]]; + } - [htmlString appendString: @""]; + [htmlString appendString:@""]; tr_metainfoFree(&inf); - NSDictionary * props = @{ (NSString *)kQLPreviewPropertyTextEncodingNameKey : @"UTF-8", - (NSString *)kQLPreviewPropertyMIMETypeKey : @"text/html", - (NSString *)kQLPreviewPropertyAttachmentsKey : allImgProps }; + NSDictionary* props = @{ + (NSString*)kQLPreviewPropertyTextEncodingNameKey : @"UTF-8", + (NSString*)kQLPreviewPropertyMIMETypeKey : @"text/html", + (NSString*)kQLPreviewPropertyAttachmentsKey : allImgProps + }; - QLPreviewRequestSetDataRepresentation(preview, (__bridge CFDataRef)[htmlString dataUsingEncoding: NSUTF8StringEncoding], kUTTypeHTML, (__bridge CFDictionaryRef)props); + QLPreviewRequestSetDataRepresentation( + preview, + (__bridge CFDataRef)[htmlString dataUsingEncoding:NSUTF8StringEncoding], + kUTTypeHTML, + (__bridge CFDictionaryRef)props); return noErr; } -void CancelPreviewGeneration(void *thisInterface, QLPreviewRequestRef preview) +void CancelPreviewGeneration(void* thisInterface, QLPreviewRequestRef preview) { // Implement only if supported } diff --git a/macosx/QuickLookPlugin/GenerateThumbnailForURL.m b/macosx/QuickLookPlugin/GenerateThumbnailForURL.m index 478a468d5..4aa8ef6ed 100644 --- a/macosx/QuickLookPlugin/GenerateThumbnailForURL.m +++ b/macosx/QuickLookPlugin/GenerateThumbnailForURL.m @@ -2,8 +2,8 @@ #import #import -OSStatus GenerateThumbnailForURL(void *thisInterface, QLThumbnailRequestRef thumbnail, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options, CGSize maxSize); -void CancelThumbnailGeneration(void *thisInterface, QLThumbnailRequestRef thumbnail); +OSStatus GenerateThumbnailForURL(void* thisInterface, QLThumbnailRequestRef thumbnail, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options, CGSize maxSize); +void CancelThumbnailGeneration(void* thisInterface, QLThumbnailRequestRef thumbnail); /* ----------------------------------------------------------------------------- Generate a thumbnail for file @@ -11,13 +11,13 @@ void CancelThumbnailGeneration(void *thisInterface, QLThumbnailRequestRef thumbn This function's job is to create thumbnail for designated file as fast as possible ----------------------------------------------------------------------------- */ -OSStatus GenerateThumbnailForURL(void *thisInterface, QLThumbnailRequestRef thumbnail, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options, CGSize maxSize) +OSStatus GenerateThumbnailForURL(void* thisInterface, QLThumbnailRequestRef thumbnail, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options, CGSize maxSize) { // To complete your generator please implement the function GenerateThumbnailForURL in GenerateThumbnailForURL.c return noErr; } -void CancelThumbnailGeneration(void *thisInterface, QLThumbnailRequestRef thumbnail) +void CancelThumbnailGeneration(void* thisInterface, QLThumbnailRequestRef thumbnail) { // Implement only if supported } diff --git a/macosx/QuickLookPlugin/main.c b/macosx/QuickLookPlugin/main.c index fb92098e1..2832b4d54 100644 --- a/macosx/QuickLookPlugin/main.c +++ b/macosx/QuickLookPlugin/main.c @@ -26,25 +26,35 @@ // names if you decide to change the names defined in the Info.plist // - // ----------------------------------------------------------------------------- // typedefs // ----------------------------------------------------------------------------- // The thumbnail generation function to be implemented in GenerateThumbnailForURL.c -OSStatus GenerateThumbnailForURL(void *thisInterface, QLThumbnailRequestRef thumbnail, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options, CGSize maxSize); +OSStatus GenerateThumbnailForURL( + void* thisInterface, + QLThumbnailRequestRef thumbnail, + CFURLRef url, + CFStringRef contentTypeUTI, + CFDictionaryRef options, + CGSize maxSize); void CancelThumbnailGeneration(void* thisInterface, QLThumbnailRequestRef thumbnail); // The preview generation function to be implemented in GeneratePreviewForURL.c -OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options); -void CancelPreviewGeneration(void *thisInterface, QLPreviewRequestRef preview); +OSStatus GeneratePreviewForURL( + void* thisInterface, + QLPreviewRequestRef preview, + CFURLRef url, + CFStringRef contentTypeUTI, + CFDictionaryRef options); +void CancelPreviewGeneration(void* thisInterface, QLPreviewRequestRef preview); // The layout for an instance of QuickLookGeneratorPlugIn typedef struct __QuickLookGeneratorPluginType { - void *conduitInterface; - CFUUIDRef factoryID; - UInt32 refCount; + void* conduitInterface; + CFUUIDRef factoryID; + UInt32 refCount; } QuickLookGeneratorPluginType; // ----------------------------------------------------------------------------- @@ -53,20 +63,20 @@ typedef struct __QuickLookGeneratorPluginType // Forward declaration for the IUnknown implementation. // -QuickLookGeneratorPluginType *AllocQuickLookGeneratorPluginType(CFUUIDRef inFactoryID); -void DeallocQuickLookGeneratorPluginType(QuickLookGeneratorPluginType *thisInstance); -HRESULT QuickLookGeneratorQueryInterface(void *thisInstance,REFIID iid,LPVOID *ppv); -void *QuickLookGeneratorPluginFactory(CFAllocatorRef allocator,CFUUIDRef typeID); -ULONG QuickLookGeneratorPluginAddRef(void *thisInstance); -ULONG QuickLookGeneratorPluginRelease(void *thisInstance); +QuickLookGeneratorPluginType* AllocQuickLookGeneratorPluginType(CFUUIDRef inFactoryID); +void DeallocQuickLookGeneratorPluginType(QuickLookGeneratorPluginType* thisInstance); +HRESULT QuickLookGeneratorQueryInterface(void* thisInstance, REFIID iid, LPVOID* ppv); +void* QuickLookGeneratorPluginFactory(CFAllocatorRef allocator, CFUUIDRef typeID); +ULONG QuickLookGeneratorPluginAddRef(void* thisInstance); +ULONG QuickLookGeneratorPluginRelease(void* thisInstance); // ----------------------------------------------------------------------------- // myInterfaceFtbl definition // ----------------------------------------------------------------------------- // The QLGeneratorInterfaceStruct function table. // -static QLGeneratorInterfaceStruct myInterfaceFtbl = { - NULL, +static QLGeneratorInterfaceStruct myInterfaceFtbl = { // + NULL, // QuickLookGeneratorQueryInterface, QuickLookGeneratorPluginAddRef, QuickLookGeneratorPluginRelease, @@ -76,7 +86,6 @@ static QLGeneratorInterfaceStruct myInterfaceFtbl = { NULL }; - // ----------------------------------------------------------------------------- // AllocQuickLookGeneratorPluginType // ----------------------------------------------------------------------------- @@ -84,21 +93,21 @@ static QLGeneratorInterfaceStruct myInterfaceFtbl = { // You can do some initial setup for the generator here if you wish // like allocating globals etc... // -QuickLookGeneratorPluginType *AllocQuickLookGeneratorPluginType(CFUUIDRef inFactoryID) +QuickLookGeneratorPluginType* AllocQuickLookGeneratorPluginType(CFUUIDRef inFactoryID) { - QuickLookGeneratorPluginType *theNewInstance; - - theNewInstance = (QuickLookGeneratorPluginType *)malloc(sizeof(QuickLookGeneratorPluginType)); - memset(theNewInstance,0,sizeof(QuickLookGeneratorPluginType)); - + QuickLookGeneratorPluginType* theNewInstance; + + theNewInstance = (QuickLookGeneratorPluginType*)malloc(sizeof(QuickLookGeneratorPluginType)); + memset(theNewInstance, 0, sizeof(QuickLookGeneratorPluginType)); + /* Point to the function table Malloc enough to store the stuff and copy the filler from myInterfaceFtbl over */ theNewInstance->conduitInterface = malloc(sizeof(QLGeneratorInterfaceStruct)); - memcpy(theNewInstance->conduitInterface,&myInterfaceFtbl,sizeof(QLGeneratorInterfaceStruct)); - + memcpy(theNewInstance->conduitInterface, &myInterfaceFtbl, sizeof(QLGeneratorInterfaceStruct)); + /* Retain and keep an open instance refcount for each factory. */ theNewInstance->factoryID = CFRetain(inFactoryID); CFPlugInAddInstanceForFactory(inFactoryID); - + /* This function returns the IUnknown interface so set the refCount to one. */ theNewInstance->refCount = 1; return theNewInstance; @@ -112,17 +121,18 @@ QuickLookGeneratorPluginType *AllocQuickLookGeneratorPluginType(CFUUIDRef inFact // In the current implementation generator interfaces are never deallocated // but implement this as this might change in the future // -void DeallocQuickLookGeneratorPluginType(QuickLookGeneratorPluginType *thisInstance) +void DeallocQuickLookGeneratorPluginType(QuickLookGeneratorPluginType* thisInstance) { CFUUIDRef theFactoryID; - + theFactoryID = thisInstance->factoryID; /* Free the conduitInterface table up */ free(thisInstance->conduitInterface); - + /* Free the instance structure */ free(thisInstance); - if (theFactoryID){ + if (theFactoryID) + { CFPlugInRemoveInstanceForFactory(theFactoryID); CFRelease(theFactoryID); } @@ -133,26 +143,31 @@ void DeallocQuickLookGeneratorPluginType(QuickLookGeneratorPluginType *thisInsta // ----------------------------------------------------------------------------- // Implementation of the IUnknown QueryInterface function. // -HRESULT QuickLookGeneratorQueryInterface(void *thisInstance,REFIID iid,LPVOID *ppv) +HRESULT QuickLookGeneratorQueryInterface(void* thisInstance, REFIID iid, LPVOID* ppv) { CFUUIDRef interfaceID; - - interfaceID = CFUUIDCreateFromUUIDBytes(kCFAllocatorDefault,iid); - - if (CFEqual(interfaceID,kQLGeneratorCallbacksInterfaceID)){ + + interfaceID = CFUUIDCreateFromUUIDBytes(kCFAllocatorDefault, iid); + + if (CFEqual(interfaceID, kQLGeneratorCallbacksInterfaceID)) + { /* If the Right interface was requested, bump the ref count, * set the ppv parameter equal to the instance, and * return good status. */ - ((QLGeneratorInterfaceStruct *)((QuickLookGeneratorPluginType *)thisInstance)->conduitInterface)->GenerateThumbnailForURL = GenerateThumbnailForURL; - ((QLGeneratorInterfaceStruct *)((QuickLookGeneratorPluginType *)thisInstance)->conduitInterface)->CancelThumbnailGeneration = CancelThumbnailGeneration; - ((QLGeneratorInterfaceStruct *)((QuickLookGeneratorPluginType *)thisInstance)->conduitInterface)->GeneratePreviewForURL = GeneratePreviewForURL; - ((QLGeneratorInterfaceStruct *)((QuickLookGeneratorPluginType *)thisInstance)->conduitInterface)->CancelPreviewGeneration = CancelPreviewGeneration; - ((QLGeneratorInterfaceStruct *)((QuickLookGeneratorPluginType*)thisInstance)->conduitInterface)->AddRef(thisInstance); + QLGeneratorInterfaceStruct* const + qlGeneratorIface = (QLGeneratorInterfaceStruct*)((QuickLookGeneratorPluginType*)thisInstance)->conduitInterface; + qlGeneratorIface->GenerateThumbnailForURL = GenerateThumbnailForURL; + qlGeneratorIface->CancelThumbnailGeneration = CancelThumbnailGeneration; + qlGeneratorIface->GeneratePreviewForURL = GeneratePreviewForURL; + qlGeneratorIface->CancelPreviewGeneration = CancelPreviewGeneration; + qlGeneratorIface->AddRef(thisInstance); *ppv = thisInstance; CFRelease(interfaceID); return S_OK; - }else{ + } + else + { /* Requested interface unknown, bail with error. */ *ppv = NULL; CFRelease(interfaceID); @@ -167,10 +182,10 @@ HRESULT QuickLookGeneratorQueryInterface(void *thisInstance,REFIID iid,LPVOID *p // is requested, bump the refCount for the instance. NOTE: returning the // refcount is a convention but is not required so don't rely on it. // -ULONG QuickLookGeneratorPluginAddRef(void *thisInstance) +ULONG QuickLookGeneratorPluginAddRef(void* thisInstance) { - ((QuickLookGeneratorPluginType *)thisInstance )->refCount += 1; - return ((QuickLookGeneratorPluginType*) thisInstance)->refCount; + ((QuickLookGeneratorPluginType*)thisInstance)->refCount += 1; + return ((QuickLookGeneratorPluginType*)thisInstance)->refCount; } // ----------------------------------------------------------------------------- @@ -179,30 +194,34 @@ ULONG QuickLookGeneratorPluginAddRef(void *thisInstance) // When an interface is released, decrement the refCount. // If the refCount goes to zero, deallocate the instance. // -ULONG QuickLookGeneratorPluginRelease(void *thisInstance) +ULONG QuickLookGeneratorPluginRelease(void* thisInstance) { ((QuickLookGeneratorPluginType*)thisInstance)->refCount -= 1; - if (((QuickLookGeneratorPluginType*)thisInstance)->refCount == 0){ - DeallocQuickLookGeneratorPluginType((QuickLookGeneratorPluginType*)thisInstance ); + if (((QuickLookGeneratorPluginType*)thisInstance)->refCount == 0) + { + DeallocQuickLookGeneratorPluginType((QuickLookGeneratorPluginType*)thisInstance); return 0; - }else{ - return ((QuickLookGeneratorPluginType*) thisInstance )->refCount; + } + else + { + return ((QuickLookGeneratorPluginType*)thisInstance)->refCount; } } // ----------------------------------------------------------------------------- // QuickLookGeneratorPluginFactory // ----------------------------------------------------------------------------- -void *QuickLookGeneratorPluginFactory(CFAllocatorRef allocator,CFUUIDRef typeID) +void* QuickLookGeneratorPluginFactory(CFAllocatorRef allocator, CFUUIDRef typeID) { - QuickLookGeneratorPluginType *result; - CFUUIDRef uuid; - + QuickLookGeneratorPluginType* result; + CFUUIDRef uuid; + /* If correct type is being requested, allocate an * instance of kQLGeneratorTypeID and return the IUnknown interface. */ - if (CFEqual(typeID,kQLGeneratorTypeID)){ - uuid = CFUUIDCreateFromString(kCFAllocatorDefault,CFSTR(PLUGIN_ID)); + if (CFEqual(typeID, kQLGeneratorTypeID)) + { + uuid = CFUUIDCreateFromString(kCFAllocatorDefault, CFSTR(PLUGIN_ID)); result = AllocQuickLookGeneratorPluginType(uuid); CFRelease(uuid); return result; @@ -210,4 +229,3 @@ void *QuickLookGeneratorPluginFactory(CFAllocatorRef allocator,CFUUIDRef typeID) /* If the requested type is incorrect, return NULL. */ return NULL; } - diff --git a/macosx/ShareToolbarItem.m b/macosx/ShareToolbarItem.m index 4f1e052d4..30c41df1f 100644 --- a/macosx/ShareToolbarItem.m +++ b/macosx/ShareToolbarItem.m @@ -12,14 +12,15 @@ @implementation ShareToolbarItem -- (NSMenuItem *) menuFormRepresentation +- (NSMenuItem*)menuFormRepresentation { - NSMenuItem * menuItem = [[NSMenuItem alloc] initWithTitle: self.label action: nil keyEquivalent: @""]; - menuItem.enabled = [self.target validateToolbarItem: self]; + NSMenuItem* menuItem = [[NSMenuItem alloc] initWithTitle:self.label action:nil keyEquivalent:@""]; + menuItem.enabled = [self.target validateToolbarItem:self]; - if (menuItem.enabled) { - NSMenu *servicesMenu = [[NSMenu alloc] initWithTitle: @""]; - for (NSMenuItem * item in ShareTorrentFileHelper.sharedHelper.menuItems) + if (menuItem.enabled) + { + NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle:@""]; + for (NSMenuItem* item in ShareTorrentFileHelper.sharedHelper.menuItems) { [servicesMenu addItem:item]; } diff --git a/macosx/ShareTorrentFileHelper.h b/macosx/ShareTorrentFileHelper.h index 5a2a6950c..2aba67670 100644 --- a/macosx/ShareTorrentFileHelper.h +++ b/macosx/ShareTorrentFileHelper.h @@ -10,9 +10,9 @@ @interface ShareTorrentFileHelper : NSObject -@property (nonatomic, class, readonly) ShareTorrentFileHelper * sharedHelper; +@property(nonatomic, class, readonly) ShareTorrentFileHelper* sharedHelper; -@property (nonatomic, readonly) NSArray *shareTorrentURLs; -@property (nonatomic, readonly) NSArray *menuItems; +@property(nonatomic, readonly) NSArray* shareTorrentURLs; +@property(nonatomic, readonly) NSArray* menuItems; @end diff --git a/macosx/ShareTorrentFileHelper.m b/macosx/ShareTorrentFileHelper.m index e8f194a6b..168b93a6d 100644 --- a/macosx/ShareTorrentFileHelper.m +++ b/macosx/ShareTorrentFileHelper.m @@ -12,9 +12,9 @@ @implementation ShareTorrentFileHelper -+ (ShareTorrentFileHelper *) sharedHelper ++ (ShareTorrentFileHelper*)sharedHelper { - static ShareTorrentFileHelper *helper; + static ShareTorrentFileHelper* helper; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ helper = [[ShareTorrentFileHelper alloc] init]; @@ -22,43 +22,44 @@ return helper; } -- (NSArray *) shareTorrentURLs +- (NSArray*)shareTorrentURLs { - NSArray * torrents = ((Controller *)NSApp.delegate).selectedTorrents; - NSMutableArray * fileURLs = [NSMutableArray arrayWithCapacity: torrents.count]; - for (Torrent * torrent in torrents) + NSArray* torrents = ((Controller*)NSApp.delegate).selectedTorrents; + NSMutableArray* fileURLs = [NSMutableArray arrayWithCapacity:torrents.count]; + for (Torrent* torrent in torrents) { - NSString * location = torrent.torrentLocation; - if (location.length > 0) { - [fileURLs addObject: [NSURL fileURLWithPath: location]]; + NSString* location = torrent.torrentLocation; + if (location.length > 0) + { + [fileURLs addObject:[NSURL fileURLWithPath:location]]; } } return fileURLs; } -- (NSArray *) menuItems +- (NSArray*)menuItems { - NSArray * services = [NSSharingService sharingServicesForItems: self.shareTorrentURLs]; - NSMutableArray * items = [NSMutableArray arrayWithCapacity: services.count]; - for (NSSharingService * service in services) + NSArray* services = [NSSharingService sharingServicesForItems:self.shareTorrentURLs]; + NSMutableArray* items = [NSMutableArray arrayWithCapacity:services.count]; + for (NSSharingService* service in services) { - NSMenuItem *item = [[NSMenuItem alloc] initWithTitle: service.title // 10.9: change to menuItemTitle - action: @selector(performShareAction:) - keyEquivalent: @""]; + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:service.title // 10.9: change to menuItemTitle + action:@selector(performShareAction:) + keyEquivalent:@""]; item.image = service.image; item.representedObject = service; - service.delegate = (Controller *)NSApp.delegate; + service.delegate = (Controller*)NSApp.delegate; item.target = self; - [items addObject: item]; + [items addObject:item]; } return items; } -- (void) performShareAction: (NSMenuItem *) item +- (void)performShareAction:(NSMenuItem*)item { - NSSharingService * service = item.representedObject; - [service performWithItems: self.shareTorrentURLs]; // on 10.9, use attachmentFileURLs? + NSSharingService* service = item.representedObject; + [service performWithItems:self.shareTorrentURLs]; // on 10.9, use attachmentFileURLs? } @end diff --git a/macosx/StatsWindowController.h b/macosx/StatsWindowController.h index 58bdc7896..c60109811 100644 --- a/macosx/StatsWindowController.h +++ b/macosx/StatsWindowController.h @@ -26,15 +26,26 @@ @interface StatsWindowController : NSWindowController { - IBOutlet NSTextField * fUploadedField, * fUploadedAllField, * fDownloadedField, * fDownloadedAllField, - * fRatioField, * fRatioAllField, * fTimeField, * fTimeAllField, * fNumOpenedField, - * fUploadedLabelField, * fDownloadedLabelField, * fRatioLabelField, * fTimeLabelField, * fNumOpenedLabelField; - IBOutlet NSButton * fResetButton; - NSTimer * fTimer; + IBOutlet NSTextField* fUploadedField; + IBOutlet NSTextField* fUploadedAllField; + IBOutlet NSTextField* fDownloadedField; + IBOutlet NSTextField* fDownloadedAllField; + IBOutlet NSTextField* fRatioField; + IBOutlet NSTextField* fRatioAllField; + IBOutlet NSTextField* fTimeField; + IBOutlet NSTextField* fTimeAllField; + IBOutlet NSTextField* fNumOpenedField; + IBOutlet NSTextField* fUploadedLabelField; + IBOutlet NSTextField* fDownloadedLabelField; + IBOutlet NSTextField* fRatioLabelField; + IBOutlet NSTextField* fTimeLabelField; + IBOutlet NSTextField* fNumOpenedLabelField; + IBOutlet NSButton* fResetButton; + NSTimer* fTimer; } -@property (nonatomic, class, readonly) StatsWindowController * statsWindow; +@property(nonatomic, class, readonly) StatsWindowController* statsWindow; -- (void) resetStats: (id) sender; +- (void)resetStats:(id)sender; @end diff --git a/macosx/StatsWindowController.m b/macosx/StatsWindowController.m index 88b7e7289..441712d79 100644 --- a/macosx/StatsWindowController.m +++ b/macosx/StatsWindowController.m @@ -29,67 +29,69 @@ @interface StatsWindowController (Private) -- (void) updateStats; +- (void)updateStats; -- (void) performResetStats; +- (void)performResetStats; @end @implementation StatsWindowController -StatsWindowController * fStatsWindowInstance = nil; -tr_session * fLib = NULL; -+ (StatsWindowController *) statsWindow +StatsWindowController* fStatsWindowInstance = nil; +tr_session* fLib = NULL; + ++ (StatsWindowController*)statsWindow { if (!fStatsWindowInstance) { if ((fStatsWindowInstance = [[self alloc] init])) { - fLib = ((Controller *)NSApp.delegate).sessionHandle; + fLib = ((Controller*)NSApp.delegate).sessionHandle; } } return fStatsWindowInstance; } -- (instancetype) init +- (instancetype)init { - return [super initWithWindowNibName: @"StatsWindow"]; + return [super initWithWindowNibName:@"StatsWindow"]; } -- (void) awakeFromNib +- (void)awakeFromNib { [self updateStats]; - fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_SECONDS target: self selector: @selector(updateStats) userInfo: nil repeats: YES]; - [NSRunLoop.currentRunLoop addTimer: fTimer forMode: NSModalPanelRunLoopMode]; - [NSRunLoop.currentRunLoop addTimer: fTimer forMode: NSEventTrackingRunLoopMode]; + fTimer = [NSTimer scheduledTimerWithTimeInterval:UPDATE_SECONDS target:self selector:@selector(updateStats) userInfo:nil + repeats:YES]; + [NSRunLoop.currentRunLoop addTimer:fTimer forMode:NSModalPanelRunLoopMode]; + [NSRunLoop.currentRunLoop addTimer:fTimer forMode:NSEventTrackingRunLoopMode]; self.window.restorationClass = [self class]; self.window.title = NSLocalizedString(@"Statistics", "Stats window -> title"); //set label text - fUploadedLabelField.stringValue = [NSLocalizedString(@"Uploaded", "Stats window -> label") stringByAppendingString: @":"]; - fDownloadedLabelField.stringValue = [NSLocalizedString(@"Downloaded", "Stats window -> label") stringByAppendingString: @":"]; - fRatioLabelField.stringValue = [NSLocalizedString(@"Ratio", "Stats window -> label") stringByAppendingString: @":"]; - fTimeLabelField.stringValue = [NSLocalizedString(@"Running Time", "Stats window -> label") stringByAppendingString: @":"]; - fNumOpenedLabelField.stringValue = [NSLocalizedString(@"Program Started", "Stats window -> label") stringByAppendingString: @":"]; + fUploadedLabelField.stringValue = [NSLocalizedString(@"Uploaded", "Stats window -> label") stringByAppendingString:@":"]; + fDownloadedLabelField.stringValue = [NSLocalizedString(@"Downloaded", "Stats window -> label") stringByAppendingString:@":"]; + fRatioLabelField.stringValue = [NSLocalizedString(@"Ratio", "Stats window -> label") stringByAppendingString:@":"]; + fTimeLabelField.stringValue = [NSLocalizedString(@"Running Time", "Stats window -> label") stringByAppendingString:@":"]; + fNumOpenedLabelField.stringValue = [NSLocalizedString(@"Program Started", "Stats window -> label") stringByAppendingString:@":"]; //size of all labels - const CGFloat oldWidth = fUploadedLabelField.frame.size.width; + CGFloat const oldWidth = fUploadedLabelField.frame.size.width; - NSArray * labels = @[fUploadedLabelField, fDownloadedLabelField, fRatioLabelField, fTimeLabelField, fNumOpenedLabelField]; + NSArray* labels = @[ fUploadedLabelField, fDownloadedLabelField, fRatioLabelField, fTimeLabelField, fNumOpenedLabelField ]; CGFloat maxWidth = CGFLOAT_MIN; - for (NSTextField * label in labels) + for (NSTextField* label in labels) { [label sizeToFit]; - const CGFloat width = label.frame.size.width; + CGFloat const width = label.frame.size.width; maxWidth = MAX(maxWidth, width); } - for (NSTextField * label in labels) + for (NSTextField* label in labels) { NSRect frame = label.frame; frame.size.width = maxWidth; @@ -99,10 +101,10 @@ tr_session * fLib = NULL; //resize window for new label width - fields are set in nib to adjust correctly NSRect windowRect = self.window.frame; windowRect.size.width += maxWidth - oldWidth; - [self.window setFrame: windowRect display: YES]; + [self.window setFrame:windowRect display:YES]; //resize reset button - const CGFloat oldButtonWidth = fResetButton.frame.size.width; + CGFloat const oldButtonWidth = fResetButton.frame.size.width; fResetButton.title = NSLocalizedString(@"Reset", "Stats window -> reset button"); [fResetButton sizeToFit]; @@ -113,49 +115,57 @@ tr_session * fLib = NULL; fResetButton.frame = buttonFrame; } -- (void) windowWillClose: (id) sender +- (void)windowWillClose:(id)sender { [fTimer invalidate]; fTimer = nil; fStatsWindowInstance = nil; } -+ (void) restoreWindowWithIdentifier: (NSString *) identifier state: (NSCoder *) state completionHandler: (void (^)(NSWindow *, NSError *)) completionHandler ++ (void)restoreWindowWithIdentifier:(NSString*)identifier + state:(NSCoder*)state + completionHandler:(void (^)(NSWindow*, NSError*))completionHandler { - NSAssert1([identifier isEqualToString: @"StatsWindow"], @"Trying to restore unexpected identifier %@", identifier); + NSAssert1([identifier isEqualToString:@"StatsWindow"], @"Trying to restore unexpected identifier %@", identifier); completionHandler(StatsWindowController.statsWindow.window, nil); } -- (void) resetStats: (id) sender +- (void)resetStats:(id)sender { - if (![NSUserDefaults.standardUserDefaults boolForKey: @"WarningResetStats"]) + if (![NSUserDefaults.standardUserDefaults boolForKey:@"WarningResetStats"]) { [self performResetStats]; return; } - NSAlert * alert = [[NSAlert alloc] init]; + NSAlert* alert = [[NSAlert alloc] init]; alert.messageText = NSLocalizedString(@"Are you sure you want to reset usage statistics?", "Stats reset -> title"); - alert.informativeText = NSLocalizedString(@"This will clear the global statistics displayed by Transmission." - " Individual transfer statistics will not be affected.", "Stats reset -> message"); + alert.informativeText = NSLocalizedString( + @"This will clear the global statistics displayed by Transmission." + " Individual transfer statistics will not be affected.", + "Stats reset -> message"); alert.alertStyle = NSWarningAlertStyle; - [alert addButtonWithTitle: NSLocalizedString(@"Reset", "Stats reset -> button")]; - [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Stats reset -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Reset", "Stats reset -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Cancel", "Stats reset -> button")]; alert.showsSuppressionButton = YES; [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { - [alert.window orderOut: nil]; + [alert.window orderOut:nil]; if (alert.suppressionButton.state == NSOnState) - [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningResetStats"]; + { + [NSUserDefaults.standardUserDefaults setBool:NO forKey:@"WarningResetStats"]; + } if (returnCode == NSAlertFirstButtonReturn) + { [self performResetStats]; + } }]; } -- (NSString *) windowFrameAutosaveName +- (NSString*)windowFrameAutosaveName { return @"StatsWindow"; } @@ -164,52 +174,60 @@ tr_session * fLib = NULL; @implementation StatsWindowController (Private) -- (void) updateStats +- (void)updateStats { tr_session_stats statsAll, statsSession; tr_sessionGetCumulativeStats(fLib, &statsAll); tr_sessionGetStats(fLib, &statsSession); - NSByteCountFormatter * byteFormatter = [[NSByteCountFormatter alloc] init]; + NSByteCountFormatter* byteFormatter = [[NSByteCountFormatter alloc] init]; byteFormatter.allowedUnits = NSByteCountFormatterUseBytes; - fUploadedField.stringValue = [NSString stringForFileSize: statsSession.uploadedBytes]; - fUploadedField.toolTip = [byteFormatter stringFromByteCount: statsSession.uploadedBytes]; - fUploadedAllField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"), [NSString stringForFileSize: statsAll.uploadedBytes]]; - fUploadedAllField.toolTip = [byteFormatter stringFromByteCount: statsAll.uploadedBytes]; + fUploadedField.stringValue = [NSString stringForFileSize:statsSession.uploadedBytes]; + fUploadedField.toolTip = [byteFormatter stringFromByteCount:statsSession.uploadedBytes]; + fUploadedAllField.stringValue = [NSString + stringWithFormat:NSLocalizedString(@"%@ total", "stats total"), [NSString stringForFileSize:statsAll.uploadedBytes]]; + fUploadedAllField.toolTip = [byteFormatter stringFromByteCount:statsAll.uploadedBytes]; - fDownloadedField.stringValue = [NSString stringForFileSize: statsSession.downloadedBytes]; - fDownloadedField.toolTip = [byteFormatter stringFromByteCount: statsSession.downloadedBytes]; - fDownloadedAllField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"), [NSString stringForFileSize: statsAll.downloadedBytes]]; - fDownloadedAllField.toolTip = [byteFormatter stringFromByteCount: statsAll.downloadedBytes]; + fDownloadedField.stringValue = [NSString stringForFileSize:statsSession.downloadedBytes]; + fDownloadedField.toolTip = [byteFormatter stringFromByteCount:statsSession.downloadedBytes]; + fDownloadedAllField.stringValue = [NSString + stringWithFormat:NSLocalizedString(@"%@ total", "stats total"), [NSString stringForFileSize:statsAll.downloadedBytes]]; + fDownloadedAllField.toolTip = [byteFormatter stringFromByteCount:statsAll.downloadedBytes]; + fRatioField.stringValue = [NSString stringForRatio:statsSession.ratio]; - fRatioField.stringValue = [NSString stringForRatio: statsSession.ratio]; - - NSString * totalRatioString = statsAll.ratio != TR_RATIO_NA - ? [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"), [NSString stringForRatio: statsAll.ratio]] - : NSLocalizedString(@"Total N/A", "stats total"); + NSString* totalRatioString = statsAll.ratio != TR_RATIO_NA ? + [NSString stringWithFormat:NSLocalizedString(@"%@ total", "stats total"), [NSString stringForRatio:statsAll.ratio]] : + NSLocalizedString(@"Total N/A", "stats total"); fRatioAllField.stringValue = totalRatioString; - - static NSDateComponentsFormatter *timeFormatter; + + static NSDateComponentsFormatter* timeFormatter; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ timeFormatter = [NSDateComponentsFormatter new]; timeFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull; timeFormatter.maximumUnitCount = 3; - timeFormatter.allowedUnits = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekOfMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute; + timeFormatter.allowedUnits = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekOfMonth | NSCalendarUnitDay | + NSCalendarUnitHour | NSCalendarUnitMinute; }); - + fTimeField.stringValue = [timeFormatter stringFromTimeInterval:statsSession.secondsActive]; - fTimeAllField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"), [timeFormatter stringFromTimeInterval:statsAll.secondsActive]]; - + fTimeAllField.stringValue = [NSString stringWithFormat:NSLocalizedString(@"%@ total", "stats total"), + [timeFormatter stringFromTimeInterval:statsAll.secondsActive]]; + if (statsAll.sessionCount == 1) + { fNumOpenedField.stringValue = NSLocalizedString(@"1 time", "stats window -> times opened"); + } else - fNumOpenedField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"%@ times", "stats window -> times opened"), [NSString formattedUInteger: statsAll.sessionCount]]; + { + fNumOpenedField.stringValue = [NSString stringWithFormat:NSLocalizedString(@"%@ times", "stats window -> times opened"), + [NSString formattedUInteger:statsAll.sessionCount]]; + } } -- (void) performResetStats +- (void)performResetStats { tr_sessionClearStats(fLib); [self updateStats]; diff --git a/macosx/StatusBarController.h b/macosx/StatusBarController.h index 00de741b8..3c3097f27 100644 --- a/macosx/StatusBarController.h +++ b/macosx/StatusBarController.h @@ -26,20 +26,23 @@ @interface StatusBarController : NSViewController { - IBOutlet NSButton * fStatusButton; - IBOutlet NSTextField * fTotalDLField, * fTotalULField; - IBOutlet NSImageView * fTotalDLImageView, * fTotalULImageView; + IBOutlet NSButton* fStatusButton; + IBOutlet NSTextField* fTotalDLField; + IBOutlet NSTextField* fTotalULField; + IBOutlet NSImageView* fTotalDLImageView; + IBOutlet NSImageView* fTotalULImageView; - tr_session * fLib; + tr_session* fLib; - CGFloat fPreviousDownloadRate, fPreviousUploadRate; + CGFloat fPreviousDownloadRate; + CGFloat fPreviousUploadRate; } -- (instancetype) initWithLib: (tr_session *) lib; +- (instancetype)initWithLib:(tr_session*)lib; -- (void) updateWithDownload: (CGFloat) dlRate upload: (CGFloat) ulRate; -- (void) setStatusLabel: (id) sender; +- (void)updateWithDownload:(CGFloat)dlRate upload:(CGFloat)ulRate; +- (void)setStatusLabel:(id)sender; -- (void) updateSpeedFieldsToolTips; +- (void)updateSpeedFieldsToolTips; @end diff --git a/macosx/StatusBarController.m b/macosx/StatusBarController.m index 5a5f3b94b..b5ab7b1f8 100644 --- a/macosx/StatusBarController.m +++ b/macosx/StatusBarController.m @@ -25,9 +25,9 @@ #import "StatusBarController.h" #import "NSStringAdditions.h" -#define STATUS_RATIO_TOTAL @"RatioTotal" -#define STATUS_RATIO_SESSION @"RatioSession" -#define STATUS_TRANSFER_TOTAL @"TransferTotal" +#define STATUS_RATIO_TOTAL @"RatioTotal" +#define STATUS_RATIO_SESSION @"RatioSession" +#define STATUS_TRANSFER_TOTAL @"TransferTotal" #define STATUS_TRANSFER_SESSION @"TransferSession" typedef NS_ENUM(unsigned int, statusTag) { @@ -39,15 +39,15 @@ typedef NS_ENUM(unsigned int, statusTag) { @interface StatusBarController (Private) -- (void) resizeStatusButton; +- (void)resizeStatusButton; @end @implementation StatusBarController -- (instancetype) initWithLib: (tr_session *) lib +- (instancetype)initWithLib:(tr_session*)lib { - if ((self = [super initWithNibName: @"StatusBar" bundle: nil])) + if ((self = [super initWithNibName:@"StatusBar" bundle:nil])) { fLib = lib; @@ -58,17 +58,13 @@ typedef NS_ENUM(unsigned int, statusTag) { return self; } -- (void) awakeFromNib +- (void)awakeFromNib { //localize menu items - [fStatusButton.menu itemWithTag: STATUS_RATIO_TOTAL_TAG].title = NSLocalizedString(@"Total Ratio", - "Status Bar -> status menu"); - [fStatusButton.menu itemWithTag: STATUS_RATIO_SESSION_TAG].title = NSLocalizedString(@"Session Ratio", - "Status Bar -> status menu"); - [fStatusButton.menu itemWithTag: STATUS_TRANSFER_TOTAL_TAG].title = NSLocalizedString(@"Total Transfer", - "Status Bar -> status menu"); - [fStatusButton.menu itemWithTag: STATUS_TRANSFER_SESSION_TAG].title = NSLocalizedString(@"Session Transfer", - "Status Bar -> status menu"); + [fStatusButton.menu itemWithTag:STATUS_RATIO_TOTAL_TAG].title = NSLocalizedString(@"Total Ratio", "Status Bar -> status menu"); + [fStatusButton.menu itemWithTag:STATUS_RATIO_SESSION_TAG].title = NSLocalizedString(@"Session Ratio", "Status Bar -> status menu"); + [fStatusButton.menu itemWithTag:STATUS_TRANSFER_TOTAL_TAG].title = NSLocalizedString(@"Total Transfer", "Status Bar -> status menu"); + [fStatusButton.menu itemWithTag:STATUS_TRANSFER_SESSION_TAG].title = NSLocalizedString(@"Session Transfer", "Status Bar -> status menu"); fStatusButton.cell.backgroundStyle = NSBackgroundStyleRaised; fTotalDLField.cell.backgroundStyle = NSBackgroundStyleRaised; @@ -79,74 +75,159 @@ typedef NS_ENUM(unsigned int, statusTag) { [self updateSpeedFieldsToolTips]; //update when speed limits are changed - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateSpeedFieldsToolTips) - name: @"SpeedLimitUpdate" object: nil]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(resizeStatusButton) - name: NSWindowDidResizeNotification object: self.view.window]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateSpeedFieldsToolTips) name:@"SpeedLimitUpdate" + object:nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(resizeStatusButton) + name:NSWindowDidResizeNotification + object:self.view.window]; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; } -- (void) updateWithDownload: (CGFloat) dlRate upload: (CGFloat) ulRate +- (void)updateWithDownload:(CGFloat)dlRate upload:(CGFloat)ulRate { //set rates if (dlRate != fPreviousDownloadRate) { - fTotalDLField.stringValue = [NSString stringForSpeed: dlRate]; + fTotalDLField.stringValue = [NSString stringForSpeed:dlRate]; fPreviousDownloadRate = dlRate; } if (ulRate != fPreviousUploadRate) { - fTotalULField.stringValue = [NSString stringForSpeed: ulRate]; + fTotalULField.stringValue = [NSString stringForSpeed:ulRate]; fPreviousUploadRate = ulRate; } //set status button text - NSString * statusLabel = [NSUserDefaults.standardUserDefaults stringForKey: @"StatusLabel"], * statusString; + NSString *statusLabel = [NSUserDefaults.standardUserDefaults stringForKey:@"StatusLabel"], *statusString; BOOL total; - if ((total = [statusLabel isEqualToString: STATUS_RATIO_TOTAL]) || [statusLabel isEqualToString: STATUS_RATIO_SESSION]) + if ((total = [statusLabel isEqualToString:STATUS_RATIO_TOTAL]) || [statusLabel isEqualToString:STATUS_RATIO_SESSION]) { tr_session_stats stats; if (total) + { tr_sessionGetCumulativeStats(fLib, &stats); + } else + { tr_sessionGetStats(fLib, &stats); + } - statusString = [NSLocalizedString(@"Ratio", "status bar -> status label") stringByAppendingFormat: @": %@", - [NSString stringForRatio: stats.ratio]]; + statusString = [NSLocalizedString(@"Ratio", "status bar -> status label") + stringByAppendingFormat:@": %@", [NSString stringForRatio:stats.ratio]]; } else //STATUS_TRANSFER_TOTAL or STATUS_TRANSFER_SESSION { - total = [statusLabel isEqualToString: STATUS_TRANSFER_TOTAL]; + total = [statusLabel isEqualToString:STATUS_TRANSFER_TOTAL]; tr_session_stats stats; if (total) + { tr_sessionGetCumulativeStats(fLib, &stats); + } else + { tr_sessionGetStats(fLib, &stats); + } - statusString = [NSString stringWithFormat: @"%@: %@ %@: %@", - NSLocalizedString(@"DL", "status bar -> status label"), [NSString stringForFileSize: stats.downloadedBytes], - NSLocalizedString(@"UL", "status bar -> status label"), [NSString stringForFileSize: stats.uploadedBytes]]; + statusString = [NSString stringWithFormat:@"%@: %@ %@: %@", + NSLocalizedString(@"DL", "status bar -> status label"), + [NSString stringForFileSize:stats.downloadedBytes], + NSLocalizedString(@"UL", "status bar -> status label"), + [NSString stringForFileSize:stats.uploadedBytes]]; } - - if (![fStatusButton.title isEqualToString: statusString]) + if (![fStatusButton.title isEqualToString:statusString]) { fStatusButton.title = statusString; [self resizeStatusButton]; } } -- (void) setStatusLabel: (id) sender +- (void)setStatusLabel:(id)sender { - NSString * statusLabel; + NSString* statusLabel; switch ([sender tag]) { + case STATUS_RATIO_TOTAL_TAG: + statusLabel = STATUS_RATIO_TOTAL; + break; + case STATUS_RATIO_SESSION_TAG: + statusLabel = STATUS_RATIO_SESSION; + break; + case STATUS_TRANSFER_TOTAL_TAG: + statusLabel = STATUS_TRANSFER_TOTAL; + break; + case STATUS_TRANSFER_SESSION_TAG: + statusLabel = STATUS_TRANSFER_SESSION; + break; + default: + NSAssert1(NO, @"Unknown status label tag received: %ld", [sender tag]); + return; + } + + [NSUserDefaults.standardUserDefaults setObject:statusLabel forKey:@"StatusLabel"]; + + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; +} + +- (void)updateSpeedFieldsToolTips +{ + NSString *uploadText, *downloadText; + + if ([NSUserDefaults.standardUserDefaults boolForKey:@"SpeedLimit"]) + { + NSString* speedString = [NSString stringWithFormat:@"%@ (%@)", + NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"), + NSLocalizedString(@"Speed Limit", "Status Bar -> speed tooltip")]; + + uploadText = [NSString stringWithFormat:speedString, [NSUserDefaults.standardUserDefaults integerForKey:@"SpeedLimitUploadLimit"]]; + downloadText = [NSString stringWithFormat:speedString, [NSUserDefaults.standardUserDefaults integerForKey:@"SpeedLimitDownloadLimit"]]; + } + else + { + if ([NSUserDefaults.standardUserDefaults boolForKey:@"CheckUpload"]) + { + uploadText = [NSString stringWithFormat:NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"), + [NSUserDefaults.standardUserDefaults integerForKey:@"UploadLimit"]]; + } + else + { + uploadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip"); + } + + if ([NSUserDefaults.standardUserDefaults boolForKey:@"CheckDownload"]) + { + downloadText = [NSString stringWithFormat:NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"), + [NSUserDefaults.standardUserDefaults integerForKey:@"DownloadLimit"]]; + } + else + { + downloadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip"); + } + } + + uploadText = [NSLocalizedString(@"Global upload limit", "Status Bar -> speed tooltip") stringByAppendingFormat:@": %@", uploadText]; + downloadText = [NSLocalizedString(@"Global download limit", "Status Bar -> speed tooltip") stringByAppendingFormat:@": %@", downloadText]; + + fTotalULField.toolTip = uploadText; + fTotalDLField.toolTip = downloadText; +} + +- (BOOL)validateMenuItem:(NSMenuItem*)menuItem +{ + SEL const action = menuItem.action; + + //enable sort options + if (action == @selector(setStatusLabel:)) + { + NSString* statusLabel; + switch (menuItem.tag) + { case STATUS_RATIO_TOTAL_TAG: statusLabel = STATUS_RATIO_TOTAL; break; @@ -160,82 +241,11 @@ typedef NS_ENUM(unsigned int, statusTag) { statusLabel = STATUS_TRANSFER_SESSION; break; default: - NSAssert1(NO, @"Unknown status label tag received: %ld", [sender tag]); - return; - } - - [NSUserDefaults.standardUserDefaults setObject: statusLabel forKey: @"StatusLabel"]; - - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; -} - -- (void) updateSpeedFieldsToolTips -{ - NSString * uploadText, * downloadText; - - if ([NSUserDefaults.standardUserDefaults boolForKey: @"SpeedLimit"]) - { - NSString * speedString = [NSString stringWithFormat: @"%@ (%@)", NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"), - NSLocalizedString(@"Speed Limit", "Status Bar -> speed tooltip")]; - - uploadText = [NSString stringWithFormat: speedString, - [NSUserDefaults.standardUserDefaults integerForKey: @"SpeedLimitUploadLimit"]]; - downloadText = [NSString stringWithFormat: speedString, - [NSUserDefaults.standardUserDefaults integerForKey: @"SpeedLimitDownloadLimit"]]; - } - else - { - if ([NSUserDefaults.standardUserDefaults boolForKey: @"CheckUpload"]) - uploadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"), - [NSUserDefaults.standardUserDefaults integerForKey: @"UploadLimit"]]; - else - uploadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip"); - - if ([NSUserDefaults.standardUserDefaults boolForKey: @"CheckDownload"]) - downloadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"), - [NSUserDefaults.standardUserDefaults integerForKey: @"DownloadLimit"]]; - else - downloadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip"); - } - - uploadText = [NSLocalizedString(@"Global upload limit", "Status Bar -> speed tooltip") - stringByAppendingFormat: @": %@", uploadText]; - downloadText = [NSLocalizedString(@"Global download limit", "Status Bar -> speed tooltip") - stringByAppendingFormat: @": %@", downloadText]; - - fTotalULField.toolTip = uploadText; - fTotalDLField.toolTip = downloadText; -} - -- (BOOL) validateMenuItem: (NSMenuItem *) menuItem -{ - const SEL action = menuItem.action; - - //enable sort options - if (action == @selector(setStatusLabel:)) - { - NSString * statusLabel; - switch (menuItem.tag) - { - case STATUS_RATIO_TOTAL_TAG: - statusLabel = STATUS_RATIO_TOTAL; - break; - case STATUS_RATIO_SESSION_TAG: - statusLabel = STATUS_RATIO_SESSION; - break; - case STATUS_TRANSFER_TOTAL_TAG: - statusLabel = STATUS_TRANSFER_TOTAL; - break; - case STATUS_TRANSFER_SESSION_TAG: - statusLabel = STATUS_TRANSFER_SESSION; - break; - default: - NSAssert1(NO, @"Unknown status label tag received: %ld", menuItem.tag); - statusLabel = STATUS_RATIO_TOTAL; + NSAssert1(NO, @"Unknown status label tag received: %ld", menuItem.tag); + statusLabel = STATUS_RATIO_TOTAL; } - menuItem.state = [statusLabel isEqualToString: [NSUserDefaults.standardUserDefaults stringForKey: @"StatusLabel"]] - ? NSOnState : NSOffState; + menuItem.state = [statusLabel isEqualToString:[NSUserDefaults.standardUserDefaults stringForKey:@"StatusLabel"]] ? NSOnState : NSOffState; return YES; } @@ -246,7 +256,7 @@ typedef NS_ENUM(unsigned int, statusTag) { @implementation StatusBarController (Private) -- (void) resizeStatusButton +- (void)resizeStatusButton { [fStatusButton sizeToFit]; @@ -254,9 +264,11 @@ typedef NS_ENUM(unsigned int, statusTag) { NSRect statusFrame = fStatusButton.frame; statusFrame.size.width -= 25.0; - const CGFloat difference = NSMaxX(statusFrame) + 5.0 - NSMinX(fTotalDLImageView.frame); + CGFloat const difference = NSMaxX(statusFrame) + 5.0 - NSMinX(fTotalDLImageView.frame); if (difference > 0.0) + { statusFrame.size.width -= difference; + } fStatusButton.frame = statusFrame; } diff --git a/macosx/StatusBarView.m b/macosx/StatusBarView.m index 14b9b477a..bbd6d0b26 100644 --- a/macosx/StatusBarView.m +++ b/macosx/StatusBarView.m @@ -25,28 +25,28 @@ @interface StatusBarView (Private) -- (void) reload; +- (void)reload; @end @implementation StatusBarView -- (BOOL) mouseDownCanMoveWindow +- (BOOL)mouseDownCanMoveWindow { return YES; } -- (BOOL) isOpaque +- (BOOL)isOpaque { return YES; } -- (void) drawRect: (NSRect) rect +- (void)drawRect:(NSRect)rect { [NSColor.windowBackgroundColor setFill]; NSRectFill(rect); - - const NSRect lineBorderRect = NSMakeRect(NSMinX(rect), 0.0, NSWidth(rect), 1.0); + + NSRect const lineBorderRect = NSMakeRect(NSMinX(rect), 0.0, NSWidth(rect), 1.0); if (NSIntersectsRect(lineBorderRect, rect)) { [NSColor.gridColor setFill]; @@ -58,7 +58,7 @@ @implementation StatusBarView (Private) -- (void) reload +- (void)reload { self.needsDisplay = YES; } diff --git a/macosx/ToolbarSegmentedCell.m b/macosx/ToolbarSegmentedCell.m index d65b472dd..f5b914bf0 100644 --- a/macosx/ToolbarSegmentedCell.m +++ b/macosx/ToolbarSegmentedCell.m @@ -25,7 +25,7 @@ @implementation ToolbarSegmentedCell //when the toolbar is set to small size, don't make the group items small -- (NSControlSize) controlSize +- (NSControlSize)controlSize { return NSRegularControlSize; } diff --git a/macosx/Torrent.h b/macosx/Torrent.h index 9881933d8..3cb37f467 100644 --- a/macosx/Torrent.h +++ b/macosx/Torrent.h @@ -34,188 +34,193 @@ typedef NS_ENUM(unsigned int, TorrentDeterminationType) { #define kTorrentDidChangeGroupNotification @"TorrentDidChangeGroup" -@interface Torrent : NSObject +@interface Torrent : NSObject -- (instancetype) initWithPath: (NSString *) path location: (NSString *) location deleteTorrentFile: (BOOL) torrentDelete - lib: (tr_session *) lib; -- (instancetype) initWithTorrentStruct: (tr_torrent *) torrentStruct location: (NSString *) location lib: (tr_session *) lib; -- (instancetype) initWithMagnetAddress: (NSString *) address location: (NSString *) location lib: (tr_session *) lib; -- (instancetype) initWithHistory: (NSDictionary *) history lib: (tr_session *) lib forcePause: (BOOL) pause; +- (instancetype)initWithPath:(NSString*)path + location:(NSString*)location + deleteTorrentFile:(BOOL)torrentDelete + lib:(tr_session*)lib; +- (instancetype)initWithTorrentStruct:(tr_torrent*)torrentStruct location:(NSString*)location lib:(tr_session*)lib; +- (instancetype)initWithMagnetAddress:(NSString*)address location:(NSString*)location lib:(tr_session*)lib; +- (instancetype)initWithHistory:(NSDictionary*)history lib:(tr_session*)lib forcePause:(BOOL)pause; -@property (nonatomic, readonly) NSDictionary *history; +@property(nonatomic, readonly) NSDictionary* history; -- (void) closeRemoveTorrent: (BOOL) trashFiles; +- (void)closeRemoveTorrent:(BOOL)trashFiles; -- (void) changeDownloadFolderBeforeUsing: (NSString *) folder determinationType: (TorrentDeterminationType) determinationType; +- (void)changeDownloadFolderBeforeUsing:(NSString*)folder determinationType:(TorrentDeterminationType)determinationType; -@property (nonatomic, readonly) NSString *currentDirectory; +@property(nonatomic, readonly) NSString* currentDirectory; -- (void) getAvailability: (int8_t *) tab size: (NSInteger) size; -- (void) getAmountFinished: (float *) tab size: (NSInteger) size; -@property (nonatomic) NSIndexSet *previousFinishedPieces; +- (void)getAvailability:(int8_t*)tab size:(NSInteger)size; +- (void)getAmountFinished:(float*)tab size:(NSInteger)size; +@property(nonatomic) NSIndexSet* previousFinishedPieces; -- (void) update; +- (void)update; -- (void) startTransferIgnoringQueue: (BOOL) ignoreQueue; -- (void) startTransferNoQueue; -- (void) startTransfer; -- (void) stopTransfer; -- (void) sleep; -- (void) wakeUp; +- (void)startTransferIgnoringQueue:(BOOL)ignoreQueue; +- (void)startTransferNoQueue; +- (void)startTransfer; +- (void)stopTransfer; +- (void)sleep; +- (void)wakeUp; -@property (nonatomic) NSUInteger queuePosition; +@property(nonatomic) NSUInteger queuePosition; -- (void) manualAnnounce; -@property (nonatomic, readonly) BOOL canManualAnnounce; +- (void)manualAnnounce; +@property(nonatomic, readonly) BOOL canManualAnnounce; -- (void) resetCache; +- (void)resetCache; -@property (nonatomic, getter=isMagnet, readonly) BOOL magnet; -@property (nonatomic, readonly) NSString *magnetLink; +@property(nonatomic, getter=isMagnet, readonly) BOOL magnet; +@property(nonatomic, readonly) NSString* magnetLink; -@property (nonatomic, readonly) CGFloat ratio; -@property (nonatomic) tr_ratiolimit ratioSetting; -@property (nonatomic) CGFloat ratioLimit; -@property (nonatomic, readonly) CGFloat progressStopRatio; +@property(nonatomic, readonly) CGFloat ratio; +@property(nonatomic) tr_ratiolimit ratioSetting; +@property(nonatomic) CGFloat ratioLimit; +@property(nonatomic, readonly) CGFloat progressStopRatio; -@property (nonatomic) tr_idlelimit idleSetting; -@property (nonatomic) NSUInteger idleLimitMinutes; +@property(nonatomic) tr_idlelimit idleSetting; +@property(nonatomic) NSUInteger idleLimitMinutes; -- (BOOL) usesSpeedLimit: (BOOL) upload; -- (void) setUseSpeedLimit: (BOOL) use upload: (BOOL) upload; -- (NSInteger) speedLimit: (BOOL) upload; -- (void) setSpeedLimit: (NSInteger) limit upload: (BOOL) upload; -@property (nonatomic) BOOL usesGlobalSpeedLimit; +- (BOOL)usesSpeedLimit:(BOOL)upload; +- (void)setUseSpeedLimit:(BOOL)use upload:(BOOL)upload; +- (NSInteger)speedLimit:(BOOL)upload; +- (void)setSpeedLimit:(NSInteger)limit upload:(BOOL)upload; +@property(nonatomic) BOOL usesGlobalSpeedLimit; -@property (nonatomic) uint16_t maxPeerConnect; +@property(nonatomic) uint16_t maxPeerConnect; -@property (nonatomic) BOOL removeWhenFinishSeeding; +@property(nonatomic) BOOL removeWhenFinishSeeding; -@property (nonatomic, readonly) BOOL waitingToStart; +@property(nonatomic, readonly) BOOL waitingToStart; -@property (nonatomic) tr_priority_t priority; +@property(nonatomic) tr_priority_t priority; -+ (BOOL) trashFile: (NSString *) path error: (NSError **) error; -- (void) moveTorrentDataFileTo: (NSString *) folder; -- (void) copyTorrentFileTo: (NSString *) path; ++ (BOOL)trashFile:(NSString*)path error:(NSError**)error; +- (void)moveTorrentDataFileTo:(NSString*)folder; +- (void)copyTorrentFileTo:(NSString*)path; -- (BOOL) alertForRemainingDiskSpace; +- (BOOL)alertForRemainingDiskSpace; -@property (nonatomic, readonly) NSImage *icon; +@property(nonatomic, readonly) NSImage* icon; -@property (nonatomic, readonly) NSString *name; -@property (nonatomic, getter=isFolder, readonly) BOOL folder; -@property (nonatomic, readonly) uint64_t size; -@property (nonatomic, readonly) uint64_t sizeLeft; +@property(nonatomic, readonly) NSString* name; +@property(nonatomic, getter=isFolder, readonly) BOOL folder; +@property(nonatomic, readonly) uint64_t size; +@property(nonatomic, readonly) uint64_t sizeLeft; -@property (nonatomic, readonly) NSMutableArray *allTrackerStats; -@property (nonatomic, readonly) NSArray *allTrackersFlat; //used by GroupRules -- (BOOL) addTrackerToNewTier: (NSString *) tracker; -- (void) removeTrackers: (NSSet *) trackers; +@property(nonatomic, readonly) NSMutableArray* allTrackerStats; +@property(nonatomic, readonly) NSArray* allTrackersFlat; //used by GroupRules +- (BOOL)addTrackerToNewTier:(NSString*)tracker; +- (void)removeTrackers:(NSSet*)trackers; -@property (nonatomic, readonly) NSString *comment; -@property (nonatomic, readonly) NSString *creator; -@property (nonatomic, readonly) NSDate *dateCreated; +@property(nonatomic, readonly) NSString* comment; +@property(nonatomic, readonly) NSString* creator; +@property(nonatomic, readonly) NSDate* dateCreated; -@property (nonatomic, readonly) NSInteger pieceSize; -@property (nonatomic, readonly) NSInteger pieceCount; -@property (nonatomic, readonly) NSString *hashString; -@property (nonatomic, readonly) BOOL privateTorrent; +@property(nonatomic, readonly) NSInteger pieceSize; +@property(nonatomic, readonly) NSInteger pieceCount; +@property(nonatomic, readonly) NSString* hashString; +@property(nonatomic, readonly) BOOL privateTorrent; -@property (nonatomic, readonly) NSString *torrentLocation; -@property (nonatomic, readonly) NSString *dataLocation; -- (NSString *) fileLocation: (FileListNode *) node; +@property(nonatomic, readonly) NSString* torrentLocation; +@property(nonatomic, readonly) NSString* dataLocation; +- (NSString*)fileLocation:(FileListNode*)node; -- (void) renameTorrent: (NSString *) newName completionHandler: (void (^)(BOOL didRename)) completionHandler; -- (void) renameFileNode: (FileListNode *) node withName: (NSString *) newName completionHandler: (void (^)(BOOL didRename)) completionHandler; +- (void)renameTorrent:(NSString*)newName completionHandler:(void (^)(BOOL didRename))completionHandler; +- (void)renameFileNode:(FileListNode*)node + withName:(NSString*)newName + completionHandler:(void (^)(BOOL didRename))completionHandler; -@property (nonatomic, readonly) CGFloat progress; -@property (nonatomic, readonly) CGFloat progressDone; -@property (nonatomic, readonly) CGFloat progressLeft; -@property (nonatomic, readonly) CGFloat checkingProgress; +@property(nonatomic, readonly) CGFloat progress; +@property(nonatomic, readonly) CGFloat progressDone; +@property(nonatomic, readonly) CGFloat progressLeft; +@property(nonatomic, readonly) CGFloat checkingProgress; -@property (nonatomic, readonly) CGFloat availableDesired; +@property(nonatomic, readonly) CGFloat availableDesired; -@property (nonatomic, getter=isActive, readonly) BOOL active; -@property (nonatomic, getter=isSeeding, readonly) BOOL seeding; -@property (nonatomic, getter=isChecking, readonly) BOOL checking; -@property (nonatomic, getter=isCheckingWaiting, readonly) BOOL checkingWaiting; -@property (nonatomic, readonly) BOOL allDownloaded; -@property (nonatomic, getter=isComplete, readonly) BOOL complete; -@property (nonatomic, getter=isFinishedSeeding, readonly) BOOL finishedSeeding; -@property (nonatomic, getter=isError, readonly) BOOL error; -@property (nonatomic, getter=isAnyErrorOrWarning, readonly) BOOL anyErrorOrWarning; -@property (nonatomic, readonly) NSString *errorMessage; +@property(nonatomic, getter=isActive, readonly) BOOL active; +@property(nonatomic, getter=isSeeding, readonly) BOOL seeding; +@property(nonatomic, getter=isChecking, readonly) BOOL checking; +@property(nonatomic, getter=isCheckingWaiting, readonly) BOOL checkingWaiting; +@property(nonatomic, readonly) BOOL allDownloaded; +@property(nonatomic, getter=isComplete, readonly) BOOL complete; +@property(nonatomic, getter=isFinishedSeeding, readonly) BOOL finishedSeeding; +@property(nonatomic, getter=isError, readonly) BOOL error; +@property(nonatomic, getter=isAnyErrorOrWarning, readonly) BOOL anyErrorOrWarning; +@property(nonatomic, readonly) NSString* errorMessage; -@property (nonatomic, readonly) NSArray *peers; +@property(nonatomic, readonly) NSArray* peers; -@property (nonatomic, readonly) NSUInteger webSeedCount; -@property (nonatomic, readonly) NSArray *webSeeds; +@property(nonatomic, readonly) NSUInteger webSeedCount; +@property(nonatomic, readonly) NSArray* webSeeds; -@property (nonatomic, readonly) NSString *progressString; -@property (nonatomic, readonly) NSString *statusString; -@property (nonatomic, readonly) NSString *shortStatusString; -@property (nonatomic, readonly) NSString *remainingTimeString; +@property(nonatomic, readonly) NSString* progressString; +@property(nonatomic, readonly) NSString* statusString; +@property(nonatomic, readonly) NSString* shortStatusString; +@property(nonatomic, readonly) NSString* remainingTimeString; -@property (nonatomic, readonly) NSString *stateString; -@property (nonatomic, readonly) NSInteger totalPeersConnected; -@property (nonatomic, readonly) NSInteger totalPeersTracker; -@property (nonatomic, readonly) NSInteger totalPeersIncoming; -@property (nonatomic, readonly) NSInteger totalPeersCache; -@property (nonatomic, readonly) NSInteger totalPeersPex; -@property (nonatomic, readonly) NSInteger totalPeersDHT; -@property (nonatomic, readonly) NSInteger totalPeersLocal; -@property (nonatomic, readonly) NSInteger totalPeersLTEP; +@property(nonatomic, readonly) NSString* stateString; +@property(nonatomic, readonly) NSInteger totalPeersConnected; +@property(nonatomic, readonly) NSInteger totalPeersTracker; +@property(nonatomic, readonly) NSInteger totalPeersIncoming; +@property(nonatomic, readonly) NSInteger totalPeersCache; +@property(nonatomic, readonly) NSInteger totalPeersPex; +@property(nonatomic, readonly) NSInteger totalPeersDHT; +@property(nonatomic, readonly) NSInteger totalPeersLocal; +@property(nonatomic, readonly) NSInteger totalPeersLTEP; -@property (nonatomic, readonly) NSInteger peersSendingToUs; -@property (nonatomic, readonly) NSInteger peersGettingFromUs; +@property(nonatomic, readonly) NSInteger peersSendingToUs; +@property(nonatomic, readonly) NSInteger peersGettingFromUs; -@property (nonatomic, readonly) CGFloat downloadRate; -@property (nonatomic, readonly) CGFloat uploadRate; -@property (nonatomic, readonly) CGFloat totalRate; -@property (nonatomic, readonly) uint64_t haveVerified; -@property (nonatomic, readonly) uint64_t haveTotal; -@property (nonatomic, readonly) uint64_t totalSizeSelected; -@property (nonatomic, readonly) uint64_t downloadedTotal; -@property (nonatomic, readonly) uint64_t uploadedTotal; -@property (nonatomic, readonly) uint64_t failedHash; +@property(nonatomic, readonly) CGFloat downloadRate; +@property(nonatomic, readonly) CGFloat uploadRate; +@property(nonatomic, readonly) CGFloat totalRate; +@property(nonatomic, readonly) uint64_t haveVerified; +@property(nonatomic, readonly) uint64_t haveTotal; +@property(nonatomic, readonly) uint64_t totalSizeSelected; +@property(nonatomic, readonly) uint64_t downloadedTotal; +@property(nonatomic, readonly) uint64_t uploadedTotal; +@property(nonatomic, readonly) uint64_t failedHash; -@property (nonatomic, readonly) NSInteger groupValue; -- (void) setGroupValue: (NSInteger) groupValue determinationType: (TorrentDeterminationType) determinationType;; -@property (nonatomic, readonly) NSInteger groupOrderValue; -- (void) checkGroupValueForRemoval: (NSNotification *) notification; +@property(nonatomic, readonly) NSInteger groupValue; +- (void)setGroupValue:(NSInteger)groupValue determinationType:(TorrentDeterminationType)determinationType; +; +@property(nonatomic, readonly) NSInteger groupOrderValue; +- (void)checkGroupValueForRemoval:(NSNotification*)notification; -@property (nonatomic, readonly) NSArray *fileList; -@property (nonatomic, readonly) NSArray *flatFileList; -@property (nonatomic, readonly) NSInteger fileCount; -- (void) updateFileStat; +@property(nonatomic, readonly) NSArray* fileList; +@property(nonatomic, readonly) NSArray* flatFileList; +@property(nonatomic, readonly) NSInteger fileCount; +- (void)updateFileStat; //methods require fileStats to have been updated recently to be accurate -- (CGFloat) fileProgress: (FileListNode *) node; -- (BOOL) canChangeDownloadCheckForFile: (NSUInteger) index; -- (BOOL) canChangeDownloadCheckForFiles: (NSIndexSet *) indexSet; -- (NSInteger) checkForFiles: (NSIndexSet *) indexSet; -- (void) setFileCheckState: (NSInteger) state forIndexes: (NSIndexSet *) indexSet; -- (void) setFilePriority: (tr_priority_t) priority forIndexes: (NSIndexSet *) indexSet; -- (BOOL) hasFilePriority: (tr_priority_t) priority forIndexes: (NSIndexSet *) indexSet; -- (NSSet *) filePrioritiesForIndexes: (NSIndexSet *) indexSet; +- (CGFloat)fileProgress:(FileListNode*)node; +- (BOOL)canChangeDownloadCheckForFile:(NSUInteger)index; +- (BOOL)canChangeDownloadCheckForFiles:(NSIndexSet*)indexSet; +- (NSInteger)checkForFiles:(NSIndexSet*)indexSet; +- (void)setFileCheckState:(NSInteger)state forIndexes:(NSIndexSet*)indexSet; +- (void)setFilePriority:(tr_priority_t)priority forIndexes:(NSIndexSet*)indexSet; +- (BOOL)hasFilePriority:(tr_priority_t)priority forIndexes:(NSIndexSet*)indexSet; +- (NSSet*)filePrioritiesForIndexes:(NSIndexSet*)indexSet; -@property (nonatomic, readonly) NSDate *dateAdded; -@property (nonatomic, readonly) NSDate *dateCompleted; -@property (nonatomic, readonly) NSDate *dateActivity; -@property (nonatomic, readonly) NSDate *dateActivityOrAdd; +@property(nonatomic, readonly) NSDate* dateAdded; +@property(nonatomic, readonly) NSDate* dateCompleted; +@property(nonatomic, readonly) NSDate* dateActivity; +@property(nonatomic, readonly) NSDate* dateActivityOrAdd; -@property (nonatomic, readonly) NSInteger secondsDownloading; -@property (nonatomic, readonly) NSInteger secondsSeeding; +@property(nonatomic, readonly) NSInteger secondsDownloading; +@property(nonatomic, readonly) NSInteger secondsSeeding; -@property (nonatomic, readonly) NSInteger stalledMinutes; -@property (nonatomic, getter=isStalled, readonly) BOOL stalled; +@property(nonatomic, readonly) NSInteger stalledMinutes; +@property(nonatomic, getter=isStalled, readonly) BOOL stalled; -- (void) updateTimeMachineExclude; +- (void)updateTimeMachineExclude; -@property (nonatomic, readonly) NSInteger stateSortKey; -@property (nonatomic, readonly) NSString *trackerSortKey; +@property(nonatomic, readonly) NSInteger stateSortKey; +@property(nonatomic, readonly) NSString* trackerSortKey; -@property (nonatomic, readonly) tr_torrent *torrentStruct; +@property(nonatomic, readonly) tr_torrent* torrentStruct; @end diff --git a/macosx/Torrent.m b/macosx/Torrent.m index 871837ae8..a011cf049 100644 --- a/macosx/Torrent.m +++ b/macosx/Torrent.m @@ -32,94 +32,111 @@ #import "NSStringAdditions.h" #import "TrackerNode.h" -#define ETA_IDLE_DISPLAY_SEC (2*60) +#define ETA_IDLE_DISPLAY_SEC (2 * 60) @interface Torrent (Private) -- (instancetype) initWithPath: (NSString *) path hash: (NSString *) hashString torrentStruct: (tr_torrent *) torrentStruct - magnetAddress: (NSString *) magnetAddress lib: (tr_session *) lib - groupValue: (NSNumber *) groupValue - removeWhenFinishSeeding: (NSNumber *) removeWhenFinishSeeding - downloadFolder: (NSString *) downloadFolder - legacyIncompleteFolder: (NSString *) incompleteFolder; +- (instancetype)initWithPath:(NSString*)path + hash:(NSString*)hashString + torrentStruct:(tr_torrent*)torrentStruct + magnetAddress:(NSString*)magnetAddress + lib:(tr_session*)lib + groupValue:(NSNumber*)groupValue + removeWhenFinishSeeding:(NSNumber*)removeWhenFinishSeeding + downloadFolder:(NSString*)downloadFolder + legacyIncompleteFolder:(NSString*)incompleteFolder; -- (void) createFileList; -- (void) insertPathForComponents: (NSArray *) components withComponentIndex: (NSUInteger) componentIndex forParent: (FileListNode *) parent fileSize: (uint64_t) size - index: (NSInteger) index flatList: (NSMutableArray *) flatFileList; -- (void) sortFileList: (NSMutableArray *) fileNodes; +- (void)createFileList; +- (void)insertPathForComponents:(NSArray*)components + withComponentIndex:(NSUInteger)componentIndex + forParent:(FileListNode*)parent + fileSize:(uint64_t)size + index:(NSInteger)index + flatList:(NSMutableArray*)flatFileList; +- (void)sortFileList:(NSMutableArray*)fileNodes; -- (void) startQueue; -- (void) completenessChange: (tr_completeness) status wasRunning: (BOOL) wasRunning; -- (void) ratioLimitHit; -- (void) idleLimitHit; -- (void) metadataRetrieved; -- (void)renameFinished: (BOOL) success nodes: (NSArray *) nodes completionHandler: (void (^)(BOOL)) completionHandler oldPath: (NSString *) oldPath newName: (NSString *) newName; +- (void)startQueue; +- (void)completenessChange:(tr_completeness)status wasRunning:(BOOL)wasRunning; +- (void)ratioLimitHit; +- (void)idleLimitHit; +- (void)metadataRetrieved; +- (void)renameFinished:(BOOL)success + nodes:(NSArray*)nodes + completionHandler:(void (^)(BOOL))completionHandler + oldPath:(NSString*)oldPath + newName:(NSString*)newName; -@property (nonatomic, readonly) BOOL shouldShowEta; -@property (nonatomic, readonly) NSString *etaString; +@property(nonatomic, readonly) BOOL shouldShowEta; +@property(nonatomic, readonly) NSString* etaString; -- (void) setTimeMachineExclude: (BOOL) exclude; +- (void)setTimeMachineExclude:(BOOL)exclude; @end -void startQueueCallback(tr_torrent * torrent, void * torrentData) +void startQueueCallback(tr_torrent* torrent, void* torrentData) { dispatch_async(dispatch_get_main_queue(), ^{ - [(__bridge Torrent *)torrentData startQueue]; + [(__bridge Torrent*)torrentData startQueue]; }); } -void completenessChangeCallback(tr_torrent * torrent, tr_completeness status, bool wasRunning, void * torrentData) +void completenessChangeCallback(tr_torrent* torrent, tr_completeness status, bool wasRunning, void* torrentData) { dispatch_async(dispatch_get_main_queue(), ^{ - [(__bridge Torrent *)torrentData completenessChange: status wasRunning: wasRunning]; + [(__bridge Torrent*)torrentData completenessChange:status wasRunning:wasRunning]; }); } -void ratioLimitHitCallback(tr_torrent * torrent, void * torrentData) +void ratioLimitHitCallback(tr_torrent* torrent, void* torrentData) { dispatch_async(dispatch_get_main_queue(), ^{ - [(__bridge Torrent *)torrentData ratioLimitHit]; + [(__bridge Torrent*)torrentData ratioLimitHit]; }); } -void idleLimitHitCallback(tr_torrent * torrent, void * torrentData) +void idleLimitHitCallback(tr_torrent* torrent, void* torrentData) { dispatch_async(dispatch_get_main_queue(), ^{ - [(__bridge Torrent *)torrentData idleLimitHit]; + [(__bridge Torrent*)torrentData idleLimitHit]; }); } -void metadataCallback(tr_torrent * torrent, void * torrentData) +void metadataCallback(tr_torrent* torrent, void* torrentData) { dispatch_async(dispatch_get_main_queue(), ^{ - [(__bridge Torrent *)torrentData metadataRetrieved]; + [(__bridge Torrent*)torrentData metadataRetrieved]; }); } -void renameCallback(tr_torrent * torrent, const char * oldPathCharString, const char * newNameCharString, int error, void * contextInfo) +void renameCallback(tr_torrent* torrent, char const* oldPathCharString, char const* newNameCharString, int error, void* contextInfo) { - @autoreleasepool { - NSString * oldPath = @(oldPathCharString); - NSString * newName = @(newNameCharString); + @autoreleasepool + { + NSString* oldPath = @(oldPathCharString); + NSString* newName = @(newNameCharString); dispatch_async(dispatch_get_main_queue(), ^{ - NSDictionary * contextDict = (__bridge_transfer NSDictionary *)contextInfo; - Torrent * torrentObject = contextDict[@"Torrent"]; - [torrentObject renameFinished: error == 0 nodes: contextDict[@"Nodes"] completionHandler: contextDict[@"CompletionHandler"] oldPath: oldPath newName: newName]; + NSDictionary* contextDict = (__bridge_transfer NSDictionary*)contextInfo; + Torrent* torrentObject = contextDict[@"Torrent"]; + [torrentObject renameFinished:error == 0 nodes:contextDict[@"Nodes"] + completionHandler:contextDict[@"CompletionHandler"] + oldPath:oldPath + newName:newName]; }); } } -bool trashDataFile(const char * filename, tr_error ** error) +bool trashDataFile(char const* filename, tr_error** error) { if (filename == NULL) + { return false; + } @autoreleasepool { - NSError * localError; - if (![Torrent trashFile: @(filename) error: &localError]) + NSError* localError; + if (![Torrent trashFile:@(filename) error:&localError]) { tr_error_set_literal(error, localError.code, localError.description.UTF8String); return false; @@ -131,21 +148,22 @@ bool trashDataFile(const char * filename, tr_error ** error) @implementation Torrent { - tr_torrent * fHandle; - const tr_info * fInfo; - const tr_stat * fStat; + tr_torrent* fHandle; + tr_info const* fInfo; + tr_stat const* fStat; - NSUserDefaults * fDefaults; + NSUserDefaults* fDefaults; - NSImage * fIcon; + NSImage* fIcon; - NSString * fHashString; + NSString* fHashString; - tr_file_stat * fFileStat; - NSArray * fFileList, * fFlatFileList; + tr_file_stat* fFileStat; + NSArray* fFileList; + NSArray* fFlatFileList; - NSIndexSet * fPreviousFinishedIndexes; - NSDate * fPreviousFinishedIndexesDate; + NSIndexSet* fPreviousFinishedIndexes; + NSDate* fPreviousFinishedIndexesDate; NSInteger fGroupValue; TorrentDeterminationType fGroupValueDetermination; @@ -157,61 +175,62 @@ bool trashDataFile(const char * filename, tr_error ** error) BOOL fTimeMachineExcludeInitialized; } -- (instancetype) initWithPath: (NSString *) path location: (NSString *) location deleteTorrentFile: (BOOL) torrentDelete - lib: (tr_session *) lib +- (instancetype)initWithPath:(NSString*)path + location:(NSString*)location + deleteTorrentFile:(BOOL)torrentDelete + lib:(tr_session*)lib { - self = [self initWithPath: path hash: nil torrentStruct: NULL magnetAddress: nil lib: lib - groupValue: nil - removeWhenFinishSeeding: nil - downloadFolder: location - legacyIncompleteFolder: nil]; + self = [self initWithPath:path hash:nil torrentStruct:NULL magnetAddress:nil lib:lib groupValue:nil + removeWhenFinishSeeding:nil + downloadFolder:location + legacyIncompleteFolder:nil]; if (self) { - if (torrentDelete && ![self.torrentLocation isEqualToString: path]) - [Torrent trashFile: path error: nil]; + if (torrentDelete && ![self.torrentLocation isEqualToString:path]) + { + [Torrent trashFile:path error:nil]; + } } return self; } -- (instancetype) initWithTorrentStruct: (tr_torrent *) torrentStruct location: (NSString *) location lib: (tr_session *) lib +- (instancetype)initWithTorrentStruct:(tr_torrent*)torrentStruct location:(NSString*)location lib:(tr_session*)lib { - self = [self initWithPath: nil hash: nil torrentStruct: torrentStruct magnetAddress: nil lib: lib - groupValue: nil - removeWhenFinishSeeding: nil - downloadFolder: location - legacyIncompleteFolder: nil]; + self = [self initWithPath:nil hash:nil torrentStruct:torrentStruct magnetAddress:nil lib:lib groupValue:nil + removeWhenFinishSeeding:nil + downloadFolder:location + legacyIncompleteFolder:nil]; return self; } -- (instancetype) initWithMagnetAddress: (NSString *) address location: (NSString *) location lib: (tr_session *) lib +- (instancetype)initWithMagnetAddress:(NSString*)address location:(NSString*)location lib:(tr_session*)lib { - self = [self initWithPath: nil hash: nil torrentStruct: nil magnetAddress: address - lib: lib groupValue: nil - removeWhenFinishSeeding: nil - downloadFolder: location legacyIncompleteFolder: nil]; + self = [self initWithPath:nil hash:nil torrentStruct:nil magnetAddress:address lib:lib groupValue:nil + removeWhenFinishSeeding:nil + downloadFolder:location + legacyIncompleteFolder:nil]; return self; } -- (instancetype) initWithHistory: (NSDictionary *) history lib: (tr_session *) lib forcePause: (BOOL) pause +- (instancetype)initWithHistory:(NSDictionary*)history lib:(tr_session*)lib forcePause:(BOOL)pause { - self = [self initWithPath: history[@"InternalTorrentPath"] - hash: history[@"TorrentHash"] - torrentStruct: NULL - magnetAddress: nil - lib: lib - groupValue: history[@"GroupValue"] - removeWhenFinishSeeding: history[@"RemoveWhenFinishSeeding"] - downloadFolder: history[@"DownloadFolder"] //upgrading from versions < 1.80 - legacyIncompleteFolder: [history[@"UseIncompleteFolder"] boolValue] //upgrading from versions < 1.80 - ? history[@"IncompleteFolder"] : nil]; + self = [self initWithPath:history[@"InternalTorrentPath"] hash:history[@"TorrentHash"] torrentStruct:NULL magnetAddress:nil + lib:lib + groupValue:history[@"GroupValue"] + removeWhenFinishSeeding:history[@"RemoveWhenFinishSeeding"] + downloadFolder:history[@"DownloadFolder"] //upgrading from versions < 1.80 + legacyIncompleteFolder:[history[@"UseIncompleteFolder"] boolValue] //upgrading from versions < 1.80 + ? + history[@"IncompleteFolder"] : + nil]; if (self) { //start transfer - NSNumber * active; + NSNumber* active; if (!pause && (active = history[@"Active"]) && active.boolValue) { fStat = tr_torrentStat(fHandle); @@ -219,131 +238,156 @@ bool trashDataFile(const char * filename, tr_error ** error) } //upgrading from versions < 1.30: get old added, activity, and done dates - NSDate * date; + NSDate* date; if ((date = history[@"Date"])) + { tr_torrentSetAddedDate(fHandle, date.timeIntervalSince1970); + } if ((date = history[@"DateActivity"])) + { tr_torrentSetActivityDate(fHandle, date.timeIntervalSince1970); + } if ((date = history[@"DateCompleted"])) + { tr_torrentSetDoneDate(fHandle, date.timeIntervalSince1970); + } //upgrading from versions < 1.60: get old stop ratio settings - NSNumber * ratioSetting; + NSNumber* ratioSetting; if ((ratioSetting = history[@"RatioSetting"])) { switch (ratioSetting.intValue) { - case NSOnState: self.ratioSetting = TR_RATIOLIMIT_SINGLE; break; - case NSOffState: self.ratioSetting = TR_RATIOLIMIT_UNLIMITED; break; - case NSMixedState: self.ratioSetting = TR_RATIOLIMIT_GLOBAL; break; + case NSOnState: + self.ratioSetting = TR_RATIOLIMIT_SINGLE; + break; + case NSOffState: + self.ratioSetting = TR_RATIOLIMIT_UNLIMITED; + break; + case NSMixedState: + self.ratioSetting = TR_RATIOLIMIT_GLOBAL; + break; } } - NSNumber * ratioLimit; + NSNumber* ratioLimit; if ((ratioLimit = history[@"RatioLimit"])) + { self.ratioLimit = ratioLimit.floatValue; + } } return self; } -- (NSDictionary *) history +- (NSDictionary*)history { return @{ - @"InternalTorrentPath": self.torrentLocation, - @"TorrentHash": self.hashString, - @"Active": @(self.active), - @"WaitToStart": @(self.waitingToStart), - @"GroupValue": @(fGroupValue), - @"RemoveWhenFinishSeeding": @(_removeWhenFinishSeeding)}; + @"InternalTorrentPath" : self.torrentLocation, + @"TorrentHash" : self.hashString, + @"Active" : @(self.active), + @"WaitToStart" : @(self.waitingToStart), + @"GroupValue" : @(fGroupValue), + @"RemoveWhenFinishSeeding" : @(_removeWhenFinishSeeding) + }; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; if (fFileStat) + { tr_torrentFilesFree(fFileStat, self.fileCount); + } } -- (NSString *) description +- (NSString*)description { - return [@"Torrent: " stringByAppendingString: self.name]; + return [@"Torrent: " stringByAppendingString:self.name]; } -- (id) copyWithZone: (NSZone *) zone +- (id)copyWithZone:(NSZone*)zone { return self; } -- (void) closeRemoveTorrent: (BOOL) trashFiles +- (void)closeRemoveTorrent:(BOOL)trashFiles { //allow the file to be indexed by Time Machine - [self setTimeMachineExclude: NO]; + [self setTimeMachineExclude:NO]; tr_torrentRemove(fHandle, trashFiles, trashDataFile); } -- (void) changeDownloadFolderBeforeUsing: (NSString *) folder determinationType: (TorrentDeterminationType) determinationType +- (void)changeDownloadFolderBeforeUsing:(NSString*)folder determinationType:(TorrentDeterminationType)determinationType { //if data existed in original download location, unexclude it before changing the location - [self setTimeMachineExclude: NO]; + [self setTimeMachineExclude:NO]; tr_torrentSetDownloadDir(fHandle, folder.UTF8String); fDownloadFolderDetermination = determinationType; } -- (NSString *) currentDirectory +- (NSString*)currentDirectory { return @(tr_torrentGetCurrentDir(fHandle)); } -- (void) getAvailability: (int8_t *) tab size: (NSInteger) size +- (void)getAvailability:(int8_t*)tab size:(NSInteger)size { tr_torrentAvailability(fHandle, tab, size); } -- (void) getAmountFinished: (float *) tab size: (NSInteger) size +- (void)getAmountFinished:(float*)tab size:(NSInteger)size { tr_torrentAmountFinished(fHandle, tab, size); } -- (NSIndexSet *) previousFinishedPieces +- (NSIndexSet*)previousFinishedPieces { //if the torrent hasn't been seen in a bit, and therefore hasn't been refreshed, return nil if (fPreviousFinishedIndexesDate && fPreviousFinishedIndexesDate.timeIntervalSinceNow > -2.0) + { return fPreviousFinishedIndexes; + } else + { return nil; + } } -- (void) setPreviousFinishedPieces: (NSIndexSet *) indexes +- (void)setPreviousFinishedPieces:(NSIndexSet*)indexes { fPreviousFinishedIndexes = indexes; fPreviousFinishedIndexesDate = indexes != nil ? [[NSDate alloc] init] : nil; } -- (void) update +- (void)update { //get previous stalled value before update - const BOOL wasStalled = fStat != NULL && self.stalled; + BOOL const wasStalled = fStat != NULL && self.stalled; fStat = tr_torrentStat(fHandle); //make sure the "active" filter is updated when stalled-ness changes if (wasStalled != self.stalled) + { //posting asynchronously with coalescing to prevent stack overflow on lots of torrents changing state at the same time - [NSNotificationQueue.defaultQueue enqueueNotification: [NSNotification notificationWithName: @"UpdateQueue" object: self] - postingStyle: NSPostASAP - coalesceMask: NSNotificationCoalescingOnName - forModes: nil]; + [NSNotificationQueue.defaultQueue enqueueNotification:[NSNotification notificationWithName:@"UpdateQueue" object:self] + postingStyle:NSPostASAP + coalesceMask:NSNotificationCoalescingOnName + forModes:nil]; + } //when the torrent is first loaded, update the time machine exclusion if (!fTimeMachineExcludeInitialized) + { [self updateTimeMachineExclude]; + } } -- (void) startTransferIgnoringQueue: (BOOL) ignoreQueue +- (void)startTransferIgnoringQueue:(BOOL)ignoreQueue { if ([self alertForRemainingDiskSpace]) { @@ -351,201 +395,206 @@ bool trashDataFile(const char * filename, tr_error ** error) [self update]; //capture, specifically, stop-seeding settings changing to unlimited - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptions" object:nil]; } } -- (void) startTransferNoQueue +- (void)startTransferNoQueue { - [self startTransferIgnoringQueue: YES]; + [self startTransferIgnoringQueue:YES]; } -- (void) startTransfer +- (void)startTransfer { - [self startTransferIgnoringQueue: NO]; + [self startTransferIgnoringQueue:NO]; } -- (void) stopTransfer +- (void)stopTransfer { tr_torrentStop(fHandle); [self update]; } -- (void) sleep +- (void)sleep { if ((fResumeOnWake = self.active)) + { tr_torrentStop(fHandle); + } } -- (void) wakeUp +- (void)wakeUp { if (fResumeOnWake) { - tr_logAddNamedInfo( fInfo->name, "restarting because of wakeUp" ); + tr_logAddNamedInfo(fInfo->name, "restarting because of wakeUp"); tr_torrentStart(fHandle); } } -- (NSUInteger) queuePosition +- (NSUInteger)queuePosition { return fStat->queuePosition; } -- (void) setQueuePosition: (NSUInteger) index +- (void)setQueuePosition:(NSUInteger)index { tr_torrentSetQueuePosition(fHandle, index); } -- (void) manualAnnounce +- (void)manualAnnounce { tr_torrentManualUpdate(fHandle); } -- (BOOL) canManualAnnounce +- (BOOL)canManualAnnounce { return tr_torrentCanManualUpdate(fHandle); } -- (void) resetCache +- (void)resetCache { tr_torrentVerify(fHandle, NULL, NULL); [self update]; } -- (BOOL) isMagnet +- (BOOL)isMagnet { return !tr_torrentHasMetadata(fHandle); } -- (NSString *) magnetLink +- (NSString*)magnetLink { return @(tr_torrentGetMagnetLink(fHandle)); } -- (CGFloat) ratio +- (CGFloat)ratio { return fStat->ratio; } -- (tr_ratiolimit) ratioSetting +- (tr_ratiolimit)ratioSetting { return tr_torrentGetRatioMode(fHandle); } -- (void) setRatioSetting: (tr_ratiolimit) setting +- (void)setRatioSetting:(tr_ratiolimit)setting { tr_torrentSetRatioMode(fHandle, setting); } -- (CGFloat) ratioLimit +- (CGFloat)ratioLimit { return tr_torrentGetRatioLimit(fHandle); } -- (void) setRatioLimit: (CGFloat) limit +- (void)setRatioLimit:(CGFloat)limit { NSParameterAssert(limit >= 0); tr_torrentSetRatioLimit(fHandle, limit); } -- (CGFloat) progressStopRatio +- (CGFloat)progressStopRatio { return fStat->seedRatioPercentDone; } -- (tr_idlelimit) idleSetting +- (tr_idlelimit)idleSetting { return tr_torrentGetIdleMode(fHandle); } -- (void) setIdleSetting: (tr_idlelimit) setting +- (void)setIdleSetting:(tr_idlelimit)setting { tr_torrentSetIdleMode(fHandle, setting); } -- (NSUInteger) idleLimitMinutes +- (NSUInteger)idleLimitMinutes { return tr_torrentGetIdleLimit(fHandle); } -- (void) setIdleLimitMinutes: (NSUInteger) limit +- (void)setIdleLimitMinutes:(NSUInteger)limit { NSParameterAssert(limit > 0); tr_torrentSetIdleLimit(fHandle, limit); } -- (BOOL) usesSpeedLimit: (BOOL) upload +- (BOOL)usesSpeedLimit:(BOOL)upload { return tr_torrentUsesSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN); } -- (void) setUseSpeedLimit: (BOOL) use upload: (BOOL) upload +- (void)setUseSpeedLimit:(BOOL)use upload:(BOOL)upload { tr_torrentUseSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN, use); } -- (NSInteger) speedLimit: (BOOL) upload +- (NSInteger)speedLimit:(BOOL)upload { return tr_torrentGetSpeedLimit_KBps(fHandle, upload ? TR_UP : TR_DOWN); } -- (void) setSpeedLimit: (NSInteger) limit upload: (BOOL) upload +- (void)setSpeedLimit:(NSInteger)limit upload:(BOOL)upload { tr_torrentSetSpeedLimit_KBps(fHandle, upload ? TR_UP : TR_DOWN, limit); } -- (BOOL) usesGlobalSpeedLimit +- (BOOL)usesGlobalSpeedLimit { return tr_torrentUsesSessionLimits(fHandle); } -- (void) setUseGlobalSpeedLimit: (BOOL) use +- (void)setUseGlobalSpeedLimit:(BOOL)use { tr_torrentUseSessionLimits(fHandle, use); } -- (void) setMaxPeerConnect: (uint16_t) count +- (void)setMaxPeerConnect:(uint16_t)count { NSParameterAssert(count > 0); tr_torrentSetPeerLimit(fHandle, count); } -- (uint16_t) maxPeerConnect +- (uint16_t)maxPeerConnect { return tr_torrentGetPeerLimit(fHandle); } -- (BOOL) waitingToStart +- (BOOL)waitingToStart { return fStat->activity == TR_STATUS_DOWNLOAD_WAIT || fStat->activity == TR_STATUS_SEED_WAIT; } -- (tr_priority_t) priority +- (tr_priority_t)priority { return tr_torrentGetPriority(fHandle); } -- (void) setPriority: (tr_priority_t) priority +- (void)setPriority:(tr_priority_t)priority { return tr_torrentSetPriority(fHandle, priority); } -+ (BOOL) trashFile: (NSString *) path error: (NSError **) error ++ (BOOL)trashFile:(NSString*)path error:(NSError**)error { //attempt to move to trash - if (![NSWorkspace.sharedWorkspace performFileOperation: NSWorkspaceRecycleOperation - source: path.stringByDeletingLastPathComponent destination: @"" - files: @[path.lastPathComponent] tag: nil]) + if (![NSWorkspace.sharedWorkspace performFileOperation:NSWorkspaceRecycleOperation source:path.stringByDeletingLastPathComponent + destination:@"" + files:@[ path.lastPathComponent ] + tag:nil]) { //if cannot trash, just delete it (will work if it's on a remote volume) - NSError * localError; - if (![NSFileManager.defaultManager removeItemAtPath: path error: &localError]) + NSError* localError; + if (![NSFileManager.defaultManager removeItemAtPath:path error:&localError]) { NSLog(@"old Could not trash %@: %@", path, localError.localizedDescription); if (error != nil) + { *error = localError; + } return NO; } else @@ -557,27 +606,26 @@ bool trashDataFile(const char * filename, tr_error ** error) return YES; } -- (void) moveTorrentDataFileTo: (NSString *) folder +- (void)moveTorrentDataFileTo:(NSString*)folder { - NSString * oldFolder = self.currentDirectory; - if ([oldFolder isEqualToString: folder]) + NSString* oldFolder = self.currentDirectory; + if ([oldFolder isEqualToString:folder]) + { return; + } //check if moving inside itself - NSArray * oldComponents = oldFolder.pathComponents, - * newComponents = folder.pathComponents; - const NSUInteger oldCount = oldComponents.count; + NSArray *oldComponents = oldFolder.pathComponents, *newComponents = folder.pathComponents; + NSUInteger const oldCount = oldComponents.count; - if (oldCount < newComponents.count && [newComponents[oldCount] isEqualToString: self.name] - && [folder hasPrefix: oldFolder]) + if (oldCount < newComponents.count && [newComponents[oldCount] isEqualToString:self.name] && [folder hasPrefix:oldFolder]) { - NSAlert * alert = [[NSAlert alloc] init]; - alert.messageText = NSLocalizedString(@"A folder cannot be moved to inside itself.", - "Move inside itself alert -> title"); - alert.informativeText = [NSString stringWithFormat: - NSLocalizedString(@"The move operation of \"%@\" cannot be done.", - "Move inside itself alert -> message"), self.name]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move inside itself alert -> button")]; + NSAlert* alert = [[NSAlert alloc] init]; + alert.messageText = NSLocalizedString(@"A folder cannot be moved to inside itself.", "Move inside itself alert -> title"); + alert.informativeText = [NSString + stringWithFormat:NSLocalizedString(@"The move operation of \"%@\" cannot be done.", "Move inside itself alert -> message"), + self.name]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Move inside itself alert -> button")]; [alert runModal]; @@ -588,17 +636,21 @@ bool trashDataFile(const char * filename, tr_error ** error) tr_torrentSetLocation(fHandle, folder.UTF8String, YES, NULL, &status); while (status == TR_LOC_MOVING) //block while moving (for now) - [NSThread sleepForTimeInterval: 0.05]; + { + [NSThread sleepForTimeInterval:0.05]; + } if (status == TR_LOC_DONE) - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateStats" object: nil]; + { + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateStats" object:nil]; + } else { - NSAlert * alert = [[NSAlert alloc] init]; + NSAlert* alert = [[NSAlert alloc] init]; alert.messageText = NSLocalizedString(@"There was an error moving the data file.", "Move error alert -> title"); - alert.informativeText = [NSString stringWithFormat: - NSLocalizedString(@"The move operation of \"%@\" cannot be done.", "Move error alert -> message"), self.name]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move error alert -> button")]; + alert.informativeText = [NSString + stringWithFormat:NSLocalizedString(@"The move operation of \"%@\" cannot be done.", "Move error alert -> message"), self.name]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Move error alert -> button")]; [alert runModal]; } @@ -606,44 +658,49 @@ bool trashDataFile(const char * filename, tr_error ** error) [self updateTimeMachineExclude]; } -- (void) copyTorrentFileTo: (NSString *) path +- (void)copyTorrentFileTo:(NSString*)path { - [NSFileManager.defaultManager copyItemAtPath: self.torrentLocation toPath: path error: NULL]; + [NSFileManager.defaultManager copyItemAtPath:self.torrentLocation toPath:path error:NULL]; } -- (BOOL) alertForRemainingDiskSpace +- (BOOL)alertForRemainingDiskSpace { - if (self.allDownloaded || ![fDefaults boolForKey: @"WarningRemainingSpace"]) - return YES; - - NSString * downloadFolder = self.currentDirectory; - NSDictionary * systemAttributes; - if ((systemAttributes = [NSFileManager.defaultManager attributesOfFileSystemForPath: downloadFolder error: NULL])) + if (self.allDownloaded || ![fDefaults boolForKey:@"WarningRemainingSpace"]) { - const uint64_t remainingSpace = ((NSNumber *)systemAttributes[NSFileSystemFreeSize]).unsignedLongLongValue; + return YES; + } + + NSString* downloadFolder = self.currentDirectory; + NSDictionary* systemAttributes; + if ((systemAttributes = [NSFileManager.defaultManager attributesOfFileSystemForPath:downloadFolder error:NULL])) + { + uint64_t const remainingSpace = ((NSNumber*)systemAttributes[NSFileSystemFreeSize]).unsignedLongLongValue; //if the remaining space is greater than the size left, then there is enough space regardless of preallocation if (remainingSpace < self.sizeLeft && remainingSpace < tr_torrentGetBytesLeftToAllocate(fHandle)) { - NSString * volumeName = [NSFileManager.defaultManager componentsToDisplayForPath: downloadFolder][0]; + NSString* volumeName = [NSFileManager.defaultManager componentsToDisplayForPath:downloadFolder][0]; - NSAlert * alert = [[NSAlert alloc] init]; - alert.messageText = [NSString stringWithFormat: - NSLocalizedString(@"Not enough remaining disk space to download \"%@\" completely.", - "Torrent disk space alert -> title"), self.name]; - alert.informativeText = [NSString stringWithFormat: NSLocalizedString(@"The transfer will be paused." - " Clear up space on %@ or deselect files in the torrent inspector to continue.", - "Torrent disk space alert -> message"), volumeName]; - [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent disk space alert -> button")]; - [alert addButtonWithTitle: NSLocalizedString(@"Download Anyway", "Torrent disk space alert -> button")]; + NSAlert* alert = [[NSAlert alloc] init]; + alert.messageText = [NSString + stringWithFormat:NSLocalizedString(@"Not enough remaining disk space to download \"%@\" completely.", "Torrent disk space alert -> title"), + self.name]; + alert.informativeText = [NSString stringWithFormat:NSLocalizedString( + @"The transfer will be paused." + " Clear up space on %@ or deselect files in the torrent inspector to continue.", + "Torrent disk space alert -> message"), + volumeName]; + [alert addButtonWithTitle:NSLocalizedString(@"OK", "Torrent disk space alert -> button")]; + [alert addButtonWithTitle:NSLocalizedString(@"Download Anyway", "Torrent disk space alert -> button")]; alert.showsSuppressionButton = YES; - alert.suppressionButton.title = NSLocalizedString(@"Do not check disk space again", - "Torrent disk space alert -> button"); + alert.suppressionButton.title = NSLocalizedString(@"Do not check disk space again", "Torrent disk space alert -> button"); - const NSInteger result = [alert runModal]; + NSInteger const result = [alert runModal]; if (alert.suppressionButton.state == NSOnState) - [fDefaults setBool: NO forKey: @"WarningRemainingSpace"]; + { + [fDefaults setBool:NO forKey:@"WarningRemainingSpace"]; + } return result != NSAlertFirstButtonReturn; } @@ -651,327 +708,355 @@ bool trashDataFile(const char * filename, tr_error ** error) return YES; } -- (NSImage *) icon +- (NSImage*)icon { if (self.magnet) - return [NSImage imageNamed: @"Magnet"]; + { + return [NSImage imageNamed:@"Magnet"]; + } if (!fIcon) - fIcon = self.folder ? [NSImage imageNamed: NSImageNameFolder] - : [NSWorkspace.sharedWorkspace iconForFileType: self.name.pathExtension]; + { + fIcon = self.folder ? [NSImage imageNamed:NSImageNameFolder] : [NSWorkspace.sharedWorkspace iconForFileType:self.name.pathExtension]; + } return fIcon; } -- (NSString *) name +- (NSString*)name { return fInfo->name != NULL ? @(fInfo->name) : fHashString; } -- (BOOL) isFolder +- (BOOL)isFolder { return fInfo->isFolder; } -- (uint64_t) size +- (uint64_t)size { return fInfo->totalSize; } -- (uint64_t) sizeLeft +- (uint64_t)sizeLeft { return fStat->leftUntilDone; } -- (NSMutableArray *) allTrackerStats +- (NSMutableArray*)allTrackerStats { int count; - tr_tracker_stat * stats = tr_torrentTrackers(fHandle, &count); + tr_tracker_stat* stats = tr_torrentTrackers(fHandle, &count); - NSMutableArray * trackers = [NSMutableArray arrayWithCapacity: (count > 0 ? count + (stats[count-1].tier + 1) : 0)]; + NSMutableArray* trackers = [NSMutableArray arrayWithCapacity:(count > 0 ? count + (stats[count - 1].tier + 1) : 0)]; int prevTier = -1; - for (int i=0; i < count; ++i) + for (int i = 0; i < count; ++i) { if (stats[i].tier != prevTier) { - [trackers addObject: @{ @"Tier" : @(stats[i].tier + 1), @"Name" : self.name }]; + [trackers addObject:@{ @"Tier" : @(stats[i].tier + 1), @"Name" : self.name }]; prevTier = stats[i].tier; } - TrackerNode * tracker = [[TrackerNode alloc] initWithTrackerStat: &stats[i] torrent: self]; - [trackers addObject: tracker]; + TrackerNode* tracker = [[TrackerNode alloc] initWithTrackerStat:&stats[i] torrent:self]; + [trackers addObject:tracker]; } tr_torrentTrackersFree(stats, count); return trackers; } -- (NSArray *) allTrackersFlat +- (NSArray*)allTrackersFlat { - NSMutableArray * allTrackers = [NSMutableArray arrayWithCapacity: fInfo->trackerCount]; + NSMutableArray* allTrackers = [NSMutableArray arrayWithCapacity:fInfo->trackerCount]; - for (NSInteger i=0; i < fInfo->trackerCount; i++) - [allTrackers addObject: @(fInfo->trackers[i].announce)]; + for (NSInteger i = 0; i < fInfo->trackerCount; i++) + { + [allTrackers addObject:@(fInfo->trackers[i].announce)]; + } return allTrackers; } -- (BOOL) addTrackerToNewTier: (NSString *) tracker +- (BOOL)addTrackerToNewTier:(NSString*)tracker { - tracker = [tracker stringByTrimmingCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; + tracker = [tracker stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; - if ([tracker rangeOfString: @"://"].location == NSNotFound) - tracker = [@"http://" stringByAppendingString: tracker]; + if ([tracker rangeOfString:@"://"].location == NSNotFound) + { + tracker = [@"http://" stringByAppendingString:tracker]; + } //recreate the tracker structure - const int oldTrackerCount = fInfo->trackerCount; - tr_tracker_info * trackerStructs = tr_new(tr_tracker_info, oldTrackerCount+1); + int const oldTrackerCount = fInfo->trackerCount; + tr_tracker_info* trackerStructs = tr_new(tr_tracker_info, oldTrackerCount + 1); for (int i = 0; i < oldTrackerCount; ++i) + { trackerStructs[i] = fInfo->trackers[i]; + } - trackerStructs[oldTrackerCount].announce = (char *)tracker.UTF8String; - trackerStructs[oldTrackerCount].tier = trackerStructs[oldTrackerCount-1].tier + 1; + trackerStructs[oldTrackerCount].announce = (char*)tracker.UTF8String; + trackerStructs[oldTrackerCount].tier = trackerStructs[oldTrackerCount - 1].tier + 1; trackerStructs[oldTrackerCount].id = oldTrackerCount; - const BOOL success = tr_torrentSetAnnounceList(fHandle, trackerStructs, oldTrackerCount+1); + BOOL const success = tr_torrentSetAnnounceList(fHandle, trackerStructs, oldTrackerCount + 1); tr_free(trackerStructs); return success; } -- (void) removeTrackers: (NSSet *) trackers +- (void)removeTrackers:(NSSet*)trackers { //recreate the tracker structure - tr_tracker_info * trackerStructs = tr_new(tr_tracker_info, fInfo->trackerCount); + tr_tracker_info* trackerStructs = tr_new(tr_tracker_info, fInfo->trackerCount); NSUInteger newCount = 0; for (NSUInteger i = 0; i < fInfo->trackerCount; i++) { - if (![trackers containsObject: @(fInfo->trackers[i].announce)]) + if (![trackers containsObject:@(fInfo->trackers[i].announce)]) + { trackerStructs[newCount++] = fInfo->trackers[i]; + } } - const BOOL success = tr_torrentSetAnnounceList(fHandle, trackerStructs, newCount); + BOOL const success = tr_torrentSetAnnounceList(fHandle, trackerStructs, newCount); NSAssert(success, @"Removing tracker addresses failed"); tr_free(trackerStructs); } -- (NSString *) comment +- (NSString*)comment { return fInfo->comment ? @(fInfo->comment) : @""; } -- (NSString *) creator +- (NSString*)creator { return fInfo->creator ? @(fInfo->creator) : @""; } -- (NSDate *) dateCreated +- (NSDate*)dateCreated { NSInteger date = fInfo->dateCreated; - return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil; + return date > 0 ? [NSDate dateWithTimeIntervalSince1970:date] : nil; } -- (NSInteger) pieceSize +- (NSInteger)pieceSize { return fInfo->pieceSize; } -- (NSInteger) pieceCount +- (NSInteger)pieceCount { return fInfo->pieceCount; } -- (NSString *) hashString +- (NSString*)hashString { return fHashString; } -- (BOOL) privateTorrent +- (BOOL)privateTorrent { return fInfo->isPrivate; } -- (NSString *) torrentLocation +- (NSString*)torrentLocation { return fInfo->torrent ? @(fInfo->torrent) : @""; } -- (NSString *) dataLocation +- (NSString*)dataLocation { if (self.magnet) + { return nil; + } if (self.folder) { - NSString * dataLocation = [self.currentDirectory stringByAppendingPathComponent: self.name]; + NSString* dataLocation = [self.currentDirectory stringByAppendingPathComponent:self.name]; - if (![NSFileManager.defaultManager fileExistsAtPath: dataLocation]) + if (![NSFileManager.defaultManager fileExistsAtPath:dataLocation]) + { return nil; + } return dataLocation; } else { - char * location = tr_torrentFindFile(fHandle, 0); + char* location = tr_torrentFindFile(fHandle, 0); if (location == NULL) + { return nil; + } - NSString * dataLocation = @(location); + NSString* dataLocation = @(location); free(location); return dataLocation; } } -- (NSString *) fileLocation: (FileListNode *) node +- (NSString*)fileLocation:(FileListNode*)node { if (node.isFolder) { - NSString * basePath = [node.path stringByAppendingPathComponent: node.name]; - NSString * dataLocation = [self.currentDirectory stringByAppendingPathComponent: basePath]; + NSString* basePath = [node.path stringByAppendingPathComponent:node.name]; + NSString* dataLocation = [self.currentDirectory stringByAppendingPathComponent:basePath]; - if (![NSFileManager.defaultManager fileExistsAtPath: dataLocation]) + if (![NSFileManager.defaultManager fileExistsAtPath:dataLocation]) + { return nil; + } return dataLocation; } else { - char * location = tr_torrentFindFile(fHandle, node.indexes.firstIndex); + char* location = tr_torrentFindFile(fHandle, node.indexes.firstIndex); if (location == NULL) + { return nil; + } - NSString * dataLocation = @(location); + NSString* dataLocation = @(location); free(location); return dataLocation; } } -- (void) renameTorrent: (NSString *) newName completionHandler: (void (^)(BOOL didRename)) completionHandler +- (void)renameTorrent:(NSString*)newName completionHandler:(void (^)(BOOL didRename))completionHandler { NSParameterAssert(newName != nil); - NSParameterAssert(![newName isEqualToString: @""]); + NSParameterAssert(![newName isEqualToString:@""]); - NSDictionary * contextInfo = @{ @"Torrent" : self, @"CompletionHandler" : [completionHandler copy] }; + NSDictionary* contextInfo = @{ @"Torrent" : self, @"CompletionHandler" : [completionHandler copy] }; - tr_torrentRenamePath(fHandle, fInfo->name, newName.UTF8String, renameCallback, (__bridge_retained void *)(contextInfo)); + tr_torrentRenamePath(fHandle, fInfo->name, newName.UTF8String, renameCallback, (__bridge_retained void*)(contextInfo)); } -- (void) renameFileNode: (FileListNode *) node withName: (NSString *) newName completionHandler: (void (^)(BOOL didRename)) completionHandler +- (void)renameFileNode:(FileListNode*)node + withName:(NSString*)newName + completionHandler:(void (^)(BOOL didRename))completionHandler { NSParameterAssert(node.torrent == self); NSParameterAssert(newName != nil); - NSParameterAssert(![newName isEqualToString: @""]); + NSParameterAssert(![newName isEqualToString:@""]); - NSDictionary * contextInfo = @{ @"Torrent" : self, @"Nodes" : @[ node ], @"CompletionHandler" : [completionHandler copy] }; + NSDictionary* contextInfo = @{ @"Torrent" : self, @"Nodes" : @[ node ], @"CompletionHandler" : [completionHandler copy] }; - NSString * oldPath = [node.path stringByAppendingPathComponent: node.name]; - tr_torrentRenamePath(fHandle, oldPath.UTF8String, newName.UTF8String, renameCallback, (__bridge_retained void *)(contextInfo)); + NSString* oldPath = [node.path stringByAppendingPathComponent:node.name]; + tr_torrentRenamePath(fHandle, oldPath.UTF8String, newName.UTF8String, renameCallback, (__bridge_retained void*)(contextInfo)); } -- (CGFloat) progress +- (CGFloat)progress { return fStat->percentComplete; } -- (CGFloat) progressDone +- (CGFloat)progressDone { return fStat->percentDone; } -- (CGFloat) progressLeft +- (CGFloat)progressLeft { if (self.size == 0) //magnet links + { return 0.0; + } return (CGFloat)self.sizeLeft / self.size; } -- (CGFloat) checkingProgress +- (CGFloat)checkingProgress { return fStat->recheckProgress; } -- (CGFloat) availableDesired +- (CGFloat)availableDesired { return (CGFloat)fStat->desiredAvailable / self.sizeLeft; } -- (BOOL) isActive +- (BOOL)isActive { return fStat->activity != TR_STATUS_STOPPED && fStat->activity != TR_STATUS_DOWNLOAD_WAIT && fStat->activity != TR_STATUS_SEED_WAIT; } -- (BOOL) isSeeding +- (BOOL)isSeeding { return fStat->activity == TR_STATUS_SEED; } -- (BOOL) isChecking +- (BOOL)isChecking { return fStat->activity == TR_STATUS_CHECK || fStat->activity == TR_STATUS_CHECK_WAIT; } -- (BOOL) isCheckingWaiting +- (BOOL)isCheckingWaiting { return fStat->activity == TR_STATUS_CHECK_WAIT; } -- (BOOL) allDownloaded +- (BOOL)allDownloaded { return self.sizeLeft == 0 && !self.magnet; } -- (BOOL) isComplete +- (BOOL)isComplete { return self.progress >= 1.0; } -- (BOOL) isFinishedSeeding +- (BOOL)isFinishedSeeding { return fStat->finished; } -- (BOOL) isError +- (BOOL)isError { return fStat->error == TR_STAT_LOCAL_ERROR; } -- (BOOL) isAnyErrorOrWarning +- (BOOL)isAnyErrorOrWarning { return fStat->error != TR_STAT_OK; } -- (NSString *) errorMessage +- (NSString*)errorMessage { if (!self.anyErrorOrWarning) + { return @""; + } - NSString * error; - if (!(error = @(fStat->errorString)) - && !(error = [NSString stringWithCString: fStat->errorString encoding: NSISOLatin1StringEncoding])) - error = [NSString stringWithFormat: @"(%@)", NSLocalizedString(@"unreadable error", "Torrent -> error string unreadable")]; + NSString* error; + if (!(error = @(fStat->errorString)) && !(error = [NSString stringWithCString:fStat->errorString encoding:NSISOLatin1StringEncoding])) + { + error = [NSString stringWithFormat:@"(%@)", NSLocalizedString(@"unreadable error", "Torrent -> error string unreadable")]; + } //libtransmission uses "Set Location", Mac client uses "Move data file to..." - very hacky! - error = [error stringByReplacingOccurrencesOfString: @"Set Location" withString: [@"Move Data File To" stringByAppendingEllipsis]]; + error = [error stringByReplacingOccurrencesOfString:@"Set Location" withString:[@"Move Data File To" stringByAppendingEllipsis]]; return error; } -- (NSArray *) peers +- (NSArray*)peers { int totalPeers; - tr_peer_stat * peers = tr_torrentPeers(fHandle, &totalPeers); + tr_peer_stat* peers = tr_torrentPeers(fHandle, &totalPeers); - NSMutableArray * peerDicts = [NSMutableArray arrayWithCapacity: totalPeers]; + NSMutableArray* peerDicts = [NSMutableArray arrayWithCapacity:totalPeers]; for (int i = 0; i < totalPeers; i++) { - tr_peer_stat * peer = &peers[i]; - NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 12]; + tr_peer_stat* peer = &peers[i]; + NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:12]; dict[@"Name"] = self.name; dict[@"From"] = @(peer->from); @@ -985,11 +1070,15 @@ bool trashDataFile(const char * filename, tr_error ** error) dict[@"Flags"] = @(peer->flagStr); if (peer->isUploadingTo) + { dict[@"UL To Rate"] = @(peer->rateToPeer_KBps); + } if (peer->isDownloadingFrom) + { dict[@"DL From Rate"] = @(peer->rateToClient_KBps); + } - [peerDicts addObject: dict]; + [peerDicts addObject:dict]; } tr_torrentPeersFree(peers, totalPeers); @@ -997,28 +1086,30 @@ bool trashDataFile(const char * filename, tr_error ** error) return peerDicts; } -- (NSUInteger) webSeedCount +- (NSUInteger)webSeedCount { return fInfo->webseedCount; } -- (NSArray *) webSeeds +- (NSArray*)webSeeds { - NSMutableArray * webSeeds = [NSMutableArray arrayWithCapacity: fInfo->webseedCount]; + NSMutableArray* webSeeds = [NSMutableArray arrayWithCapacity:fInfo->webseedCount]; - double * dlSpeeds = tr_torrentWebSpeeds_KBps(fHandle); + double* dlSpeeds = tr_torrentWebSpeeds_KBps(fHandle); for (NSInteger i = 0; i < fInfo->webseedCount; i++) { - NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 3]; + NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:3]; dict[@"Name"] = self.name; dict[@"Address"] = @(fInfo->webseeds[i]); if (dlSpeeds[i] != -1.0) + { dict[@"DL From Rate"] = @(dlSpeeds[i]); + } - [webSeeds addObject: dict]; + [webSeeds addObject:dict]; } tr_free(dlSpeeds); @@ -1026,178 +1117,113 @@ bool trashDataFile(const char * filename, tr_error ** error) return webSeeds; } -- (NSString *) progressString +- (NSString*)progressString { if (self.magnet) { - NSString * progressString = fStat->metadataPercentComplete > 0.0 - ? [NSString stringWithFormat: NSLocalizedString(@"%@ of torrent metadata retrieved", - "Torrent -> progress string"), [NSString percentString: fStat->metadataPercentComplete longDecimals: YES]] - : NSLocalizedString(@"torrent metadata needed", "Torrent -> progress string"); + NSString* progressString = fStat->metadataPercentComplete > 0.0 ? + [NSString stringWithFormat:NSLocalizedString(@"%@ of torrent metadata retrieved", "Torrent -> progress string"), + [NSString percentString:fStat->metadataPercentComplete longDecimals:YES]] : + NSLocalizedString(@"torrent metadata needed", "Torrent -> progress string"); - return [NSString stringWithFormat: @"%@ - %@", NSLocalizedString(@"Magnetized transfer", "Torrent -> progress string"), - progressString]; + return [NSString stringWithFormat:@"%@ - %@", NSLocalizedString(@"Magnetized transfer", "Torrent -> progress string"), progressString]; } - NSString * string; + NSString* string; if (!self.allDownloaded) { CGFloat progress; - if (self.folder && [fDefaults boolForKey: @"DisplayStatusProgressSelected"]) + if (self.folder && [fDefaults boolForKey:@"DisplayStatusProgressSelected"]) { - string = [NSString stringForFilePartialSize: self.haveTotal fullSize: self.totalSizeSelected]; + string = [NSString stringForFilePartialSize:self.haveTotal fullSize:self.totalSizeSelected]; progress = self.progressDone; } else { - string = [NSString stringForFilePartialSize: self.haveTotal fullSize: self.size]; + string = [NSString stringForFilePartialSize:self.haveTotal fullSize:self.size]; progress = self.progress; } - string = [string stringByAppendingFormat: @" (%@)", [NSString percentString: progress longDecimals: YES]]; + string = [string stringByAppendingFormat:@" (%@)", [NSString percentString:progress longDecimals:YES]]; } else { - NSString * downloadString; + NSString* downloadString; if (!self.complete) //only multifile possible { - if ([fDefaults boolForKey: @"DisplayStatusProgressSelected"]) - downloadString = [NSString stringWithFormat: NSLocalizedString(@"%@ selected", "Torrent -> progress string"), - [NSString stringForFileSize: self.haveTotal]]; + if ([fDefaults boolForKey:@"DisplayStatusProgressSelected"]) + { + downloadString = [NSString stringWithFormat:NSLocalizedString(@"%@ selected", "Torrent -> progress string"), + [NSString stringForFileSize:self.haveTotal]]; + } else { - downloadString = [NSString stringForFilePartialSize: self.haveTotal fullSize: self.size]; - downloadString = [downloadString stringByAppendingFormat: @" (%@)", - [NSString percentString: self.progress longDecimals: YES]]; + downloadString = [NSString stringForFilePartialSize:self.haveTotal fullSize:self.size]; + downloadString = [downloadString stringByAppendingFormat:@" (%@)", [NSString percentString:self.progress longDecimals:YES]]; } } else - downloadString = [NSString stringForFileSize: self.size]; + { + downloadString = [NSString stringForFileSize:self.size]; + } - NSString * uploadString = [NSString stringWithFormat: NSLocalizedString(@"uploaded %@ (Ratio: %@)", - "Torrent -> progress string"), [NSString stringForFileSize: self.uploadedTotal], - [NSString stringForRatio: self.ratio]]; + NSString* uploadString = [NSString stringWithFormat:NSLocalizedString(@"uploaded %@ (Ratio: %@)", "Torrent -> progress string"), + [NSString stringForFileSize:self.uploadedTotal], + [NSString stringForRatio:self.ratio]]; - string = [downloadString stringByAppendingFormat: @", %@", uploadString]; + string = [downloadString stringByAppendingFormat:@", %@", uploadString]; } //add time when downloading or seed limit set if (self.shouldShowEta) - string = [string stringByAppendingFormat: @" - %@", self.etaString]; + { + string = [string stringByAppendingFormat:@" - %@", self.etaString]; + } return string; } -- (NSString *) statusString +- (NSString*)statusString { - NSString * string; + NSString* string; if (self.anyErrorOrWarning) { switch (fStat->error) { - case TR_STAT_LOCAL_ERROR: string = NSLocalizedString(@"Error", "Torrent -> status string"); break; - case TR_STAT_TRACKER_ERROR: string = NSLocalizedString(@"Tracker returned error", "Torrent -> status string"); break; - case TR_STAT_TRACKER_WARNING: string = NSLocalizedString(@"Tracker returned warning", "Torrent -> status string"); break; - default: NSAssert(NO, @"unknown error state"); + case TR_STAT_LOCAL_ERROR: + string = NSLocalizedString(@"Error", "Torrent -> status string"); + break; + case TR_STAT_TRACKER_ERROR: + string = NSLocalizedString(@"Tracker returned error", "Torrent -> status string"); + break; + case TR_STAT_TRACKER_WARNING: + string = NSLocalizedString(@"Tracker returned warning", "Torrent -> status string"); + break; + default: + NSAssert(NO, @"unknown error state"); } - NSString * errorString = self.errorMessage; - if (errorString && ![errorString isEqualToString: @""]) - string = [string stringByAppendingFormat: @": %@", errorString]; + NSString* errorString = self.errorMessage; + if (errorString && ![errorString isEqualToString:@""]) + { + string = [string stringByAppendingFormat:@": %@", errorString]; + } } else { switch (fStat->activity) { - case TR_STATUS_STOPPED: - if (self.finishedSeeding) - string = NSLocalizedString(@"Seeding complete", "Torrent -> status string"); - else - string = NSLocalizedString(@"Paused", "Torrent -> status string"); - break; - - case TR_STATUS_DOWNLOAD_WAIT: - string = [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]; - break; - - case TR_STATUS_SEED_WAIT: - string = [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis]; - break; - - case TR_STATUS_CHECK_WAIT: - string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis]; - break; - - case TR_STATUS_CHECK: - string = [NSString stringWithFormat: @"%@ (%@)", - NSLocalizedString(@"Checking existing data", "Torrent -> status string"), - [NSString percentString: self.checkingProgress longDecimals: YES]]; - break; - - case TR_STATUS_DOWNLOAD: - if (self.totalPeersConnected != 1) - string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of %d peers", - "Torrent -> status string"), self.peersSendingToUs, self.totalPeersConnected]; - else - string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of 1 peer", - "Torrent -> status string"), self.peersSendingToUs]; - - const NSInteger webSeedCount = fStat->webseedsSendingToUs; - if (webSeedCount > 0) - { - NSString * webSeedString; - if (webSeedCount == 1) - webSeedString = NSLocalizedString(@"web seed", "Torrent -> status string"); - else - webSeedString = [NSString stringWithFormat: NSLocalizedString(@"%d web seeds", "Torrent -> status string"), - webSeedCount]; - - string = [string stringByAppendingFormat: @" + %@", webSeedString]; - } - - break; - - case TR_STATUS_SEED: - if (self.totalPeersConnected != 1) - string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"), - self.peersGettingFromUs, self.totalPeersConnected]; - else - string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of 1 peer", "Torrent -> status string"), - self.peersGettingFromUs]; - } - - if (self.stalled) - string = [NSLocalizedString(@"Stalled", "Torrent -> status string") stringByAppendingFormat: @", %@", string]; - } - - //append even if error - if (self.active && !self.checking) - { - if (fStat->activity == TR_STATUS_DOWNLOAD) - string = [string stringByAppendingFormat: @" - %@: %@, %@: %@", - NSLocalizedString(@"DL", "Torrent -> status string"), [NSString stringForSpeed: self.downloadRate], - NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: self.uploadRate]]; - else - string = [string stringByAppendingFormat: @" - %@: %@", - NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: self.uploadRate]]; - } - - return string; -} - -- (NSString *) shortStatusString -{ - NSString * string; - - switch (fStat->activity) - { case TR_STATUS_STOPPED: if (self.finishedSeeding) + { string = NSLocalizedString(@"Seeding complete", "Torrent -> status string"); + } else + { string = NSLocalizedString(@"Paused", "Torrent -> status string"); + } break; case TR_STATUS_DOWNLOAD_WAIT: @@ -1213,260 +1239,394 @@ bool trashDataFile(const char * filename, tr_error ** error) break; case TR_STATUS_CHECK: - string = [NSString stringWithFormat: @"%@ (%@)", - NSLocalizedString(@"Checking existing data", "Torrent -> status string"), - [NSString percentString: self.checkingProgress longDecimals: YES]]; + string = [NSString stringWithFormat:@"%@ (%@)", + NSLocalizedString(@"Checking existing data", "Torrent -> status string"), + [NSString percentString:self.checkingProgress longDecimals:YES]]; break; case TR_STATUS_DOWNLOAD: - string = [NSString stringWithFormat: @"%@: %@, %@: %@", - NSLocalizedString(@"DL", "Torrent -> status string"), [NSString stringForSpeed: self.downloadRate], - NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: self.uploadRate]]; + if (self.totalPeersConnected != 1) + { + string = [NSString stringWithFormat:NSLocalizedString(@"Downloading from %d of %d peers", "Torrent -> status string"), + self.peersSendingToUs, + self.totalPeersConnected]; + } + else + { + string = [NSString stringWithFormat:NSLocalizedString(@"Downloading from %d of 1 peer", "Torrent -> status string"), + self.peersSendingToUs]; + } + + NSInteger const webSeedCount = fStat->webseedsSendingToUs; + if (webSeedCount > 0) + { + NSString* webSeedString; + if (webSeedCount == 1) + { + webSeedString = NSLocalizedString(@"web seed", "Torrent -> status string"); + } + else + { + webSeedString = [NSString stringWithFormat:NSLocalizedString(@"%d web seeds", "Torrent -> status string"), webSeedCount]; + } + + string = [string stringByAppendingFormat:@" + %@", webSeedString]; + } + break; case TR_STATUS_SEED: - string = [NSString stringWithFormat: @"%@: %@, %@: %@", - NSLocalizedString(@"Ratio", "Torrent -> status string"), [NSString stringForRatio: self.ratio], - NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: self.uploadRate]]; + if (self.totalPeersConnected != 1) + { + string = [NSString stringWithFormat:NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"), + self.peersGettingFromUs, + self.totalPeersConnected]; + } + else + { + string = [NSString stringWithFormat:NSLocalizedString(@"Seeding to %d of 1 peer", "Torrent -> status string"), + self.peersGettingFromUs]; + } + } + + if (self.stalled) + { + string = [NSLocalizedString(@"Stalled", "Torrent -> status string") stringByAppendingFormat:@", %@", string]; + } + } + + //append even if error + if (self.active && !self.checking) + { + if (fStat->activity == TR_STATUS_DOWNLOAD) + { + string = [string stringByAppendingFormat:@" - %@: %@, %@: %@", + NSLocalizedString(@"DL", "Torrent -> status string"), + [NSString stringForSpeed:self.downloadRate], + NSLocalizedString(@"UL", "Torrent -> status string"), + [NSString stringForSpeed:self.uploadRate]]; + } + else + { + string = [string stringByAppendingFormat:@" - %@: %@", + NSLocalizedString(@"UL", "Torrent -> status string"), + [NSString stringForSpeed:self.uploadRate]]; + } } return string; } -- (NSString *) remainingTimeString +- (NSString*)shortStatusString { - if (self.shouldShowEta) - return self.etaString; - else - return self.shortStatusString; -} + NSString* string; -- (NSString *) stateString -{ switch (fStat->activity) { - case TR_STATUS_STOPPED: - case TR_STATUS_DOWNLOAD_WAIT: - case TR_STATUS_SEED_WAIT: + case TR_STATUS_STOPPED: + if (self.finishedSeeding) { - NSString * string = NSLocalizedString(@"Paused", "Torrent -> status string"); - - NSString * extra = nil; - if (self.waitingToStart) - { - extra = fStat->activity == TR_STATUS_DOWNLOAD_WAIT - ? NSLocalizedString(@"Waiting to download", "Torrent -> status string") - : NSLocalizedString(@"Waiting to seed", "Torrent -> status string"); - } - else if (self.finishedSeeding) - extra = NSLocalizedString(@"Seeding complete", "Torrent -> status string"); - else; - - return extra ? [string stringByAppendingFormat: @" (%@)", extra] : string; + string = NSLocalizedString(@"Seeding complete", "Torrent -> status string"); } + else + { + string = NSLocalizedString(@"Paused", "Torrent -> status string"); + } + break; - case TR_STATUS_CHECK_WAIT: - return [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis]; + case TR_STATUS_DOWNLOAD_WAIT: + string = [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]; + break; - case TR_STATUS_CHECK: - return [NSString stringWithFormat: @"%@ (%@)", - NSLocalizedString(@"Checking existing data", "Torrent -> status string"), - [NSString percentString: self.checkingProgress longDecimals: YES]]; + case TR_STATUS_SEED_WAIT: + string = [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis]; + break; - case TR_STATUS_DOWNLOAD: - return NSLocalizedString(@"Downloading", "Torrent -> status string"); + case TR_STATUS_CHECK_WAIT: + string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis]; + break; - case TR_STATUS_SEED: - return NSLocalizedString(@"Seeding", "Torrent -> status string"); + case TR_STATUS_CHECK: + string = [NSString stringWithFormat:@"%@ (%@)", + NSLocalizedString(@"Checking existing data", "Torrent -> status string"), + [NSString percentString:self.checkingProgress longDecimals:YES]]; + break; + + case TR_STATUS_DOWNLOAD: + string = [NSString stringWithFormat:@"%@: %@, %@: %@", + NSLocalizedString(@"DL", "Torrent -> status string"), + [NSString stringForSpeed:self.downloadRate], + NSLocalizedString(@"UL", "Torrent -> status string"), + [NSString stringForSpeed:self.uploadRate]]; + break; + + case TR_STATUS_SEED: + string = [NSString stringWithFormat:@"%@: %@, %@: %@", + NSLocalizedString(@"Ratio", "Torrent -> status string"), + [NSString stringForRatio:self.ratio], + NSLocalizedString(@"UL", "Torrent -> status string"), + [NSString stringForSpeed:self.uploadRate]]; + } + + return string; +} + +- (NSString*)remainingTimeString +{ + if (self.shouldShowEta) + { + return self.etaString; + } + else + { + return self.shortStatusString; } } -- (NSInteger) totalPeersConnected +- (NSString*)stateString +{ + switch (fStat->activity) + { + case TR_STATUS_STOPPED: + case TR_STATUS_DOWNLOAD_WAIT: + case TR_STATUS_SEED_WAIT: + { + NSString* string = NSLocalizedString(@"Paused", "Torrent -> status string"); + + NSString* extra = nil; + if (self.waitingToStart) + { + extra = fStat->activity == TR_STATUS_DOWNLOAD_WAIT ? + NSLocalizedString(@"Waiting to download", "Torrent -> status string") : + NSLocalizedString(@"Waiting to seed", "Torrent -> status string"); + } + else if (self.finishedSeeding) + { + extra = NSLocalizedString(@"Seeding complete", "Torrent -> status string"); + } + + return extra ? [string stringByAppendingFormat:@" (%@)", extra] : string; + } + + case TR_STATUS_CHECK_WAIT: + return [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis]; + + case TR_STATUS_CHECK: + return [NSString stringWithFormat:@"%@ (%@)", + NSLocalizedString(@"Checking existing data", "Torrent -> status string"), + [NSString percentString:self.checkingProgress longDecimals:YES]]; + + case TR_STATUS_DOWNLOAD: + return NSLocalizedString(@"Downloading", "Torrent -> status string"); + + case TR_STATUS_SEED: + return NSLocalizedString(@"Seeding", "Torrent -> status string"); + } +} + +- (NSInteger)totalPeersConnected { return fStat->peersConnected; } -- (NSInteger) totalPeersTracker +- (NSInteger)totalPeersTracker { return fStat->peersFrom[TR_PEER_FROM_TRACKER]; } -- (NSInteger) totalPeersIncoming +- (NSInteger)totalPeersIncoming { return fStat->peersFrom[TR_PEER_FROM_INCOMING]; } -- (NSInteger) totalPeersCache +- (NSInteger)totalPeersCache { return fStat->peersFrom[TR_PEER_FROM_RESUME]; } -- (NSInteger) totalPeersPex +- (NSInteger)totalPeersPex { return fStat->peersFrom[TR_PEER_FROM_PEX]; } -- (NSInteger) totalPeersDHT +- (NSInteger)totalPeersDHT { return fStat->peersFrom[TR_PEER_FROM_DHT]; } -- (NSInteger) totalPeersLocal +- (NSInteger)totalPeersLocal { return fStat->peersFrom[TR_PEER_FROM_LPD]; } -- (NSInteger) totalPeersLTEP +- (NSInteger)totalPeersLTEP { return fStat->peersFrom[TR_PEER_FROM_LTEP]; } -- (NSInteger) peersSendingToUs +- (NSInteger)peersSendingToUs { return fStat->peersSendingToUs; } -- (NSInteger) peersGettingFromUs +- (NSInteger)peersGettingFromUs { return fStat->peersGettingFromUs; } -- (CGFloat) downloadRate +- (CGFloat)downloadRate { return fStat->pieceDownloadSpeed_KBps; } -- (CGFloat) uploadRate +- (CGFloat)uploadRate { return fStat->pieceUploadSpeed_KBps; } -- (CGFloat) totalRate +- (CGFloat)totalRate { return self.downloadRate + self.uploadRate; } -- (uint64_t) haveVerified +- (uint64_t)haveVerified { return fStat->haveValid; } -- (uint64_t) haveTotal +- (uint64_t)haveTotal { return self.haveVerified + fStat->haveUnchecked; } -- (uint64_t) totalSizeSelected +- (uint64_t)totalSizeSelected { return fStat->sizeWhenDone; } -- (uint64_t) downloadedTotal +- (uint64_t)downloadedTotal { return fStat->downloadedEver; } -- (uint64_t) uploadedTotal +- (uint64_t)uploadedTotal { return fStat->uploadedEver; } -- (uint64_t) failedHash +- (uint64_t)failedHash { return fStat->corruptEver; } -- (NSInteger) groupValue +- (NSInteger)groupValue { return fGroupValue; } -- (void) setGroupValue: (NSInteger) groupValue determinationType: (TorrentDeterminationType) determinationType +- (void)setGroupValue:(NSInteger)groupValue determinationType:(TorrentDeterminationType)determinationType { if (groupValue != fGroupValue) { fGroupValue = groupValue; - [NSNotificationCenter.defaultCenter postNotificationName: kTorrentDidChangeGroupNotification object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:kTorrentDidChangeGroupNotification object:self]; } fGroupValueDetermination = determinationType; } -- (NSInteger) groupOrderValue +- (NSInteger)groupOrderValue { - return [GroupsController.groups rowValueForIndex: fGroupValue]; + return [GroupsController.groups rowValueForIndex:fGroupValue]; } -- (void) checkGroupValueForRemoval: (NSNotification *) notification +- (void)checkGroupValueForRemoval:(NSNotification*)notification { if (fGroupValue != -1 && [notification.userInfo[@"Index"] integerValue] == fGroupValue) + { fGroupValue = -1; + } } -- (NSArray *) fileList +- (NSArray*)fileList { return fFileList; } -- (NSArray *) flatFileList +- (NSArray*)flatFileList { return fFlatFileList; } -- (NSInteger) fileCount +- (NSInteger)fileCount { return fInfo->fileCount; } -- (void) updateFileStat +- (void)updateFileStat { if (fFileStat) + { tr_torrentFilesFree(fFileStat, self.fileCount); + } fFileStat = tr_torrentFiles(fHandle, NULL); } -- (CGFloat) fileProgress: (FileListNode *) node +- (CGFloat)fileProgress:(FileListNode*)node { if (self.fileCount == 1 || self.complete) + { return self.progress; + } if (!fFileStat) + { [self updateFileStat]; + } // #5501 - if (node.size == 0) { + if (node.size == 0) + { return 1.0; } - NSIndexSet * indexSet = node.indexes; + NSIndexSet* indexSet = node.indexes; if (indexSet.count == 1) + { return fFileStat[indexSet.firstIndex].progress; + } uint64_t have = 0; - for (NSInteger index = indexSet.firstIndex; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index]) + for (NSInteger index = indexSet.firstIndex; index != NSNotFound; index = [indexSet indexGreaterThanIndex:index]) + { have += fFileStat[index].bytesCompleted; + } return (CGFloat)have / node.size; } -- (BOOL) canChangeDownloadCheckForFile: (NSUInteger) index +- (BOOL)canChangeDownloadCheckForFile:(NSUInteger)index { NSAssert2((NSInteger)index < self.fileCount, @"Index %ld is greater than file count %ld", index, self.fileCount); - return [self canChangeDownloadCheckForFiles: [NSIndexSet indexSetWithIndex: index]]; + return [self canChangeDownloadCheckForFiles:[NSIndexSet indexSetWithIndex:index]]; } -- (BOOL) canChangeDownloadCheckForFiles: (NSIndexSet *) indexSet +- (BOOL)canChangeDownloadCheckForFiles:(NSIndexSet*)indexSet { if (self.fileCount == 1 || self.complete) + { return NO; + } if (!fFileStat) + { [self updateFileStat]; + } __block BOOL canChange = NO; - [indexSet enumerateIndexesWithOptions: NSEnumerationConcurrent usingBlock: ^(NSUInteger index, BOOL *stop) { + [indexSet enumerateIndexesWithOptions:NSEnumerationConcurrent usingBlock:^(NSUInteger index, BOOL* stop) { if (fFileStat[index].progress < 1.0) { canChange = YES; @@ -1476,232 +1636,287 @@ bool trashDataFile(const char * filename, tr_error ** error) return canChange; } -- (NSInteger) checkForFiles: (NSIndexSet *) indexSet +- (NSInteger)checkForFiles:(NSIndexSet*)indexSet { BOOL onState = NO, offState = NO; - for (NSUInteger index = indexSet.firstIndex; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index]) + for (NSUInteger index = indexSet.firstIndex; index != NSNotFound; index = [indexSet indexGreaterThanIndex:index]) { - if (!fInfo->files[index].dnd || ![self canChangeDownloadCheckForFile: index]) + if (!fInfo->files[index].dnd || ![self canChangeDownloadCheckForFile:index]) + { onState = YES; + } else + { offState = YES; + } if (onState && offState) + { return NSMixedState; + } } return onState ? NSOnState : NSOffState; } -- (void) setFileCheckState: (NSInteger) state forIndexes: (NSIndexSet *) indexSet +- (void)setFileCheckState:(NSInteger)state forIndexes:(NSIndexSet*)indexSet { NSUInteger count = indexSet.count; - tr_file_index_t * files = malloc(count * sizeof(tr_file_index_t)); - for (NSUInteger index = indexSet.firstIndex, i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++) + tr_file_index_t* files = malloc(count * sizeof(tr_file_index_t)); + for (NSUInteger index = indexSet.firstIndex, i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex:index], i++) + { files[i] = index; + } tr_torrentSetFileDLs(fHandle, files, count, state != NSOffState); free(files); [self update]; - [NSNotificationCenter.defaultCenter postNotificationName: @"TorrentFileCheckChange" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"TorrentFileCheckChange" object:self]; } -- (void) setFilePriority: (tr_priority_t) priority forIndexes: (NSIndexSet *) indexSet +- (void)setFilePriority:(tr_priority_t)priority forIndexes:(NSIndexSet*)indexSet { - const NSUInteger count = indexSet.count; - tr_file_index_t * files = tr_malloc(count * sizeof(tr_file_index_t)); - for (NSUInteger index = indexSet.firstIndex, i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++) + NSUInteger const count = indexSet.count; + tr_file_index_t* files = tr_malloc(count * sizeof(tr_file_index_t)); + for (NSUInteger index = indexSet.firstIndex, i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex:index], i++) + { files[i] = index; + } tr_torrentSetFilePriorities(fHandle, files, count, priority); tr_free(files); } -- (BOOL) hasFilePriority: (tr_priority_t) priority forIndexes: (NSIndexSet *) indexSet +- (BOOL)hasFilePriority:(tr_priority_t)priority forIndexes:(NSIndexSet*)indexSet { - for (NSUInteger index = indexSet.firstIndex; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index]) - if (priority == fInfo->files[index].priority && [self canChangeDownloadCheckForFile: index]) + for (NSUInteger index = indexSet.firstIndex; index != NSNotFound; index = [indexSet indexGreaterThanIndex:index]) + { + if (priority == fInfo->files[index].priority && [self canChangeDownloadCheckForFile:index]) + { return YES; + } + } return NO; } -- (NSSet *) filePrioritiesForIndexes: (NSIndexSet *) indexSet +- (NSSet*)filePrioritiesForIndexes:(NSIndexSet*)indexSet { BOOL low = NO, normal = NO, high = NO; - NSMutableSet * priorities = [NSMutableSet setWithCapacity: MIN(indexSet.count, 3u)]; + NSMutableSet* priorities = [NSMutableSet setWithCapacity:MIN(indexSet.count, 3u)]; - for (NSUInteger index = indexSet.firstIndex; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index]) + for (NSUInteger index = indexSet.firstIndex; index != NSNotFound; index = [indexSet indexGreaterThanIndex:index]) { - if (![self canChangeDownloadCheckForFile: index]) - continue; - - const tr_priority_t priority = fInfo->files[index].priority; - switch (priority) + if (![self canChangeDownloadCheckForFile:index]) { - case TR_PRI_LOW: - if (low) - continue; - low = YES; - break; - case TR_PRI_NORMAL: - if (normal) - continue; - normal = YES; - break; - case TR_PRI_HIGH: - if (high) - continue; - high = YES; - break; - default: - NSAssert2(NO, @"Unknown priority %d for file index %ld", priority, index); + continue; } - [priorities addObject: @(priority)]; - if (low && normal && high) + tr_priority_t const priority = fInfo->files[index].priority; + switch (priority) + { + case TR_PRI_LOW: + if (low) + { + continue; + } + low = YES; break; + case TR_PRI_NORMAL: + if (normal) + { + continue; + } + normal = YES; + break; + case TR_PRI_HIGH: + if (high) + { + continue; + } + high = YES; + break; + default: + NSAssert2(NO, @"Unknown priority %d for file index %ld", priority, index); + } + + [priorities addObject:@(priority)]; + if (low && normal && high) + { + break; + } } return priorities; } -- (NSDate *) dateAdded +- (NSDate*)dateAdded { - const time_t date = fStat->addedDate; - return [NSDate dateWithTimeIntervalSince1970: date]; + time_t const date = fStat->addedDate; + return [NSDate dateWithTimeIntervalSince1970:date]; } -- (NSDate *) dateCompleted +- (NSDate*)dateCompleted { - const time_t date = fStat->doneDate; - return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil; + time_t const date = fStat->doneDate; + return date != 0 ? [NSDate dateWithTimeIntervalSince1970:date] : nil; } -- (NSDate *) dateActivity +- (NSDate*)dateActivity { - const time_t date = fStat->activityDate; - return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil; + time_t const date = fStat->activityDate; + return date != 0 ? [NSDate dateWithTimeIntervalSince1970:date] : nil; } -- (NSDate *) dateActivityOrAdd +- (NSDate*)dateActivityOrAdd { - NSDate * date = self.dateActivity; + NSDate* date = self.dateActivity; return date ? date : self.dateAdded; } -- (NSInteger) secondsDownloading +- (NSInteger)secondsDownloading { return fStat->secondsDownloading; } -- (NSInteger) secondsSeeding +- (NSInteger)secondsSeeding { return fStat->secondsSeeding; } -- (NSInteger) stalledMinutes +- (NSInteger)stalledMinutes { if (fStat->idleSecs == -1) + { return -1; + } return fStat->idleSecs / 60; } -- (BOOL) isStalled +- (BOOL)isStalled { return fStat->isStalled; } -- (void) updateTimeMachineExclude +- (void)updateTimeMachineExclude { - [self setTimeMachineExclude: !self.allDownloaded]; + [self setTimeMachineExclude:!self.allDownloaded]; } -- (NSInteger) stateSortKey +- (NSInteger)stateSortKey { if (!self.active) //paused { if (self.waitingToStart) + { return 1; + } else + { return 0; + } } else if (self.seeding) //seeding + { return 10; + } else //downloading + { return 20; + } } -- (NSString *) trackerSortKey +- (NSString*)trackerSortKey { int count; - tr_tracker_stat * stats = tr_torrentTrackers(fHandle, &count); + tr_tracker_stat* stats = tr_torrentTrackers(fHandle, &count); - NSString * best = nil; + NSString* best = nil; - for (int i=0; i < count; ++i) + for (int i = 0; i < count; ++i) { - NSString * tracker = @(stats[i].host); - if (!best || [tracker localizedCaseInsensitiveCompare: best] == NSOrderedAscending) + NSString* tracker = @(stats[i].host); + if (!best || [tracker localizedCaseInsensitiveCompare:best] == NSOrderedAscending) + { best = tracker; + } } tr_torrentTrackersFree(stats, count); return best; } -- (tr_torrent *) torrentStruct +- (tr_torrent*)torrentStruct { return fHandle; } -- (NSURL *) previewItemURL +- (NSURL*)previewItemURL { - NSString * location = self.dataLocation; - return location ? [NSURL fileURLWithPath: location] : nil; + NSString* location = self.dataLocation; + return location ? [NSURL fileURLWithPath:location] : nil; } @end @implementation Torrent (Private) -- (instancetype) initWithPath: (NSString *) path hash: (NSString *) hashString torrentStruct: (tr_torrent *) torrentStruct - magnetAddress: (NSString *) magnetAddress lib: (tr_session *) lib - groupValue: (NSNumber *) groupValue - removeWhenFinishSeeding: (NSNumber *) removeWhenFinishSeeding - downloadFolder: (NSString *) downloadFolder - legacyIncompleteFolder: (NSString *) incompleteFolder +- (instancetype)initWithPath:(NSString*)path + hash:(NSString*)hashString + torrentStruct:(tr_torrent*)torrentStruct + magnetAddress:(NSString*)magnetAddress + lib:(tr_session*)lib + groupValue:(NSNumber*)groupValue + removeWhenFinishSeeding:(NSNumber*)removeWhenFinishSeeding + downloadFolder:(NSString*)downloadFolder + legacyIncompleteFolder:(NSString*)incompleteFolder { if (!(self = [super init])) + { return nil; + } fDefaults = NSUserDefaults.standardUserDefaults; if (torrentStruct) + { fHandle = torrentStruct; + } else { //set libtransmission settings for initialization - tr_ctor * ctor = tr_ctorNew(lib); + tr_ctor* ctor = tr_ctorNew(lib); tr_ctorSetPaused(ctor, TR_FORCE, YES); if (downloadFolder) + { tr_ctorSetDownloadDir(ctor, TR_FORCE, downloadFolder.UTF8String); + } if (incompleteFolder) + { tr_ctorSetIncompleteDir(ctor, incompleteFolder.UTF8String); + } tr_parse_result result = TR_PARSE_ERR; if (path) + { result = tr_ctorSetMetainfoFromFile(ctor, path.UTF8String); + } if (result != TR_PARSE_OK && magnetAddress) + { result = tr_ctorSetMetainfoFromMagnetLink(ctor, magnetAddress.UTF8String); + } //backup - shouldn't be needed after upgrade to 1.70 if (result != TR_PARSE_OK && hashString) + { result = tr_ctorSetMetainfoFromHash(ctor, hashString.UTF8String); + } if (result == TR_PARSE_OK) + { fHandle = tr_torrentNew(ctor, NULL, NULL); + } tr_ctorFree(ctor); @@ -1713,11 +1928,11 @@ bool trashDataFile(const char * filename, tr_error ** error) fInfo = tr_torrentInfo(fHandle); - tr_torrentSetQueueStartCallback(fHandle, startQueueCallback, (__bridge void *)(self)); - tr_torrentSetCompletenessCallback(fHandle, completenessChangeCallback, (__bridge void *)(self)); - tr_torrentSetRatioLimitHitCallback(fHandle, ratioLimitHitCallback, (__bridge void *)(self)); - tr_torrentSetIdleLimitHitCallback(fHandle, idleLimitHitCallback, (__bridge void *)(self)); - tr_torrentSetMetadataCallback(fHandle, metadataCallback, (__bridge void *)(self)); + tr_torrentSetQueueStartCallback(fHandle, startQueueCallback, (__bridge void*)(self)); + tr_torrentSetCompletenessCallback(fHandle, completenessChangeCallback, (__bridge void*)(self)); + tr_torrentSetRatioLimitHitCallback(fHandle, ratioLimitHitCallback, (__bridge void*)(self)); + tr_torrentSetIdleLimitHitCallback(fHandle, idleLimitHitCallback, (__bridge void*)(self)); + tr_torrentSetMetadataCallback(fHandle, metadataCallback, (__bridge void*)(self)); fHashString = @(fInfo->hashString); @@ -1725,7 +1940,9 @@ bool trashDataFile(const char * filename, tr_error ** error) //don't do after this point - it messes with auto-group functionality if (!self.magnet) + { [self createFileList]; + } fDownloadFolderDetermination = TorrentDeterminationAutomatic; @@ -1737,13 +1954,15 @@ bool trashDataFile(const char * filename, tr_error ** error) else { fGroupValueDetermination = TorrentDeterminationAutomatic; - fGroupValue = [GroupsController.groups groupIndexForTorrent: self]; + fGroupValue = [GroupsController.groups groupIndexForTorrent:self]; } - _removeWhenFinishSeeding = removeWhenFinishSeeding ? removeWhenFinishSeeding.boolValue : [fDefaults boolForKey: @"RemoveWhenFinishSeeding"]; + _removeWhenFinishSeeding = removeWhenFinishSeeding ? removeWhenFinishSeeding.boolValue : + [fDefaults boolForKey:@"RemoveWhenFinishSeeding"]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(checkGroupValueForRemoval:) - name: @"GroupValueRemoved" object: nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(checkGroupValueForRemoval:) + name:@"GroupValueRemoved" + object:nil]; fTimeMachineExcludeInitialized = NO; [self update]; @@ -1751,150 +1970,171 @@ bool trashDataFile(const char * filename, tr_error ** error) return self; } -- (void) createFileList +- (void)createFileList { NSAssert(!self.magnet, @"Cannot create a file list until the torrent is demagnetized"); if (self.folder) { - const NSInteger count = self.fileCount; - NSMutableArray * flatFileList = [NSMutableArray arrayWithCapacity: count]; + NSInteger const count = self.fileCount; + NSMutableArray* flatFileList = [NSMutableArray arrayWithCapacity:count]; - FileListNode * tempNode = nil; + FileListNode* tempNode = nil; for (NSInteger i = 0; i < count; i++) { - tr_file * file = &fInfo->files[i]; + tr_file* file = &fInfo->files[i]; - NSString * fullPath = @(file->name); - NSArray * pathComponents = fullPath.pathComponents; + NSString* fullPath = @(file->name); + NSArray* pathComponents = fullPath.pathComponents; if (!tempNode) + { tempNode = [[FileListNode alloc] initWithFolderName:pathComponents[0] path:@"" torrent:self]; + } - [self insertPathForComponents: pathComponents withComponentIndex: 1 forParent: tempNode fileSize: file->length index: i flatList: flatFileList]; + [self insertPathForComponents:pathComponents + withComponentIndex:1 + forParent:tempNode + fileSize:file->length + index:i + flatList:flatFileList]; } - [self sortFileList: tempNode.children]; - [self sortFileList: flatFileList]; + [self sortFileList:tempNode.children]; + [self sortFileList:flatFileList]; - fFileList = [[NSArray alloc] initWithArray: tempNode.children]; - fFlatFileList = [[NSArray alloc] initWithArray: flatFileList]; + fFileList = [[NSArray alloc] initWithArray:tempNode.children]; + fFlatFileList = [[NSArray alloc] initWithArray:flatFileList]; } else { - FileListNode * node = [[FileListNode alloc] initWithFileName: self.name path: @"" size: self.size index: 0 torrent: self]; - fFileList = @[node]; + FileListNode* node = [[FileListNode alloc] initWithFileName:self.name path:@"" size:self.size index:0 torrent:self]; + fFileList = @[ node ]; fFlatFileList = fFileList; } } -- (void) insertPathForComponents: (NSArray *) components withComponentIndex: (NSUInteger) componentIndex forParent: (FileListNode *) parent fileSize: (uint64_t) size - index: (NSInteger) index flatList: (NSMutableArray *) flatFileList +- (void)insertPathForComponents:(NSArray*)components + withComponentIndex:(NSUInteger)componentIndex + forParent:(FileListNode*)parent + fileSize:(uint64_t)size + index:(NSInteger)index + flatList:(NSMutableArray*)flatFileList { NSParameterAssert(components.count > 0); NSParameterAssert(componentIndex < components.count); - NSString * name = components[componentIndex]; - const BOOL isFolder = componentIndex < (components.count-1); + NSString* name = components[componentIndex]; + BOOL const isFolder = componentIndex < (components.count - 1); //determine if folder node already exists - __block FileListNode * node = nil; + __block FileListNode* node = nil; if (isFolder) { - [parent.children enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(FileListNode * searchNode, NSUInteger idx, BOOL * stop) { - if ([searchNode.name isEqualToString: name] && searchNode.isFolder) - { - node = searchNode; - *stop = YES; - } - }]; + [parent.children enumerateObjectsWithOptions:NSEnumerationConcurrent + usingBlock:^(FileListNode* searchNode, NSUInteger idx, BOOL* stop) { + if ([searchNode.name isEqualToString:name] && searchNode.isFolder) + { + node = searchNode; + *stop = YES; + } + }]; } //create new folder or file if it doesn't already exist if (!node) { - NSString * path = [parent.path stringByAppendingPathComponent: parent.name]; + NSString* path = [parent.path stringByAppendingPathComponent:parent.name]; if (isFolder) - node = [[FileListNode alloc] initWithFolderName: name path: path torrent: self]; + { + node = [[FileListNode alloc] initWithFolderName:name path:path torrent:self]; + } else { - node = [[FileListNode alloc] initWithFileName: name path: path size: size index: index torrent: self]; - [flatFileList addObject: node]; + node = [[FileListNode alloc] initWithFileName:name path:path size:size index:index torrent:self]; + [flatFileList addObject:node]; } - [parent insertChild: node]; + [parent insertChild:node]; } if (isFolder) { - [node insertIndex: index withSize: size]; + [node insertIndex:index withSize:size]; - [self insertPathForComponents: components withComponentIndex: (componentIndex+1) forParent: node fileSize: size index: index flatList: flatFileList]; + [self insertPathForComponents:components withComponentIndex:(componentIndex + 1) forParent:node fileSize:size + index:index + flatList:flatFileList]; } } -- (void) sortFileList: (NSMutableArray *) fileNodes +- (void)sortFileList:(NSMutableArray*)fileNodes { - NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey: @"name" ascending: YES selector: @selector(localizedStandardCompare:)]; - [fileNodes sortUsingDescriptors: @[descriptor]]; + NSSortDescriptor* descriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES + selector:@selector(localizedStandardCompare:)]; + [fileNodes sortUsingDescriptors:@[ descriptor ]]; - [fileNodes enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(FileListNode * node, NSUInteger idx, BOOL * stop) { + [fileNodes enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(FileListNode* node, NSUInteger idx, BOOL* stop) { if (node.isFolder) - [self sortFileList: node.children]; + [self sortFileList:node.children]; }]; } -- (void) startQueue +- (void)startQueue { - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateQueue" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateQueue" object:self]; } -- (void) completenessChange: (tr_completeness) status wasRunning: (BOOL) wasRunning +- (void)completenessChange:(tr_completeness)status wasRunning:(BOOL)wasRunning { fStat = tr_torrentStat(fHandle); //don't call update yet to avoid auto-stop switch (status) { - case TR_SEED: - case TR_PARTIAL_SEED: + case TR_SEED: + case TR_PARTIAL_SEED: { - NSDictionary * statusInfo = @{ @"Status" : @(status), @"WasRunning" : @(wasRunning) }; - [NSNotificationCenter.defaultCenter postNotificationName: @"TorrentFinishedDownloading" object: self userInfo: statusInfo]; + NSDictionary* statusInfo = @{@"Status" : @(status), @"WasRunning" : @(wasRunning)}; + [NSNotificationCenter.defaultCenter postNotificationName:@"TorrentFinishedDownloading" object:self userInfo:statusInfo]; //quarantine the finished data - NSString * dataLocation = [self.currentDirectory stringByAppendingPathComponent: self.name]; - NSURL * dataLocationUrl = [NSURL fileURLWithPath: dataLocation]; - NSDictionary * quarantineProperties = @{ (NSString *)kLSQuarantineTypeKey : (NSString *)kLSQuarantineTypeOtherDownload }; - NSError * error = nil; - if (![dataLocationUrl setResourceValue: quarantineProperties forKey: NSURLQuarantinePropertiesKey error: &error]) - NSLog(@"Failed to quarantine %@: %@", dataLocation, error.description); + NSString* dataLocation = [self.currentDirectory stringByAppendingPathComponent:self.name]; + NSURL* dataLocationUrl = [NSURL fileURLWithPath:dataLocation]; + NSDictionary* quarantineProperties = @{ + (NSString*)kLSQuarantineTypeKey : (NSString*)kLSQuarantineTypeOtherDownload + }; + NSError* error = nil; + if (![dataLocationUrl setResourceValue:quarantineProperties forKey:NSURLQuarantinePropertiesKey error:&error]) + { + NSLog(@"Failed to quarantine %@: %@", dataLocation, error.description); + } break; } - case TR_LEECH: - [NSNotificationCenter.defaultCenter postNotificationName: @"TorrentRestartedDownloading" object: self]; - break; + case TR_LEECH: + [NSNotificationCenter.defaultCenter postNotificationName:@"TorrentRestartedDownloading" object:self]; + break; } [self update]; [self updateTimeMachineExclude]; } -- (void) ratioLimitHit +- (void)ratioLimitHit { fStat = tr_torrentStat(fHandle); - [NSNotificationCenter.defaultCenter postNotificationName: @"TorrentFinishedSeeding" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"TorrentFinishedSeeding" object:self]; } -- (void) idleLimitHit +- (void)idleLimitHit { fStat = tr_torrentStat(fHandle); - [NSNotificationCenter.defaultCenter postNotificationName: @"TorrentFinishedSeeding" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName:@"TorrentFinishedSeeding" object:self]; } -- (void) metadataRetrieved +- (void)metadataRetrieved { fStat = tr_torrentStat(fHandle); @@ -1904,84 +2144,102 @@ bool trashDataFile(const char * filename, tr_error ** error) * before we had metadata for this torrent, redetermine the group */ if ((fGroupValueDetermination == TorrentDeterminationAutomatic) || (self.groupValue == -1)) - [self setGroupValue: [GroupsController.groups groupIndexForTorrent: self] determinationType: TorrentDeterminationAutomatic]; + { + [self setGroupValue:[GroupsController.groups groupIndexForTorrent:self] determinationType:TorrentDeterminationAutomatic]; + } //change the location if the group calls for it and it's either not already set or was set automatically before if (((fDownloadFolderDetermination == TorrentDeterminationAutomatic) || !tr_torrentGetCurrentDir(fHandle)) && - [GroupsController.groups usesCustomDownloadLocationForIndex: self.groupValue]) + [GroupsController.groups usesCustomDownloadLocationForIndex:self.groupValue]) { - NSString *location = [GroupsController.groups customDownloadLocationForIndex: self.groupValue]; - [self changeDownloadFolderBeforeUsing: location determinationType:TorrentDeterminationAutomatic]; + NSString* location = [GroupsController.groups customDownloadLocationForIndex:self.groupValue]; + [self changeDownloadFolderBeforeUsing:location determinationType:TorrentDeterminationAutomatic]; } - [NSNotificationCenter.defaultCenter postNotificationName: @"ResetInspector" object: self userInfo: @{ @"Torrent" : self }]; + [NSNotificationCenter.defaultCenter postNotificationName:@"ResetInspector" object:self userInfo:@{ @"Torrent" : self }]; } -- (void)renameFinished: (BOOL) success nodes: (NSArray *) nodes completionHandler: (void (^)(BOOL)) completionHandler oldPath: (NSString *) oldPath newName: (NSString *) newName +- (void)renameFinished:(BOOL)success + nodes:(NSArray*)nodes + completionHandler:(void (^)(BOOL))completionHandler + oldPath:(NSString*)oldPath + newName:(NSString*)newName { NSParameterAssert(completionHandler != nil); NSParameterAssert(oldPath != nil); NSParameterAssert(newName != nil); - NSString * path = oldPath.stringByDeletingLastPathComponent; + NSString* path = oldPath.stringByDeletingLastPathComponent; if (success) { - NSString * oldName = oldPath.lastPathComponent; - void (^__block __weak weakUpdateNodeAndChildrenForRename)(FileListNode *); - void (^updateNodeAndChildrenForRename)(FileListNode *); - weakUpdateNodeAndChildrenForRename = updateNodeAndChildrenForRename = ^(FileListNode * node) { - [node updateFromOldName: oldName toNewName: newName inPath: path]; + NSString* oldName = oldPath.lastPathComponent; + void (^__block __weak weakUpdateNodeAndChildrenForRename)(FileListNode*); + void (^updateNodeAndChildrenForRename)(FileListNode*); + weakUpdateNodeAndChildrenForRename = updateNodeAndChildrenForRename = ^(FileListNode* node) { + [node updateFromOldName:oldName toNewName:newName inPath:path]; - if (node.isFolder) { - [node.children enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(FileListNode * childNode, NSUInteger idx, BOOL * stop) { - weakUpdateNodeAndChildrenForRename(childNode); - }]; + if (node.isFolder) + { + [node.children enumerateObjectsWithOptions:NSEnumerationConcurrent + usingBlock:^(FileListNode* childNode, NSUInteger idx, BOOL* stop) { + weakUpdateNodeAndChildrenForRename(childNode); + }]; } }; if (!nodes) + { nodes = fFlatFileList; - [nodes enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(FileListNode * node, NSUInteger idx, BOOL *stop) { + } + [nodes enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(FileListNode* node, NSUInteger idx, BOOL* stop) { updateNodeAndChildrenForRename(node); }]; //resort lists - NSMutableArray * fileList = [fFileList mutableCopy]; - [self sortFileList: fileList]; + NSMutableArray* fileList = [fFileList mutableCopy]; + [self sortFileList:fileList]; fFileList = fileList; - NSMutableArray * flatFileList = [fFlatFileList mutableCopy]; - [self sortFileList: flatFileList]; + NSMutableArray* flatFileList = [fFlatFileList mutableCopy]; + [self sortFileList:flatFileList]; fFlatFileList = flatFileList; fIcon = nil; } else - NSLog(@"Error renaming %@ to %@", oldPath, [path stringByAppendingPathComponent: newName]); + { + NSLog(@"Error renaming %@ to %@", oldPath, [path stringByAppendingPathComponent:newName]); + } completionHandler(success); } -- (BOOL) shouldShowEta +- (BOOL)shouldShowEta { if (fStat->activity == TR_STATUS_DOWNLOAD) + { return YES; + } else if (self.seeding) { //ratio: show if it's set at all if (tr_torrentGetSeedRatio(fHandle, NULL)) + { return YES; + } //idle: show only if remaining time is less than cap if (fStat->etaIdle != TR_ETA_NOT_AVAIL && fStat->etaIdle < ETA_IDLE_DISPLAY_SEC) + { return YES; + } } return NO; } -- (NSString *) etaString +- (NSString*)etaString { NSInteger eta; BOOL fromIdle; @@ -1997,9 +2255,11 @@ bool trashDataFile(const char * filename, tr_error ** error) fromIdle = YES; } else + { return NSLocalizedString(@"remaining time unknown", "Torrent -> eta string"); + } - static NSDateComponentsFormatter *formatter; + static NSDateComponentsFormatter* formatter; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ formatter = [NSDateComponentsFormatter new]; @@ -2008,21 +2268,22 @@ bool trashDataFile(const char * filename, tr_error ** error) formatter.collapsesLargestUnit = YES; formatter.includesTimeRemainingPhrase = YES; }); - NSString * idleString = [formatter stringFromTimeInterval: eta]; - - if (fromIdle) { - idleString = [idleString stringByAppendingFormat: @" (%@)", NSLocalizedString(@"inactive", "Torrent -> eta string")]; + NSString* idleString = [formatter stringFromTimeInterval:eta]; + + if (fromIdle) + { + idleString = [idleString stringByAppendingFormat:@" (%@)", NSLocalizedString(@"inactive", "Torrent -> eta string")]; } return idleString; } -- (void) setTimeMachineExclude: (BOOL) exclude +- (void)setTimeMachineExclude:(BOOL)exclude { - NSString * path; + NSString* path; if ((path = self.dataLocation)) { - CSBackupSetItemExcluded((__bridge CFURLRef)[NSURL fileURLWithPath: path], exclude, false); + CSBackupSetItemExcluded((__bridge CFURLRef)[NSURL fileURLWithPath:path], exclude, false); fTimeMachineExcludeInitialized = YES; } } diff --git a/macosx/TorrentCell.h b/macosx/TorrentCell.h index f80b0059a..4384b062b 100644 --- a/macosx/TorrentCell.h +++ b/macosx/TorrentCell.h @@ -24,24 +24,35 @@ @interface TorrentCell : NSActionCell { - NSUserDefaults * fDefaults; + NSUserDefaults* fDefaults; - NSMutableDictionary * fTitleAttributes, * fStatusAttributes; + NSMutableDictionary* fTitleAttributes; + NSMutableDictionary* fStatusAttributes; - BOOL fTracking, fMouseDownControlButton, fMouseDownRevealButton, fMouseDownActionButton, - fHover, fHoverControl, fHoverReveal, fHoverAction; + BOOL fTracking; + BOOL fMouseDownControlButton; + BOOL fMouseDownRevealButton; + BOOL fMouseDownActionButton; + BOOL fHover; + BOOL fHoverControl; + BOOL fHoverReveal; + BOOL fHoverAction; - NSColor * fBarBorderColor, * fBluePieceColor, * fBarMinimalBorderColor; + NSColor* fBarBorderColor; + NSColor* fBluePieceColor; + NSColor* fBarMinimalBorderColor; } -- (NSRect) iconRectForBounds: (NSRect) bounds; +- (NSRect)iconRectForBounds:(NSRect)bounds; -- (void) addTrackingAreasForView: (NSView *) controlView inRect: (NSRect) cellFrame withUserInfo: (NSDictionary *) userInfo - mouseLocation: (NSPoint) mouseLocation; -- (void) setHover: (BOOL) hover; -- (void) setControlHover: (BOOL) hover; -- (void) setRevealHover: (BOOL) hover; -- (void) setActionHover: (BOOL) hover; -- (void) setActionPushed: (BOOL) pushed; +- (void)addTrackingAreasForView:(NSView*)controlView + inRect:(NSRect)cellFrame + withUserInfo:(NSDictionary*)userInfo + mouseLocation:(NSPoint)mouseLocation; +- (void)setHover:(BOOL)hover; +- (void)setControlHover:(BOOL)hover; +- (void)setRevealHover:(BOOL)hover; +- (void)setActionHover:(BOOL)hover; +- (void)setActionPushed:(BOOL)pushed; @end diff --git a/macosx/TorrentCell.m b/macosx/TorrentCell.m index b241e5cee..3695bbbff 100644 --- a/macosx/TorrentCell.m +++ b/macosx/TorrentCell.m @@ -59,138 +59,139 @@ #define PIECES_TOTAL_PERCENT 0.6 -#define MAX_PIECES (18*18) +#define MAX_PIECES (18 * 18) @interface TorrentCell (Private) -- (void) drawBar: (NSRect) barRect; -- (void) drawRegularBar: (NSRect) barRect; -- (void) drawPiecesBar: (NSRect) barRect; +- (void)drawBar:(NSRect)barRect; +- (void)drawRegularBar:(NSRect)barRect; +- (void)drawPiecesBar:(NSRect)barRect; -- (NSRect) rectForMinimalStatusWithString: (NSAttributedString *) string inBounds: (NSRect) bounds; -- (NSRect) rectForTitleWithString: (NSAttributedString *) string withRightBound: (CGFloat) rightBound inBounds: (NSRect) bounds; -- (NSRect) rectForProgressWithStringInBounds: (NSRect) bounds; -- (NSRect) rectForStatusWithStringInBounds: (NSRect) bounds; -- (NSRect) barRectRegForBounds: (NSRect) bounds; -- (NSRect) barRectMinForBounds: (NSRect) bounds; +- (NSRect)rectForMinimalStatusWithString:(NSAttributedString*)string inBounds:(NSRect)bounds; +- (NSRect)rectForTitleWithString:(NSAttributedString*)string withRightBound:(CGFloat)rightBound inBounds:(NSRect)bounds; +- (NSRect)rectForProgressWithStringInBounds:(NSRect)bounds; +- (NSRect)rectForStatusWithStringInBounds:(NSRect)bounds; +- (NSRect)barRectRegForBounds:(NSRect)bounds; +- (NSRect)barRectMinForBounds:(NSRect)bounds; -- (NSRect) controlButtonRectForBounds: (NSRect) bounds; -- (NSRect) revealButtonRectForBounds: (NSRect) bounds; -- (NSRect) actionButtonRectForBounds: (NSRect) bounds; +- (NSRect)controlButtonRectForBounds:(NSRect)bounds; +- (NSRect)revealButtonRectForBounds:(NSRect)bounds; +- (NSRect)actionButtonRectForBounds:(NSRect)bounds; -@property (nonatomic, readonly) NSAttributedString *attributedTitle; -- (NSAttributedString *) attributedStatusString: (NSString *) string; +@property(nonatomic, readonly) NSAttributedString* attributedTitle; +- (NSAttributedString*)attributedStatusString:(NSString*)string; -@property (nonatomic, readonly) NSString *buttonString; -@property (nonatomic, readonly) NSString *statusString; -@property (nonatomic, readonly) NSString *minimalStatusString; +@property(nonatomic, readonly) NSString* buttonString; +@property(nonatomic, readonly) NSString* statusString; +@property(nonatomic, readonly) NSString* minimalStatusString; @end @implementation TorrentCell //only called once and the main table is always needed, so don't worry about releasing -- (instancetype) init +- (instancetype)init { if ((self = [super init])) { fDefaults = NSUserDefaults.standardUserDefaults; - NSMutableParagraphStyle * paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + NSMutableParagraphStyle* paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; paragraphStyle.lineBreakMode = NSLineBreakByTruncatingMiddle; - fTitleAttributes = [[NSMutableDictionary alloc] initWithCapacity: 3]; - fTitleAttributes[NSFontAttributeName] = [NSFont messageFontOfSize: 12.0]; + fTitleAttributes = [[NSMutableDictionary alloc] initWithCapacity:3]; + fTitleAttributes[NSFontAttributeName] = [NSFont messageFontOfSize:12.0]; fTitleAttributes[NSParagraphStyleAttributeName] = paragraphStyle; - fStatusAttributes = [[NSMutableDictionary alloc] initWithCapacity: 3]; - fStatusAttributes[NSFontAttributeName] = [NSFont messageFontOfSize: 9.0]; + fStatusAttributes = [[NSMutableDictionary alloc] initWithCapacity:3]; + fStatusAttributes[NSFontAttributeName] = [NSFont messageFontOfSize:9.0]; fStatusAttributes[NSParagraphStyleAttributeName] = paragraphStyle; - - fBluePieceColor = [NSColor colorWithCalibratedRed: 0.0 green: 0.4 blue: 0.8 alpha: 1.0]; - fBarBorderColor = [NSColor colorWithCalibratedWhite: 0.0 alpha: 0.2]; - fBarMinimalBorderColor = [NSColor colorWithCalibratedWhite: 0.0 alpha: 0.015]; + fBluePieceColor = [NSColor colorWithCalibratedRed:0.0 green:0.4 blue:0.8 alpha:1.0]; + fBarBorderColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.2]; + fBarMinimalBorderColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.015]; } return self; } -- (id) copyWithZone: (NSZone *) zone +- (id)copyWithZone:(NSZone*)zone { - id value = [super copyWithZone: zone]; - [value setRepresentedObject: self.representedObject]; + id value = [super copyWithZone:zone]; + [value setRepresentedObject:self.representedObject]; return value; } -- (NSRect) iconRectForBounds: (NSRect) bounds +- (NSRect)iconRectForBounds:(NSRect)bounds { - const CGFloat imageSize = [fDefaults boolForKey: @"SmallView"] ? IMAGE_SIZE_MIN : IMAGE_SIZE_REG; + CGFloat const imageSize = [fDefaults boolForKey:@"SmallView"] ? IMAGE_SIZE_MIN : IMAGE_SIZE_REG; - return NSMakeRect(NSMinX(bounds) + PADDING_HORIZONTAL, ceil(NSMidY(bounds) - imageSize * 0.5), - imageSize, imageSize); + return NSMakeRect(NSMinX(bounds) + PADDING_HORIZONTAL, ceil(NSMidY(bounds) - imageSize * 0.5), imageSize, imageSize); } -- (NSCellHitResult) hitTestForEvent: (NSEvent *) event inRect: (NSRect) cellFrame ofView: (NSView *) controlView +- (NSCellHitResult)hitTestForEvent:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView { - NSPoint point = [controlView convertPoint: event.locationInWindow fromView: nil]; + NSPoint point = [controlView convertPoint:event.locationInWindow fromView:nil]; - if (NSMouseInRect(point, [self controlButtonRectForBounds: cellFrame], controlView.flipped) - || NSMouseInRect(point, [self revealButtonRectForBounds: cellFrame], controlView.flipped)) + if (NSMouseInRect(point, [self controlButtonRectForBounds:cellFrame], controlView.flipped) || + NSMouseInRect(point, [self revealButtonRectForBounds:cellFrame], controlView.flipped)) + { return NSCellHitContentArea | NSCellHitTrackableArea; + } return NSCellHitContentArea; } -+ (BOOL) prefersTrackingUntilMouseUp ++ (BOOL)prefersTrackingUntilMouseUp { return YES; } -- (BOOL) trackMouse: (NSEvent *) event inRect: (NSRect) cellFrame ofView: (NSView *) controlView untilMouseUp: (BOOL) flag +- (BOOL)trackMouse:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView untilMouseUp:(BOOL)flag { fTracking = YES; self.controlView = controlView; - NSPoint point = [controlView convertPoint: event.locationInWindow fromView: nil]; + NSPoint point = [controlView convertPoint:event.locationInWindow fromView:nil]; - const NSRect controlRect = [self controlButtonRectForBounds: cellFrame]; - const BOOL checkControl = NSMouseInRect(point, controlRect, controlView.flipped); + NSRect const controlRect = [self controlButtonRectForBounds:cellFrame]; + BOOL const checkControl = NSMouseInRect(point, controlRect, controlView.flipped); - const NSRect revealRect = [self revealButtonRectForBounds: cellFrame]; - const BOOL checkReveal = NSMouseInRect(point, revealRect, controlView.flipped); + NSRect const revealRect = [self revealButtonRectForBounds:cellFrame]; + BOOL const checkReveal = NSMouseInRect(point, revealRect, controlView.flipped); - [(TorrentTableView *)controlView removeTrackingAreas]; + [(TorrentTableView*)controlView removeTrackingAreas]; while (event.type != NSLeftMouseUp) { - point = [controlView convertPoint: event.locationInWindow fromView: nil]; + point = [controlView convertPoint:event.locationInWindow fromView:nil]; if (checkControl) { - const BOOL inControlButton = NSMouseInRect(point, controlRect, controlView.flipped); + BOOL const inControlButton = NSMouseInRect(point, controlRect, controlView.flipped); if (fMouseDownControlButton != inControlButton) { fMouseDownControlButton = inControlButton; - [controlView setNeedsDisplayInRect: cellFrame]; + [controlView setNeedsDisplayInRect:cellFrame]; } } else if (checkReveal) { - const BOOL inRevealButton = NSMouseInRect(point, revealRect, controlView.flipped); + BOOL const inRevealButton = NSMouseInRect(point, revealRect, controlView.flipped); if (fMouseDownRevealButton != inRevealButton) { fMouseDownRevealButton = inRevealButton; - [controlView setNeedsDisplayInRect: cellFrame]; + [controlView setNeedsDisplayInRect:cellFrame]; } } - else; //send events to where necessary if (event.type == NSMouseEntered || event.type == NSMouseExited) - [NSApp sendEvent: event]; - event = [controlView.window nextEventMatchingMask: - (NSLeftMouseUpMask | NSLeftMouseDraggedMask | NSMouseEnteredMask | NSMouseExitedMask)]; + { + [NSApp sendEvent:event]; + } + event = [controlView.window + nextEventMatchingMask:(NSLeftMouseUpMask | NSLeftMouseDraggedMask | NSMouseEnteredMask | NSMouseExitedMask)]; } fTracking = NO; @@ -199,132 +200,132 @@ { fMouseDownControlButton = NO; - [(TorrentTableView *)controlView toggleControlForTorrent: self.representedObject]; + [(TorrentTableView*)controlView toggleControlForTorrent:self.representedObject]; } else if (fMouseDownRevealButton) { fMouseDownRevealButton = NO; - [controlView setNeedsDisplayInRect: cellFrame]; + [controlView setNeedsDisplayInRect:cellFrame]; - NSString * location = ((Torrent *)self.representedObject).dataLocation; + NSString* location = ((Torrent*)self.representedObject).dataLocation; if (location) { - NSURL * file = [NSURL fileURLWithPath: location]; - [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs: @[file]]; + NSURL* file = [NSURL fileURLWithPath:location]; + [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs:@[ file ]]; } } - else; [controlView updateTrackingAreas]; return YES; } -- (void) addTrackingAreasForView: (NSView *) controlView inRect: (NSRect) cellFrame withUserInfo: (NSDictionary *) userInfo - mouseLocation: (NSPoint) mouseLocation +- (void)addTrackingAreasForView:(NSView*)controlView + inRect:(NSRect)cellFrame + withUserInfo:(NSDictionary*)userInfo + mouseLocation:(NSPoint)mouseLocation { - const NSTrackingAreaOptions options = NSTrackingEnabledDuringMouseDrag | NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways; + NSTrackingAreaOptions const options = NSTrackingEnabledDuringMouseDrag | NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways; //whole row - if ([fDefaults boolForKey: @"SmallView"]) + if ([fDefaults boolForKey:@"SmallView"]) { NSTrackingAreaOptions rowOptions = options; if (NSMouseInRect(mouseLocation, cellFrame, controlView.flipped)) { rowOptions |= NSTrackingAssumeInside; - [(TorrentTableView *)controlView setRowHover: [userInfo[@"Row"] integerValue]]; + [(TorrentTableView*)controlView setRowHover:[userInfo[@"Row"] integerValue]]; } - NSMutableDictionary * rowInfo = [userInfo mutableCopy]; + NSMutableDictionary* rowInfo = [userInfo mutableCopy]; rowInfo[@"Type"] = @"Row"; - NSTrackingArea * area = [[NSTrackingArea alloc] initWithRect: cellFrame options: rowOptions owner: controlView userInfo: rowInfo]; - [controlView addTrackingArea: area]; + NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect:cellFrame options:rowOptions owner:controlView userInfo:rowInfo]; + [controlView addTrackingArea:area]; } //control button - NSRect controlButtonRect = [self controlButtonRectForBounds: cellFrame]; + NSRect controlButtonRect = [self controlButtonRectForBounds:cellFrame]; NSTrackingAreaOptions controlOptions = options; if (NSMouseInRect(mouseLocation, controlButtonRect, controlView.flipped)) { controlOptions |= NSTrackingAssumeInside; - [(TorrentTableView *)controlView setControlButtonHover: [userInfo[@"Row"] integerValue]]; + [(TorrentTableView*)controlView setControlButtonHover:[userInfo[@"Row"] integerValue]]; } - NSMutableDictionary * controlInfo = [userInfo mutableCopy]; + NSMutableDictionary* controlInfo = [userInfo mutableCopy]; controlInfo[@"Type"] = @"Control"; - NSTrackingArea * area = [[NSTrackingArea alloc] initWithRect: controlButtonRect options: controlOptions owner: controlView - userInfo: controlInfo]; - [controlView addTrackingArea: area]; + NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect:controlButtonRect options:controlOptions owner:controlView + userInfo:controlInfo]; + [controlView addTrackingArea:area]; //reveal button - NSRect revealButtonRect = [self revealButtonRectForBounds: cellFrame]; + NSRect revealButtonRect = [self revealButtonRectForBounds:cellFrame]; NSTrackingAreaOptions revealOptions = options; if (NSMouseInRect(mouseLocation, revealButtonRect, controlView.flipped)) { revealOptions |= NSTrackingAssumeInside; - [(TorrentTableView *)controlView setRevealButtonHover: [userInfo[@"Row"] integerValue]]; + [(TorrentTableView*)controlView setRevealButtonHover:[userInfo[@"Row"] integerValue]]; } - NSMutableDictionary * revealInfo = [userInfo mutableCopy]; + NSMutableDictionary* revealInfo = [userInfo mutableCopy]; revealInfo[@"Type"] = @"Reveal"; - area = [[NSTrackingArea alloc] initWithRect: revealButtonRect options: revealOptions owner: controlView - userInfo: revealInfo]; - [controlView addTrackingArea: area]; + area = [[NSTrackingArea alloc] initWithRect:revealButtonRect options:revealOptions owner:controlView userInfo:revealInfo]; + [controlView addTrackingArea:area]; //action button - NSRect actionButtonRect = [self iconRectForBounds: cellFrame]; //use the whole icon + NSRect actionButtonRect = [self iconRectForBounds:cellFrame]; //use the whole icon NSTrackingAreaOptions actionOptions = options; if (NSMouseInRect(mouseLocation, actionButtonRect, controlView.flipped)) { actionOptions |= NSTrackingAssumeInside; - [(TorrentTableView *)controlView setActionButtonHover: [userInfo[@"Row"] integerValue]]; + [(TorrentTableView*)controlView setActionButtonHover:[userInfo[@"Row"] integerValue]]; } - NSMutableDictionary * actionInfo = [userInfo mutableCopy]; + NSMutableDictionary* actionInfo = [userInfo mutableCopy]; actionInfo[@"Type"] = @"Action"; - area = [[NSTrackingArea alloc] initWithRect: actionButtonRect options: actionOptions owner: controlView userInfo: actionInfo]; - [controlView addTrackingArea: area]; + area = [[NSTrackingArea alloc] initWithRect:actionButtonRect options:actionOptions owner:controlView userInfo:actionInfo]; + [controlView addTrackingArea:area]; } -- (void) setHover: (BOOL) hover +- (void)setHover:(BOOL)hover { fHover = hover; } -- (void) setControlHover: (BOOL) hover +- (void)setControlHover:(BOOL)hover { fHoverControl = hover; } -- (void) setRevealHover: (BOOL) hover +- (void)setRevealHover:(BOOL)hover { fHoverReveal = hover; } -- (void) setActionHover: (BOOL) hover +- (void)setActionHover:(BOOL)hover { fHoverAction = hover; } -- (void) setActionPushed: (BOOL) pushed +- (void)setActionPushed:(BOOL)pushed { fMouseDownActionButton = pushed; } -- (void) drawInteriorWithFrame: (NSRect) cellFrame inView: (NSView *) controlView +- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView*)controlView { - Torrent * torrent = self.representedObject; + Torrent* torrent = self.representedObject; NSAssert(torrent != nil, @"can't have a TorrentCell without a Torrent"); - const BOOL minimal = [fDefaults boolForKey: @"SmallView"]; + BOOL const minimal = [fDefaults boolForKey:@"SmallView"]; //bar - [self drawBar: minimal ? [self barRectMinForBounds: cellFrame] : [self barRectRegForBounds: cellFrame]]; + [self drawBar:minimal ? [self barRectMinForBounds:cellFrame] : [self barRectRegForBounds:cellFrame]]; //group coloring - const NSRect iconRect = [self iconRectForBounds: cellFrame]; + NSRect const iconRect = [self iconRectForBounds:cellFrame]; - const NSInteger groupValue = torrent.groupValue; + NSInteger const groupValue = torrent.groupValue; if (groupValue != -1) { NSRect groupRect = NSInsetRect(iconRect, -1.0, -2.0); @@ -333,46 +334,49 @@ groupRect.size.height -= 1.0; groupRect.origin.y -= 1.0; } - const CGFloat radius = minimal ? 3.0 : 6.0; + CGFloat const radius = minimal ? 3.0 : 6.0; - NSColor * groupColor = [GroupsController.groups colorForIndex: groupValue], - * darkGroupColor = [groupColor blendedColorWithFraction: 0.2 ofColor: NSColor.whiteColor]; + NSColor *groupColor = [GroupsController.groups colorForIndex:groupValue], + *darkGroupColor = [groupColor blendedColorWithFraction:0.2 ofColor:NSColor.whiteColor]; //border - NSBezierPath * bp = [NSBezierPath bezierPathWithRoundedRect: groupRect xRadius: radius yRadius: radius]; + NSBezierPath* bp = [NSBezierPath bezierPathWithRoundedRect:groupRect xRadius:radius yRadius:radius]; [darkGroupColor set]; bp.lineWidth = 2.0; [bp stroke]; //inside - bp = [NSBezierPath bezierPathWithRoundedRect: groupRect xRadius: radius yRadius: radius]; - NSGradient * gradient = [[NSGradient alloc] initWithStartingColor: [groupColor blendedColorWithFraction: 0.7 - ofColor: NSColor.whiteColor] endingColor: darkGroupColor]; - [gradient drawInBezierPath: bp angle: 90.0]; + bp = [NSBezierPath bezierPathWithRoundedRect:groupRect xRadius:radius yRadius:radius]; + NSGradient* gradient = [[NSGradient alloc] initWithStartingColor:[groupColor blendedColorWithFraction:0.7 + ofColor:NSColor.whiteColor] + endingColor:darkGroupColor]; + [gradient drawInBezierPath:bp angle:90.0]; } - const BOOL error = torrent.anyErrorOrWarning; + BOOL const error = torrent.anyErrorOrWarning; //icon if (!minimal || !(!fTracking && fHoverAction)) //don't show in minimal mode when hovered over { - NSImage * icon = (minimal && error) ? [NSImage imageNamed: NSImageNameCaution] - : torrent.icon; - [icon drawInRect: iconRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; + NSImage* icon = (minimal && error) ? [NSImage imageNamed:NSImageNameCaution] : torrent.icon; + [icon drawInRect:iconRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 respectFlipped:YES hints:nil]; } //error badge if (error && !minimal) { - NSImage * errorImage = [NSImage imageNamed: NSImageNameCaution]; - const NSRect errorRect = NSMakeRect(NSMaxX(iconRect) - ERROR_IMAGE_SIZE, NSMaxY(iconRect) - ERROR_IMAGE_SIZE, ERROR_IMAGE_SIZE, ERROR_IMAGE_SIZE); - [errorImage drawInRect: errorRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; + NSImage* errorImage = [NSImage imageNamed:NSImageNameCaution]; + NSRect const errorRect = NSMakeRect(NSMaxX(iconRect) - ERROR_IMAGE_SIZE, NSMaxY(iconRect) - ERROR_IMAGE_SIZE, ERROR_IMAGE_SIZE, ERROR_IMAGE_SIZE); + [errorImage drawInRect:errorRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 respectFlipped:YES + hints:nil]; } //text color - NSColor * titleColor, * statusColor; + NSColor *titleColor, *statusColor; if (self.backgroundStyle == NSBackgroundStyleDark) + { titleColor = statusColor = NSColor.whiteColor; + } else { titleColor = NSColor.labelColor; @@ -386,11 +390,13 @@ CGFloat minimalTitleRightBound; if (minimal) { - NSAttributedString * minimalString = [self attributedStatusString: self.minimalStatusString]; - NSRect minimalStatusRect = [self rectForMinimalStatusWithString: minimalString inBounds: cellFrame]; + NSAttributedString* minimalString = [self attributedStatusString:self.minimalStatusString]; + NSRect minimalStatusRect = [self rectForMinimalStatusWithString:minimalString inBounds:cellFrame]; if (!fHover) - [minimalString drawInRect: minimalStatusRect]; + { + [minimalString drawInRect:minimalStatusRect]; + } minimalTitleRightBound = NSMinX(minimalStatusRect); } @@ -398,123 +404,162 @@ //progress if (!minimal) { - NSAttributedString * progressString = [self attributedStatusString: torrent.progressString]; - NSRect progressRect = [self rectForProgressWithStringInBounds: cellFrame]; + NSAttributedString* progressString = [self attributedStatusString:torrent.progressString]; + NSRect progressRect = [self rectForProgressWithStringInBounds:cellFrame]; - [progressString drawInRect: progressRect]; + [progressString drawInRect:progressRect]; } if (!minimal || fHover) { //control button - NSString * controlImageSuffix; + NSString* controlImageSuffix; if (fMouseDownControlButton) + { controlImageSuffix = @"On"; + } else if (!fTracking && fHoverControl) + { controlImageSuffix = @"Hover"; + } else + { controlImageSuffix = @"Off"; + } - NSImage * controlImage; + NSImage* controlImage; if (torrent.active) - controlImage = [NSImage imageNamed: [@"Pause" stringByAppendingString: controlImageSuffix]]; + { + controlImage = [NSImage imageNamed:[@"Pause" stringByAppendingString:controlImageSuffix]]; + } else { if (NSApp.currentEvent.modifierFlags & NSAlternateKeyMask) - controlImage = [NSImage imageNamed: [@"ResumeNoWait" stringByAppendingString: controlImageSuffix]]; + { + controlImage = [NSImage imageNamed:[@"ResumeNoWait" stringByAppendingString:controlImageSuffix]]; + } else if (torrent.waitingToStart) - controlImage = [NSImage imageNamed: [@"Pause" stringByAppendingString: controlImageSuffix]]; + { + controlImage = [NSImage imageNamed:[@"Pause" stringByAppendingString:controlImageSuffix]]; + } else - controlImage = [NSImage imageNamed: [@"Resume" stringByAppendingString: controlImageSuffix]]; + { + controlImage = [NSImage imageNamed:[@"Resume" stringByAppendingString:controlImageSuffix]]; + } } - const NSRect controlRect = [self controlButtonRectForBounds: cellFrame]; - [controlImage drawInRect: controlRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; + NSRect const controlRect = [self controlButtonRectForBounds:cellFrame]; + [controlImage drawInRect:controlRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 respectFlipped:YES + hints:nil]; minimalTitleRightBound = MIN(minimalTitleRightBound, NSMinX(controlRect)); //reveal button - NSString * revealImageString; + NSString* revealImageString; if (fMouseDownRevealButton) + { revealImageString = @"RevealOn"; + } else if (!fTracking && fHoverReveal) + { revealImageString = @"RevealHover"; + } else + { revealImageString = @"RevealOff"; + } - NSImage * revealImage = [NSImage imageNamed: revealImageString]; - [revealImage drawInRect: [self revealButtonRectForBounds: cellFrame] fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; + NSImage* revealImage = [NSImage imageNamed:revealImageString]; + [revealImage drawInRect:[self revealButtonRectForBounds:cellFrame] fromRect:NSZeroRect operation:NSCompositeSourceOver + fraction:1.0 + respectFlipped:YES + hints:nil]; //action button - #warning image should use new gear - NSString * actionImageString; +#warning image should use new gear + NSString* actionImageString; if (fMouseDownActionButton) - #warning we can get rid of this on 10.7 + { +#warning we can get rid of this on 10.7 actionImageString = @"ActionOn"; + } else if (!fTracking && fHoverAction) + { actionImageString = @"ActionHover"; + } else + { actionImageString = nil; + } if (actionImageString) { - NSImage * actionImage = [NSImage imageNamed: actionImageString]; - [actionImage drawInRect: [self actionButtonRectForBounds: cellFrame] fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; + NSImage* actionImage = [NSImage imageNamed:actionImageString]; + [actionImage drawInRect:[self actionButtonRectForBounds:cellFrame] fromRect:NSZeroRect + operation:NSCompositeSourceOver + fraction:1.0 + respectFlipped:YES + hints:nil]; } } //title - NSAttributedString * titleString = self.attributedTitle; - NSRect titleRect = [self rectForTitleWithString: titleString withRightBound: minimalTitleRightBound inBounds: cellFrame]; - [titleString drawInRect: titleRect]; + NSAttributedString* titleString = self.attributedTitle; + NSRect titleRect = [self rectForTitleWithString:titleString withRightBound:minimalTitleRightBound inBounds:cellFrame]; + [titleString drawInRect:titleRect]; //priority icon if (torrent.priority != TR_PRI_NORMAL) { - const NSRect priorityRect = NSMakeRect(NSMaxX(titleRect) + PADDING_BETWEEN_TITLE_AND_PRIORITY, - NSMidY(titleRect) - PRIORITY_ICON_HEIGHT * 0.5, - PRIORITY_ICON_WIDTH, PRIORITY_ICON_HEIGHT); + NSRect const priorityRect = NSMakeRect( + NSMaxX(titleRect) + PADDING_BETWEEN_TITLE_AND_PRIORITY, + NSMidY(titleRect) - PRIORITY_ICON_HEIGHT * 0.5, + PRIORITY_ICON_WIDTH, + PRIORITY_ICON_HEIGHT); - NSColor * priorityColor = self.backgroundStyle == NSBackgroundStyleDark ? NSColor.whiteColor : NSColor.labelColor; + NSColor* priorityColor = self.backgroundStyle == NSBackgroundStyleDark ? NSColor.whiteColor : NSColor.labelColor; - NSImage * priorityImage = [[NSImage imageNamed: (torrent.priority == TR_PRI_HIGH ? @"PriorityHighTemplate" : @"PriorityLowTemplate")] imageWithColor: priorityColor]; - [priorityImage drawInRect: priorityRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; + NSImage* priorityImage = [[NSImage imageNamed:(torrent.priority == TR_PRI_HIGH ? @"PriorityHighTemplate" : @"PriorityLowTemplate")] + imageWithColor:priorityColor]; + [priorityImage drawInRect:priorityRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 + respectFlipped:YES + hints:nil]; } //status if (!minimal) { - NSAttributedString * statusString = [self attributedStatusString: self.statusString]; - [statusString drawInRect: [self rectForStatusWithStringInBounds: cellFrame]]; + NSAttributedString* statusString = [self attributedStatusString:self.statusString]; + [statusString drawInRect:[self rectForStatusWithStringInBounds:cellFrame]]; } } -- (NSRect) expansionFrameWithFrame: (NSRect) cellFrame inView: (NSView *) view +- (NSRect)expansionFrameWithFrame:(NSRect)cellFrame inView:(NSView*)view { - BOOL minimal = [fDefaults boolForKey: @"SmallView"]; + BOOL minimal = [fDefaults boolForKey:@"SmallView"]; //this code needs to match the code in drawInteriorWithFrame:withView: CGFloat minimalTitleRightBound; if (minimal) { - NSAttributedString * minimalString = [self attributedStatusString: self.minimalStatusString]; - NSRect minimalStatusRect = [self rectForMinimalStatusWithString: minimalString inBounds: cellFrame]; + NSAttributedString* minimalString = [self attributedStatusString:self.minimalStatusString]; + NSRect minimalStatusRect = [self rectForMinimalStatusWithString:minimalString inBounds:cellFrame]; minimalTitleRightBound = NSMinX(minimalStatusRect); } if (!minimal || fHover) { - const NSRect controlRect = [self controlButtonRectForBounds: cellFrame]; + NSRect const controlRect = [self controlButtonRectForBounds:cellFrame]; minimalTitleRightBound = MIN(minimalTitleRightBound, NSMinX(controlRect)); } - NSAttributedString * titleString = self.attributedTitle; - NSRect realRect = [self rectForTitleWithString: titleString withRightBound: minimalTitleRightBound inBounds: cellFrame]; + NSAttributedString* titleString = self.attributedTitle; + NSRect realRect = [self rectForTitleWithString:titleString withRightBound:minimalTitleRightBound inBounds:cellFrame]; NSAssert([titleString size].width >= NSWidth(realRect), @"Full rect width should not be less than the used title rect width!"); - if ([titleString size].width > NSWidth(realRect) - && NSMouseInRect([view convertPoint: view.window.mouseLocationOutsideOfEventStream fromView: nil], realRect, view.flipped)) + if ([titleString size].width > NSWidth(realRect) && + NSMouseInRect([view convertPoint:view.window.mouseLocationOutsideOfEventStream fromView:nil], realRect, view.flipped)) { realRect.size.width = [titleString size].width; return NSInsetRect(realRect, -PADDING_EXPANSION_FRAME, -PADDING_EXPANSION_FRAME); @@ -523,49 +568,48 @@ return NSZeroRect; } -- (void) drawWithExpansionFrame: (NSRect) cellFrame inView: (NSView *)view +- (void)drawWithExpansionFrame:(NSRect)cellFrame inView:(NSView*)view { cellFrame.origin.x += PADDING_EXPANSION_FRAME; cellFrame.origin.y += PADDING_EXPANSION_FRAME; fTitleAttributes[NSForegroundColorAttributeName] = NSColor.labelColor; - NSAttributedString * titleString = self.attributedTitle; - [titleString drawInRect: cellFrame]; + NSAttributedString* titleString = self.attributedTitle; + [titleString drawInRect:cellFrame]; } @end @implementation TorrentCell (Private) -- (void) drawBar: (NSRect) barRect +- (void)drawBar:(NSRect)barRect { - const BOOL minimal = [fDefaults boolForKey: @"SmallView"]; + BOOL const minimal = [fDefaults boolForKey:@"SmallView"]; - const CGFloat piecesBarPercent = ((TorrentTableView *)self.controlView).piecesBarPercent; + CGFloat const piecesBarPercent = ((TorrentTableView*)self.controlView).piecesBarPercent; if (piecesBarPercent > 0.0) { NSRect piecesBarRect, regularBarRect; - NSDivideRect(barRect, &piecesBarRect, ®ularBarRect, floor(NSHeight(barRect) * PIECES_TOTAL_PERCENT * piecesBarPercent), - NSMaxYEdge); + NSDivideRect(barRect, &piecesBarRect, ®ularBarRect, floor(NSHeight(barRect) * PIECES_TOTAL_PERCENT * piecesBarPercent), NSMaxYEdge); - [self drawRegularBar: regularBarRect]; - [self drawPiecesBar: piecesBarRect]; + [self drawRegularBar:regularBarRect]; + [self drawPiecesBar:piecesBarRect]; } else { - ((Torrent *)self.representedObject).previousFinishedPieces = nil; + ((Torrent*)self.representedObject).previousFinishedPieces = nil; - [self drawRegularBar: barRect]; + [self drawRegularBar:barRect]; } - NSColor * borderColor = minimal ? fBarMinimalBorderColor : fBarBorderColor; + NSColor* borderColor = minimal ? fBarMinimalBorderColor : fBarBorderColor; [borderColor set]; - [NSBezierPath strokeRect: NSInsetRect(barRect, 0.5, 0.5)]; + [NSBezierPath strokeRect:NSInsetRect(barRect, 0.5, 0.5)]; } -- (void) drawRegularBar: (NSRect) barRect +- (void)drawRegularBar:(NSRect)barRect { - Torrent * torrent = self.representedObject; + Torrent* torrent = self.representedObject; NSRect haveRect, missingRect; NSDivideRect(barRect, &haveRect, &missingRect, round(torrent.progress * NSWidth(barRect)), NSMinXEdge); @@ -575,104 +619,126 @@ if (torrent.active) { if (torrent.checking) - [ProgressGradients.progressYellowGradient drawInRect: haveRect angle: 90]; + { + [ProgressGradients.progressYellowGradient drawInRect:haveRect angle:90]; + } else if (torrent.seeding) { NSRect ratioHaveRect, ratioRemainingRect; - NSDivideRect(haveRect, &ratioHaveRect, &ratioRemainingRect, round(torrent.progressStopRatio * NSWidth(haveRect)), - NSMinXEdge); + NSDivideRect(haveRect, &ratioHaveRect, &ratioRemainingRect, round(torrent.progressStopRatio * NSWidth(haveRect)), NSMinXEdge); - [ProgressGradients.progressGreenGradient drawInRect: ratioHaveRect angle: 90]; - [ProgressGradients.progressLightGreenGradient drawInRect: ratioRemainingRect angle: 90]; + [ProgressGradients.progressGreenGradient drawInRect:ratioHaveRect angle:90]; + [ProgressGradients.progressLightGreenGradient drawInRect:ratioRemainingRect angle:90]; } else - [ProgressGradients.progressBlueGradient drawInRect: haveRect angle: 90]; + { + [ProgressGradients.progressBlueGradient drawInRect:haveRect angle:90]; + } } else { if (torrent.waitingToStart) { if (torrent.allDownloaded) - [ProgressGradients.progressDarkGreenGradient drawInRect: haveRect angle: 90]; + { + [ProgressGradients.progressDarkGreenGradient drawInRect:haveRect angle:90]; + } else - [ProgressGradients.progressDarkBlueGradient drawInRect: haveRect angle: 90]; + { + [ProgressGradients.progressDarkBlueGradient drawInRect:haveRect angle:90]; + } } else - [ProgressGradients.progressGrayGradient drawInRect: haveRect angle: 90]; + { + [ProgressGradients.progressGrayGradient drawInRect:haveRect angle:90]; + } } } if (!torrent.allDownloaded) { - const CGFloat widthRemaining = round(NSWidth(barRect) * torrent.progressLeft); + CGFloat const widthRemaining = round(NSWidth(barRect) * torrent.progressLeft); NSRect wantedRect; NSDivideRect(missingRect, &wantedRect, &missingRect, widthRemaining, NSMinXEdge); //not-available section - if (torrent.active && !torrent.checking && torrent.availableDesired < 1.0 - && [fDefaults boolForKey: @"DisplayProgressBarAvailable"]) + if (torrent.active && !torrent.checking && torrent.availableDesired < 1.0 && [fDefaults boolForKey:@"DisplayProgressBarAvailable"]) { NSRect unavailableRect; - NSDivideRect(wantedRect, &wantedRect, &unavailableRect, round(NSWidth(wantedRect) * torrent.availableDesired), - NSMinXEdge); + NSDivideRect(wantedRect, &wantedRect, &unavailableRect, round(NSWidth(wantedRect) * torrent.availableDesired), NSMinXEdge); - [ProgressGradients.progressRedGradient drawInRect: unavailableRect angle: 90]; + [ProgressGradients.progressRedGradient drawInRect:unavailableRect angle:90]; } //remaining section - [ProgressGradients.progressWhiteGradient drawInRect: wantedRect angle: 90]; + [ProgressGradients.progressWhiteGradient drawInRect:wantedRect angle:90]; } //unwanted section if (!NSIsEmptyRect(missingRect)) { if (!torrent.magnet) - [ProgressGradients.progressLightGrayGradient drawInRect: missingRect angle: 90]; + { + [ProgressGradients.progressLightGrayGradient drawInRect:missingRect angle:90]; + } else - [ProgressGradients.progressRedGradient drawInRect: missingRect angle: 90]; + { + [ProgressGradients.progressRedGradient drawInRect:missingRect angle:90]; + } } } -- (void) drawPiecesBar: (NSRect) barRect +- (void)drawPiecesBar:(NSRect)barRect { - Torrent * torrent = self.representedObject; + Torrent* torrent = self.representedObject; //fill an all-white bar for magnet links if (torrent.magnet) { - [[NSColor colorWithCalibratedWhite: 1.0 alpha: [fDefaults boolForKey: @"SmallView"] ? 0.25 : 1.0] set]; + [[NSColor colorWithCalibratedWhite:1.0 alpha:[fDefaults boolForKey:@"SmallView"] ? 0.25 : 1.0] set]; NSRectFillUsingOperation(barRect, NSCompositeSourceOver); return; } NSInteger pieceCount = MIN(torrent.pieceCount, MAX_PIECES); - float * piecesPercent = malloc(pieceCount * sizeof(float)); - [torrent getAmountFinished: piecesPercent size: pieceCount]; + float* piecesPercent = malloc(pieceCount * sizeof(float)); + [torrent getAmountFinished:piecesPercent size:pieceCount]; - NSBitmapImageRep * bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: nil - pixelsWide: pieceCount pixelsHigh: 1 bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES - isPlanar: NO colorSpaceName: NSCalibratedRGBColorSpace bytesPerRow: 0 bitsPerPixel: 0]; + NSBitmapImageRep* bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil pixelsWide:pieceCount pixelsHigh:1 + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSCalibratedRGBColorSpace + bytesPerRow:0 + bitsPerPixel:0]; - NSIndexSet * previousFinishedIndexes = torrent.previousFinishedPieces; - NSMutableIndexSet * finishedIndexes = [NSMutableIndexSet indexSet]; + NSIndexSet* previousFinishedIndexes = torrent.previousFinishedPieces; + NSMutableIndexSet* finishedIndexes = [NSMutableIndexSet indexSet]; for (NSInteger i = 0; i < pieceCount; i++) { - NSColor * pieceColor; + NSColor* pieceColor; if (piecesPercent[i] == 1.0f) { - if (previousFinishedIndexes && ![previousFinishedIndexes containsIndex: i]) + if (previousFinishedIndexes && ![previousFinishedIndexes containsIndex:i]) + { pieceColor = NSColor.orangeColor; + } else + { pieceColor = fBluePieceColor; - [finishedIndexes addIndex: i]; + } + [finishedIndexes addIndex:i]; } else - pieceColor = [NSColor.whiteColor blendedColorWithFraction: piecesPercent[i] ofColor: fBluePieceColor]; + { + pieceColor = [NSColor.whiteColor blendedColorWithFraction:piecesPercent[i] ofColor:fBluePieceColor]; + } //it's faster to just set color instead of checking previous color - [bitmap setColor: pieceColor atX: i y: 0]; + [bitmap setColor:pieceColor atX:i y:0]; } free(piecesPercent); @@ -680,12 +746,12 @@ torrent.previousFinishedPieces = finishedIndexes.count > 0 ? finishedIndexes : nil; //don't bother saving if none are complete //actually draw image - [bitmap drawInRect: barRect fromRect: NSZeroRect operation: NSCompositeSourceOver - fraction: ([fDefaults boolForKey: @"SmallView"] ? 0.25 : 1.0) respectFlipped: YES hints: nil]; - + [bitmap drawInRect:barRect fromRect:NSZeroRect operation:NSCompositeSourceOver + fraction:([fDefaults boolForKey:@"SmallView"] ? 0.25 : 1.0)respectFlipped:YES + hints:nil]; } -- (NSRect) rectForMinimalStatusWithString: (NSAttributedString *) string inBounds: (NSRect) bounds +- (NSRect)rectForMinimalStatusWithString:(NSAttributedString*)string inBounds:(NSRect)bounds { NSRect result; result.size = [string size]; @@ -696,13 +762,12 @@ return result; } -- (NSRect) rectForTitleWithString: (NSAttributedString *) string withRightBound: (CGFloat) rightBound inBounds: (NSRect) bounds +- (NSRect)rectForTitleWithString:(NSAttributedString*)string withRightBound:(CGFloat)rightBound inBounds:(NSRect)bounds { - const BOOL minimal = [fDefaults boolForKey: @"SmallView"]; + BOOL const minimal = [fDefaults boolForKey:@"SmallView"]; NSRect result; - result.origin.x = NSMinX(bounds) + PADDING_HORIZONTAL - + (minimal ? IMAGE_SIZE_MIN : IMAGE_SIZE_REG) + PADDING_BETWEEN_IMAGE_AND_TITLE; + result.origin.x = NSMinX(bounds) + PADDING_HORIZONTAL + (minimal ? IMAGE_SIZE_MIN : IMAGE_SIZE_REG) + PADDING_BETWEEN_IMAGE_AND_TITLE; result.size.height = HEIGHT_TITLE; if (minimal) @@ -716,14 +781,16 @@ result.size.width = NSMaxX(bounds) - NSMinX(result) - PADDING_HORIZONTAL; } - if (((Torrent *)self.representedObject).priority != TR_PRI_NORMAL) + if (((Torrent*)self.representedObject).priority != TR_PRI_NORMAL) + { result.size.width -= PRIORITY_ICON_WIDTH + PADDING_BETWEEN_TITLE_AND_PRIORITY; + } result.size.width = MIN(NSWidth(result), [string size].width); return result; } -- (NSRect) rectForProgressWithStringInBounds: (NSRect) bounds +- (NSRect)rectForProgressWithStringInBounds:(NSRect)bounds { NSRect result; result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE + PADDING_BETWEEN_TITLE_AND_PROGRESS; @@ -735,11 +802,11 @@ return result; } -- (NSRect) rectForStatusWithStringInBounds: (NSRect) bounds +- (NSRect)rectForStatusWithStringInBounds:(NSRect)bounds { NSRect result; - result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE + PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS - + PADDING_BETWEEN_PROGRESS_AND_BAR + BAR_HEIGHT + PADDING_BETWEEN_BAR_AND_STATUS; + result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE + PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS + + PADDING_BETWEEN_PROGRESS_AND_BAR + BAR_HEIGHT + PADDING_BETWEEN_BAR_AND_STATUS; result.origin.x = NSMinX(bounds) + PADDING_HORIZONTAL + IMAGE_SIZE_REG + PADDING_BETWEEN_IMAGE_AND_TITLE; result.size.height = HEIGHT_STATUS; @@ -748,21 +815,20 @@ return result; } -- (NSRect) barRectRegForBounds: (NSRect) bounds +- (NSRect)barRectRegForBounds:(NSRect)bounds { NSRect result; result.size.height = BAR_HEIGHT; result.origin.x = NSMinX(bounds) + PADDING_HORIZONTAL + IMAGE_SIZE_REG + PADDING_BETWEEN_IMAGE_AND_BAR; - result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE + PADDING_BETWEEN_TITLE_AND_PROGRESS - + HEIGHT_STATUS + PADDING_BETWEEN_PROGRESS_AND_BAR; + result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE + PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS + + PADDING_BETWEEN_PROGRESS_AND_BAR; - result.size.width = floor(NSMaxX(bounds) - NSMinX(result) - PADDING_HORIZONTAL - - 2.0 * (PADDING_BETWEEN_BUTTONS + NORMAL_BUTTON_WIDTH)); + result.size.width = floor(NSMaxX(bounds) - NSMinX(result) - PADDING_HORIZONTAL - 2.0 * (PADDING_BETWEEN_BUTTONS + NORMAL_BUTTON_WIDTH)); return result; } -- (NSRect) barRectMinForBounds: (NSRect) bounds +- (NSRect)barRectMinForBounds:(NSRect)bounds { NSRect result; result.origin.x = NSMinX(bounds) + PADDING_HORIZONTAL + IMAGE_SIZE_MIN + PADDING_BETWEEN_IMAGE_AND_BAR; @@ -773,96 +839,119 @@ return result; } -- (NSRect) controlButtonRectForBounds: (NSRect) bounds +- (NSRect)controlButtonRectForBounds:(NSRect)bounds { NSRect result; result.size.height = NORMAL_BUTTON_WIDTH; result.size.width = NORMAL_BUTTON_WIDTH; result.origin.x = NSMaxX(bounds) - (PADDING_HORIZONTAL + NORMAL_BUTTON_WIDTH + PADDING_BETWEEN_BUTTONS + NORMAL_BUTTON_WIDTH); - if (![fDefaults boolForKey: @"SmallView"]) - result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE - (NORMAL_BUTTON_WIDTH - BAR_HEIGHT) * 0.5 - + PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS + PADDING_BETWEEN_PROGRESS_AND_BAR; + if (![fDefaults boolForKey:@"SmallView"]) + { + result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE - (NORMAL_BUTTON_WIDTH - BAR_HEIGHT) * 0.5 + + PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS + PADDING_BETWEEN_PROGRESS_AND_BAR; + } else + { result.origin.y = ceil(NSMidY(bounds) - NSHeight(result) * 0.5); + } return result; } -- (NSRect) revealButtonRectForBounds: (NSRect) bounds +- (NSRect)revealButtonRectForBounds:(NSRect)bounds { NSRect result; result.size.height = NORMAL_BUTTON_WIDTH; result.size.width = NORMAL_BUTTON_WIDTH; result.origin.x = NSMaxX(bounds) - (PADDING_HORIZONTAL + NORMAL_BUTTON_WIDTH); - if (![fDefaults boolForKey: @"SmallView"]) - result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE - (NORMAL_BUTTON_WIDTH - BAR_HEIGHT) * 0.5 - + PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS + PADDING_BETWEEN_PROGRESS_AND_BAR; + if (![fDefaults boolForKey:@"SmallView"]) + { + result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE - (NORMAL_BUTTON_WIDTH - BAR_HEIGHT) * 0.5 + + PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS + PADDING_BETWEEN_PROGRESS_AND_BAR; + } else + { result.origin.y = ceil(NSMidY(bounds) - NSHeight(result) * 0.5); + } return result; } -- (NSRect) actionButtonRectForBounds: (NSRect) bounds +- (NSRect)actionButtonRectForBounds:(NSRect)bounds { - const NSRect iconRect = [self iconRectForBounds: bounds]; + NSRect const iconRect = [self iconRectForBounds:bounds]; //in minimal view the rect will be the icon rect, but avoid the extra defaults lookup with some cheap math - return NSMakeRect(NSMidX(iconRect) - ACTION_BUTTON_WIDTH * 0.5, NSMidY(iconRect) - ACTION_BUTTON_WIDTH * 0.5, - ACTION_BUTTON_WIDTH, ACTION_BUTTON_WIDTH); + return NSMakeRect(NSMidX(iconRect) - ACTION_BUTTON_WIDTH * 0.5, NSMidY(iconRect) - ACTION_BUTTON_WIDTH * 0.5, ACTION_BUTTON_WIDTH, ACTION_BUTTON_WIDTH); } -- (NSAttributedString *) attributedTitle +- (NSAttributedString*)attributedTitle { - NSString * title = ((Torrent *)self.representedObject).name; - return [[NSAttributedString alloc] initWithString: title attributes: fTitleAttributes]; + NSString* title = ((Torrent*)self.representedObject).name; + return [[NSAttributedString alloc] initWithString:title attributes:fTitleAttributes]; } -- (NSAttributedString *) attributedStatusString: (NSString *) string +- (NSAttributedString*)attributedStatusString:(NSString*)string { - return [[NSAttributedString alloc] initWithString: string attributes: fStatusAttributes]; + return [[NSAttributedString alloc] initWithString:string attributes:fStatusAttributes]; } -- (NSString *) buttonString +- (NSString*)buttonString { if (fMouseDownRevealButton || (!fTracking && fHoverReveal)) + { return NSLocalizedString(@"Show the data file in Finder", "Torrent cell -> button info"); + } else if (fMouseDownControlButton || (!fTracking && fHoverControl)) { - Torrent * torrent = self.representedObject; + Torrent* torrent = self.representedObject; if (torrent.active) return NSLocalizedString(@"Pause the transfer", "Torrent Table -> tooltip"); else { if (NSApp.currentEvent.modifierFlags & NSAlternateKeyMask) + { return NSLocalizedString(@"Resume the transfer right away", "Torrent cell -> button info"); + } else if (torrent.waitingToStart) + { return NSLocalizedString(@"Stop waiting to start", "Torrent cell -> button info"); + } else + { return NSLocalizedString(@"Resume the transfer", "Torrent cell -> button info"); + } } } else if (!fTracking && fHoverAction) + { return NSLocalizedString(@"Change transfer settings", "Torrent Table -> tooltip"); + } else + { return nil; + } } -- (NSString *) statusString +- (NSString*)statusString { - NSString * buttonString; + NSString* buttonString; if ((buttonString = self.buttonString)) + { return buttonString; + } else - return ((Torrent *)self.representedObject).statusString; + { + return ((Torrent*)self.representedObject).statusString; + } } -- (NSString *) minimalStatusString +- (NSString*)minimalStatusString { - Torrent * torrent = self.representedObject; - return [fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? torrent.shortStatusString : torrent.remainingTimeString; + Torrent* torrent = self.representedObject; + return [fDefaults boolForKey:@"DisplaySmallStatusRegular"] ? torrent.shortStatusString : torrent.remainingTimeString; } @end diff --git a/macosx/TorrentGroup.h b/macosx/TorrentGroup.h index df1395645..fef673e5f 100644 --- a/macosx/TorrentGroup.h +++ b/macosx/TorrentGroup.h @@ -25,17 +25,17 @@ @interface TorrentGroup : NSObject { NSInteger fGroup; - NSMutableArray * fTorrents; + NSMutableArray* fTorrents; } -- (instancetype) initWithGroup: (NSInteger) group; +- (instancetype)initWithGroup:(NSInteger)group; -@property (nonatomic, readonly) NSInteger groupIndex; -@property (nonatomic, readonly) NSInteger groupOrderValue; -@property (nonatomic, readonly) NSMutableArray *torrents; +@property(nonatomic, readonly) NSInteger groupIndex; +@property(nonatomic, readonly) NSInteger groupOrderValue; +@property(nonatomic, readonly) NSMutableArray* torrents; -@property (nonatomic, readonly) CGFloat ratio; -@property (nonatomic, readonly) CGFloat uploadRate; -@property (nonatomic, readonly) CGFloat downloadRate; +@property(nonatomic, readonly) CGFloat ratio; +@property(nonatomic, readonly) CGFloat uploadRate; +@property(nonatomic, readonly) CGFloat downloadRate; @end diff --git a/macosx/TorrentGroup.m b/macosx/TorrentGroup.m index f3827d19a..8d4363921 100644 --- a/macosx/TorrentGroup.m +++ b/macosx/TorrentGroup.m @@ -29,7 +29,7 @@ @implementation TorrentGroup -- (instancetype) initWithGroup: (NSInteger) group +- (instancetype)initWithGroup:(NSInteger)group { if ((self = [super init])) { @@ -39,31 +39,30 @@ return self; } - -- (NSString *) description +- (NSString*)description { - return [NSString stringWithFormat: @"Torrent Group %ld: %@", fGroup, fTorrents]; + return [NSString stringWithFormat:@"Torrent Group %ld: %@", fGroup, fTorrents]; } -- (NSInteger) groupIndex +- (NSInteger)groupIndex { return fGroup; } -- (NSInteger) groupOrderValue +- (NSInteger)groupOrderValue { - return [GroupsController.groups rowValueForIndex: fGroup]; + return [GroupsController.groups rowValueForIndex:fGroup]; } -- (NSMutableArray *) torrents +- (NSMutableArray*)torrents { return fTorrents; } -- (CGFloat) ratio +- (CGFloat)ratio { uint64_t uploaded = 0, downloaded = 0; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) { uploaded += torrent.uploadedTotal; downloaded += torrent.downloadedTotal; @@ -72,20 +71,24 @@ return tr_getRatio(uploaded, downloaded); } -- (CGFloat) uploadRate +- (CGFloat)uploadRate { CGFloat rate = 0.0; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { rate += torrent.uploadRate; + } return rate; } -- (CGFloat) downloadRate +- (CGFloat)downloadRate { CGFloat rate = 0.0; - for (Torrent * torrent in fTorrents) + for (Torrent* torrent in fTorrents) + { rate += torrent.downloadRate; + } return rate; } diff --git a/macosx/TorrentTableView.h b/macosx/TorrentTableView.h index 324e71b88..80387e6dd 100644 --- a/macosx/TorrentTableView.h +++ b/macosx/TorrentTableView.h @@ -30,66 +30,74 @@ #define GROUP_SEPARATOR_HEIGHT 18.0 -@interface TorrentTableView : NSOutlineView +@interface TorrentTableView : NSOutlineView { - IBOutlet Controller * fController; + IBOutlet Controller* fController; - TorrentCell * fTorrentCell; + TorrentCell* fTorrentCell; - NSUserDefaults * fDefaults; + NSUserDefaults* fDefaults; - NSMutableIndexSet * fCollapsedGroups; + NSMutableIndexSet* fCollapsedGroups; - IBOutlet NSMenu * fContextRow, * fContextNoRow; + IBOutlet NSMenu* fContextRow; + IBOutlet NSMenu* fContextNoRow; - NSInteger fMouseRow, fMouseControlRow, fMouseRevealRow, fMouseActionRow; - NSArray * fSelectedValues; + NSInteger fMouseRow; + NSInteger fMouseControlRow; + NSInteger fMouseRevealRow; + NSInteger fMouseActionRow; + NSArray* fSelectedValues; - IBOutlet NSMenu * fActionMenu, * fUploadMenu, * fDownloadMenu, * fRatioMenu, * fPriorityMenu; - IBOutlet NSMenuItem * fGlobalLimitItem; - Torrent * fMenuTorrent; + IBOutlet NSMenu* fActionMenu; + IBOutlet NSMenu* fUploadMenu; + IBOutlet NSMenu* fDownloadMenu; + IBOutlet NSMenu* fRatioMenu; + IBOutlet NSMenu* fPriorityMenu; + IBOutlet NSMenuItem* fGlobalLimitItem; + Torrent* fMenuTorrent; CGFloat fPiecesBarPercent; - NSAnimation * fPiecesBarAnimation; + NSAnimation* fPiecesBarAnimation; BOOL fActionPopoverShown; } -- (BOOL) isGroupCollapsed: (NSInteger) value; -- (void) removeCollapsedGroup: (NSInteger) value; -- (void) removeAllCollapsedGroups; -- (void) saveCollapsedGroups; +- (BOOL)isGroupCollapsed:(NSInteger)value; +- (void)removeCollapsedGroup:(NSInteger)value; +- (void)removeAllCollapsedGroups; +- (void)saveCollapsedGroups; -- (void) removeTrackingAreas; -- (void) setRowHover: (NSInteger) row; -- (void) setControlButtonHover: (NSInteger) row; -- (void) setRevealButtonHover: (NSInteger) row; -- (void) setActionButtonHover: (NSInteger) row; +- (void)removeTrackingAreas; +- (void)setRowHover:(NSInteger)row; +- (void)setControlButtonHover:(NSInteger)row; +- (void)setRevealButtonHover:(NSInteger)row; +- (void)setActionButtonHover:(NSInteger)row; -- (void) selectValues: (NSArray *) values; -@property (nonatomic, readonly) NSArray *selectedValues; -@property (nonatomic, readonly) NSArray *selectedTorrents; +- (void)selectValues:(NSArray*)values; +@property(nonatomic, readonly) NSArray* selectedValues; +@property(nonatomic, readonly) NSArray* selectedTorrents; -- (NSRect) iconRectForRow: (NSInteger) row; +- (NSRect)iconRectForRow:(NSInteger)row; -- (void) paste: (id) sender; +- (void)paste:(id)sender; -- (void) toggleControlForTorrent: (Torrent *) torrent; +- (void)toggleControlForTorrent:(Torrent*)torrent; -- (void) displayTorrentActionPopoverForEvent: (NSEvent *) event; +- (void)displayTorrentActionPopoverForEvent:(NSEvent*)event; -- (void) setQuickLimitMode: (id) sender; -- (void) setQuickLimit: (id) sender; -- (void) setGlobalLimit: (id) sender; +- (void)setQuickLimitMode:(id)sender; +- (void)setQuickLimit:(id)sender; +- (void)setGlobalLimit:(id)sender; -- (void) setQuickRatioMode: (id) sender; -- (void) setQuickRatio: (id) sender; +- (void)setQuickRatioMode:(id)sender; +- (void)setQuickRatio:(id)sender; -- (void) setPriority: (id) sender; +- (void)setPriority:(id)sender; -- (void) togglePiecesBar; -@property (nonatomic, readonly) CGFloat piecesBarPercent; +- (void)togglePiecesBar; +@property(nonatomic, readonly) CGFloat piecesBarPercent; -- (void) selectAndScrollToRow: (NSInteger) row; +- (void)selectAndScrollToRow:(NSInteger)row; @end diff --git a/macosx/TorrentTableView.m b/macosx/TorrentTableView.m index fc1e58501..675516314 100644 --- a/macosx/TorrentTableView.m +++ b/macosx/TorrentTableView.m @@ -45,27 +45,31 @@ @interface TorrentTableView (Private) -- (BOOL) pointInGroupStatusRect: (NSPoint) point; +- (BOOL)pointInGroupStatusRect:(NSPoint)point; -- (void) setGroupStatusColumns; +- (void)setGroupStatusColumns; @end @implementation TorrentTableView -- (instancetype) initWithCoder: (NSCoder *) decoder +- (instancetype)initWithCoder:(NSCoder*)decoder { - if ((self = [super initWithCoder: decoder])) + if ((self = [super initWithCoder:decoder])) { fDefaults = NSUserDefaults.standardUserDefaults; fTorrentCell = [[TorrentCell alloc] init]; - NSData * groupData = [fDefaults dataForKey: @"CollapsedGroups"]; + NSData* groupData = [fDefaults dataForKey:@"CollapsedGroups"]; if (groupData) - fCollapsedGroups = [[NSUnarchiver unarchiveObjectWithData: groupData] mutableCopy]; + { + fCollapsedGroups = [[NSUnarchiver unarchiveObjectWithData:groupData] mutableCopy]; + } else + { fCollapsedGroups = [[NSMutableIndexSet alloc] init]; + } fMouseRow = -1; fMouseControlRow = -1; @@ -76,9 +80,10 @@ self.delegate = self; - fPiecesBarPercent = [fDefaults boolForKey: @"PiecesBar"] ? 1.0 : 0.0; - - if (@available(macOS 11.0, *)) { + fPiecesBarPercent = [fDefaults boolForKey:@"PiecesBar"] ? 1.0 : 0.0; + + if (@available(macOS 11.0, *)) + { self.style = NSTableViewStyleFullWidth; } } @@ -86,75 +91,85 @@ return self; } -- (void) dealloc +- (void)dealloc { - [NSNotificationCenter.defaultCenter removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver:self]; } -- (void) awakeFromNib +- (void)awakeFromNib { //set group columns to show ratio, needs to be in awakeFromNib to size columns correctly [self setGroupStatusColumns]; - [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(setNeedsDisplay) name: @"RefreshTorrentTable" object: nil]; + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(setNeedsDisplay) name:@"RefreshTorrentTable" object:nil]; } -- (BOOL) isGroupCollapsed: (NSInteger) value +- (BOOL)isGroupCollapsed:(NSInteger)value { if (value == -1) + { value = MAX_GROUP; + } - return [fCollapsedGroups containsIndex: value]; + return [fCollapsedGroups containsIndex:value]; } -- (void) removeCollapsedGroup: (NSInteger) value +- (void)removeCollapsedGroup:(NSInteger)value { if (value == -1) + { value = MAX_GROUP; + } - [fCollapsedGroups removeIndex: value]; + [fCollapsedGroups removeIndex:value]; } -- (void) removeAllCollapsedGroups +- (void)removeAllCollapsedGroups { [fCollapsedGroups removeAllIndexes]; } -- (void) saveCollapsedGroups +- (void)saveCollapsedGroups { - [fDefaults setObject: [NSArchiver archivedDataWithRootObject: fCollapsedGroups] forKey: @"CollapsedGroups"]; + [fDefaults setObject:[NSArchiver archivedDataWithRootObject:fCollapsedGroups] forKey:@"CollapsedGroups"]; } -- (BOOL) outlineView: (NSOutlineView *) outlineView isGroupItem: (id) item +- (BOOL)outlineView:(NSOutlineView*)outlineView isGroupItem:(id)item { - return ![item isKindOfClass: [Torrent class]]; + return ![item isKindOfClass:[Torrent class]]; } -- (CGFloat) outlineView: (NSOutlineView *) outlineView heightOfRowByItem: (id) item +- (CGFloat)outlineView:(NSOutlineView*)outlineView heightOfRowByItem:(id)item { - return [item isKindOfClass: [Torrent class]] ? self.rowHeight : GROUP_SEPARATOR_HEIGHT; + return [item isKindOfClass:[Torrent class]] ? self.rowHeight : GROUP_SEPARATOR_HEIGHT; } -- (NSCell *) outlineView: (NSOutlineView *) outlineView dataCellForTableColumn: (NSTableColumn *) tableColumn item: (id) item +- (NSCell*)outlineView:(NSOutlineView*)outlineView dataCellForTableColumn:(NSTableColumn*)tableColumn item:(id)item { - const BOOL group = ![item isKindOfClass: [Torrent class]]; + BOOL const group = ![item isKindOfClass:[Torrent class]]; if (!tableColumn) + { return !group ? fTorrentCell : nil; + } else - return group ? [tableColumn dataCellForRow: [self rowForItem: item]] : nil; + { + return group ? [tableColumn dataCellForRow:[self rowForItem:item]] : nil; + } } -- (void) outlineView: (NSOutlineView *) outlineView willDisplayCell: (id) cell forTableColumn: (NSTableColumn *) tableColumn - item: (id) item +- (void)outlineView:(NSOutlineView*)outlineView + willDisplayCell:(id)cell + forTableColumn:(NSTableColumn*)tableColumn + item:(id)item { - if ([item isKindOfClass: [Torrent class]]) + if ([item isKindOfClass:[Torrent class]]) { if (!tableColumn) { - TorrentCell * torrentCell = cell; + TorrentCell* torrentCell = cell; torrentCell.representedObject = item; - const NSInteger row = [self rowForItem: item]; + NSInteger const row = [self rowForItem:item]; torrentCell.hover = (row == fMouseRow); torrentCell.controlHover = (row == fMouseControlRow); torrentCell.revealHover = (row == fMouseRevealRow); @@ -163,632 +178,747 @@ } } -- (NSRect) frameOfCellAtColumn: (NSInteger) column row: (NSInteger) row +- (NSRect)frameOfCellAtColumn:(NSInteger)column row:(NSInteger)row { if (column == -1) - return [self rectOfRow: row]; + { + return [self rectOfRow:row]; + } else { - NSRect rect = [super frameOfCellAtColumn: column row: row]; + NSRect rect = [super frameOfCellAtColumn:column row:row]; //adjust placement for proper vertical alignment - if (column == [self columnWithIdentifier: @"Group"]) + if (column == [self columnWithIdentifier:@"Group"]) + { rect.size.height -= 1.0f; + } return rect; } } -- (NSString *) outlineView: (NSOutlineView *) outlineView typeSelectStringForTableColumn: (NSTableColumn *) tableColumn item: (id) item +- (NSString*)outlineView:(NSOutlineView*)outlineView typeSelectStringForTableColumn:(NSTableColumn*)tableColumn item:(id)item { - if ([item isKindOfClass: [Torrent class]]) - return ((Torrent *)item).name; - else - return [self.dataSource outlineView:outlineView objectValueForTableColumn:[self tableColumnWithIdentifier:@"Group"] byItem:item]; -} - -- (NSString *) outlineView: (NSOutlineView *) outlineView toolTipForCell: (NSCell *) cell rect: (NSRectPointer) rect tableColumn: (NSTableColumn *) column item: (id) item mouseLocation: (NSPoint) mouseLocation -{ - NSString * ident = column.identifier; - if ([ident isEqualToString: @"DL"] || [ident isEqualToString: @"DL Image"]) - return NSLocalizedString(@"Download speed", "Torrent table -> group row -> tooltip"); - else if ([ident isEqualToString: @"UL"] || [ident isEqualToString: @"UL Image"]) - return [fDefaults boolForKey: @"DisplayGroupRowRatio"] ? NSLocalizedString(@"Ratio", "Torrent table -> group row -> tooltip") - : NSLocalizedString(@"Upload speed", "Torrent table -> group row -> tooltip"); - else if (ident) + if ([item isKindOfClass:[Torrent class]]) { - NSUInteger count = ((TorrentGroup *)item).torrents.count; - if (count == 1) - return NSLocalizedString(@"1 transfer", "Torrent table -> group row -> tooltip"); - else - return [NSString stringWithFormat: NSLocalizedString(@"%@ transfers", "Torrent table -> group row -> tooltip"), - [NSString formattedUInteger: count]]; + return ((Torrent*)item).name; } else - return nil; + { + return [self.dataSource outlineView:outlineView objectValueForTableColumn:[self tableColumnWithIdentifier:@"Group"] + byItem:item]; + } } -- (void) updateTrackingAreas +- (NSString*)outlineView:(NSOutlineView*)outlineView + toolTipForCell:(NSCell*)cell + rect:(NSRectPointer)rect + tableColumn:(NSTableColumn*)column + item:(id)item + mouseLocation:(NSPoint)mouseLocation +{ + NSString* ident = column.identifier; + if ([ident isEqualToString:@"DL"] || [ident isEqualToString:@"DL Image"]) + { + return NSLocalizedString(@"Download speed", "Torrent table -> group row -> tooltip"); + } + else if ([ident isEqualToString:@"UL"] || [ident isEqualToString:@"UL Image"]) + { + return [fDefaults boolForKey:@"DisplayGroupRowRatio"] ? + NSLocalizedString(@"Ratio", "Torrent table -> group row -> tooltip") : + NSLocalizedString(@"Upload speed", "Torrent table -> group row -> tooltip"); + } + else if (ident) + { + NSUInteger count = ((TorrentGroup*)item).torrents.count; + if (count == 1) + { + return NSLocalizedString(@"1 transfer", "Torrent table -> group row -> tooltip"); + } + else + { + return [NSString stringWithFormat:NSLocalizedString(@"%@ transfers", "Torrent table -> group row -> tooltip"), + [NSString formattedUInteger:count]]; + } + } + else + { + return nil; + } +} + +- (void)updateTrackingAreas { [super updateTrackingAreas]; [self removeTrackingAreas]; - const NSRange rows = [self rowsInRect: self.visibleRect]; + NSRange const rows = [self rowsInRect:self.visibleRect]; if (rows.length == 0) + { return; + } - NSPoint mouseLocation = [self convertPoint: self.window.mouseLocationOutsideOfEventStream fromView: nil]; + NSPoint mouseLocation = [self convertPoint:self.window.mouseLocationOutsideOfEventStream fromView:nil]; for (NSUInteger row = rows.location; row < NSMaxRange(rows); row++) { - if (![[self itemAtRow: row] isKindOfClass: [Torrent class]]) + if (![[self itemAtRow:row] isKindOfClass:[Torrent class]]) + { continue; + } - NSDictionary * userInfo = @{@"Row": @(row)}; - TorrentCell * cell = (TorrentCell *)[self preparedCellAtColumn: -1 row: row]; - [cell addTrackingAreasForView: self inRect: [self rectOfRow: row] withUserInfo: userInfo mouseLocation: mouseLocation]; + NSDictionary* userInfo = @{ @"Row" : @(row) }; + TorrentCell* cell = (TorrentCell*)[self preparedCellAtColumn:-1 row:row]; + [cell addTrackingAreasForView:self inRect:[self rectOfRow:row] withUserInfo:userInfo mouseLocation:mouseLocation]; } } -- (void) removeTrackingAreas +- (void)removeTrackingAreas { fMouseRow = -1; fMouseControlRow = -1; fMouseRevealRow = -1; fMouseActionRow = -1; - for (NSTrackingArea * area in self.trackingAreas) + for (NSTrackingArea* area in self.trackingAreas) { if (area.owner == self && area.userInfo[@"Row"]) - [self removeTrackingArea: area]; + { + [self removeTrackingArea:area]; + } } } -- (void) setRowHover: (NSInteger) row +- (void)setRowHover:(NSInteger)row { - NSAssert([fDefaults boolForKey: @"SmallView"], @"cannot set a hover row when not in compact view"); + NSAssert([fDefaults boolForKey:@"SmallView"], @"cannot set a hover row when not in compact view"); fMouseRow = row; if (row >= 0) - [self setNeedsDisplayInRect: [self rectOfRow: row]]; + { + [self setNeedsDisplayInRect:[self rectOfRow:row]]; + } } -- (void) setControlButtonHover: (NSInteger) row +- (void)setControlButtonHover:(NSInteger)row { fMouseControlRow = row; if (row >= 0) - [self setNeedsDisplayInRect: [self rectOfRow: row]]; + { + [self setNeedsDisplayInRect:[self rectOfRow:row]]; + } } -- (void) setRevealButtonHover: (NSInteger) row +- (void)setRevealButtonHover:(NSInteger)row { fMouseRevealRow = row; if (row >= 0) - [self setNeedsDisplayInRect: [self rectOfRow: row]]; + { + [self setNeedsDisplayInRect:[self rectOfRow:row]]; + } } -- (void) setActionButtonHover: (NSInteger) row +- (void)setActionButtonHover:(NSInteger)row { fMouseActionRow = row; if (row >= 0) - [self setNeedsDisplayInRect: [self rectOfRow: row]]; + { + [self setNeedsDisplayInRect:[self rectOfRow:row]]; + } } -- (void) mouseEntered: (NSEvent *) event +- (void)mouseEntered:(NSEvent*)event { - NSDictionary * dict = (NSDictionary *)event.userData; + NSDictionary* dict = (NSDictionary*)event.userData; - NSNumber * row; + NSNumber* row; if ((row = dict[@"Row"])) { NSInteger rowVal = row.integerValue; - NSString * type = dict[@"Type"]; - if ([type isEqualToString: @"Action"]) + NSString* type = dict[@"Type"]; + if ([type isEqualToString:@"Action"]) + { fMouseActionRow = rowVal; - else if ([type isEqualToString: @"Control"]) + } + else if ([type isEqualToString:@"Control"]) + { fMouseControlRow = rowVal; - else if ([type isEqualToString: @"Reveal"]) + } + else if ([type isEqualToString:@"Reveal"]) + { fMouseRevealRow = rowVal; + } else { fMouseRow = rowVal; - if (![fDefaults boolForKey: @"SmallView"]) + if (![fDefaults boolForKey:@"SmallView"]) + { return; + } } - [self setNeedsDisplayInRect: [self rectOfRow: rowVal]]; + [self setNeedsDisplayInRect:[self rectOfRow:rowVal]]; } } -- (void) mouseExited: (NSEvent *) event +- (void)mouseExited:(NSEvent*)event { - NSDictionary * dict = (NSDictionary *)event.userData; + NSDictionary* dict = (NSDictionary*)event.userData; - NSNumber * row; + NSNumber* row; if ((row = dict[@"Row"])) { - NSString * type = dict[@"Type"]; - if ([type isEqualToString: @"Action"]) + NSString* type = dict[@"Type"]; + if ([type isEqualToString:@"Action"]) + { fMouseActionRow = -1; - else if ([type isEqualToString: @"Control"]) + } + else if ([type isEqualToString:@"Control"]) + { fMouseControlRow = -1; - else if ([type isEqualToString: @"Reveal"]) + } + else if ([type isEqualToString:@"Reveal"]) + { fMouseRevealRow = -1; + } else { fMouseRow = -1; - if (![fDefaults boolForKey: @"SmallView"]) + if (![fDefaults boolForKey:@"SmallView"]) + { return; + } } - [self setNeedsDisplayInRect: [self rectOfRow: row.integerValue]]; + [self setNeedsDisplayInRect:[self rectOfRow:row.integerValue]]; } } -- (void) outlineViewSelectionIsChanging: (NSNotification *) notification +- (void)outlineViewSelectionIsChanging:(NSNotification*)notification { - #warning elliminate when view-based? +#warning elliminate when view-based? //if pushing a button, don't change the selected rows if (fSelectedValues) - [self selectValues: fSelectedValues]; -} - -- (void) outlineViewItemDidExpand: (NSNotification *) notification -{ - TorrentGroup * group = notification.userInfo[@"NSObject"]; - NSInteger value = group.groupIndex; - if (value < 0) - value = MAX_GROUP; - - if ([fCollapsedGroups containsIndex: value]) { - [fCollapsedGroups removeIndex: value]; - [NSNotificationCenter.defaultCenter postNotificationName: @"OutlineExpandCollapse" object: self]; + [self selectValues:fSelectedValues]; } } -- (void) outlineViewItemDidCollapse: (NSNotification *) notification +- (void)outlineViewItemDidExpand:(NSNotification*)notification { - TorrentGroup * group = notification.userInfo[@"NSObject"]; + TorrentGroup* group = notification.userInfo[@"NSObject"]; NSInteger value = group.groupIndex; if (value < 0) + { value = MAX_GROUP; + } - [fCollapsedGroups addIndex: value]; - [NSNotificationCenter.defaultCenter postNotificationName: @"OutlineExpandCollapse" object: self]; + if ([fCollapsedGroups containsIndex:value]) + { + [fCollapsedGroups removeIndex:value]; + [NSNotificationCenter.defaultCenter postNotificationName:@"OutlineExpandCollapse" object:self]; + } } -- (void) mouseDown: (NSEvent *) event +- (void)outlineViewItemDidCollapse:(NSNotification*)notification { - NSPoint point = [self convertPoint: event.locationInWindow fromView: nil]; - const NSInteger row = [self rowAtPoint: point]; + TorrentGroup* group = notification.userInfo[@"NSObject"]; + NSInteger value = group.groupIndex; + if (value < 0) + { + value = MAX_GROUP; + } + + [fCollapsedGroups addIndex:value]; + [NSNotificationCenter.defaultCenter postNotificationName:@"OutlineExpandCollapse" object:self]; +} + +- (void)mouseDown:(NSEvent*)event +{ + NSPoint point = [self convertPoint:event.locationInWindow fromView:nil]; + NSInteger const row = [self rowAtPoint:point]; //check to toggle group status before anything else - if ([self pointInGroupStatusRect: point]) + if ([self pointInGroupStatusRect:point]) { - [fDefaults setBool: ![fDefaults boolForKey: @"DisplayGroupRowRatio"] forKey: @"DisplayGroupRowRatio"]; + [fDefaults setBool:![fDefaults boolForKey:@"DisplayGroupRowRatio"] forKey:@"DisplayGroupRowRatio"]; [self setGroupStatusColumns]; return; } - const BOOL pushed = row != -1 && (fMouseActionRow == row || fMouseRevealRow == row || fMouseControlRow == row); + BOOL const pushed = row != -1 && (fMouseActionRow == row || fMouseRevealRow == row || fMouseControlRow == row); //if pushing a button, don't change the selected rows if (pushed) + { fSelectedValues = self.selectedValues; + } - [super mouseDown: event]; + [super mouseDown:event]; fSelectedValues = nil; //avoid weird behavior when showing menu by doing this after mouse down if (row != -1 && fMouseActionRow == row) { - #warning maybe make appear on mouse down - [self displayTorrentActionPopoverForEvent: event]; +#warning maybe make appear on mouse down + [self displayTorrentActionPopoverForEvent:event]; } else if (!pushed && event.clickCount == 2) //double click { id item = nil; if (row != -1) - item = [self itemAtRow: row]; + { + item = [self itemAtRow:row]; + } - if (!item || [item isKindOfClass: [Torrent class]]) - [fController showInfo: nil]; + if (!item || [item isKindOfClass:[Torrent class]]) + { + [fController showInfo:nil]; + } else { - if ([self isItemExpanded: item]) - [self collapseItem: item]; + if ([self isItemExpanded:item]) + { + [self collapseItem:item]; + } else - [self expandItem: item]; + { + [self expandItem:item]; + } } } - else; } -- (void) selectValues: (NSArray *) values +- (void)selectValues:(NSArray*)values { - NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet]; + NSMutableIndexSet* indexSet = [NSMutableIndexSet indexSet]; for (id item in values) { - if ([item isKindOfClass: [Torrent class]]) + if ([item isKindOfClass:[Torrent class]]) { - const NSInteger index = [self rowForItem: item]; + NSInteger const index = [self rowForItem:item]; if (index != -1) - [indexSet addIndex: index]; + { + [indexSet addIndex:index]; + } } else { - TorrentGroup * group = (TorrentGroup *)item; - const NSInteger groupIndex = group.groupIndex; + TorrentGroup* group = (TorrentGroup*)item; + NSInteger const groupIndex = group.groupIndex; for (NSInteger i = 0; i < self.numberOfRows; i++) { - id tableItem = [self itemAtRow: i]; - if ([tableItem isKindOfClass: [TorrentGroup class]] && groupIndex == ((TorrentGroup *)tableItem).groupIndex) + id tableItem = [self itemAtRow:i]; + if ([tableItem isKindOfClass:[TorrentGroup class]] && groupIndex == ((TorrentGroup*)tableItem).groupIndex) { - [indexSet addIndex: i]; + [indexSet addIndex:i]; break; } } } } - [self selectRowIndexes: indexSet byExtendingSelection: NO]; + [self selectRowIndexes:indexSet byExtendingSelection:NO]; } -- (NSArray *) selectedValues +- (NSArray*)selectedValues { - NSIndexSet * selectedIndexes = self.selectedRowIndexes; - NSMutableArray * values = [NSMutableArray arrayWithCapacity: selectedIndexes.count]; + NSIndexSet* selectedIndexes = self.selectedRowIndexes; + NSMutableArray* values = [NSMutableArray arrayWithCapacity:selectedIndexes.count]; - for (NSUInteger i = selectedIndexes.firstIndex; i != NSNotFound; i = [selectedIndexes indexGreaterThanIndex: i]) - [values addObject: [self itemAtRow: i]]; + for (NSUInteger i = selectedIndexes.firstIndex; i != NSNotFound; i = [selectedIndexes indexGreaterThanIndex:i]) + { + [values addObject:[self itemAtRow:i]]; + } return values; } -- (NSArray *) selectedTorrents +- (NSArray*)selectedTorrents { - NSIndexSet * selectedIndexes = self.selectedRowIndexes; - NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: selectedIndexes.count]; //take a shot at guessing capacity + NSIndexSet* selectedIndexes = self.selectedRowIndexes; + NSMutableArray* torrents = [NSMutableArray arrayWithCapacity:selectedIndexes.count]; //take a shot at guessing capacity - for (NSUInteger i = selectedIndexes.firstIndex; i != NSNotFound; i = [selectedIndexes indexGreaterThanIndex: i]) + for (NSUInteger i = selectedIndexes.firstIndex; i != NSNotFound; i = [selectedIndexes indexGreaterThanIndex:i]) { - id item = [self itemAtRow: i]; - if ([item isKindOfClass: [Torrent class]]) - [torrents addObject: item]; + id item = [self itemAtRow:i]; + if ([item isKindOfClass:[Torrent class]]) + { + [torrents addObject:item]; + } else { - NSArray * groupTorrents = ((TorrentGroup *)item).torrents; - [torrents addObjectsFromArray: groupTorrents]; - if ([self isItemExpanded: item]) - i +=groupTorrents.count; + NSArray* groupTorrents = ((TorrentGroup*)item).torrents; + [torrents addObjectsFromArray:groupTorrents]; + if ([self isItemExpanded:item]) + { + i += groupTorrents.count; + } } } return torrents; } -- (NSMenu *) menuForEvent: (NSEvent *) event +- (NSMenu*)menuForEvent:(NSEvent*)event { - NSInteger row = [self rowAtPoint: [self convertPoint: event.locationInWindow fromView: nil]]; + NSInteger row = [self rowAtPoint:[self convertPoint:event.locationInWindow fromView:nil]]; if (row >= 0) { - if (![self isRowSelected: row]) - [self selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; + if (![self isRowSelected:row]) + { + [self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO]; + } return fContextRow; } else { - [self deselectAll: self]; + [self deselectAll:self]; return fContextNoRow; } } //make sure that the pause buttons become orange when holding down the option key -- (void) flagsChanged: (NSEvent *) event +- (void)flagsChanged:(NSEvent*)event { [self display]; - [super flagsChanged: event]; + [super flagsChanged:event]; } //option-command-f will focus the filter bar's search field -- (void) keyDown: (NSEvent *) event +- (void)keyDown:(NSEvent*)event { - const unichar firstChar = [event.charactersIgnoringModifiers characterAtIndex: 0]; + unichar const firstChar = [event.charactersIgnoringModifiers characterAtIndex:0]; if (firstChar == 'f' && event.modifierFlags & NSAlternateKeyMask && event.modifierFlags & NSCommandKeyMask) + { [fController focusFilterField]; + } else if (firstChar == ' ') - [fController toggleQuickLook: nil]; + { + [fController toggleQuickLook:nil]; + } else if (event.keyCode == 53) //esc key - [self deselectAll: nil]; - else - [super keyDown: event]; -} - -- (NSRect) iconRectForRow: (NSInteger) row -{ - return [fTorrentCell iconRectForBounds: [self rectOfRow: row]]; -} - -- (void) paste: (id) sender -{ - NSURL * url; - if ((url = [NSURL URLFromPasteboard: NSPasteboard.generalPasteboard])) - [fController openURL: url.absoluteString]; + { + [self deselectAll:nil]; + } else { - NSArray * items = [NSPasteboard.generalPasteboard readObjectsForClasses: @[[NSString class]] options: nil]; + [super keyDown:event]; + } +} + +- (NSRect)iconRectForRow:(NSInteger)row +{ + return [fTorrentCell iconRectForBounds:[self rectOfRow:row]]; +} + +- (void)paste:(id)sender +{ + NSURL* url; + if ((url = [NSURL URLFromPasteboard:NSPasteboard.generalPasteboard])) + { + [fController openURL:url.absoluteString]; + } + else + { + NSArray* items = [NSPasteboard.generalPasteboard readObjectsForClasses:@[ [NSString class] ] options:nil]; if (items) { - NSDataDetector * detector = [NSDataDetector dataDetectorWithTypes: NSTextCheckingTypeLink error: nil]; - for (__strong NSString * pbItem in items) + NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil]; + for (__strong NSString* pbItem in items) { - pbItem = [pbItem stringByTrimmingCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; - if ([pbItem rangeOfString: @"magnet:" options: (NSAnchoredSearch | NSCaseInsensitiveSearch)].location != NSNotFound) - [fController openURL: pbItem]; + pbItem = [pbItem stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; + if ([pbItem rangeOfString:@"magnet:" options:(NSAnchoredSearch | NSCaseInsensitiveSearch)].location != NSNotFound) + { + [fController openURL:pbItem]; + } else { - #warning only accept full text? - for (NSTextCheckingResult * result in [detector matchesInString: pbItem options: 0 range: NSMakeRange(0, pbItem.length)]) - [fController openURL: result.URL.absoluteString]; +#warning only accept full text? + for (NSTextCheckingResult* result in [detector matchesInString:pbItem options:0 + range:NSMakeRange(0, pbItem.length)]) + [fController openURL:result.URL.absoluteString]; } } } } } -- (BOOL) validateMenuItem: (NSMenuItem *) menuItem +- (BOOL)validateMenuItem:(NSMenuItem*)menuItem { SEL action = menuItem.action; if (action == @selector(paste:)) { - if ([NSPasteboard.generalPasteboard.types containsObject: NSURLPboardType]) + if ([NSPasteboard.generalPasteboard.types containsObject:NSURLPboardType]) + { return YES; + } - NSArray * items = [NSPasteboard.generalPasteboard readObjectsForClasses: @[[NSString class]] options: nil]; + NSArray* items = [NSPasteboard.generalPasteboard readObjectsForClasses:@[ [NSString class] ] options:nil]; if (items) { - NSDataDetector * detector = [NSDataDetector dataDetectorWithTypes: NSTextCheckingTypeLink error: nil]; - for (__strong NSString * pbItem in items) + NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil]; + for (__strong NSString* pbItem in items) { - pbItem = [pbItem stringByTrimmingCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; - if (([pbItem rangeOfString: @"magnet:" options: (NSAnchoredSearch | NSCaseInsensitiveSearch)].location != NSNotFound) - || [detector firstMatchInString: pbItem options: 0 range: NSMakeRange(0, pbItem.length)]) + pbItem = [pbItem stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; + if (([pbItem rangeOfString:@"magnet:" options:(NSAnchoredSearch | NSCaseInsensitiveSearch)].location != NSNotFound) || + [detector firstMatchInString:pbItem options:0 range:NSMakeRange(0, pbItem.length)]) + { return YES; + } } } - return NO; + return NO; } return YES; } -- (void) toggleControlForTorrent: (Torrent *) torrent +- (void)toggleControlForTorrent:(Torrent*)torrent { if (torrent.active) - [fController stopTorrents: @[torrent]]; + { + [fController stopTorrents:@[ torrent ]]; + } else { if (NSEvent.modifierFlags & NSAlternateKeyMask) - [fController resumeTorrentsNoWait: @[torrent]]; + { + [fController resumeTorrentsNoWait:@[ torrent ]]; + } else if (torrent.waitingToStart) - [fController stopTorrents: @[torrent]]; + { + [fController stopTorrents:@[ torrent ]]; + } else - [fController resumeTorrents: @[torrent]]; + { + [fController resumeTorrents:@[ torrent ]]; + } } } -- (void) displayTorrentActionPopoverForEvent: (NSEvent *) event +- (void)displayTorrentActionPopoverForEvent:(NSEvent*)event { - const NSInteger row = [self rowAtPoint: [self convertPoint: event.locationInWindow fromView: nil]]; + NSInteger const row = [self rowAtPoint:[self convertPoint:event.locationInWindow fromView:nil]]; if (row < 0) + { return; + } - const NSRect rect = [fTorrentCell iconRectForBounds: [self rectOfRow: row]]; + NSRect const rect = [fTorrentCell iconRectForBounds:[self rectOfRow:row]]; if (fActionPopoverShown) + { return; + } - Torrent * torrent = [self itemAtRow: row]; + Torrent* torrent = [self itemAtRow:row]; - NSPopover * popover = [[NSPopover alloc] init]; + NSPopover* popover = [[NSPopover alloc] init]; popover.behavior = NSPopoverBehaviorTransient; - InfoOptionsViewController * infoViewController = [[InfoOptionsViewController alloc] init]; + InfoOptionsViewController* infoViewController = [[InfoOptionsViewController alloc] init]; popover.contentViewController = infoViewController; popover.delegate = self; - [popover showRelativeToRect: rect ofView: self preferredEdge: NSMaxYEdge]; - [infoViewController setInfoForTorrents: @[torrent]]; + [popover showRelativeToRect:rect ofView:self preferredEdge:NSMaxYEdge]; + [infoViewController setInfoForTorrents:@[ torrent ]]; [infoViewController updateInfo]; - } //don't show multiple popovers when clicking the gear button repeatedly -- (void) popoverWillShow: (NSNotification *) notification +- (void)popoverWillShow:(NSNotification*)notification { fActionPopoverShown = YES; } -- (void) popoverWillClose: (NSNotification *) notification +- (void)popoverWillClose:(NSNotification*)notification { fActionPopoverShown = NO; } //eliminate when Lion-only, along with all the menu item instance variables -- (void) menuNeedsUpdate: (NSMenu *) menu +- (void)menuNeedsUpdate:(NSMenu*)menu { //this method seems to be called when it shouldn't be if (!fMenuTorrent || !menu.supermenu) + { return; + } if (menu == fUploadMenu || menu == fDownloadMenu) { - NSMenuItem * item; + NSMenuItem* item; if (menu.numberOfItems == 3) { - const NSInteger speedLimitActionValue[] = { 0, 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, - 750, 1000, 1500, 2000, -1 }; + NSInteger const speedLimitActionValue[] = { 0, 5, 10, 20, 30, 40, 50, 75, 100, + 150, 200, 250, 500, 750, 1000, 1500, 2000, -1 }; for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++) { - item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", - "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimit:) - keyEquivalent: @""]; + item = [[NSMenuItem alloc] + initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"%d KB/s", "Action menu -> upload/download limit"), + speedLimitActionValue[i]] + action:@selector(setQuickLimit:) + keyEquivalent:@""]; item.target = self; item.representedObject = @(speedLimitActionValue[i]); - [menu addItem: item]; + [menu addItem:item]; } } - const BOOL upload = menu == fUploadMenu; - const BOOL limit = [fMenuTorrent usesSpeedLimit: upload]; + BOOL const upload = menu == fUploadMenu; + BOOL const limit = [fMenuTorrent usesSpeedLimit:upload]; - item = [menu itemWithTag: ACTION_MENU_LIMIT_TAG]; + item = [menu itemWithTag:ACTION_MENU_LIMIT_TAG]; item.state = limit ? NSOnState : NSOffState; - item.title = [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)", - "torrent action menu -> upload/download limit"), [fMenuTorrent speedLimit: upload]]; + item.title = [NSString stringWithFormat:NSLocalizedString(@"Limit (%d KB/s)", "torrent action menu -> upload/download limit"), + [fMenuTorrent speedLimit:upload]]; - item = [menu itemWithTag: ACTION_MENU_UNLIMITED_TAG]; + item = [menu itemWithTag:ACTION_MENU_UNLIMITED_TAG]; item.state = !limit ? NSOnState : NSOffState; } else if (menu == fRatioMenu) { - NSMenuItem * item; + NSMenuItem* item; if (menu.numberOfItems == 4) { - const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1.0 }; + float const ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1.0 }; for (NSInteger i = 0; ratioLimitActionValue[i] != -1.0; i++) { - item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]] - action: @selector(setQuickRatio:) keyEquivalent: @""]; + item = [[NSMenuItem alloc] initWithTitle:[NSString localizedStringWithFormat:@"%.2f", ratioLimitActionValue[i]] + action:@selector(setQuickRatio:) + keyEquivalent:@""]; item.target = self; item.representedObject = @(ratioLimitActionValue[i]); - [menu addItem: item]; + [menu addItem:item]; } } - const tr_ratiolimit mode = fMenuTorrent.ratioSetting; + tr_ratiolimit const mode = fMenuTorrent.ratioSetting; - item = [menu itemWithTag: ACTION_MENU_LIMIT_TAG]; + item = [menu itemWithTag:ACTION_MENU_LIMIT_TAG]; item.state = mode == TR_RATIOLIMIT_SINGLE ? NSOnState : NSOffState; - item.title = [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)", - "torrent action menu -> ratio stop"), fMenuTorrent.ratioLimit]; + item.title = [NSString localizedStringWithFormat:NSLocalizedString(@"Stop at Ratio (%.2f)", "torrent action menu -> ratio stop"), + fMenuTorrent.ratioLimit]; - item = [menu itemWithTag: ACTION_MENU_UNLIMITED_TAG]; + item = [menu itemWithTag:ACTION_MENU_UNLIMITED_TAG]; item.state = mode == TR_RATIOLIMIT_UNLIMITED ? NSOnState : NSOffState; - item = [menu itemWithTag: ACTION_MENU_GLOBAL_TAG]; + item = [menu itemWithTag:ACTION_MENU_GLOBAL_TAG]; item.state = mode == TR_RATIOLIMIT_GLOBAL ? NSOnState : NSOffState; } else if (menu == fPriorityMenu) { - const tr_priority_t priority = fMenuTorrent.priority; + tr_priority_t const priority = fMenuTorrent.priority; - NSMenuItem * item = [menu itemWithTag: ACTION_MENU_PRIORITY_HIGH_TAG]; + NSMenuItem* item = [menu itemWithTag:ACTION_MENU_PRIORITY_HIGH_TAG]; item.state = priority == TR_PRI_HIGH ? NSOnState : NSOffState; - item = [menu itemWithTag: ACTION_MENU_PRIORITY_NORMAL_TAG]; + item = [menu itemWithTag:ACTION_MENU_PRIORITY_NORMAL_TAG]; item.state = priority == TR_PRI_NORMAL ? NSOnState : NSOffState; - item = [menu itemWithTag: ACTION_MENU_PRIORITY_LOW_TAG]; + item = [menu itemWithTag:ACTION_MENU_PRIORITY_LOW_TAG]; item.state = priority == TR_PRI_LOW ? NSOnState : NSOffState; } } //the following methods might not be needed when Lion-only -- (void) setQuickLimitMode: (id) sender +- (void)setQuickLimitMode:(id)sender { - const BOOL limit = [sender tag] == ACTION_MENU_LIMIT_TAG; - [fMenuTorrent setUseSpeedLimit: limit upload: [sender menu] == fUploadMenu]; + BOOL const limit = [sender tag] == ACTION_MENU_LIMIT_TAG; + [fMenuTorrent setUseSpeedLimit:limit upload:[sender menu] == fUploadMenu]; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptions" object:nil]; } -- (void) setQuickLimit: (id) sender +- (void)setQuickLimit:(id)sender { - const BOOL upload = [sender menu] == fUploadMenu; - [fMenuTorrent setUseSpeedLimit: YES upload: upload]; - [fMenuTorrent setSpeedLimit: [[sender representedObject] intValue] upload: upload]; + BOOL const upload = [sender menu] == fUploadMenu; + [fMenuTorrent setUseSpeedLimit:YES upload:upload]; + [fMenuTorrent setSpeedLimit:[[sender representedObject] intValue] upload:upload]; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptions" object:nil]; } -- (void) setGlobalLimit: (id) sender +- (void)setGlobalLimit:(id)sender { - fMenuTorrent.usesGlobalSpeedLimit = ((NSButton *)sender).state != NSOnState; + fMenuTorrent.usesGlobalSpeedLimit = ((NSButton*)sender).state != NSOnState; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptions" object:nil]; } -- (void) setQuickRatioMode: (id) sender +- (void)setQuickRatioMode:(id)sender { tr_ratiolimit mode; switch ([sender tag]) { - case ACTION_MENU_UNLIMITED_TAG: - mode = TR_RATIOLIMIT_UNLIMITED; - break; - case ACTION_MENU_LIMIT_TAG: - mode = TR_RATIOLIMIT_SINGLE; - break; - case ACTION_MENU_GLOBAL_TAG: - mode = TR_RATIOLIMIT_GLOBAL; - break; - default: - return; + case ACTION_MENU_UNLIMITED_TAG: + mode = TR_RATIOLIMIT_UNLIMITED; + break; + case ACTION_MENU_LIMIT_TAG: + mode = TR_RATIOLIMIT_SINGLE; + break; + case ACTION_MENU_GLOBAL_TAG: + mode = TR_RATIOLIMIT_GLOBAL; + break; + default: + return; } fMenuTorrent.ratioSetting = mode; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptions" object:nil]; } -- (void) setQuickRatio: (id) sender +- (void)setQuickRatio:(id)sender { fMenuTorrent.ratioSetting = TR_RATIOLIMIT_SINGLE; fMenuTorrent.ratioLimit = [[sender representedObject] floatValue]; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateOptions" object:nil]; } -- (void) setPriority: (id) sender +- (void)setPriority:(id)sender { tr_priority_t priority; switch ([sender tag]) { - case ACTION_MENU_PRIORITY_HIGH_TAG: - priority = TR_PRI_HIGH; - break; - case ACTION_MENU_PRIORITY_NORMAL_TAG: - priority = TR_PRI_NORMAL; - break; - case ACTION_MENU_PRIORITY_LOW_TAG: - priority = TR_PRI_LOW; - break; - default: - NSAssert1(NO, @"Unknown priority: %ld", [sender tag]); - priority = TR_PRI_NORMAL; + case ACTION_MENU_PRIORITY_HIGH_TAG: + priority = TR_PRI_HIGH; + break; + case ACTION_MENU_PRIORITY_NORMAL_TAG: + priority = TR_PRI_NORMAL; + break; + case ACTION_MENU_PRIORITY_LOW_TAG: + priority = TR_PRI_LOW; + break; + default: + NSAssert1(NO, @"Unknown priority: %ld", [sender tag]); + priority = TR_PRI_NORMAL; } fMenuTorrent.priority = priority; - [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName:@"UpdateUI" object:nil]; } -- (void) togglePiecesBar +- (void)togglePiecesBar { - NSMutableArray * progressMarks = [NSMutableArray arrayWithCapacity: 16]; + NSMutableArray* progressMarks = [NSMutableArray arrayWithCapacity:16]; for (NSAnimationProgress i = 0.0625; i <= 1.0; i += 0.0625) - [progressMarks addObject: @(i)]; + { + [progressMarks addObject:@(i)]; + } //this stops a previous animation - fPiecesBarAnimation = [[NSAnimation alloc] initWithDuration: TOGGLE_PROGRESS_SECONDS animationCurve: NSAnimationEaseIn]; + fPiecesBarAnimation = [[NSAnimation alloc] initWithDuration:TOGGLE_PROGRESS_SECONDS animationCurve:NSAnimationEaseIn]; fPiecesBarAnimation.animationBlockingMode = NSAnimationNonblocking; fPiecesBarAnimation.progressMarks = progressMarks; fPiecesBarAnimation.delegate = self; @@ -796,7 +926,7 @@ [fPiecesBarAnimation startAnimation]; } -- (void) animationDidEnd: (NSAnimation *) animation +- (void)animationDidEnd:(NSAnimation*)animation { if (animation == fPiecesBarAnimation) { @@ -804,63 +934,71 @@ } } -- (void) animation: (NSAnimation *) animation didReachProgressMark: (NSAnimationProgress) progress +- (void)animation:(NSAnimation*)animation didReachProgressMark:(NSAnimationProgress)progress { if (animation == fPiecesBarAnimation) { - if ([fDefaults boolForKey: @"PiecesBar"]) + if ([fDefaults boolForKey:@"PiecesBar"]) + { fPiecesBarPercent = progress; + } else + { fPiecesBarPercent = 1.0 - progress; + } self.needsDisplay = YES; } } -- (CGFloat) piecesBarPercent +- (CGFloat)piecesBarPercent { return fPiecesBarPercent; } -- (void) selectAndScrollToRow: (NSInteger) row +- (void)selectAndScrollToRow:(NSInteger)row { NSParameterAssert(row >= 0); NSParameterAssert(row < self.numberOfRows); - [self selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; + [self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO]; - const NSRect rowRect = [self rectOfRow: row]; - const NSRect viewRect = self.superview.frame; + NSRect const rowRect = [self rectOfRow:row]; + NSRect const viewRect = self.superview.frame; NSPoint scrollOrigin = rowRect.origin; scrollOrigin.y += (rowRect.size.height - viewRect.size.height) / 2; if (scrollOrigin.y < 0) + { scrollOrigin.y = 0; + } - [[self.superview animator] setBoundsOrigin: scrollOrigin]; + [[self.superview animator] setBoundsOrigin:scrollOrigin]; } @end @implementation TorrentTableView (Private) -- (BOOL) pointInGroupStatusRect: (NSPoint) point +- (BOOL)pointInGroupStatusRect:(NSPoint)point { - NSInteger row = [self rowAtPoint: point]; - if (row < 0 || [[self itemAtRow: row] isKindOfClass: [Torrent class]]) + NSInteger row = [self rowAtPoint:point]; + if (row < 0 || [[self itemAtRow:row] isKindOfClass:[Torrent class]]) + { return NO; + } - NSString * ident = (self.tableColumns[[self columnAtPoint: point]]).identifier; - return [ident isEqualToString: @"UL"] || [ident isEqualToString: @"UL Image"] - || [ident isEqualToString: @"DL"] || [ident isEqualToString: @"DL Image"]; + NSString* ident = (self.tableColumns[[self columnAtPoint:point]]).identifier; + return [ident isEqualToString:@"UL"] || [ident isEqualToString:@"UL Image"] || [ident isEqualToString:@"DL"] || + [ident isEqualToString:@"DL Image"]; } -- (void) setGroupStatusColumns +- (void)setGroupStatusColumns { - const BOOL ratio = [fDefaults boolForKey: @"DisplayGroupRowRatio"]; + BOOL const ratio = [fDefaults boolForKey:@"DisplayGroupRowRatio"]; - [self tableColumnWithIdentifier: @"DL"].hidden = ratio; - [self tableColumnWithIdentifier: @"DL Image"].hidden = ratio; + [self tableColumnWithIdentifier:@"DL"].hidden = ratio; + [self tableColumnWithIdentifier:@"DL Image"].hidden = ratio; } @end diff --git a/macosx/TrackerCell.h b/macosx/TrackerCell.h index 8d2bfd26c..b8ffa8c3c 100644 --- a/macosx/TrackerCell.h +++ b/macosx/TrackerCell.h @@ -24,7 +24,7 @@ @interface TrackerCell : NSActionCell { - NSMutableDictionary * fNameAttributes, * fStatusAttributes; + NSMutableDictionary *fNameAttributes, *fStatusAttributes; } @end diff --git a/macosx/TrackerCell.m b/macosx/TrackerCell.m index a693e6b63..d1dc2ad94 100644 --- a/macosx/TrackerCell.m +++ b/macosx/TrackerCell.m @@ -38,57 +38,55 @@ @interface TrackerCell (Private) -@property (nonatomic, readonly) NSImage *favIcon; -- (void) loadTrackerIcon: (NSString *) baseAddress; +@property(nonatomic, readonly) NSImage* favIcon; +- (void)loadTrackerIcon:(NSString*)baseAddress; -- (NSRect) imageRectForBounds: (NSRect) bounds; -- (NSRect) rectForNameWithString: (NSAttributedString *) string inBounds: (NSRect) bounds; -- (NSRect) rectForCountWithString: (NSAttributedString *) string withAboveRect: (NSRect) aboveRect inBounds: (NSRect) bounds; -- (NSRect) rectForCountLabelWithString: (NSAttributedString *) string withRightRect: (NSRect) rightRect inBounds: (NSRect) bounds; -- (NSRect) rectForStatusWithString: (NSAttributedString *) string withAboveRect: (NSRect) aboveRect withRightRect: (NSRect) rightRect - inBounds: (NSRect) bounds; +- (NSRect)imageRectForBounds:(NSRect)bounds; +- (NSRect)rectForNameWithString:(NSAttributedString*)string inBounds:(NSRect)bounds; +- (NSRect)rectForCountWithString:(NSAttributedString*)string withAboveRect:(NSRect)aboveRect inBounds:(NSRect)bounds; +- (NSRect)rectForCountLabelWithString:(NSAttributedString*)string withRightRect:(NSRect)rightRect inBounds:(NSRect)bounds; +- (NSRect)rectForStatusWithString:(NSAttributedString*)string + withAboveRect:(NSRect)aboveRect + withRightRect:(NSRect)rightRect + inBounds:(NSRect)bounds; -@property (nonatomic, readonly) NSAttributedString *attributedName; -- (NSAttributedString *) attributedStatusWithString: (NSString *) statusString; -- (NSAttributedString *) attributedCount: (NSInteger) count; +@property(nonatomic, readonly) NSAttributedString* attributedName; +- (NSAttributedString*)attributedStatusWithString:(NSString*)statusString; +- (NSAttributedString*)attributedCount:(NSInteger)count; @end @implementation TrackerCell //make the favicons accessible to all tracker cells -NSCache * fTrackerIconCache; -NSMutableSet * fTrackerIconLoading; +NSCache* fTrackerIconCache; +NSMutableSet* fTrackerIconLoading; -+ (void) initialize ++ (void)initialize { fTrackerIconCache = [[NSCache alloc] init]; fTrackerIconLoading = [[NSMutableSet alloc] init]; } -- (instancetype) init +- (instancetype)init { if ((self = [super init])) { - NSMutableParagraphStyle * paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + NSMutableParagraphStyle* paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; - fNameAttributes = [[NSMutableDictionary alloc] initWithObjectsAndKeys: - [NSFont messageFontOfSize: 12.0], NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, nil]; - - fStatusAttributes = [[NSMutableDictionary alloc] initWithObjectsAndKeys: - [NSFont messageFontOfSize: 9.0], NSFontAttributeName, - paragraphStyle, NSParagraphStyleAttributeName, nil]; + fNameAttributes = [[NSMutableDictionary alloc] + initWithObjectsAndKeys:[NSFont messageFontOfSize:12.0], NSFontAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil]; + fStatusAttributes = [[NSMutableDictionary alloc] + initWithObjectsAndKeys:[NSFont messageFontOfSize:9.0], NSFontAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil]; } return self; } - -- (id) copyWithZone: (NSZone *) zone +- (id)copyWithZone:(NSZone*)zone { - TrackerCell * copy = [super copyWithZone: zone]; + TrackerCell* copy = [super copyWithZone:zone]; copy->fNameAttributes = fNameAttributes; copy->fStatusAttributes = fStatusAttributes; @@ -96,15 +94,20 @@ NSMutableSet * fTrackerIconLoading; return copy; } -- (void) drawWithFrame: (NSRect) cellFrame inView: (NSView *) controlView +- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView { //icon - [self.favIcon drawInRect: [self imageRectForBounds: cellFrame] fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; + [self.favIcon drawInRect:[self imageRectForBounds:cellFrame] fromRect:NSZeroRect operation:NSCompositeSourceOver + fraction:1.0 + respectFlipped:YES + hints:nil]; //set table colors - NSColor * nameColor, * statusColor; + NSColor *nameColor, *statusColor; if (self.backgroundStyle == NSBackgroundStyleDark) + { nameColor = statusColor = NSColor.whiteColor; + } else { nameColor = NSColor.labelColor; @@ -114,142 +117,155 @@ NSMutableSet * fTrackerIconLoading; fNameAttributes[NSForegroundColorAttributeName] = nameColor; fStatusAttributes[NSForegroundColorAttributeName] = statusColor; - TrackerNode * node = (TrackerNode *)self.objectValue; + TrackerNode* node = (TrackerNode*)self.objectValue; //name - NSAttributedString * nameString = self.attributedName; - const NSRect nameRect = [self rectForNameWithString: nameString inBounds: cellFrame]; - [nameString drawInRect: nameRect]; + NSAttributedString* nameString = self.attributedName; + NSRect const nameRect = [self rectForNameWithString:nameString inBounds:cellFrame]; + [nameString drawInRect:nameRect]; //count strings - NSAttributedString * seederString = [self attributedCount: node.totalSeeders]; - const NSRect seederRect = [self rectForCountWithString: seederString withAboveRect: nameRect inBounds: cellFrame]; - [seederString drawInRect: seederRect]; + NSAttributedString* seederString = [self attributedCount:node.totalSeeders]; + NSRect const seederRect = [self rectForCountWithString:seederString withAboveRect:nameRect inBounds:cellFrame]; + [seederString drawInRect:seederRect]; - NSAttributedString * leecherString = [self attributedCount: node.totalLeechers]; - const NSRect leecherRect = [self rectForCountWithString: leecherString withAboveRect: seederRect inBounds: cellFrame]; - [leecherString drawInRect: leecherRect]; + NSAttributedString* leecherString = [self attributedCount:node.totalLeechers]; + NSRect const leecherRect = [self rectForCountWithString:leecherString withAboveRect:seederRect inBounds:cellFrame]; + [leecherString drawInRect:leecherRect]; - NSAttributedString * downloadedString = [self attributedCount: node.totalDownloaded]; - const NSRect downloadedRect = [self rectForCountWithString: downloadedString withAboveRect: leecherRect inBounds: cellFrame]; - [downloadedString drawInRect: downloadedRect]; + NSAttributedString* downloadedString = [self attributedCount:node.totalDownloaded]; + NSRect const downloadedRect = [self rectForCountWithString:downloadedString withAboveRect:leecherRect inBounds:cellFrame]; + [downloadedString drawInRect:downloadedRect]; //count label strings - NSString * seederLabelBaseString = [NSLocalizedString(@"Seeders", "tracker peer stat") stringByAppendingFormat: @": "]; - NSAttributedString * seederLabelString = [self attributedStatusWithString: seederLabelBaseString]; - const NSRect seederLabelRect = [self rectForCountLabelWithString: seederLabelString withRightRect: seederRect - inBounds: cellFrame]; - [seederLabelString drawInRect: seederLabelRect]; + NSString* seederLabelBaseString = [NSLocalizedString(@"Seeders", "tracker peer stat") stringByAppendingFormat:@": "]; + NSAttributedString* seederLabelString = [self attributedStatusWithString:seederLabelBaseString]; + NSRect const seederLabelRect = [self rectForCountLabelWithString:seederLabelString withRightRect:seederRect inBounds:cellFrame]; + [seederLabelString drawInRect:seederLabelRect]; - NSString * leecherLabelBaseString = [NSLocalizedString(@"Leechers", "tracker peer stat") stringByAppendingFormat: @": "]; - NSAttributedString * leecherLabelString = [self attributedStatusWithString: leecherLabelBaseString]; - const NSRect leecherLabelRect = [self rectForCountLabelWithString: leecherLabelString withRightRect: leecherRect - inBounds: cellFrame]; - [leecherLabelString drawInRect: leecherLabelRect]; + NSString* leecherLabelBaseString = [NSLocalizedString(@"Leechers", "tracker peer stat") stringByAppendingFormat:@": "]; + NSAttributedString* leecherLabelString = [self attributedStatusWithString:leecherLabelBaseString]; + NSRect const leecherLabelRect = [self rectForCountLabelWithString:leecherLabelString withRightRect:leecherRect + inBounds:cellFrame]; + [leecherLabelString drawInRect:leecherLabelRect]; - NSString * downloadedLabelBaseString = [NSLocalizedString(@"Downloaded", "tracker peer stat") stringByAppendingFormat: @": "]; - NSAttributedString * downloadedLabelString = [self attributedStatusWithString: downloadedLabelBaseString]; - const NSRect downloadedLabelRect = [self rectForCountLabelWithString: downloadedLabelString withRightRect: downloadedRect - inBounds: cellFrame]; - [downloadedLabelString drawInRect: downloadedLabelRect]; + NSString* downloadedLabelBaseString = [NSLocalizedString(@"Downloaded", "tracker peer stat") stringByAppendingFormat:@": "]; + NSAttributedString* downloadedLabelString = [self attributedStatusWithString:downloadedLabelBaseString]; + NSRect const downloadedLabelRect = [self rectForCountLabelWithString:downloadedLabelString withRightRect:downloadedRect + inBounds:cellFrame]; + [downloadedLabelString drawInRect:downloadedLabelRect]; //status strings - NSAttributedString * lastAnnounceString = [self attributedStatusWithString: node.lastAnnounceStatusString]; - const NSRect lastAnnounceRect = [self rectForStatusWithString: lastAnnounceString withAboveRect: nameRect - withRightRect: seederLabelRect inBounds: cellFrame]; - [lastAnnounceString drawInRect: lastAnnounceRect]; + NSAttributedString* lastAnnounceString = [self attributedStatusWithString:node.lastAnnounceStatusString]; + NSRect const lastAnnounceRect = [self rectForStatusWithString:lastAnnounceString withAboveRect:nameRect + withRightRect:seederLabelRect + inBounds:cellFrame]; + [lastAnnounceString drawInRect:lastAnnounceRect]; - NSAttributedString * nextAnnounceString = [self attributedStatusWithString: node.nextAnnounceStatusString]; - const NSRect nextAnnounceRect = [self rectForStatusWithString: nextAnnounceString withAboveRect: lastAnnounceRect - withRightRect: leecherLabelRect inBounds: cellFrame]; - [nextAnnounceString drawInRect: nextAnnounceRect]; + NSAttributedString* nextAnnounceString = [self attributedStatusWithString:node.nextAnnounceStatusString]; + NSRect const nextAnnounceRect = [self rectForStatusWithString:nextAnnounceString withAboveRect:lastAnnounceRect + withRightRect:leecherLabelRect + inBounds:cellFrame]; + [nextAnnounceString drawInRect:nextAnnounceRect]; - NSAttributedString * lastScrapeString = [self attributedStatusWithString: node.lastScrapeStatusString]; - const NSRect lastScrapeRect = [self rectForStatusWithString: lastScrapeString withAboveRect: nextAnnounceRect - withRightRect: downloadedLabelRect inBounds: cellFrame]; - [lastScrapeString drawInRect: lastScrapeRect]; + NSAttributedString* lastScrapeString = [self attributedStatusWithString:node.lastScrapeStatusString]; + NSRect const lastScrapeRect = [self rectForStatusWithString:lastScrapeString withAboveRect:nextAnnounceRect + withRightRect:downloadedLabelRect + inBounds:cellFrame]; + [lastScrapeString drawInRect:lastScrapeRect]; } @end @implementation TrackerCell (Private) -- (NSImage *) favIcon +- (NSImage*)favIcon { id icon = nil; - NSURL * address = [NSURL URLWithString: ((TrackerNode *)self.objectValue).fullAnnounceAddress]; - NSString * host; + NSURL* address = [NSURL URLWithString:((TrackerNode*)self.objectValue).fullAnnounceAddress]; + NSString* host; if ((host = address.host)) { //don't try to parse ip address - const BOOL separable = !tr_addressIsIP(host.UTF8String); + BOOL const separable = !tr_addressIsIP(host.UTF8String); - NSArray * hostComponents = separable ? [host componentsSeparatedByString: @"."] : nil; + NSArray* hostComponents = separable ? [host componentsSeparatedByString:@"."] : nil; //let's try getting the tracker address without using any subdomains - NSString * baseAddress; + NSString* baseAddress; if (separable && hostComponents.count > 1) - baseAddress = [NSString stringWithFormat: @"http://%@.%@", - hostComponents[hostComponents.count-2], hostComponents.lastObject]; + { + baseAddress = [NSString stringWithFormat:@"http://%@.%@", hostComponents[hostComponents.count - 2], hostComponents.lastObject]; + } else - baseAddress = [NSString stringWithFormat: @"http://%@", host]; + { + baseAddress = [NSString stringWithFormat:@"http://%@", host]; + } - icon = [fTrackerIconCache objectForKey: baseAddress]; + icon = [fTrackerIconCache objectForKey:baseAddress]; if (!icon) - [self loadTrackerIcon: baseAddress]; + { + [self loadTrackerIcon:baseAddress]; + } } - return (icon && icon != [NSNull null]) ? icon : [NSImage imageNamed: @"FavIcon"]; + return (icon && icon != [NSNull null]) ? icon : [NSImage imageNamed:@"FavIcon"]; } #warning better favicon detection -- (void) loadTrackerIcon: (NSString *) baseAddress +- (void)loadTrackerIcon:(NSString*)baseAddress { - if ([fTrackerIconLoading containsObject: baseAddress]) { + if ([fTrackerIconLoading containsObject:baseAddress]) + { return; } - [fTrackerIconLoading addObject: baseAddress]; - + [fTrackerIconLoading addObject:baseAddress]; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - NSImage *icon = nil; - - NSArray *filenamesToTry = @[ @"favicon.png", @"favicon.ico" ]; - for (NSString *filename in filenamesToTry) { - NSURL * favIconUrl = [NSURL URLWithString: [baseAddress stringByAppendingPathComponent:filename]]; - - NSURLRequest * request = [NSURLRequest requestWithURL: favIconUrl cachePolicy: NSURLRequestUseProtocolCachePolicy - timeoutInterval: 30.0]; - - NSData * iconData = [NSURLConnection sendSynchronousRequest: request returningResponse: NULL error: NULL]; - if (iconData) { - icon = [[NSImage alloc] initWithData: iconData]; - if (icon) { + NSImage* icon = nil; + + NSArray* filenamesToTry = @[ @"favicon.png", @"favicon.ico" ]; + for (NSString* filename in filenamesToTry) + { + NSURL* favIconUrl = [NSURL URLWithString:[baseAddress stringByAppendingPathComponent:filename]]; + + NSURLRequest* request = [NSURLRequest requestWithURL:favIconUrl cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:30.0]; + + NSData* iconData = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL]; + if (iconData) + { + icon = [[NSImage alloc] initWithData:iconData]; + if (icon) + { break; } } } - + dispatch_async(dispatch_get_main_queue(), ^{ if (icon) { - [fTrackerIconCache setObject: icon forKey: baseAddress]; - - [[self controlView] setNeedsDisplay: YES]; + [fTrackerIconCache setObject:icon forKey:baseAddress]; + + [[self controlView] setNeedsDisplay:YES]; } else - [fTrackerIconCache setObject: [NSNull null] forKey: baseAddress]; - - [fTrackerIconLoading removeObject: baseAddress]; + { + [fTrackerIconCache setObject:[NSNull null] forKey:baseAddress]; + } + + [fTrackerIconLoading removeObject:baseAddress]; }); }); } -- (NSRect) imageRectForBounds: (NSRect) bounds +- (NSRect)imageRectForBounds:(NSRect)bounds { return NSMakeRect(NSMinX(bounds) + PADDING_HORIZONAL, NSMinY(bounds) + PADDING_ABOVE_ICON, ICON_SIZE, ICON_SIZE); } -- (NSRect) rectForNameWithString: (NSAttributedString *) string inBounds: (NSRect) bounds +- (NSRect)rectForNameWithString:(NSAttributedString*)string inBounds:(NSRect)bounds { NSRect result; result.origin.x = NSMinX(bounds) + PADDING_HORIZONAL + ICON_SIZE + PADDING_BETWEEN_ICON_AND_NAME; @@ -261,14 +277,16 @@ NSMutableSet * fTrackerIconLoading; return result; } -- (NSRect) rectForCountWithString: (NSAttributedString *) string withAboveRect: (NSRect) aboveRect inBounds: (NSRect) bounds +- (NSRect)rectForCountWithString:(NSAttributedString*)string withAboveRect:(NSRect)aboveRect inBounds:(NSRect)bounds { - return NSMakeRect(NSMaxX(bounds) - PADDING_HORIZONAL - COUNT_WIDTH, - NSMaxY(aboveRect) + PADDING_BETWEEN_LINES, - COUNT_WIDTH, [string size].height); + return NSMakeRect( + NSMaxX(bounds) - PADDING_HORIZONAL - COUNT_WIDTH, + NSMaxY(aboveRect) + PADDING_BETWEEN_LINES, + COUNT_WIDTH, + [string size].height); } -- (NSRect) rectForCountLabelWithString: (NSAttributedString *) string withRightRect: (NSRect) rightRect inBounds: (NSRect) bounds +- (NSRect)rectForCountLabelWithString:(NSAttributedString*)string withRightRect:(NSRect)rightRect inBounds:(NSRect)bounds { NSRect result = rightRect; result.size.width = [string size].width; @@ -277,8 +295,10 @@ NSMutableSet * fTrackerIconLoading; return result; } -- (NSRect) rectForStatusWithString: (NSAttributedString *) string withAboveRect: (NSRect) aboveRect withRightRect: (NSRect) rightRect - inBounds: (NSRect) bounds +- (NSRect)rectForStatusWithString:(NSAttributedString*)string + withAboveRect:(NSRect)aboveRect + withRightRect:(NSRect)rightRect + inBounds:(NSRect)bounds { NSRect result; result.origin.x = NSMinX(bounds) + PADDING_STATUS_HORIZONAL; @@ -290,21 +310,21 @@ NSMutableSet * fTrackerIconLoading; return result; } -- (NSAttributedString *) attributedName +- (NSAttributedString*)attributedName { - NSString * name = ((TrackerNode *)self.objectValue).host; - return [[NSAttributedString alloc] initWithString: name attributes: fNameAttributes]; + NSString* name = ((TrackerNode*)self.objectValue).host; + return [[NSAttributedString alloc] initWithString:name attributes:fNameAttributes]; } -- (NSAttributedString *) attributedStatusWithString: (NSString *) statusString +- (NSAttributedString*)attributedStatusWithString:(NSString*)statusString { - return [[NSAttributedString alloc] initWithString: statusString attributes: fStatusAttributes]; + return [[NSAttributedString alloc] initWithString:statusString attributes:fStatusAttributes]; } -- (NSAttributedString *) attributedCount: (NSInteger) count +- (NSAttributedString*)attributedCount:(NSInteger)count { - NSString * countString = count != -1 ? [NSString stringWithFormat: @"%ld", count] : NSLocalizedString(@"N/A", "tracker peer stat"); - return [[NSAttributedString alloc] initWithString: countString attributes: fStatusAttributes]; + NSString* countString = count != -1 ? [NSString stringWithFormat:@"%ld", count] : NSLocalizedString(@"N/A", "tracker peer stat"); + return [[NSAttributedString alloc] initWithString:countString attributes:fStatusAttributes]; } @end diff --git a/macosx/TrackerNode.h b/macosx/TrackerNode.h index 1d740a93f..38514f58f 100644 --- a/macosx/TrackerNode.h +++ b/macosx/TrackerNode.h @@ -28,25 +28,25 @@ @interface TrackerNode : NSObject -@property (nonatomic, weak, readonly) Torrent * torrent; +@property(nonatomic, weak, readonly) Torrent* torrent; -- (instancetype) initWithTrackerStat: (tr_tracker_stat *) stat torrent: (Torrent *) torrent; +- (instancetype)initWithTrackerStat:(tr_tracker_stat*)stat torrent:(Torrent*)torrent; -- (BOOL) isEqual: (id) object; +- (BOOL)isEqual:(id)object; -@property (nonatomic, readonly) NSString *host; -@property (nonatomic, readonly) NSString *fullAnnounceAddress; +@property(nonatomic, readonly) NSString* host; +@property(nonatomic, readonly) NSString* fullAnnounceAddress; -@property (nonatomic, readonly) NSInteger tier; +@property(nonatomic, readonly) NSInteger tier; -@property (nonatomic, readonly) NSUInteger identifier; +@property(nonatomic, readonly) NSUInteger identifier; -@property (nonatomic, readonly) NSInteger totalSeeders; -@property (nonatomic, readonly) NSInteger totalLeechers; -@property (nonatomic, readonly) NSInteger totalDownloaded; +@property(nonatomic, readonly) NSInteger totalSeeders; +@property(nonatomic, readonly) NSInteger totalLeechers; +@property(nonatomic, readonly) NSInteger totalDownloaded; -@property (nonatomic, readonly) NSString *lastAnnounceStatusString; -@property (nonatomic, readonly) NSString *nextAnnounceStatusString; -@property (nonatomic, readonly) NSString *lastScrapeStatusString; +@property(nonatomic, readonly) NSString* lastAnnounceStatusString; +@property(nonatomic, readonly) NSString* nextAnnounceStatusString; +@property(nonatomic, readonly) NSString* lastScrapeStatusString; @end diff --git a/macosx/TrackerNode.m b/macosx/TrackerNode.m index c00cba512..92b92cac5 100644 --- a/macosx/TrackerNode.m +++ b/macosx/TrackerNode.m @@ -29,7 +29,7 @@ tr_tracker_stat fStat; } -- (instancetype) initWithTrackerStat: (tr_tracker_stat *) stat torrent: (Torrent *) torrent +- (instancetype)initWithTrackerStat:(tr_tracker_stat*)stat torrent:(Torrent*)torrent { if ((self = [super init])) { @@ -40,125 +40,142 @@ return self; } -- (NSString *) description +- (NSString*)description { - return [@"Tracker: " stringByAppendingString: self.fullAnnounceAddress]; + return [@"Tracker: " stringByAppendingString:self.fullAnnounceAddress]; } -- (id) copyWithZone: (NSZone *) zone +- (id)copyWithZone:(NSZone*)zone { //this object is essentially immutable after initial setup return self; } -- (BOOL) isEqual: (id) object +- (BOOL)isEqual:(id)object { if (self == object) + { return YES; + } - if (![object isKindOfClass: [self class]]) + if (![object isKindOfClass:[self class]]) + { return NO; - + } + typeof(self) other = (typeof(self))object; if (self.torrent != other.torrent) + { return NO; + } - return self.tier == other.tier && [self.fullAnnounceAddress isEqualToString: other.fullAnnounceAddress]; + return self.tier == other.tier && [self.fullAnnounceAddress isEqualToString:other.fullAnnounceAddress]; } -- (NSString *) host +- (NSString*)host { return @(fStat.host); } -- (NSString *) fullAnnounceAddress +- (NSString*)fullAnnounceAddress { return @(fStat.announce); } -- (NSInteger) tier +- (NSInteger)tier { return fStat.tier; } -- (NSUInteger) identifier +- (NSUInteger)identifier { return fStat.id; } -- (NSInteger) totalSeeders +- (NSInteger)totalSeeders { return fStat.seederCount; } -- (NSInteger) totalLeechers +- (NSInteger)totalLeechers { return fStat.leecherCount; } -- (NSInteger) totalDownloaded +- (NSInteger)totalDownloaded { return fStat.downloadCount; } -- (NSString *) lastAnnounceStatusString +- (NSString*)lastAnnounceStatusString { - NSString * dateString; + NSString* dateString; if (fStat.hasAnnounced) { - NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; + NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateStyle = NSDateFormatterFullStyle; dateFormatter.timeStyle = NSDateFormatterShortStyle; dateFormatter.doesRelativeDateFormatting = YES; - dateString = [dateFormatter stringFromDate: [NSDate dateWithTimeIntervalSince1970: fStat.lastAnnounceTime]]; + dateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:fStat.lastAnnounceTime]]; } else + { dateString = NSLocalizedString(@"N/A", "Tracker last announce"); + } - NSString * baseString; + NSString* baseString; if (fStat.hasAnnounced && fStat.lastAnnounceTimedOut) - baseString = [NSLocalizedString(@"Announce timed out", "Tracker last announce") stringByAppendingFormat: @": %@", dateString]; + { + baseString = [NSLocalizedString(@"Announce timed out", "Tracker last announce") stringByAppendingFormat:@": %@", dateString]; + } else if (fStat.hasAnnounced && !fStat.lastAnnounceSucceeded) { baseString = NSLocalizedString(@"Announce error", "Tracker last announce"); - NSString * errorString = @(fStat.lastAnnounceResult); - if ([errorString isEqualToString: @""]) - baseString = [baseString stringByAppendingFormat: @": %@", dateString]; + NSString* errorString = @(fStat.lastAnnounceResult); + if ([errorString isEqualToString:@""]) + { + baseString = [baseString stringByAppendingFormat:@": %@", dateString]; + } else - baseString = [baseString stringByAppendingFormat: @": %@ - %@", errorString, dateString]; + { + baseString = [baseString stringByAppendingFormat:@": %@ - %@", errorString, dateString]; + } } else { - baseString = [NSLocalizedString(@"Last Announce", "Tracker last announce") stringByAppendingFormat: @": %@", dateString]; + baseString = [NSLocalizedString(@"Last Announce", "Tracker last announce") stringByAppendingFormat:@": %@", dateString]; if (fStat.hasAnnounced && fStat.lastAnnounceSucceeded && fStat.lastAnnouncePeerCount > 0) { - NSString * peerString; + NSString* peerString; if (fStat.lastAnnouncePeerCount == 1) + { peerString = NSLocalizedString(@"got 1 peer", "Tracker last announce"); + } else - peerString = [NSString stringWithFormat: NSLocalizedString(@"got %d peers", "Tracker last announce"), - fStat.lastAnnouncePeerCount]; - baseString = [baseString stringByAppendingFormat: @" (%@)", peerString]; + { + peerString = [NSString stringWithFormat:NSLocalizedString(@"got %d peers", "Tracker last announce"), fStat.lastAnnouncePeerCount]; + } + baseString = [baseString stringByAppendingFormat:@" (%@)", peerString]; } } return baseString; } -- (NSString *) nextAnnounceStatusString +- (NSString*)nextAnnounceStatusString { switch (fStat.announceState) { - case TR_TRACKER_ACTIVE: - return [NSLocalizedString(@"Announce in progress", "Tracker next announce") stringByAppendingEllipsis]; + case TR_TRACKER_ACTIVE: + return [NSLocalizedString(@"Announce in progress", "Tracker next announce") stringByAppendingEllipsis]; - case TR_TRACKER_WAITING: + case TR_TRACKER_WAITING: { - const NSTimeInterval nextAnnounceTimeLeft = fStat.nextAnnounceTime - [NSDate date].timeIntervalSince1970; - - static NSDateComponentsFormatter *formatter; + NSTimeInterval const nextAnnounceTimeLeft = fStat.nextAnnounceTime - [NSDate date].timeIntervalSince1970; + + static NSDateComponentsFormatter* formatter; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ formatter = [NSDateComponentsFormatter new]; @@ -166,54 +183,63 @@ formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropLeading; formatter.collapsesLargestUnit = YES; }); - - NSString *timeString = [formatter stringFromTimeInterval: nextAnnounceTimeLeft]; - return [NSString stringWithFormat: NSLocalizedString(@"Next announce in %@", "Tracker next announce"), - timeString]; + + NSString* timeString = [formatter stringFromTimeInterval:nextAnnounceTimeLeft]; + return [NSString stringWithFormat:NSLocalizedString(@"Next announce in %@", "Tracker next announce"), timeString]; } - case TR_TRACKER_QUEUED: - return [NSLocalizedString(@"Announce is queued", "Tracker next announce") stringByAppendingEllipsis]; + case TR_TRACKER_QUEUED: + return [NSLocalizedString(@"Announce is queued", "Tracker next announce") stringByAppendingEllipsis]; - case TR_TRACKER_INACTIVE: - return fStat.isBackup ? NSLocalizedString(@"Tracker will be used as a backup", "Tracker next announce") - : NSLocalizedString(@"Announce not scheduled", "Tracker next announce"); + case TR_TRACKER_INACTIVE: + return fStat.isBackup ? NSLocalizedString(@"Tracker will be used as a backup", "Tracker next announce") : + NSLocalizedString(@"Announce not scheduled", "Tracker next announce"); - default: - NSAssert1(NO, @"unknown announce state: %d", fStat.announceState); - return nil; + default: + NSAssert1(NO, @"unknown announce state: %d", fStat.announceState); + return nil; } } -- (NSString *) lastScrapeStatusString +- (NSString*)lastScrapeStatusString { - NSString * dateString; + NSString* dateString; if (fStat.hasScraped) { - NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; + NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateStyle = NSDateFormatterFullStyle; dateFormatter.timeStyle = NSDateFormatterShortStyle; dateFormatter.doesRelativeDateFormatting = YES; - dateString = [dateFormatter stringFromDate: [NSDate dateWithTimeIntervalSince1970: fStat.lastScrapeTime]]; + dateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:fStat.lastScrapeTime]]; } else + { dateString = NSLocalizedString(@"N/A", "Tracker last scrape"); + } - NSString * baseString; + NSString* baseString; if (fStat.hasScraped && fStat.lastScrapeTimedOut) - baseString = [NSLocalizedString(@"Scrape timed out", "Tracker last scrape") stringByAppendingFormat: @": %@", dateString]; + { + baseString = [NSLocalizedString(@"Scrape timed out", "Tracker last scrape") stringByAppendingFormat:@": %@", dateString]; + } else if (fStat.hasScraped && !fStat.lastScrapeSucceeded) { baseString = NSLocalizedString(@"Scrape error", "Tracker last scrape"); - NSString * errorString = @(fStat.lastScrapeResult); - if ([errorString isEqualToString: @""]) - baseString = [baseString stringByAppendingFormat: @": %@", dateString]; + NSString* errorString = @(fStat.lastScrapeResult); + if ([errorString isEqualToString:@""]) + { + baseString = [baseString stringByAppendingFormat:@": %@", dateString]; + } else - baseString = [baseString stringByAppendingFormat: @": %@ - %@", errorString, dateString]; + { + baseString = [baseString stringByAppendingFormat:@": %@ - %@", errorString, dateString]; + } } else - baseString = [NSLocalizedString(@"Last Scrape", "Tracker last scrape") stringByAppendingFormat: @": %@", dateString]; + { + baseString = [NSLocalizedString(@"Last Scrape", "Tracker last scrape") stringByAppendingFormat:@": %@", dateString]; + } return baseString; } diff --git a/macosx/TrackerTableView.h b/macosx/TrackerTableView.h index 5a33c95b6..0bb8a9dab 100644 --- a/macosx/TrackerTableView.h +++ b/macosx/TrackerTableView.h @@ -27,14 +27,14 @@ @interface TrackerTableView : NSTableView { //weak references - Torrent * fTorrent; - NSArray * fTrackers; + Torrent* fTorrent; + NSArray* fTrackers; } -- (void) setTorrent: (Torrent *) torrent; -- (void) setTrackers: (NSArray *) trackers; +- (void)setTorrent:(Torrent*)torrent; +- (void)setTrackers:(NSArray*)trackers; -- (void) copy: (id) sender; -- (void) paste: (id) sender; +- (void)copy:(id)sender; +- (void)paste:(id)sender; @end diff --git a/macosx/TrackerTableView.m b/macosx/TrackerTableView.m index 3715ad765..77906cde7 100644 --- a/macosx/TrackerTableView.m +++ b/macosx/TrackerTableView.m @@ -26,76 +26,90 @@ @implementation TrackerTableView -- (void) mouseDown: (NSEvent *) event +- (void)mouseDown:(NSEvent*)event { [self.window makeKeyWindow]; - [super mouseDown: event]; + [super mouseDown:event]; } -- (void) setTorrent: (Torrent *) torrent +- (void)setTorrent:(Torrent*)torrent { fTorrent = torrent; } -- (void) setTrackers: (NSArray *) trackers +- (void)setTrackers:(NSArray*)trackers { fTrackers = trackers; } -- (void) copy: (id) sender +- (void)copy:(id)sender { - NSMutableArray * addresses = [NSMutableArray arrayWithCapacity: fTrackers.count]; - NSIndexSet * indexes = self.selectedRowIndexes; - for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex: i]) + NSMutableArray* addresses = [NSMutableArray arrayWithCapacity:fTrackers.count]; + NSIndexSet* indexes = self.selectedRowIndexes; + for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex:i]) { id item = fTrackers[i]; - if (![item isKindOfClass: [TrackerNode class]]) + if (![item isKindOfClass:[TrackerNode class]]) { - for (++i; i < fTrackers.count && [fTrackers[i] isKindOfClass: [TrackerNode class]]; ++i) - [addresses addObject: ((TrackerNode *)fTrackers[i]).fullAnnounceAddress]; + for (++i; i < fTrackers.count && [fTrackers[i] isKindOfClass:[TrackerNode class]]; ++i) + { + [addresses addObject:((TrackerNode*)fTrackers[i]).fullAnnounceAddress]; + } --i; } else - [addresses addObject: ((TrackerNode *)item).fullAnnounceAddress]; + { + [addresses addObject:((TrackerNode*)item).fullAnnounceAddress]; + } } - NSString * text = [addresses componentsJoinedByString: @"\n"]; + NSString* text = [addresses componentsJoinedByString:@"\n"]; - NSPasteboard * pb = NSPasteboard.generalPasteboard; + NSPasteboard* pb = NSPasteboard.generalPasteboard; [pb clearContents]; - [pb writeObjects: @[text]]; + [pb writeObjects:@[ text ]]; } -- (void) paste: (id) sender +- (void)paste:(id)sender { NSAssert(fTorrent != nil, @"no torrent but trying to paste; should not be able to call this method"); BOOL added = NO; - NSArray * items = [NSPasteboard.generalPasteboard readObjectsForClasses: @[[NSString class]] options: nil]; + NSArray* items = [NSPasteboard.generalPasteboard readObjectsForClasses:@[ [NSString class] ] options:nil]; NSAssert(items != nil, @"no string items to paste; should not be able to call this method"); - for (NSString * pbItem in items) + for (NSString* pbItem in items) { - for (NSString * item in [pbItem componentsSeparatedByString: @"\n"]) - if ([fTorrent addTrackerToNewTier: item]) + for (NSString* item in [pbItem componentsSeparatedByString:@"\n"]) + { + if ([fTorrent addTrackerToNewTier:item]) + { added = YES; + } + } } //none added if (!added) + { NSBeep(); + } } -- (BOOL) validateMenuItem: (NSMenuItem *) menuItem +- (BOOL)validateMenuItem:(NSMenuItem*)menuItem { - const SEL action = menuItem.action; + SEL const action = menuItem.action; if (action == @selector(copy:)) + { return self.numberOfSelectedRows > 0; + } if (action == @selector(paste:)) - return fTorrent && [NSPasteboard.generalPasteboard canReadObjectForClasses: @[[NSString class]] options: nil]; + { + return fTorrent && [NSPasteboard.generalPasteboard canReadObjectForClasses:@[ [NSString class] ] options:nil]; + } return YES; } diff --git a/macosx/URLSheetWindowController.h b/macosx/URLSheetWindowController.h index c372bd35c..d79e6be5c 100644 --- a/macosx/URLSheetWindowController.h +++ b/macosx/URLSheetWindowController.h @@ -26,18 +26,19 @@ @interface URLSheetWindowController : NSWindowController { - IBOutlet NSTextField * fLabelField; - IBOutlet NSTextField * fTextField; - IBOutlet NSButton * fOpenButton, * fCancelButton; + IBOutlet NSTextField* fLabelField; + IBOutlet NSTextField* fTextField; + IBOutlet NSButton* fOpenButton; + IBOutlet NSButton* fCancelButton; - Controller * fController; + Controller* fController; } -- (instancetype) initWithController: (Controller *) controller; +- (instancetype)initWithController:(Controller*)controller; -- (void) openURLEndSheet: (id) sender; -- (void) openURLCancelEndSheet: (id) sender; +- (void)openURLEndSheet:(id)sender; +- (void)openURLCancelEndSheet:(id)sender; -@property (nonatomic, readonly) NSString *urlString; +@property(nonatomic, readonly) NSString* urlString; @end diff --git a/macosx/URLSheetWindowController.m b/macosx/URLSheetWindowController.m index 55f44ced4..5afe3c156 100644 --- a/macosx/URLSheetWindowController.m +++ b/macosx/URLSheetWindowController.m @@ -25,33 +25,33 @@ @interface URLSheetWindowController (Private) -- (void) updateOpenButtonForURL: (NSString *) string; +- (void)updateOpenButtonForURL:(NSString*)string; @end @implementation URLSheetWindowController -NSString * urlString = nil; +NSString* urlString = nil; -- (instancetype) initWithController: (Controller *) controller +- (instancetype)initWithController:(Controller*)controller { - if ((self = [self initWithWindowNibName: @"URLSheetWindow"])) + if ((self = [self initWithWindowNibName:@"URLSheetWindow"])) { fController = controller; } return self; } -- (void) awakeFromNib +- (void)awakeFromNib { fLabelField.stringValue = NSLocalizedString(@"Internet address of torrent file:", "URL sheet label"); if (urlString) { fTextField.stringValue = urlString; - [fTextField selectText: self]; + [fTextField selectText:self]; - [self updateOpenButtonForURL: urlString]; + [self updateOpenButtonForURL:urlString]; } fOpenButton.title = NSLocalizedString(@"Open", "URL sheet button"); @@ -67,9 +67,13 @@ NSString * urlString = nil; cancelFrame.size.width += 10.0; if (NSWidth(openFrame) > NSWidth(cancelFrame)) + { cancelFrame.size.width = NSWidth(openFrame); + } else + { openFrame.size.width = NSWidth(cancelFrame); + } openFrame.origin.x = NSWidth(self.window.frame) - NSWidth(openFrame) - 20.0 + 6.0; //I don't know why the extra 6.0 is needed fOpenButton.frame = openFrame; @@ -78,42 +82,46 @@ NSString * urlString = nil; fCancelButton.frame = cancelFrame; } -- (void) openURLEndSheet: (id) sender +- (void)openURLEndSheet:(id)sender { - [self.window orderOut: sender]; - [NSApp endSheet: self.window returnCode: 1]; + [self.window orderOut:sender]; + [NSApp endSheet:self.window returnCode:1]; } -- (void) openURLCancelEndSheet: (id) sender +- (void)openURLCancelEndSheet:(id)sender { - [self.window orderOut: sender]; - [NSApp endSheet: self.window returnCode: 0]; + [self.window orderOut:sender]; + [NSApp endSheet:self.window returnCode:0]; } -- (NSString *) urlString +- (NSString*)urlString { return fTextField.stringValue; } -- (void) controlTextDidChange: (NSNotification *) notification +- (void)controlTextDidChange:(NSNotification*)notification { - [self updateOpenButtonForURL: fTextField.stringValue]; + [self updateOpenButtonForURL:fTextField.stringValue]; } @end @implementation URLSheetWindowController (Private) -- (void) updateOpenButtonForURL: (NSString *) string +- (void)updateOpenButtonForURL:(NSString*)string { BOOL enable = YES; - if ([string isEqualToString: @""]) + if ([string isEqualToString:@""]) + { enable = NO; + } else { - NSRange prefixRange = [string rangeOfString: @"://"]; + NSRange prefixRange = [string rangeOfString:@"://"]; if (prefixRange.location != NSNotFound && string.length == NSMaxRange(prefixRange)) + { enable = NO; + } } fOpenButton.enabled = enable; diff --git a/macosx/WebSeedTableView.h b/macosx/WebSeedTableView.h index a6c47931d..a7570ca04 100644 --- a/macosx/WebSeedTableView.h +++ b/macosx/WebSeedTableView.h @@ -25,11 +25,11 @@ @interface WebSeedTableView : NSTableView { //weak references - NSArray * fWebSeeds; + NSArray* fWebSeeds; } -- (void) setWebSeeds: (NSArray *) webSeeds; +- (void)setWebSeeds:(NSArray*)webSeeds; -- (void) copy: (id) sender; +- (void)copy:(id)sender; @end diff --git a/macosx/WebSeedTableView.m b/macosx/WebSeedTableView.m index 0bd58094e..7e7ac464b 100644 --- a/macosx/WebSeedTableView.m +++ b/macosx/WebSeedTableView.m @@ -24,38 +24,40 @@ @implementation WebSeedTableView -- (void) mouseDown: (NSEvent *) event +- (void)mouseDown:(NSEvent*)event { [self.window makeKeyWindow]; - [super mouseDown: event]; + [super mouseDown:event]; } -- (void) setWebSeeds: (NSArray *) webSeeds +- (void)setWebSeeds:(NSArray*)webSeeds { fWebSeeds = webSeeds; } -- (void) copy: (id) sender +- (void)copy:(id)sender { - NSIndexSet * indexes = self.selectedRowIndexes; - NSMutableArray * addresses = [NSMutableArray arrayWithCapacity: indexes.count]; - [fWebSeeds enumerateObjectsAtIndexes: indexes options: 0 usingBlock: ^(NSDictionary * webSeed, NSUInteger idx, BOOL * stop) { - [addresses addObject: webSeed[@"Address"]]; + NSIndexSet* indexes = self.selectedRowIndexes; + NSMutableArray* addresses = [NSMutableArray arrayWithCapacity:indexes.count]; + [fWebSeeds enumerateObjectsAtIndexes:indexes options:0 usingBlock:^(NSDictionary* webSeed, NSUInteger idx, BOOL* stop) { + [addresses addObject:webSeed[@"Address"]]; }]; - NSString * text = [addresses componentsJoinedByString: @"\n"]; + NSString* text = [addresses componentsJoinedByString:@"\n"]; - NSPasteboard * pb = NSPasteboard.generalPasteboard; + NSPasteboard* pb = NSPasteboard.generalPasteboard; [pb clearContents]; - [pb writeObjects: @[text]]; + [pb writeObjects:@[ text ]]; } -- (BOOL) validateMenuItem: (NSMenuItem *) menuItem +- (BOOL)validateMenuItem:(NSMenuItem*)menuItem { - const SEL action = menuItem.action; + SEL const action = menuItem.action; if (action == @selector(copy:)) + { return self.numberOfSelectedRows > 0; + } return YES; } diff --git a/macosx/main.m b/macosx/main.m index d78b13537..bb02c6a12 100644 --- a/macosx/main.m +++ b/macosx/main.m @@ -22,15 +22,15 @@ #import -int main( int argc, char ** argv ) +int main(int argc, char** argv) { - if( argc > 1 && strncmp( argv[1], "-v", 2 ) == 0 ) + if (argc > 1 && strncmp(argv[1], "-v", 2) == 0) { - char * env; - int debug = atoi( &argv[1][2] ); - asprintf( &env, "TR_DEBUG=%d", debug ); - putenv( env ); - free( env ); + char* env; + int debug = atoi(&argv[1][2]); + asprintf(&env, "TR_DEBUG=%d", debug); + putenv(env); + free(env); } - return NSApplicationMain( argc, (const char **) argv ); + return NSApplicationMain(argc, (char const**)argv); } diff --git a/qt/AboutDialog.cc b/qt/AboutDialog.cc index 1013d8339..f28e77b16 100644 --- a/qt/AboutDialog.cc +++ b/qt/AboutDialog.cc @@ -19,8 +19,8 @@ #include "Session.h" #include "Utils.h" -AboutDialog::AboutDialog(Session& session, QWidget* parent) : - BaseDialog(parent) +AboutDialog::AboutDialog(Session& session, QWidget* parent) + : BaseDialog(parent) { ui_.setupUi(this); @@ -29,7 +29,7 @@ AboutDialog::AboutDialog(Session& session, QWidget* parent) : if (session.isServer()) { auto const title = QStringLiteral("Transmission %1") - .arg(QStringLiteral(LONG_VERSION_STRING)); + .arg(QStringLiteral(LONG_VERSION_STRING)); ui_.titleLabel->setText(title); } else @@ -37,11 +37,9 @@ AboutDialog::AboutDialog(Session& session, QWidget* parent) : QString title = QStringLiteral( "
Transmission
"); title += QStringLiteral("
%1: %2
") - .arg(tr("This GUI")) - .arg(QStringLiteral(LONG_VERSION_STRING)); - title += QStringLiteral("
%1: %2
") - .arg(tr("Remote")) - .arg(session.sessionVersion()); + .arg(tr("This GUI")) + .arg(QStringLiteral(LONG_VERSION_STRING)); + title += QStringLiteral("
%1: %2
").arg(tr("Remote")).arg(session.sessionVersion()); ui_.titleLabel->setText(title); } @@ -56,10 +54,12 @@ AboutDialog::AboutDialog(Session& session, QWidget* parent) : void AboutDialog::showCredits() { - QMessageBox::about(this, tr("Credits"), QString::fromUtf8( - "Charles Kerr (Backend; Daemon; GTK+; Qt)\n" - "Mitchell Livingston (OS X)\n" - "Mike Gelfand\n")); + QMessageBox::about( + this, + tr("Credits"), + QString::fromUtf8("Charles Kerr (Backend; Daemon; GTK+; Qt)\n" + "Mitchell Livingston (OS X)\n" + "Mike Gelfand\n")); } void AboutDialog::showLicense() diff --git a/qt/AddData.cc b/qt/AddData.cc index ebf3c7ac9..3f0610602 100644 --- a/qt/AddData.cc +++ b/qt/AddData.cc @@ -36,7 +36,7 @@ QString getNameFromMetainfo(QByteArray const& metainfo) return name; } -} // anonymous namespace +} // namespace int AddData::set(QString const& key) { diff --git a/qt/Application.cc b/qt/Application.cc index b31dd5f33..dae4d4e67 100644 --- a/qt/Application.cc +++ b/qt/Application.cc @@ -44,8 +44,7 @@ namespace { -std::array const Opts = -{ +std::array const Opts = { tr_option{ 'g', "config-dir", "Where to look for configuration files", "g", true, "" }, { 'm', "minimized", "Start minimized in system tray", "m", false, nullptr }, { 'p', "port", "Port to use when connecting to an existing session", "p", true, "" }, @@ -59,7 +58,7 @@ std::array const Opts = char const* getUsage() { return "Usage:\n" - " transmission [OPTIONS...] [torrent files]"; + " transmission [OPTIONS...] [torrent files]"; } enum @@ -84,10 +83,10 @@ bool loadTranslation(QTranslator& translator, QString const& name, QLocale const } // namespace -Application::Application(int& argc, char** argv) : - QApplication(argc, argv), - config_name_{QStringLiteral("transmission")}, - display_name_{QStringLiteral("transmission-qt")} +Application::Application(int& argc, char** argv) + : QApplication(argc, argv) + , config_name_{ QStringLiteral("transmission") } + , display_name_{ QStringLiteral("transmission-qt") } { setApplicationName(config_name_); loadTranslations(); @@ -329,10 +328,15 @@ Application::Application(int& argc, char** argv) : if (!prefs_->getBool(Prefs::USER_HAS_GIVEN_INFORMED_CONSENT)) { - auto* dialog = new QMessageBox(QMessageBox::Information, QString(), - tr("Transmission is a file sharing program."), QMessageBox::Ok | QMessageBox::Cancel, window_.get()); - dialog->setInformativeText(tr("When you run a torrent, its data will be made available to others by means of upload. " - "Any content you share is your sole responsibility.")); + auto* dialog = new QMessageBox( + QMessageBox::Information, + QString(), + tr("Transmission is a file sharing program."), + QMessageBox::Ok | QMessageBox::Cancel, + window_.get()); + dialog->setInformativeText( + tr("When you run a torrent, its data will be made available to others by means of upload. " + "Any content you share is your sole responsibility.")); dialog->button(QMessageBox::Ok)->setText(tr("I &Agree")); dialog->setDefaultButton(QMessageBox::Ok); dialog->setModal(true); @@ -487,8 +491,7 @@ void Application::refreshPref(int key) const case Prefs::DIR_WATCH: case Prefs::DIR_WATCH_ENABLED: - watch_dir_->setPath(prefs_->getString(Prefs::DIR_WATCH), - prefs_->getBool(Prefs::DIR_WATCH_ENABLED)); + watch_dir_->setPath(prefs_->getString(Prefs::DIR_WATCH), prefs_->getBool(Prefs::DIR_WATCH_ENABLED)); break; default: @@ -589,8 +592,11 @@ bool Application::notifyApp(QString const& title, QString const& body) const if (bus.isConnected()) { - QDBusMessage m = - QDBusMessage::createMethodCall(dbus_service_name, dbus_path, dbus_interface_name, QStringLiteral("Notify")); + QDBusMessage m = QDBusMessage::createMethodCall( + dbus_service_name, + dbus_path, + dbus_interface_name, + QStringLiteral("Notify")); QVariantList args; args.append(QStringLiteral("Transmission")); // app_name args.append(0U); // replaces_id @@ -599,7 +605,7 @@ bool Application::notifyApp(QString const& title, QString const& body) const args.append(body); // body args.append(QStringList()); // actions - unused for plain passive popups args.append(QVariantMap({ - std::make_pair(QStringLiteral("category"), QVariant(QStringLiteral("transfer.complete"))) + std::make_pair(QStringLiteral("category"), QVariant(QStringLiteral("transfer.complete"))), })); // hints args.append(static_cast(-1)); // use the default timeout period m.setArguments(args); diff --git a/qt/Application.h b/qt/Application.h index 36494f6e5..cf6f32e82 100644 --- a/qt/Application.h +++ b/qt/Application.h @@ -39,7 +39,11 @@ public: void raise() const; bool notifyApp(QString const& title, QString const& body) const; - QString const& intern(QString const& in) { return *interned_strings_.insert(in).first; } + QString const& intern(QString const& in) + { + return *interned_strings_.insert(in).first; + } + FaviconCache& faviconCache(); public slots: diff --git a/qt/BaseDialog.h b/qt/BaseDialog.h index 30c1e65bf..17ef3bcfe 100644 --- a/qt/BaseDialog.h +++ b/qt/BaseDialog.h @@ -13,8 +13,8 @@ class BaseDialog : public QDialog { public: - BaseDialog(QWidget* parent = nullptr, Qt::WindowFlags flags = {}) : - QDialog(parent, flags) + BaseDialog(QWidget* parent = nullptr, Qt::WindowFlags flags = {}) + : QDialog(parent, flags) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); } diff --git a/qt/ColumnResizer.cc b/qt/ColumnResizer.cc index 76bcc322c..f7791ed20 100644 --- a/qt/ColumnResizer.cc +++ b/qt/ColumnResizer.cc @@ -36,8 +36,8 @@ int itemColumnSpan(QGridLayout const* layout, QLayoutItem const* item) } // namespace -ColumnResizer::ColumnResizer(QObject* parent) : - QObject(parent) +ColumnResizer::ColumnResizer(QObject* parent) + : QObject(parent) { timer_.setSingleShot(true); connect(&timer_, &QTimer::timeout, this, &ColumnResizer::update); diff --git a/qt/ComInteropHelper.cc b/qt/ComInteropHelper.cc index b78513182..ea6bff4d8 100644 --- a/qt/ComInteropHelper.cc +++ b/qt/ComInteropHelper.cc @@ -27,8 +27,8 @@ extern bool qAxOutProcServer; // NOLINT extern wchar_t qAxModuleFilename[MAX_PATH]; // NOLINT extern QString qAxInit(); // NOLINT -ComInteropHelper::ComInteropHelper() : - client_(new QAxObject(QStringLiteral("Transmission.QtClient"))) +ComInteropHelper::ComInteropHelper() + : client_(new QAxObject(QStringLiteral("Transmission.QtClient"))) { } diff --git a/qt/DBusInteropHelper.cc b/qt/DBusInteropHelper.cc index 57459039d..5791addf0 100644 --- a/qt/DBusInteropHelper.cc +++ b/qt/DBusInteropHelper.cc @@ -27,8 +27,7 @@ QVariant DBusInteropHelper::addMetainfo(QString const& metainfo) const QStringLiteral("com.transmissionbt.Transmission"), QStringLiteral("/com/transmissionbt/Transmission"), QStringLiteral("com.transmissionbt.Transmission"), - QStringLiteral("AddMetainfo") - ); + QStringLiteral("AddMetainfo")); request.setArguments(QVariantList() << metainfo); QDBusReply const response = QDBusConnection::sessionBus().call(request); diff --git a/qt/DetailsDialog.cc b/qt/DetailsDialog.cc index 2c37e2a12..929cf0f08 100644 --- a/qt/DetailsDialog.cc +++ b/qt/DetailsDialog.cc @@ -91,8 +91,7 @@ QString collateAddress(QString const& 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')); + collated = QStringLiteral("1-") + QString::fromUtf8(QByteArray::number(ipv4_address, 16).rightJustified(8, '0')); } else if (ip_address.protocol() == QAbstractSocket::IPv6Protocol) { @@ -129,8 +128,8 @@ class PeerItem : public QTreeWidgetItem QString status_; public: - explicit PeerItem(Peer p) : - peer_(std::move(p)) + explicit PeerItem(Peer p) + : peer_(std::move(p)) { } @@ -149,7 +148,7 @@ public: status_ = s; } - bool operator <(QTreeWidgetItem const& other) const override + bool operator<(QTreeWidgetItem const& other) const override { auto const* i = dynamic_cast(&other); auto const* tw = treeWidget(); @@ -210,11 +209,11 @@ QIcon DetailsDialog::getStockIcon(QString const& freedesktop_name, int fallback) return icon; } -DetailsDialog::DetailsDialog(Session& session, Prefs& prefs, TorrentModel const& model, QWidget* parent) : - BaseDialog(parent), - session_(session), - prefs_(prefs), - model_(model) +DetailsDialog::DetailsDialog(Session& session, Prefs& prefs, TorrentModel const& model, QWidget* parent) + : BaseDialog(parent) + , session_(session) + , prefs_(prefs) + , model_(model) { ui_.setupUi(this); @@ -227,10 +226,9 @@ DetailsDialog::DetailsDialog(Session& session, Prefs& prefs, TorrentModel const& adjustSize(); ui_.commentBrowser->setMaximumHeight(QWIDGETSIZE_MAX); - static std::array constexpr InitKeys = - { + static std::array constexpr InitKeys = { Prefs::SHOW_TRACKER_SCRAPES, - Prefs::SHOW_BACKUP_TRACKERS + Prefs::SHOW_BACKUP_TRACKERS, }; for (int const key : InitKeys) @@ -308,8 +306,11 @@ void DetailsDialog::onTorrentsEdited(torrent_ids_t const& ids) // 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::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()) @@ -517,10 +518,7 @@ 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(fmt.sizeToString(have_verified)) - .arg(size_when_done_str) - .arg(pct); + string = tr("%1 of %2 (%3%)").arg(fmt.sizeToString(have_verified)).arg(size_when_done_str).arg(pct); } else { @@ -530,10 +528,10 @@ void DetailsDialog::refreshUI() //: %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(fmt.sizeToString(have_verified + have_unverified)) - .arg(size_when_done_str) - .arg(pct) - .arg(fmt.sizeToString(have_unverified)); + .arg(fmt.sizeToString(have_verified + have_unverified)) + .arg(size_when_done_str) + .arg(pct) + .arg(fmt.sizeToString(have_unverified)); } } @@ -599,9 +597,7 @@ void DetailsDialog::refreshUI() d += t->downloadedEver(); } - string = tr("%1 (Ratio: %2)") - .arg(fmt.sizeToString(u)) - .arg(fmt.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); @@ -775,14 +771,11 @@ void DetailsDialog::refreshUI() } else if (piece_size > 0) { - string = tr("%1 (%Ln pieces @ %2)", "", pieces) - .arg(fmt.sizeToString(size)) - .arg(fmt.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(fmt.sizeToString(size)); + string = tr("%1 (%Ln pieces)", "", pieces).arg(fmt.sizeToString(size)); } } @@ -1154,10 +1147,8 @@ void DetailsDialog::refreshUI() } 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() : 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_DOWN, 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); item->setToolTip(COL_STATUS, code_tip); @@ -1298,8 +1289,8 @@ void DetailsDialog::onTrackerSelectionChanged() void DetailsDialog::onAddTrackerClicked() { bool ok = false; - QString const url = QInputDialog::getText(this, tr("Add URL "), tr("Add tracker announce URL:"), QLineEdit::Normal, - QString(), &ok); + QString const + url = QInputDialog::getText(this, tr("Add URL "), tr("Add tracker announce URL:"), QLineEdit::Normal, QString(), &ok); if (!ok) { @@ -1342,8 +1333,13 @@ void DetailsDialog::onEditTrackerClicked() 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); + QString const newval = QInputDialog::getText( + this, + tr("Edit URL "), + tr("Edit tracker announce URL:"), + QLineEdit::Normal, + tracker_info.st.announce, + &ok); if (!ok) { @@ -1418,8 +1414,8 @@ void DetailsDialog::initOptionsTab() cr->addLayout(ui_.peerConnectionsSectionLayout); cr->update(); - void (QComboBox::* combo_index_changed)(int) = &QComboBox::currentIndexChanged; - void (QSpinBox::* spin_value_changed)(int) = &QSpinBox::valueChanged; + 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); @@ -1440,7 +1436,10 @@ void DetailsDialog::initOptionsTab() void DetailsDialog::initTrackerTab() { - auto deleter = [](QObject* o) { o->deleteLater(); }; + auto deleter = [](QObject* o) + { + o->deleteLater(); + }; // NOLINTNEXTLINE(modernize-make-shared) no custom deleters in make_shared tracker_model_.reset(new TrackerModel, deleter); @@ -1466,7 +1465,9 @@ void DetailsDialog::initTrackerTab() connect(ui_.showBackupTrackersCheck, &QAbstractButton::clicked, this, &DetailsDialog::onShowBackupTrackersToggled); connect(ui_.showTrackerScrapesCheck, &QAbstractButton::clicked, this, &DetailsDialog::onShowTrackerScrapesToggled); connect( - ui_.trackersView->selectionModel(), &QItemSelectionModel::selectionChanged, this, + ui_.trackersView->selectionModel(), + &QItemSelectionModel::selectionChanged, + this, &DetailsDialog::onTrackerSelectionChanged); onTrackerSelectionChanged(); diff --git a/qt/DetailsDialog.h b/qt/DetailsDialog.h index d13b6219e..20202ce2c 100644 --- a/qt/DetailsDialog.h +++ b/qt/DetailsDialog.h @@ -97,7 +97,10 @@ private: until we know the server has processed the request. This keeps the UI from appearing to undo the change if we receive a refresh that was already in-flight _before_ the property was edited. */ - bool canEdit() const { return std::empty(pending_changes_tags_); } + bool canEdit() const + { + return std::empty(pending_changes_tags_); + } std::unordered_set pending_changes_tags_; QMetaObject::Connection pending_changes_connection_; diff --git a/qt/FaviconCache.cc b/qt/FaviconCache.cc index d3d276eb3..333c19946 100644 --- a/qt/FaviconCache.cc +++ b/qt/FaviconCache.cc @@ -20,8 +20,8 @@ **** ***/ -FaviconCache::FaviconCache() : - nam_(new QNetworkAccessManager(this)) +FaviconCache::FaviconCache() + : nam_(new QNetworkAccessManager(this)) { connect(nam_, &QNetworkAccessManager::finished, this, &FaviconCache::onRequestFinished); } @@ -60,7 +60,7 @@ void markUrlAsScraped(QString const& url_str) } } -} // unnamed namespace +} // namespace void FaviconCache::ensureCacheDirHasBeenScanned() { @@ -152,7 +152,7 @@ FaviconCache::Key FaviconCache::add(QString const& url_str) return k_it->second; } - auto const url = QUrl { url_str }; + auto const url = QUrl{ url_str }; auto const key = getKey(url); keys_.insert({ url_str, key }); @@ -163,27 +163,27 @@ FaviconCache::Key FaviconCache::add(QString const& url_str) markUrlAsScraped(url_str); auto const scrape = [this](auto const host) - { - auto const schemes = std::array{ - QStringLiteral("http"), - QStringLiteral("https") - }; - auto const suffixes = std::array{ - QStringLiteral("gif"), - QStringLiteral("ico"), - QStringLiteral("jpg"), - QStringLiteral("png"), - QStringLiteral("svg") - }; - for (auto const& scheme : schemes) - { - for (auto const& suffix : suffixes) - { - auto const path = QStringLiteral("%1://%2/favicon.%3").arg(scheme).arg(host).arg(suffix); - nam_->get(QNetworkRequest(path)); - } - } + { + auto const schemes = std::array{ + QStringLiteral("http"), + QStringLiteral("https"), }; + auto const suffixes = std::array{ + QStringLiteral("gif"), // + QStringLiteral("ico"), // + QStringLiteral("jpg"), // + QStringLiteral("png"), // + QStringLiteral("svg"), // + }; + for (auto const& scheme : schemes) + { + for (auto const& suffix : suffixes) + { + auto const path = QStringLiteral("%1://%2/favicon.%3").arg(scheme).arg(host).arg(suffix); + nam_->get(QNetworkRequest(path)); + } + } + }; // tracker.domain.com auto host = url.host(); diff --git a/qt/FileTreeDelegate.h b/qt/FileTreeDelegate.h index 197fb65f7..71a13fde8 100644 --- a/qt/FileTreeDelegate.h +++ b/qt/FileTreeDelegate.h @@ -18,8 +18,8 @@ class FileTreeDelegate : public QItemDelegate TR_DISABLE_COPY_MOVE(FileTreeDelegate) public: - explicit FileTreeDelegate(QObject* parent = nullptr) : - QItemDelegate(parent) + explicit FileTreeDelegate(QObject* parent = nullptr) + : QItemDelegate(parent) { } diff --git a/qt/FileTreeItem.cc b/qt/FileTreeItem.cc index 18d1338ce..21ce569ae 100644 --- a/qt/FileTreeItem.cc +++ b/qt/FileTreeItem.cc @@ -172,9 +172,7 @@ QVariant FileTreeItem::data(int column, int role) const else { auto const& icon_cache = IconCache::get(); - value = childCount() > 0 ? - icon_cache.folderIcon() : - icon_cache.guessMimeIcon(name(), icon_cache.fileIcon()); + value = childCount() > 0 ? icon_cache.folderIcon() : icon_cache.guessMimeIcon(name(), icon_cache.fileIcon()); } } diff --git a/qt/FileTreeItem.h b/qt/FileTreeItem.h index c52d01d7e..12dc95358 100644 --- a/qt/FileTreeItem.h +++ b/qt/FileTreeItem.h @@ -25,19 +25,17 @@ class FileTreeItem TR_DISABLE_COPY_MOVE(FileTreeItem) public: -/* *INDENT-OFF* */ enum { LOW = (1 << 0), NORMAL = (1 << 1), HIGH = (1 << 2) }; -/* *INDENT-ON* */ - FileTreeItem(QString const& name = QString(), int file_index = -1, uint64_t size = 0) : - name_(name), - total_size_(size), - file_index_(file_index) + FileTreeItem(QString const& name = QString(), int file_index = -1, uint64_t size = 0) + : name_(name) + , total_size_(size) + , file_index_(file_index) { } diff --git a/qt/FileTreeModel.cc b/qt/FileTreeModel.cc index 2a2b56818..796b9a402 100644 --- a/qt/FileTreeModel.cc +++ b/qt/FileTreeModel.cc @@ -20,9 +20,9 @@ namespace class PathIteratorBase { protected: - PathIteratorBase(QString const& path, int slash_index) : - path_(path), - slash_index_(slash_index) + PathIteratorBase(QString const& path, int slash_index) + : path_(path) + , slash_index_(slash_index) { token_.reserve(path.size() / 2); } @@ -39,8 +39,8 @@ QChar const PathIteratorBase::SlashChar = QLatin1Char('/'); class ForwardPathIterator : public PathIteratorBase { public: - explicit ForwardPathIterator(QString const& path) : - PathIteratorBase(path, path.size() - 1) + explicit ForwardPathIterator(QString const& path) + : PathIteratorBase(path, path.size() - 1) { } @@ -62,8 +62,8 @@ public: class BackwardPathIterator : public PathIteratorBase { public: - explicit BackwardPathIterator(QString const& path) : - PathIteratorBase(path, 0) + explicit BackwardPathIterator(QString const& path) + : PathIteratorBase(path, 0) { } @@ -90,10 +90,10 @@ public: } // namespace -FileTreeModel::FileTreeModel(QObject* parent, bool is_editable) : - QAbstractItemModel(parent), - root_item_(new FileTreeItem), - is_editable_(is_editable) +FileTreeModel::FileTreeModel(QObject* parent, bool is_editable) + : QAbstractItemModel(parent) + , root_item_(new FileTreeItem) + , is_editable_(is_editable) { } @@ -270,9 +270,7 @@ QModelIndex FileTreeModel::parent(QModelIndex const& child, int column) const int FileTreeModel::rowCount(QModelIndex const& parent) const { - FileTreeItem const* parent_item = parent.isValid() ? - itemFromIndex(parent) : - root_item_; + FileTreeItem const* parent_item = parent.isValid() ? itemFromIndex(parent) : root_item_; return parent_item->childCount(); } @@ -332,8 +330,14 @@ FileTreeItem* FileTreeModel::findItemForFileIndex(int file_index) const return index_cache_.value(file_index, nullptr); } -void FileTreeModel::addFile(int file_index, QString const& filename, bool wanted, int priority, uint64_t total_size, - uint64_t have, bool update_fields) +void FileTreeModel::addFile( + int file_index, + QString const& filename, + bool wanted, + int priority, + uint64_t total_size, + uint64_t have, + bool update_fields) { FileTreeItem* item; @@ -422,7 +426,10 @@ void FileTreeModel::addFile(int file_index, QString const& filename, bool wanted } } -void FileTreeModel::emitParentsChanged(QModelIndex const& index, int first_column, int last_column, +void FileTreeModel::emitParentsChanged( + QModelIndex const& index, + int first_column, + int last_column, QSet* visited_parent_indices) { assert(first_column <= last_column); diff --git a/qt/FileTreeModel.h b/qt/FileTreeModel.h index 1112eca4b..8a7390c6f 100644 --- a/qt/FileTreeModel.h +++ b/qt/FileTreeModel.h @@ -49,7 +49,13 @@ public: void setEditable(bool editable); void clear(); - void addFile(int index, QString const& filename, bool wanted, int priority, uint64_t size, uint64_t have, + void addFile( + int index, + QString const& filename, + bool wanted, + int priority, + uint64_t size, + uint64_t have, bool torrent_changed); bool openFile(QModelIndex const& index); @@ -81,7 +87,10 @@ signals: private: void clearSubtree(QModelIndex const&); QModelIndex indexOf(FileTreeItem*, int column) const; - void emitParentsChanged(QModelIndex const&, int first_column, int last_column, + void emitParentsChanged( + QModelIndex const&, + int first_column, + int last_column, QSet* visited_parent_indices = nullptr); void emitSubtreeChanged(QModelIndex const&, int first_column, int last_column); FileTreeItem* findItemForFileIndex(int file_index) const; diff --git a/qt/FileTreeView.cc b/qt/FileTreeView.cc index b0187313a..05ec9103a 100644 --- a/qt/FileTreeView.cc +++ b/qt/FileTreeView.cc @@ -31,11 +31,11 @@ char const* const PriorityKey = "priority"; } -FileTreeView::FileTreeView(QWidget* parent, bool is_editable) : - QTreeView(parent), - model_(new FileTreeModel(this, is_editable)), - proxy_(new QSortFilterProxyModel(this)), - delegate_(new FileTreeDelegate(this)) +FileTreeView::FileTreeView(QWidget* parent, bool is_editable) + : QTreeView(parent) + , model_(new FileTreeModel(this, is_editable)) + , proxy_(new QSortFilterProxyModel(this)) + , delegate_(new FileTreeDelegate(this)) { proxy_->setSourceModel(model_); proxy_->setSortRole(FileTreeModel::SortRole); @@ -93,8 +93,8 @@ void FileTreeView::resizeEvent(QResizeEvent* event) case FileTreeModel::COL_SIZE: for (int s = Formatter::get().B; s <= Formatter::get().TB; ++s) { - item_texts << QStringLiteral("999.9 ") + Formatter::get().unitStr(Formatter::MEM, - static_cast(s)); + item_texts + << (QStringLiteral("999.9 ") + Formatter::get().unitStr(Formatter::MEM, static_cast(s))); } break; @@ -108,8 +108,8 @@ void FileTreeView::resizeEvent(QResizeEvent* event) break; case FileTreeModel::COL_PRIORITY: - item_texts << FileTreeItem::tr("Low") << FileTreeItem::tr("Normal") << FileTreeItem::tr("High") << - FileTreeItem::tr("Mixed"); + item_texts << FileTreeItem::tr("Low") << FileTreeItem::tr("Normal") << FileTreeItem::tr("High") + << FileTreeItem::tr("Mixed"); break; } @@ -346,7 +346,8 @@ void FileTreeView::refreshContextMenuActionsSensitivity() uncheck_selected_action_->setEnabled(have_checked); only_check_selected_action_->setEnabled(have_selection); priority_menu_->setEnabled(have_selection); - open_action_->setEnabled(have_single_selection && selected_rows.first().data(FileTreeModel::FileIndexRole).toInt() >= 0 && + open_action_->setEnabled( + have_single_selection && selected_rows.first().data(FileTreeModel::FileIndexRole).toInt() >= 0 && selected_rows.first().data(FileTreeModel::CompleteRole).toBool()); rename_action_->setEnabled(have_single_selection); } diff --git a/qt/FilterBar.cc b/qt/FilterBar.cc index 9a9ab5387..9ca0c0aa9 100644 --- a/qt/FilterBar.cc +++ b/qt/FilterBar.cc @@ -98,8 +98,8 @@ QString getCountString(size_t n) } Torrent::fields_t constexpr TrackerFields = { - uint64_t(1) << Torrent::TRACKER_STATS - }; + uint64_t(1) << Torrent::TRACKER_STATS, +}; auto constexpr ActivityFields = FilterMode::TorrentFields; @@ -109,7 +109,9 @@ void FilterBar::refreshTrackers() { enum { - ROW_TOTALS = 0, ROW_SEPARATOR, ROW_FIRST_TRACKER + ROW_TOTALS = 0, + ROW_SEPARATOR, + ROW_FIRST_TRACKER }; auto torrents_per_tracker = std::unordered_map{}; @@ -128,20 +130,20 @@ void FilterBar::refreshTrackers() item->setData(getCountString(num_trackers), FilterBarComboBox::CountStringRole); auto update_tracker_item = [](QStandardItem* i, auto const& it) - { - auto const& key = it->first; - auto const& display_name = FaviconCache::getDisplayName(key); - auto const& count = it->second; - auto const icon = trApp->faviconCache().find(key); + { + auto const& key = it->first; + auto const& display_name = FaviconCache::getDisplayName(key); + auto const& count = it->second; + auto const icon = trApp->faviconCache().find(key); - i->setData(display_name, Qt::DisplayRole); - i->setData(display_name, TRACKER_ROLE); - i->setData(getCountString(static_cast(count)), FilterBarComboBox::CountStringRole); - i->setData(icon, Qt::DecorationRole); - i->setData(int(count), FilterBarComboBox::CountRole); + i->setData(display_name, Qt::DisplayRole); + i->setData(display_name, TRACKER_ROLE); + i->setData(getCountString(static_cast(count)), FilterBarComboBox::CountStringRole); + i->setData(icon, Qt::DecorationRole); + i->setData(int(count), FilterBarComboBox::CountRole); - return i; - }; + return i; + }; auto new_trackers = std::map(torrents_per_tracker.begin(), torrents_per_tracker.end()); auto old_it = tracker_counts_.cbegin(); @@ -206,12 +208,12 @@ FilterBarComboBox* FilterBar::createTrackerCombo(QStandardItemModel* model) **** ***/ -FilterBar::FilterBar(Prefs& prefs, TorrentModel const& torrents, TorrentFilter const& filter, QWidget* parent) : - QWidget(parent), - prefs_(prefs), - torrents_(torrents), - filter_(filter), - is_bootstrapping_(true) +FilterBar::FilterBar(Prefs& prefs, TorrentModel const& torrents, TorrentFilter const& filter, QWidget* parent) + : QWidget(parent) + , prefs_(prefs) + , torrents_(torrents) + , filter_(filter) + , is_bootstrapping_(true) { auto* h = new QHBoxLayout(this); h->setContentsMargins(3, 3, 3, 3); diff --git a/qt/FilterBar.h b/qt/FilterBar.h index ce63fabdc..57cafa017 100644 --- a/qt/FilterBar.h +++ b/qt/FilterBar.h @@ -72,9 +72,21 @@ private: private slots: void recount(); void recountSoon(Pending const& fields); - void recountActivitySoon() { recountSoon(Pending().set(ACTIVITY)); } - void recountTrackersSoon() { recountSoon(Pending().set(TRACKERS)); } - void recountAllSoon() { recountSoon(Pending().set(ACTIVITY).set(TRACKERS)); } + + void recountActivitySoon() + { + recountSoon(Pending().set(ACTIVITY)); + } + + void recountTrackersSoon() + { + recountSoon(Pending().set(TRACKERS)); + } + + void recountAllSoon() + { + recountSoon(Pending().set(ACTIVITY).set(TRACKERS)); + } void refreshPref(int key); void onActivityIndexChanged(int index); diff --git a/qt/FilterBarComboBox.cc b/qt/FilterBarComboBox.cc index 662790746..c2b532c89 100644 --- a/qt/FilterBarComboBox.cc +++ b/qt/FilterBarComboBox.cc @@ -24,8 +24,8 @@ int getHSpacing(QWidget const* w) } // namespace -FilterBarComboBox::FilterBarComboBox(QWidget* parent) : - QComboBox(parent) +FilterBarComboBox::FilterBarComboBox(QWidget* parent) + : QComboBox(parent) { setSizeAdjustPolicy(QComboBox::AdjustToContents); } @@ -113,8 +113,11 @@ void FilterBarComboBox::paintEvent(QPaintEvent* e) { QPen const pen = painter.pen(); painter.setPen(Utils::getFadedColor(pen.color())); - QRect const text_rect = QStyle::alignedRect(opt.direction, Qt::AlignRight | Qt::AlignVCenter, - QSize(opt.fontMetrics.boundingRect(text).width(), rect.height()), rect); + QRect const text_rect = QStyle::alignedRect( + opt.direction, + Qt::AlignRight | Qt::AlignVCenter, + QSize(opt.fontMetrics.boundingRect(text).width(), rect.height()), + rect); painter.drawText(text_rect, Qt::AlignRight | Qt::AlignVCenter, text); Utils::narrowRect(rect, 0, text_rect.width() + hmargin, opt.direction); painter.setPen(pen); diff --git a/qt/FilterBarComboBoxDelegate.cc b/qt/FilterBarComboBoxDelegate.cc index 95ede247a..f2c0a1535 100644 --- a/qt/FilterBarComboBoxDelegate.cc +++ b/qt/FilterBarComboBoxDelegate.cc @@ -26,9 +26,9 @@ int getHSpacing(QWidget const* w) } // namespace -FilterBarComboBoxDelegate::FilterBarComboBoxDelegate(QObject* parent, QComboBox* combo) : - QItemDelegate(parent), - combo_(combo) +FilterBarComboBoxDelegate::FilterBarComboBoxDelegate(QObject* parent, QComboBox* combo) + : QItemDelegate(parent) + , combo_(combo) { } @@ -69,9 +69,11 @@ void FilterBarComboBoxDelegate::paint(QPainter* painter, QStyleOptionViewItem co { QStyleOptionViewItem disabled_option = option; QPalette::ColorRole const disabled_color_role = (disabled_option.state & QStyle::State_Selected) != 0 ? - QPalette::HighlightedText : QPalette::Text; - disabled_option.palette.setColor(disabled_color_role, Utils::getFadedColor(disabled_option.palette.color( - disabled_color_role))); + QPalette::HighlightedText : + QPalette::Text; + disabled_option.palette.setColor( + disabled_color_role, + Utils::getFadedColor(disabled_option.palette.color(disabled_color_role))); QRect bounding_box = option.rect; @@ -80,7 +82,10 @@ void FilterBarComboBoxDelegate::paint(QPainter* painter, QStyleOptionViewItem co QRect decoration_rect = rect(option, index, Qt::DecorationRole); decoration_rect.setSize(combo_->iconSize()); - decoration_rect = QStyle::alignedRect(option.direction, Qt::AlignLeft | Qt::AlignVCenter, decoration_rect.size(), + decoration_rect = QStyle::alignedRect( + option.direction, + Qt::AlignLeft | Qt::AlignVCenter, + decoration_rect.size(), bounding_box); Utils::narrowRect(bounding_box, decoration_rect.width() + hmargin, 0, option.direction); diff --git a/qt/Filters.h b/qt/Filters.h index 53e3848a0..f295969a7 100644 --- a/qt/Filters.h +++ b/qt/Filters.h @@ -28,8 +28,8 @@ public: NUM_MODES }; - explicit FilterMode(int mode = SHOW_ALL) : - mode_(mode) + explicit FilterMode(int mode = SHOW_ALL) + : mode_(mode) { } @@ -40,16 +40,19 @@ public: /* The Torrent properties that can affect this filter. When one of these changes, it's time to refilter. */ - static Torrent::fields_t constexpr TorrentFields = { - (uint64_t(1) << Torrent::ERROR) | - (uint64_t(1) << Torrent::IS_FINISHED) | - (uint64_t(1) << Torrent::PEERS_GETTING_FROM_US) | - (uint64_t(1) << Torrent::PEERS_SENDING_TO_US) | - (uint64_t(1) << Torrent::STATUS) - }; + static Torrent::fields_t constexpr TorrentFields = // + (uint64_t(1) << Torrent::ERROR) | // + (uint64_t(1) << Torrent::IS_FINISHED) | // + (uint64_t(1) << Torrent::PEERS_GETTING_FROM_US) | // + (uint64_t(1) << Torrent::PEERS_SENDING_TO_US) | // + (uint64_t(1) << Torrent::STATUS); static bool test(Torrent const& tor, int mode); - bool test(Torrent const& tor) const { return test(tor, mode()); } + + bool test(Torrent const& tor) const + { + return test(tor, mode()); + } private: int mode_; @@ -75,8 +78,8 @@ public: NUM_MODES }; - explicit SortMode(int mode = SORT_BY_ID) : - mode_(mode) + explicit SortMode(int mode = SORT_BY_ID) + : mode_(mode) { } diff --git a/qt/Formatter.cc b/qt/Formatter.cc index 0e61316a4..e6cc63139 100644 --- a/qt/Formatter.cc +++ b/qt/Formatter.cc @@ -22,29 +22,32 @@ Formatter& Formatter::get() return singleton; } -Formatter::Formatter() : - UnitStrings{{ - { tr("B/s"), tr("kB/s"), tr("MB/s"), tr("GB/s"), tr("TB/s") }, // SPEED - { tr("B"), tr("kB"), tr("MB"), tr("GB"), tr("TB") }, // SIZE - { tr("B"), tr("KiB"), tr("MiB"), tr("GiB"), tr("TiB") } // MEM - }} +Formatter::Formatter() + : UnitStrings{ { + { tr("B/s"), tr("kB/s"), tr("MB/s"), tr("GB/s"), tr("TB/s") }, // SPEED + { tr("B"), tr("kB"), tr("MB"), tr("GB"), tr("TB") }, // SIZE + { tr("B"), tr("KiB"), tr("MiB"), tr("GiB"), tr("TiB") } // MEM + } } { auto const& speed = UnitStrings[SPEED]; - tr_formatter_speed_init(SpeedBase, + tr_formatter_speed_init( + SpeedBase, speed[KB].toUtf8().constData(), speed[MB].toUtf8().constData(), speed[GB].toUtf8().constData(), speed[TB].toUtf8().constData()); auto const& size = UnitStrings[SIZE]; - tr_formatter_size_init(SizeBase, + tr_formatter_size_init( + SizeBase, size[KB].toUtf8().constData(), size[MB].toUtf8().constData(), size[GB].toUtf8().constData(), size[TB].toUtf8().constData()); auto const& mem = UnitStrings[MEM]; - tr_formatter_mem_init(MemBase, + tr_formatter_mem_init( + MemBase, mem[KB].toUtf8().constData(), mem[MB].toUtf8().constData(), mem[GB].toUtf8().constData(), diff --git a/qt/FreeSpaceLabel.cc b/qt/FreeSpaceLabel.cc index 393eb8597..ade444bbc 100644 --- a/qt/FreeSpaceLabel.cc +++ b/qt/FreeSpaceLabel.cc @@ -27,9 +27,9 @@ int const IntervalMSec = 15000; } // namespace -FreeSpaceLabel::FreeSpaceLabel(QWidget* parent) : - QLabel(parent), - timer_(this) +FreeSpaceLabel::FreeSpaceLabel(QWidget* parent) + : QLabel(parent) + , timer_(this) { timer_.setSingleShot(true); timer_.setInterval(IntervalMSec); @@ -73,12 +73,10 @@ void FreeSpaceLabel::onTimer() auto* q = new RpcQueue(this); - q->add([this, &args]() - { - return session_->exec("free-space", &args); - }); + q->add([this, &args]() { return session_->exec("free-space", &args); }); - q->add([this](RpcResponse const& r) + q->add( + [this](RpcResponse const& r) { // update the label auto const bytes = dictFind(r.args.get(), TR_KEY_size_bytes); diff --git a/qt/FreeSpaceLabel.h b/qt/FreeSpaceLabel.h index 742c60323..17dca47c0 100644 --- a/qt/FreeSpaceLabel.h +++ b/qt/FreeSpaceLabel.h @@ -18,7 +18,7 @@ class Session; extern "C" { -struct tr_variant; + struct tr_variant; } class FreeSpaceLabel : public QLabel diff --git a/qt/IconCache.cc b/qt/IconCache.cc index 7c4dbd87e..80df3a516 100644 --- a/qt/IconCache.cc +++ b/qt/IconCache.cc @@ -140,8 +140,12 @@ void IconCache::addAssociatedFileIcon(QFileInfo const& file_info, unsigned int i SHFILEINFO shell_file_info; - if (::SHGetFileInfoW(filename.data(), FILE_ATTRIBUTE_NORMAL, &shell_file_info, - sizeof(shell_file_info), SHGFI_ICON | icon_size | SHGFI_USEFILEATTRIBUTES) != 0) + if (::SHGetFileInfoW( + filename.data(), + FILE_ATTRIBUTE_NORMAL, + &shell_file_info, + sizeof(shell_file_info), + SHGFI_ICON | icon_size | SHGFI_USEFILEATTRIBUTES) != 0) { if (shell_file_info.hIcon != nullptr) { diff --git a/qt/IconCache.h b/qt/IconCache.h index e4b2bc12a..ceff5525a 100644 --- a/qt/IconCache.h +++ b/qt/IconCache.h @@ -31,8 +31,16 @@ class IconCache public: static IconCache& get(); - QIcon folderIcon() const { return folder_icon_; } - QIcon fileIcon() const { return file_icon_; } + QIcon folderIcon() const + { + return folder_icon_; + } + + QIcon fileIcon() const + { + return file_icon_; + } + QIcon guessMimeIcon(QString const& filename, QIcon fallback = {}) const; QIcon getMimeTypeIcon(QString const& mime_type, bool multifile) const; diff --git a/qt/IconToolButton.cc b/qt/IconToolButton.cc index 8684b6eea..eb8ce1acd 100644 --- a/qt/IconToolButton.cc +++ b/qt/IconToolButton.cc @@ -13,8 +13,8 @@ #include "IconToolButton.h" -IconToolButton::IconToolButton(QWidget* parent) : - QToolButton(parent) +IconToolButton::IconToolButton(QWidget* parent) + : QToolButton(parent) { } diff --git a/qt/InteropObject.cc b/qt/InteropObject.cc index c8d8f0802..918b270fe 100644 --- a/qt/InteropObject.cc +++ b/qt/InteropObject.cc @@ -10,8 +10,8 @@ #include "Application.h" #include "InteropObject.h" -InteropObject::InteropObject(QObject* parent) : - QObject(parent) +InteropObject::InteropObject(QObject* parent) + : QObject(parent) { } diff --git a/qt/LicenseDialog.cc b/qt/LicenseDialog.cc index 5ab6fb15d..9a0b054f9 100644 --- a/qt/LicenseDialog.cc +++ b/qt/LicenseDialog.cc @@ -8,8 +8,8 @@ #include "LicenseDialog.h" -LicenseDialog::LicenseDialog(QWidget* parent) : - BaseDialog(parent) +LicenseDialog::LicenseDialog(QWidget* parent) + : BaseDialog(parent) { ui_.setupUi(this); } diff --git a/qt/Macros.h b/qt/Macros.h index 70a98f3a2..6a08c555f 100644 --- a/qt/Macros.h +++ b/qt/Macros.h @@ -3,15 +3,13 @@ #include #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) -# define TR_DISABLE_MOVE(Class) \ - Q_DISABLE_MOVE(Class) -# define TR_DISABLE_COPY_MOVE(Class) \ - Q_DISABLE_COPY_MOVE(Class) +#define TR_DISABLE_MOVE(Class) Q_DISABLE_MOVE(Class) +#define TR_DISABLE_COPY_MOVE(Class) Q_DISABLE_COPY_MOVE(Class) #else -# define TR_DISABLE_MOVE(Class) \ - Class(Class &&) = delete; \ - Class& operator =(Class &&) = delete; -# define TR_DISABLE_COPY_MOVE(Class) \ +#define TR_DISABLE_MOVE(Class) \ + Class(Class&&) = delete; \ + Class& operator=(Class&&) = delete; +#define TR_DISABLE_COPY_MOVE(Class) \ Q_DISABLE_COPY(Class) \ TR_DISABLE_MOVE(Class) #endif diff --git a/qt/MainWindow.cc b/qt/MainWindow.cc index d8a489cd2..95e781737 100644 --- a/qt/MainWindow.cc +++ b/qt/MainWindow.cc @@ -53,7 +53,7 @@ char const* const PrefVariantsKey = "submenu"; char const* const StatsModeKey = "stats-mode"; char const* const SortModeKey = "sort-mode"; -} +} // namespace /** * This is a proxy-style for that forces it to be always disabled. @@ -63,7 +63,10 @@ char const* const SortModeKey = "sort-mode"; class ListViewProxyStyle : public QProxyStyle { public: - int styleHint(StyleHint hint, QStyleOption const* option = nullptr, QWidget const* widget = nullptr, + int styleHint( + StyleHint hint, + QStyleOption const* option = nullptr, + QWidget const* widget = nullptr, QStyleHintReturn* return_data = nullptr) const override { if (hint == QStyle::SH_ItemView_ActivateItemOnSingleClick) @@ -116,7 +119,10 @@ QIcon MainWindow::addEmblem(QIcon base_icon, QStringList const& emblem_names) co for (QSize const& size : base_icon.availableSizes()) { QSize const emblem_size = size / 2; - QRect const emblem_rect = QStyle::alignedRect(layoutDirection(), Qt::AlignBottom | Qt::AlignRight, emblem_size, + QRect const emblem_rect = QStyle::alignedRect( + layoutDirection(), + Qt::AlignBottom | Qt::AlignRight, + emblem_size, QRect(QPoint(0, 0), size)); QPixmap pixmap = base_icon.pixmap(size); @@ -129,16 +135,16 @@ QIcon MainWindow::addEmblem(QIcon base_icon, QStringList const& emblem_names) co return icon; } -MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool minimized) : - session_(session), - prefs_(prefs), - model_(model), - lvp_style_(std::make_shared()), - filter_model_(prefs), - torrent_delegate_(new TorrentDelegate(this)), - torrent_delegate_min_(new TorrentDelegateMin(this)), - network_timer_(this), - refresh_timer_(this) +MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool minimized) + : session_(session) + , prefs_(prefs) + , model_(model) + , lvp_style_(std::make_shared()) + , filter_model_(prefs) + , torrent_delegate_(new TorrentDelegate(this)) + , torrent_delegate_min_(new TorrentDelegateMin(this)) + , network_timer_(this) + , refresh_timer_(this) { setAcceptDrops(true); @@ -155,8 +161,8 @@ MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool QIcon const icon_pause = getStockIcon(QStringLiteral("media-playback-pause"), QStyle::SP_MediaPause); QIcon const icon_open = getStockIcon(QStringLiteral("document-open"), QStyle::SP_DialogOpenButton); ui_.action_OpenFile->setIcon(icon_open); - ui_.action_AddURL->setIcon(addEmblem(icon_open, - QStringList() << QStringLiteral("emblem-web") << QStringLiteral("applications-internet"))); + ui_.action_AddURL->setIcon( + addEmblem(icon_open, QStringList() << QStringLiteral("emblem-web") << QStringLiteral("applications-internet"))); ui_.action_New->setIcon(getStockIcon(QStringLiteral("document-new"), QStyle::SP_DesktopIcon)); ui_.action_Properties->setIcon(getStockIcon(QStringLiteral("document-properties"), QStyle::SP_DesktopIcon)); ui_.action_OpenFolder->setIcon(getStockIcon(QStringLiteral("folder-open"), QStyle::SP_DirOpenIcon)); @@ -180,9 +186,9 @@ MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool ui_.action_QueueMoveBottom->setIcon(getStockIcon(QStringLiteral("go-bottom"))); auto make_network_pixmap = [this](QString name, QSize size = { 16, 16 }) - { - return getStockIcon(name, QStyle::SP_DriveNetIcon).pixmap(size); - }; + { + return getStockIcon(name, QStyle::SP_DriveNetIcon).pixmap(size); + }; pixmap_network_error_ = make_network_pixmap(QStringLiteral("network-error")); pixmap_network_idle_ = make_network_pixmap(QStringLiteral("network-idle")); pixmap_network_receive_ = make_network_pixmap(QStringLiteral("network-receive")); @@ -226,14 +232,20 @@ MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool connect(ui_.action_DeselectAll, &QAction::triggered, ui_.listView, &QAbstractItemView::clearSelection); connect(ui_.action_Quit, &QAction::triggered, qApp, &QCoreApplication::quit); - auto refresh_action_sensitivity_soon = [this]() { refreshSoon(REFRESH_ACTION_SENSITIVITY); }; + auto refresh_action_sensitivity_soon = [this]() + { + refreshSoon(REFRESH_ACTION_SENSITIVITY); + }; connect(&filter_model_, &TorrentFilter::rowsInserted, this, refresh_action_sensitivity_soon); connect(&filter_model_, &TorrentFilter::rowsRemoved, this, refresh_action_sensitivity_soon); connect(&model_, &TorrentModel::torrentsChanged, this, refresh_action_sensitivity_soon); // torrent view filter_model_.setSourceModel(&model_); - auto refresh_soon_adapter = [this]() { refreshSoon(); }; + auto refresh_soon_adapter = [this]() + { + refreshSoon(); + }; connect(&model_, &TorrentModel::modelReset, this, refresh_soon_adapter); connect(&model_, &TorrentModel::rowsRemoved, this, refresh_soon_adapter); connect(&model_, &TorrentModel::rowsInserted, this, refresh_soon_adapter); @@ -242,8 +254,7 @@ MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool ui_.listView->setModel(&filter_model_); connect(ui_.listView->selectionModel(), &QItemSelectionModel::selectionChanged, refresh_action_sensitivity_soon); - std::array, 9> const sort_modes = - {{ + std::array, 9> const sort_modes = { { { ui_.action_SortByActivity, SortMode::SORT_BY_ACTIVITY }, { ui_.action_SortByAge, SortMode::SORT_BY_AGE }, { ui_.action_SortByETA, SortMode::SORT_BY_ETA }, @@ -252,8 +263,8 @@ MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool { ui_.action_SortByQueue, SortMode::SORT_BY_QUEUE }, { ui_.action_SortByRatio, SortMode::SORT_BY_RATIO }, { ui_.action_SortBySize, SortMode::SORT_BY_SIZE }, - { ui_.action_SortByState, SortMode::SORT_BY_STATE } - }}; + { ui_.action_SortByState, SortMode::SORT_BY_STATE }, + } }; // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) auto* action_group = new QActionGroup(this); @@ -300,38 +311,43 @@ MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool ui_.verticalLayout->insertWidget(0, filter_bar); filter_bar_ = filter_bar; - auto refresh_header_soon = [this]() { refreshSoon(REFRESH_TORRENT_VIEW_HEADER); }; + auto refresh_header_soon = [this]() + { + refreshSoon(REFRESH_TORRENT_VIEW_HEADER); + }; connect(&model_, &TorrentModel::rowsInserted, this, refresh_header_soon); connect(&model_, &TorrentModel::rowsRemoved, this, refresh_header_soon); connect(&filter_model_, &TorrentFilter::rowsInserted, this, refresh_header_soon); connect(&filter_model_, &TorrentFilter::rowsRemoved, this, refresh_header_soon); connect(ui_.listView, &TorrentView::headerDoubleClicked, filter_bar, &FilterBar::clear); - static std::array constexpr InitKeys = - { - Prefs::ALT_SPEED_LIMIT_ENABLED, - Prefs::COMPACT_VIEW, - Prefs::DSPEED, - Prefs::DSPEED_ENABLED, - Prefs::FILTERBAR, - Prefs::MAIN_WINDOW_X, - Prefs::RATIO, - Prefs::RATIO_ENABLED, - Prefs::SHOW_TRAY_ICON, - Prefs::SORT_MODE, - Prefs::SORT_REVERSED, - Prefs::STATUSBAR, - Prefs::STATUSBAR_STATS, - Prefs::TOOLBAR, - Prefs::USPEED, - Prefs::USPEED_ENABLED, + static std::array constexpr InitKeys = { + Prefs::ALT_SPEED_LIMIT_ENABLED, // + Prefs::COMPACT_VIEW, // + Prefs::DSPEED, // + Prefs::DSPEED_ENABLED, // + Prefs::FILTERBAR, // + Prefs::MAIN_WINDOW_X, // + Prefs::RATIO, // + Prefs::RATIO_ENABLED, // + Prefs::SHOW_TRAY_ICON, // + Prefs::SORT_MODE, // + Prefs::SORT_REVERSED, // + Prefs::STATUSBAR, // + Prefs::STATUSBAR_STATS, // + Prefs::TOOLBAR, // + Prefs::USPEED, // + Prefs::USPEED_ENABLED, // }; for (auto const key : InitKeys) { refreshPref(key); } - auto refresh_status_soon = [this]() { refreshSoon(REFRESH_STATUS_BAR); }; + auto refresh_status_soon = [this]() + { + refreshSoon(REFRESH_STATUS_BAR); + }; connect(&session_, &Session::sourceChanged, this, &MainWindow::onSessionSourceChanged); connect(&session_, &Session::statsUpdated, this, refresh_status_soon); connect(&session_, &Session::dataReadProgress, this, &MainWindow::dataReadProgress); @@ -385,8 +401,9 @@ void MainWindow::initStatusBar() { ui_.optionsButton->setMenu(createOptionsMenu()); - int const minimum_speed_width = - ui_.downloadSpeedLabel->fontMetrics().boundingRect(Formatter::get().uploadSpeedToString(Speed::fromKBps(999.99))).width(); + int const minimum_speed_width = ui_.downloadSpeedLabel->fontMetrics() + .boundingRect(Formatter::get().uploadSpeedToString(Speed::fromKBps(999.99))) + .width(); ui_.downloadSpeedLabel->setMinimumWidth(minimum_speed_width); ui_.uploadSpeedLabel->setMinimumWidth(minimum_speed_width); @@ -398,76 +415,87 @@ void MainWindow::initStatusBar() QMenu* MainWindow::createOptionsMenu() { auto const init_speed_sub_menu = [this](QMenu* menu, QAction*& off_action, QAction*& on_action, int pref, int enabled_pref) + { + std::array stock_speeds = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750 }; + int const current_value = prefs_.get(pref); + + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + auto* action_group = new QActionGroup(this); + + off_action = menu->addAction(tr("Unlimited")); + off_action->setCheckable(true); + off_action->setProperty(PrefVariantsKey, QVariantList{ enabled_pref, false }); + action_group->addAction(off_action); + connect(off_action, &QAction::triggered, this, qOverload(&MainWindow::onSetPrefs)); + + on_action = menu->addAction(tr("Limited at %1").arg(Formatter::get().speedToString(Speed::fromKBps(current_value)))); + on_action->setCheckable(true); + on_action->setProperty(PrefVariantsKey, QVariantList{ pref, current_value, enabled_pref, true }); + action_group->addAction(on_action); + connect(on_action, &QAction::triggered, this, qOverload(&MainWindow::onSetPrefs)); + + menu->addSeparator(); + + for (int const i : stock_speeds) { - std::array stock_speeds = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750 }; - int const current_value = prefs_.get(pref); - - // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) - auto* action_group = new QActionGroup(this); - - off_action = menu->addAction(tr("Unlimited")); - off_action->setCheckable(true); - off_action->setProperty(PrefVariantsKey, QVariantList{ enabled_pref, false }); - action_group->addAction(off_action); - connect(off_action, &QAction::triggered, this, qOverload(&MainWindow::onSetPrefs)); - - on_action = - menu->addAction(tr("Limited at %1").arg(Formatter::get().speedToString(Speed::fromKBps(current_value)))); - on_action->setCheckable(true); - on_action->setProperty(PrefVariantsKey, QVariantList{ pref, current_value, enabled_pref, true }); - action_group->addAction(on_action); - connect(on_action, &QAction::triggered, this, qOverload(&MainWindow::onSetPrefs)); - - menu->addSeparator(); - - for (int const i : stock_speeds) - { - QAction* action = menu->addAction(Formatter::get().speedToString(Speed::fromKBps(i))); - action->setProperty(PrefVariantsKey, QVariantList{ pref, i, enabled_pref, true }); - connect(action, &QAction::triggered, this, qOverload<>(&MainWindow::onSetPrefs)); - } - }; + QAction* action = menu->addAction(Formatter::get().speedToString(Speed::fromKBps(i))); + action->setProperty(PrefVariantsKey, QVariantList{ pref, i, enabled_pref, true }); + connect(action, &QAction::triggered, this, qOverload<>(&MainWindow::onSetPrefs)); + } + }; auto const init_seed_ratio_sub_menu = [this](QMenu* menu, QAction*& off_action, QAction*& on_action, int pref, int enabled_pref) + { + std::array stock_ratios = { 0.25, 0.50, 0.75, 1, 1.5, 2, 3 }; + auto const current_value = prefs_.get(pref); + + auto* action_group = new QActionGroup(this); + + off_action = menu->addAction(tr("Seed Forever")); + off_action->setCheckable(true); + off_action->setProperty(PrefVariantsKey, QVariantList{ enabled_pref, false }); + action_group->addAction(off_action); + connect(off_action, &QAction::triggered, this, qOverload(&MainWindow::onSetPrefs)); + + on_action = menu->addAction(tr("Stop at Ratio (%1)").arg(Formatter::get().ratioToString(current_value))); + on_action->setCheckable(true); + on_action->setProperty(PrefVariantsKey, QVariantList{ pref, current_value, enabled_pref, true }); + action_group->addAction(on_action); + connect(on_action, &QAction::triggered, this, qOverload(&MainWindow::onSetPrefs)); + + menu->addSeparator(); + + for (double const i : stock_ratios) { - std::array stock_ratios = { 0.25, 0.50, 0.75, 1, 1.5, 2, 3 }; - auto const current_value = prefs_.get(pref); - - auto* action_group = new QActionGroup(this); - - off_action = menu->addAction(tr("Seed Forever")); - off_action->setCheckable(true); - off_action->setProperty(PrefVariantsKey, QVariantList{ enabled_pref, false }); - action_group->addAction(off_action); - connect(off_action, &QAction::triggered, this, qOverload(&MainWindow::onSetPrefs)); - - on_action = menu->addAction(tr("Stop at Ratio (%1)").arg(Formatter::get().ratioToString(current_value))); - on_action->setCheckable(true); - on_action->setProperty(PrefVariantsKey, QVariantList{ pref, current_value, enabled_pref, true }); - action_group->addAction(on_action); - connect(on_action, &QAction::triggered, this, qOverload(&MainWindow::onSetPrefs)); - - menu->addSeparator(); - - for (double const i : stock_ratios) - { - QAction* action = menu->addAction(Formatter::get().ratioToString(i)); - action->setProperty(PrefVariantsKey, QVariantList{ pref, i, enabled_pref, true }); - connect(action, &QAction::triggered, this, qOverload<>(&MainWindow::onSetPrefs)); - } - }; + QAction* action = menu->addAction(Formatter::get().ratioToString(i)); + action->setProperty(PrefVariantsKey, QVariantList{ pref, i, enabled_pref, true }); + connect(action, &QAction::triggered, this, qOverload<>(&MainWindow::onSetPrefs)); + } + }; auto* menu = new QMenu(this); - init_speed_sub_menu(menu->addMenu(tr("Limit Download Speed")), dlimit_off_action_, dlimit_on_action_, Prefs::DSPEED, + init_speed_sub_menu( + menu->addMenu(tr("Limit Download Speed")), + dlimit_off_action_, + dlimit_on_action_, + Prefs::DSPEED, Prefs::DSPEED_ENABLED); - init_speed_sub_menu(menu->addMenu(tr("Limit Upload Speed")), ulimit_off_action_, ulimit_on_action_, Prefs::USPEED, + init_speed_sub_menu( + menu->addMenu(tr("Limit Upload Speed")), + ulimit_off_action_, + ulimit_on_action_, + Prefs::USPEED, Prefs::USPEED_ENABLED); menu->addSeparator(); - init_seed_ratio_sub_menu(menu->addMenu(tr("Stop Seeding at Ratio")), ratio_off_action_, ratio_on_action_, Prefs::RATIO, + init_seed_ratio_sub_menu( + menu->addMenu(tr("Stop Seeding at Ratio")), + ratio_off_action_, + ratio_on_action_, + Prefs::RATIO, Prefs::RATIO_ENABLED); return menu; @@ -475,8 +503,7 @@ QMenu* MainWindow::createOptionsMenu() QMenu* MainWindow::createStatsModeMenu() { - std::array, 4> stats_modes = - { + std::array, 4> stats_modes = { qMakePair(ui_.action_TotalRatio, total_ratio_stats_mode_name_), qMakePair(ui_.action_TotalTransfer, total_transfer_stats_mode_name_), qMakePair(ui_.action_SessionRatio, session_ratio_stats_mode_name_), @@ -599,8 +626,7 @@ void openSelect(QString const& path) void openSelect(QString const& path) { QStringList script_args; - script_args << QStringLiteral("-e") << - QStringLiteral("tell application \"Finder\" to reveal POSIX file \"%1\"").arg(path); + script_args << QStringLiteral("-e") << QStringLiteral("tell application \"Finder\" to reveal POSIX file \"%1\"").arg(path); QProcess::execute(QStringLiteral("/usr/bin/osascript"), script_args); script_args.clear(); @@ -681,8 +707,8 @@ void MainWindow::openAbout() void MainWindow::openHelp() const { - QDesktopServices::openUrl(QUrl(QStringLiteral("https://transmissionbt.com/help/gtk/%1.%2x").arg(MAJOR_VERSION). - arg(MINOR_VERSION / 10))); + QDesktopServices::openUrl( + QUrl(QStringLiteral("https://transmissionbt.com/help/gtk/%1.%2x").arg(MAJOR_VERSION).arg(MINOR_VERSION / 10))); } /**** @@ -782,8 +808,7 @@ void MainWindow::refreshTrayIcon(TransferStats const& stats) else if (stats.peers_sending != 0) { tip = Formatter::get().downloadSpeedToString(stats.speed_down) + QStringLiteral(" ") + - Formatter::get().uploadSpeedToString( - stats.speed_up); + Formatter::get().uploadSpeedToString(stats.speed_up); } else if (stats.peers_receiving != 0) { @@ -804,32 +829,26 @@ void MainWindow::refreshStatusBar(TransferStats const& stats) ui_.networkLabel->setVisible(!session_.isServer()); auto const mode = prefs_.getString(Prefs::STATUSBAR_STATS); - auto str = QString {}; + auto str = QString{}; if (mode == session_ratio_stats_mode_name_) { - str = tr("Ratio: %1") - .arg(fmt.ratioToString(session_.getStats().ratio)); + str = tr("Ratio: %1").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(fmt.sizeToString(st.downloadedBytes)) - .arg(fmt.sizeToString(st.uploadedBytes)); + str = tr("Down: %1, Up: %2").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(fmt.sizeToString(st.downloadedBytes)) - .arg(fmt.sizeToString(st.uploadedBytes)); + str = tr("Down: %1, Up: %2").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(fmt.ratioToString(session_.getCumulativeStats().ratio)); + str = tr("Ratio: %1").arg(fmt.ratioToString(session_.getCumulativeStats().ratio)); } ui_.statsLabel->setText(str); @@ -891,7 +910,10 @@ void MainWindow::refreshActionSensitivity() } auto const& torrents = model_.torrents(); - auto const is_paused = [](auto const* tor) { return tor->isPaused(); }; + auto const is_paused = [](auto const* tor) + { + return tor->isPaused(); + }; auto const any_paused = std::any_of(std::begin(torrents), std::end(torrents), is_paused); auto const any_not_paused = !std::all_of(std::begin(torrents), std::end(torrents), is_paused); @@ -1145,8 +1167,8 @@ void MainWindow::refreshPref(int key) break; case Prefs::DSPEED: - dlimit_on_action_->setText(tr("Limited at %1").arg(Formatter::get().speedToString(Speed::fromKBps(prefs_.get( - key))))); + dlimit_on_action_->setText( + tr("Limited at %1").arg(Formatter::get().speedToString(Speed::fromKBps(prefs_.get(key))))); break; case Prefs::USPEED_ENABLED: @@ -1154,8 +1176,8 @@ void MainWindow::refreshPref(int key) break; case Prefs::USPEED: - ulimit_on_action_->setText(tr("Limited at %1").arg(Formatter::get().speedToString(Speed::fromKBps(prefs_.get( - key))))); + ulimit_on_action_->setText( + tr("Limited at %1").arg(Formatter::get().speedToString(Speed::fromKBps(prefs_.get(key))))); break; case Prefs::RATIO_ENABLED: @@ -1222,8 +1244,11 @@ void MainWindow::refreshPref(int key) case Prefs::MAIN_WINDOW_Y: case Prefs::MAIN_WINDOW_WIDTH: case Prefs::MAIN_WINDOW_HEIGHT: - setGeometry(prefs_.getInt(Prefs::MAIN_WINDOW_X), prefs_.getInt(Prefs::MAIN_WINDOW_Y), - prefs_.getInt(Prefs::MAIN_WINDOW_WIDTH), prefs_.getInt(Prefs::MAIN_WINDOW_HEIGHT)); + setGeometry( + prefs_.getInt(Prefs::MAIN_WINDOW_X), + prefs_.getInt(Prefs::MAIN_WINDOW_Y), + prefs_.getInt(Prefs::MAIN_WINDOW_WIDTH), + prefs_.getInt(Prefs::MAIN_WINDOW_HEIGHT)); break; case Prefs::ALT_SPEED_LIMIT_ENABLED: @@ -1234,7 +1259,7 @@ void MainWindow::refreshPref(int key) alt_speed_action_->setChecked(b); ui_.altSpeedButton->setChecked(b); QString const fmt = b ? tr("Click to disable Temporary Speed Limits\n (%1 down, %2 up)") : - tr("Click to enable Temporary Speed Limits\n (%1 down, %2 up)"); + tr("Click to enable Temporary Speed Limits\n (%1 down, %2 up)"); Speed const d = Speed::fromKBps(prefs_.getInt(Prefs::ALT_SPEED_LIMIT_DOWN)); Speed const u = Speed::fromKBps(prefs_.getInt(Prefs::ALT_SPEED_LIMIT_UP)); ui_.altSpeedButton->setToolTip(fmt.arg(Formatter::get().speedToString(d)).arg(Formatter::get().speedToString(u))); @@ -1260,7 +1285,10 @@ void MainWindow::newTorrent() void MainWindow::openTorrent() { QFileDialog* d; - d = new QFileDialog(this, tr("Open Torrent"), prefs_.getString(Prefs::OPEN_DIALOG_FOLDER), + d = new QFileDialog( + this, + tr("Open Torrent"), + prefs_.getString(Prefs::OPEN_DIALOG_FOLDER), tr("Torrent Files (*.torrent);;All Files (*.*)")); d->setFileMode(QFileDialog::ExistingFiles); d->setAttribute(Qt::WA_DeleteOnClose); @@ -1374,7 +1402,7 @@ void MainWindow::removeTorrents(bool const delete_files) else { primary_text = count == 1 ? tr("Delete this torrent's downloaded files?") : - tr("Delete these %Ln torrent(s)' downloaded files?", nullptr, count); + tr("Delete these %Ln torrent(s)' downloaded files?", nullptr, count); } if (incomplete == 0 && connected == 0) @@ -1386,19 +1414,18 @@ void MainWindow::removeTorrents(bool const delete_files) else if (count == incomplete) { secondary_text = count == 1 ? tr("This torrent has not finished downloading.") : - tr("These torrents have not finished downloading."); + tr("These torrents have not finished downloading."); } else if (count == connected) { - secondary_text = count == 1 ? tr("This torrent is connected to peers.") : - tr("These torrents are connected to peers."); + secondary_text = count == 1 ? tr("This torrent is connected to peers.") : tr("These torrents are connected to peers."); } else { if (connected != 0) { secondary_text = connected == 1 ? tr("One of these torrents is connected to peers.") : - tr("Some of these torrents are connected to peers."); + tr("Some of these torrents are connected to peers."); } if (connected != 0 && incomplete != 0) @@ -1409,7 +1436,7 @@ void MainWindow::removeTorrents(bool const delete_files) if (incomplete != 0) { secondary_text += incomplete == 1 ? tr("One of these torrents has not finished downloading.") : - tr("Some of these torrents have not finished downloading."); + tr("Some of these torrents have not finished downloading."); } } diff --git a/qt/MainWindow.h b/qt/MainWindow.h index 72d568b64..a536079a8 100644 --- a/qt/MainWindow.h +++ b/qt/MainWindow.h @@ -45,7 +45,7 @@ class TorrentModel; extern "C" { -struct tr_variant; + struct tr_variant; } class MainWindow : public QMainWindow diff --git a/qt/MakeDialog.cc b/qt/MakeDialog.cc index 7a0728a64..62f52e7b8 100644 --- a/qt/MakeDialog.cc +++ b/qt/MakeDialog.cc @@ -48,10 +48,10 @@ private: } // namespace -MakeProgressDialog::MakeProgressDialog(Session& session, tr_metainfo_builder& builder, QWidget* parent) : - BaseDialog(parent), - session_(session), - builder_(builder) +MakeProgressDialog::MakeProgressDialog(Session& session, tr_metainfo_builder& builder, QWidget* parent) + : BaseDialog(parent) + , session_(session) + , builder_(builder) { ui_.setupUi(this); @@ -68,7 +68,8 @@ void MakeProgressDialog::onButtonBoxClicked(QAbstractButton* button) switch (ui_.dialogButtons->standardButton(button)) { case QDialogButtonBox::Open: - session_.addNewlyCreatedTorrent(QString::fromUtf8(builder_.outputFile), + session_.addNewlyCreatedTorrent( + QString::fromUtf8(builder_.outputFile), QFileInfo(QString::fromUtf8(builder_.top)).dir().path()); break; @@ -113,13 +114,11 @@ void MakeProgressDialog::onProgress() } else if (b.result == TR_MAKEMETA_IO_READ) { - str = tr("Error reading \"%1\": %2").arg(QString::fromUtf8(b.errfile)). - arg(QString::fromUtf8(tr_strerror(b.my_errno))); + str = tr("Error reading \"%1\": %2").arg(QString::fromUtf8(b.errfile)).arg(QString::fromUtf8(tr_strerror(b.my_errno))); } else if (b.result == TR_MAKEMETA_IO_WRITE) { - str = tr("Error writing \"%1\": %2").arg(QString::fromUtf8(b.errfile)). - arg(QString::fromUtf8(tr_strerror(b.my_errno))); + str = tr("Error writing \"%1\": %2").arg(QString::fromUtf8(b.errfile)).arg(QString::fromUtf8(tr_strerror(b.my_errno))); } ui_.progressLabel->setText(str); @@ -178,8 +177,13 @@ void MakeDialog::makeTorrent() } // start making the torrent - tr_makeMetaInfo(builder_.get(), target.toUtf8().constData(), trackers.isEmpty() ? nullptr : trackers.data(), - trackers.size(), comment.isEmpty() ? nullptr : comment.toUtf8().constData(), ui_.privateCheck->isChecked()); + tr_makeMetaInfo( + builder_.get(), + target.toUtf8().constData(), + trackers.isEmpty() ? nullptr : trackers.data(), + trackers.size(), + comment.isEmpty() ? nullptr : comment.toUtf8().constData(), + ui_.privateCheck->isChecked()); // pop up the dialog auto* dialog = new MakeProgressDialog(session_, *builder_, this); @@ -222,19 +226,19 @@ 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(static_cast(builder_->pieceSize))); + .arg(Formatter::get().sizeToString(builder_->totalSize)) + .arg(files) + .arg(pieces) + .arg(Formatter::get().sizeToString(static_cast(builder_->pieceSize))); } ui_.sourceSizeLabel->setText(text); } -MakeDialog::MakeDialog(Session& session, QWidget* parent) : - BaseDialog(parent), - session_(session), - builder_(nullptr, &tr_metaInfoBuilderFree) +MakeDialog::MakeDialog(Session& session, QWidget* parent) + : BaseDialog(parent) + , session_(session) + , builder_(nullptr, &tr_metaInfoBuilderFree) { ui_.setupUi(this); diff --git a/qt/MakeDialog.h b/qt/MakeDialog.h index 134d52ebf..77f6e148d 100644 --- a/qt/MakeDialog.h +++ b/qt/MakeDialog.h @@ -20,7 +20,7 @@ class Session; extern "C" { -struct tr_metainfo_builder; + struct tr_metainfo_builder; } class MakeDialog : public BaseDialog diff --git a/qt/OptionsDialog.cc b/qt/OptionsDialog.cc index 60c641c6a..c6698b299 100644 --- a/qt/OptionsDialog.cc +++ b/qt/OptionsDialog.cc @@ -29,12 +29,12 @@ using ::trqt::variant_helpers::listAdd; **** ***/ -OptionsDialog::OptionsDialog(Session& session, Prefs const& prefs, AddData addme, QWidget* parent) : - BaseDialog(parent), - add_(std::move(addme)), - verify_button_(new QPushButton(tr("&Verify Local Data"), this)), - session_(session), - is_local_(session_.isLocal()) +OptionsDialog::OptionsDialog(Session& session, Prefs const& prefs, AddData addme, QWidget* parent) + : BaseDialog(parent) + , add_(std::move(addme)) + , verify_button_(new QPushButton(tr("&Verify Local Data"), this)) + , session_(session) + , is_local_(session_.isLocal()) { ui_.setupUi(this); diff --git a/qt/OptionsDialog.h b/qt/OptionsDialog.h index fefa38bc0..6aaf28e76 100644 --- a/qt/OptionsDialog.h +++ b/qt/OptionsDialog.h @@ -27,7 +27,7 @@ class Session; extern "C" { -struct tr_variant; + struct tr_variant; } class OptionsDialog : public BaseDialog diff --git a/qt/PathButton.cc b/qt/PathButton.cc index 4a1c0666d..dc3dfea81 100644 --- a/qt/PathButton.cc +++ b/qt/PathButton.cc @@ -18,8 +18,8 @@ #include "PathButton.h" #include "Utils.h" -PathButton::PathButton(QWidget* parent) : - QToolButton(parent) +PathButton::PathButton(QWidget* parent) + : QToolButton(parent) { setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed)); setToolButtonStyle(Qt::ToolButtonTextBesideIcon); diff --git a/qt/Prefs.cc b/qt/Prefs.cc index d46fe8e52..8025b114e 100644 --- a/qt/Prefs.cc +++ b/qt/Prefs.cc @@ -44,17 +44,19 @@ void ensureSoundCommandIsAList(tr_variant* dict) } tr_variantDictRemove(dict, key); - dictAdd(dict, key, std::array{ + dictAdd( + dict, + key, + std::array{ "canberra-gtk-play", - "-i", "complete-download", - "-d", "transmission torrent downloaded" + TR_ARG_TUPLE("-i", "complete-download"), + TR_ARG_TUPLE("-d", "transmission torrent downloaded"), }); } -} // anonymous namespace +} // namespace -std::array const Prefs::Items -{ +std::array const Prefs::Items{ /* gui settings */ PrefItem{ OPTIONS_PROMPT, TR_KEY_show_options_window, QVariant::Bool }, { OPEN_DIALOG_FOLDER, TR_KEY_open_dialog_dir, QVariant::String }, @@ -146,14 +148,13 @@ std::array const Prefs::Items { RPC_WHITELIST, TR_KEY_rpc_whitelist, QVariant::String }, { USPEED_ENABLED, TR_KEY_speed_limit_up_enabled, QVariant::Bool }, { USPEED, TR_KEY_speed_limit_up, QVariant::Int }, - { UPLOAD_SLOTS_PER_TORRENT, TR_KEY_upload_slots_per_torrent, QVariant::Int } + { UPLOAD_SLOTS_PER_TORRENT, TR_KEY_upload_slots_per_torrent, QVariant::Int }, }; namespace { -auto const FilterModes = std::array, FilterMode::NUM_MODES> -{{ +auto const FilterModes = std::array, FilterMode::NUM_MODES>{ { { FilterMode::SHOW_ALL, "show-all" }, { FilterMode::SHOW_ACTIVE, "show-active" }, { FilterMode::SHOW_DOWNLOADING, "show-downloading" }, @@ -161,11 +162,10 @@ auto const FilterModes = std::array, FilterMode { FilterMode::SHOW_PAUSED, "show-paused" }, { FilterMode::SHOW_FINISHED, "show-finished" }, { FilterMode::SHOW_VERIFYING, "show-verifying" }, - { FilterMode::SHOW_ERROR, "show-error" } -}}; + { FilterMode::SHOW_ERROR, "show-error" }, +} }; -auto const SortModes = std::array, SortMode::NUM_MODES> -{{ +auto const SortModes = std::array, SortMode::NUM_MODES>{ { { SortMode::SORT_BY_NAME, "sort-by-name" }, { SortMode::SORT_BY_ACTIVITY, "sort-by-activity" }, { SortMode::SORT_BY_AGE, "sort-by-age" }, @@ -175,13 +175,13 @@ auto const SortModes = std::array, SortMode::NU { SortMode::SORT_BY_RATIO, "sort-by-ratio" }, { SortMode::SORT_BY_SIZE, "sort-by-size" }, { SortMode::SORT_BY_STATE, "sort-by-state" }, - { SortMode::SORT_BY_ID, "sort-by-id" } -}}; + { SortMode::SORT_BY_ID, "sort-by-id" }, +} }; bool isValidUtf8(QByteArray const& byteArray) { auto const* const codec = QTextCodec::codecForName("UTF-8"); - auto state = QTextCodec::ConverterState {}; + auto state = QTextCodec::ConverterState{}; auto const text = codec->toUnicode(byteArray.constData(), byteArray.size(), &state); return state.invalidChars == 0; } @@ -192,8 +192,8 @@ bool isValidUtf8(QByteArray const& byteArray) **** ***/ -Prefs::Prefs(QString config_dir) : - config_dir_(std::move(config_dir)) +Prefs::Prefs(QString config_dir) + : config_dir_(std::move(config_dir)) { static_assert(sizeof(Items) / sizeof(Items[0]) == PREFS_COUNT); @@ -236,7 +236,10 @@ Prefs::Prefs(QString config_dir) : auto const value = getValue(b); if (value) { - auto const test = [&value](auto const& item) { return item.second == *value; }; + auto const test = [&value](auto const& item) + { + return item.second == *value; + }; // NOLINTNEXTLINE(readability-qualified-auto) auto const it = std::find_if(std::cbegin(SortModes), std::cend(SortModes), test); auto const& pair = it == std::end(SortModes) ? SortModes.front() : *it; @@ -250,7 +253,10 @@ Prefs::Prefs(QString config_dir) : auto const value = getValue(b); if (value) { - auto const test = [&value](auto const& item) { return item.second == *value; }; + auto const test = [&value](auto const& item) + { + return item.second == *value; + }; // NOLINTNEXTLINE(readability-qualified-auto) auto const it = std::find_if(std::cbegin(FilterModes), std::cend(FilterModes), test); auto const& pair = it == std::end(FilterModes) ? FilterModes.front() : *it; @@ -343,7 +349,10 @@ Prefs::~Prefs() case CustomVariantType::SortModeType: { auto const mode = val.value().mode(); - auto const test = [&mode](auto const& item) { return item.first == mode; }; + auto const test = [&mode](auto const& item) + { + return item.first == mode; + }; // NOLINTNEXTLINE(readability-qualified-auto) auto const it = std::find_if(std::cbegin(SortModes), std::cend(SortModes), test); auto const& pair = it == std::end(SortModes) ? SortModes.front() : *it; @@ -354,7 +363,10 @@ Prefs::~Prefs() case CustomVariantType::FilterModeType: { auto const mode = val.value().mode(); - auto const test = [&mode](auto const& item) { return item.first == mode; }; + auto const test = [&mode](auto const& item) + { + return item.first == mode; + }; // NOLINTNEXTLINE(readability-qualified-auto) auto const it = std::find_if(std::cbegin(FilterModes), std::cend(FilterModes), test); auto const& pair = it == std::end(FilterModes) ? FilterModes.front() : *it; @@ -411,15 +423,15 @@ Prefs::~Prefs() */ void Prefs::initDefaults(tr_variant* d) const { - auto constexpr FilterMode = std::string_view { "all" }; - auto constexpr SessionHost = std::string_view { "localhost" }; - auto constexpr SessionPassword = std::string_view {}; - auto constexpr SessionUsername = std::string_view {}; - auto constexpr SortMode = std::string_view { "sort-by-name" }; - auto constexpr StatsMode = std::string_view { "total-ratio" }; - auto constexpr WindowLayout = std::string_view { "menu,toolbar,filter,list,statusbar" }; + auto constexpr FilterMode = std::string_view{ "all" }; + auto constexpr SessionHost = std::string_view{ "localhost" }; + auto constexpr SessionPassword = std::string_view{}; + auto constexpr SessionUsername = std::string_view{}; + auto constexpr SortMode = std::string_view{ "sort-by-name" }; + auto constexpr StatsMode = std::string_view{ "total-ratio" }; + auto constexpr WindowLayout = std::string_view{ "menu,toolbar,filter,list,statusbar" }; - auto const download_dir = std::string_view { tr_getDefaultDownloadDir() }; + auto const download_dir = std::string_view{ tr_getDefaultDownloadDir() }; tr_variantDictReserve(d, 38); dictAdd(d, TR_KEY_blocklist_updates_enabled, true); diff --git a/qt/Prefs.h b/qt/Prefs.h index 090d91f65..32b4cbfca 100644 --- a/qt/Prefs.h +++ b/qt/Prefs.h @@ -24,7 +24,7 @@ class QDateTime; extern "C" { -struct tr_variant; + struct tr_variant; } class Prefs : public QObject diff --git a/qt/PrefsDialog.cc b/qt/PrefsDialog.cc index 1418264be..45454dca0 100644 --- a/qt/PrefsDialog.cc +++ b/qt/PrefsDialog.cc @@ -56,8 +56,8 @@ class PreferenceWidget static char const* const PrefKey; public: - explicit PreferenceWidget(QObject* object) : - object_(object) + explicit PreferenceWidget(QObject* object) + : object_(object) { } @@ -361,8 +361,8 @@ void PrefsDialog::initSpeedTab() ui_.altSpeedLimitDaysCombo->addItem(qtDayName(i), qtDayToTrDay(i)); } - ui_.altSpeedLimitDaysCombo->setCurrentIndex(ui_.altSpeedLimitDaysCombo->findData(prefs_.getInt( - Prefs::ALT_SPEED_LIMIT_TIME_DAY))); + ui_.altSpeedLimitDaysCombo->setCurrentIndex( + ui_.altSpeedLimitDaysCombo->findData(prefs_.getInt(Prefs::ALT_SPEED_LIMIT_TIME_DAY))); linkWidgetToPref(ui_.uploadSpeedLimitCheck, Prefs::USPEED_ENABLED); linkWidgetToPref(ui_.uploadSpeedLimitSpin, Prefs::USPEED); @@ -374,8 +374,8 @@ void PrefsDialog::initSpeedTab() linkWidgetToPref(ui_.altSpeedLimitStartTimeEdit, Prefs::ALT_SPEED_LIMIT_TIME_BEGIN); linkWidgetToPref(ui_.altSpeedLimitEndTimeEdit, Prefs::ALT_SPEED_LIMIT_TIME_END); - sched_widgets_ << ui_.altSpeedLimitStartTimeEdit << ui_.altSpeedLimitToLabel << ui_.altSpeedLimitEndTimeEdit << - ui_.altSpeedLimitDaysLabel << ui_.altSpeedLimitDaysCombo; + sched_widgets_ << ui_.altSpeedLimitStartTimeEdit << ui_.altSpeedLimitToLabel << ui_.altSpeedLimitEndTimeEdit + << ui_.altSpeedLimitDaysLabel << ui_.altSpeedLimitDaysCombo; auto* cr = new ColumnResizer(this); cr->addLayout(ui_.speedLimitsSectionLayout); @@ -466,8 +466,12 @@ void PrefsDialog::onBlocklistUpdated(int n) void PrefsDialog::onUpdateBlocklistClicked() { - blocklist_dialog_ = new QMessageBox(QMessageBox::Information, QString(), - tr("Update Blocklist

Getting new blocklist..."), QMessageBox::Close, this); + blocklist_dialog_ = new QMessageBox( + QMessageBox::Information, + QString(), + tr("Update Blocklist

Getting new blocklist..."), + QMessageBox::Close, + this); connect(blocklist_dialog_, &QDialog::rejected, this, &PrefsDialog::onUpdateBlocklistCancelled); connect(&session_, &Session::blocklistUpdated, this, &PrefsDialog::onBlocklistUpdated); blocklist_dialog_->show(); @@ -491,8 +495,8 @@ void PrefsDialog::initPrivacyTab() linkWidgetToPref(ui_.blocklistEdit, Prefs::BLOCKLIST_URL); linkWidgetToPref(ui_.autoUpdateBlocklistCheck, Prefs::BLOCKLIST_UPDATES_ENABLED); - block_widgets_ << ui_.blocklistEdit << ui_.blocklistStatusLabel << ui_.updateBlocklistButton << - ui_.autoUpdateBlocklistCheck; + block_widgets_ << ui_.blocklistEdit << ui_.blocklistStatusLabel << ui_.updateBlocklistButton + << ui_.autoUpdateBlocklistCheck; auto* cr = new ColumnResizer(this); cr->addLayout(ui_.encryptionSectionLayout); @@ -585,8 +589,11 @@ void PrefsDialog::initDownloadingTab() cr->addLayout(ui_.incompleteSectionLayout); cr->update(); - connect(ui_.queueStalledMinutesSpin, qOverload( - &QSpinBox::valueChanged), this, &PrefsDialog::onQueueStalledMinutesChanged); + connect( + ui_.queueStalledMinutesSpin, + qOverload(&QSpinBox::valueChanged), + this, + &PrefsDialog::onQueueStalledMinutesChanged); updateDownloadingWidgetsLocality(); onQueueStalledMinutesChanged(); @@ -596,9 +603,10 @@ void PrefsDialog::updateDownloadingWidgetsLocality() { ui_.watchDirStack->setCurrentWidget(is_local_ ? static_cast(ui_.watchDirButton) : ui_.watchDirEdit); ui_.downloadDirStack->setCurrentWidget(is_local_ ? static_cast(ui_.downloadDirButton) : ui_.downloadDirEdit); - ui_.incompleteDirStack->setCurrentWidget(is_local_ ? static_cast(ui_.incompleteDirButton) : ui_.incompleteDirEdit); - ui_.completionScriptStack->setCurrentWidget(is_local_ ? static_cast(ui_.completionScriptButton) : - ui_.completionScriptEdit); + ui_.incompleteDirStack->setCurrentWidget( + is_local_ ? static_cast(ui_.incompleteDirButton) : ui_.incompleteDirEdit); + ui_.completionScriptStack->setCurrentWidget( + is_local_ ? static_cast(ui_.completionScriptButton) : ui_.completionScriptEdit); ui_.watchDirStack->setFixedHeight(ui_.watchDirStack->currentWidget()->sizeHint().height()); ui_.downloadDirStack->setFixedHeight(ui_.downloadDirStack->currentWidget()->sizeHint().height()); @@ -612,12 +620,12 @@ void PrefsDialog::updateDownloadingWidgetsLocality() **** ***/ -PrefsDialog::PrefsDialog(Session& session, Prefs& prefs, QWidget* parent) : - BaseDialog(parent), - session_(session), - prefs_(prefs), - is_server_(session.isServer()), - is_local_(session_.isLocal()) +PrefsDialog::PrefsDialog(Session& session, Prefs& prefs, QWidget* parent) + : BaseDialog(parent) + , session_(session) + , prefs_(prefs) + , is_server_(session.isServer()) + , is_local_(session_.isLocal()) { ui_.setupUi(this); @@ -631,8 +639,7 @@ PrefsDialog::PrefsDialog(Session& session, Prefs& prefs, QWidget* parent) : connect(&session_, &Session::sessionUpdated, this, &PrefsDialog::sessionUpdated); - static std::array constexpr InitKeys = - { + static std::array constexpr InitKeys = { Prefs::ALT_SPEED_LIMIT_ENABLED, Prefs::ALT_SPEED_LIMIT_TIME_ENABLED, Prefs::BLOCKLIST_ENABLED, @@ -642,7 +649,7 @@ PrefsDialog::PrefsDialog(Session& session, Prefs& prefs, QWidget* parent) : Prefs::INCOMPLETE_DIR, Prefs::INCOMPLETE_DIR_ENABLED, Prefs::RPC_ENABLED, - Prefs::SCRIPT_TORRENT_DONE_FILENAME + Prefs::SCRIPT_TORRENT_DONE_FILENAME, }; for (auto const key : InitKeys) diff --git a/qt/RelocateDialog.cc b/qt/RelocateDialog.cc index 8ecdb8a0b..0acb6cff0 100644 --- a/qt/RelocateDialog.cc +++ b/qt/RelocateDialog.cc @@ -27,10 +27,10 @@ void RelocateDialog::onMoveToggled(bool b) const move_flag = b; } -RelocateDialog::RelocateDialog(Session& session, TorrentModel const& model, torrent_ids_t ids, QWidget* parent) : - BaseDialog(parent), - session_(session), - ids_(std::move(ids)) +RelocateDialog::RelocateDialog(Session& session, TorrentModel const& model, torrent_ids_t ids, QWidget* parent) + : BaseDialog(parent) + , session_(session) + , ids_(std::move(ids)) { ui_.setupUi(this); @@ -93,5 +93,5 @@ RelocateDialog::RelocateDialog(Session& session, TorrentModel const& model, torr QString RelocateDialog::newLocation() const { return ui_.newLocationStack->currentWidget() == ui_.newLocationButton ? ui_.newLocationButton->path() : - ui_.newLocationEdit->text(); + ui_.newLocationEdit->text(); } diff --git a/qt/RpcClient.cc b/qt/RpcClient.cc index 6d0ac183c..0bcb8d731 100644 --- a/qt/RpcClient.cc +++ b/qt/RpcClient.cc @@ -31,8 +31,8 @@ using ::trqt::variant_helpers::variantInit; namespace { -char const constexpr* const RequestDataPropertyKey { "requestData" }; -char const constexpr* const RequestFutureinterfacePropertyKey { "requestReplyFutureInterface" }; +char const constexpr* const RequestDataPropertyKey{ "requestData" }; +char const constexpr* const RequestFutureinterfacePropertyKey{ "requestReplyFutureInterface" }; bool const Verbose = tr_env_key_exists("TR_RPC_VERBOSE"); @@ -49,8 +49,8 @@ TrVariantPtr createVariant() } // namespace -RpcClient::RpcClient(QObject* parent) : - QObject(parent) +RpcClient::RpcClient(QObject* parent) + : QObject(parent) { qRegisterMetaType("TrVariantPtr"); } @@ -132,8 +132,9 @@ void RpcClient::sendNetworkRequest(TrVariantPtr json, QFutureInterfacerawHeaderList()) { @@ -231,8 +233,7 @@ void RpcClient::networkRequestFinished(QNetworkReply* reply) { reply->deleteLater(); - auto promise = reply->property(RequestFutureinterfacePropertyKey). - value>(); + auto promise = reply->property(RequestFutureinterfacePropertyKey).value>(); if (Verbose) { diff --git a/qt/RpcClient.h b/qt/RpcClient.h index 6c68701ed..dac7870ee 100644 --- a/qt/RpcClient.h +++ b/qt/RpcClient.h @@ -35,8 +35,8 @@ Q_DECLARE_METATYPE(TrVariantPtr) extern "C" { -struct evbuffer; -struct tr_session; + struct evbuffer; + struct tr_session; } struct RpcResponse diff --git a/qt/RpcQueue.cc b/qt/RpcQueue.cc index e95658eaf..7aa879d71 100644 --- a/qt/RpcQueue.cc +++ b/qt/RpcQueue.cc @@ -13,9 +13,9 @@ // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) RpcQueue::Tag RpcQueue::next_tag = {}; -RpcQueue::RpcQueue(QObject* parent) : - QObject(parent), - tag_(next_tag++) +RpcQueue::RpcQueue(QObject* parent) + : QObject(parent) + , tag_(next_tag++) { connect(&future_watcher_, &QFutureWatcher::finished, this, &RpcQueue::stepFinished); } diff --git a/qt/RpcQueue.h b/qt/RpcQueue.h index b5e0b9b8c..3999cc6d1 100644 --- a/qt/RpcQueue.h +++ b/qt/RpcQueue.h @@ -51,7 +51,11 @@ public: void run(); using Tag = uint64_t; - Tag tag() const { return tag_; } + + Tag tag() const + { + return tag_; + } private: // Internally queued function. Takes the last response future, makes a @@ -59,84 +63,81 @@ private: using QueuedFunction = std::function; // Internally stored error handler function. Takes the last response future and returns nothing. - using ErrorHandlerFunction = std::function; + using ErrorHandlerFunction = std::function; void runNext(RpcResponseFuture const& response); // These overloads convert various forms of input closures to what we store internally. // normal closure, takes response and returns new future - template, RpcResponseFuture> - >::type* = nullptr> + template< + typename Func, + typename std::enable_if< + std::is_same_v, RpcResponseFuture>>::type* = nullptr> QueuedFunction normalizeFunc(Func const& func) const { return [func](RpcResponseFuture const& r) - { - return func(r.result()); - }; + { + return func(r.result()); + }; } // closure without argument (first step), takes nothing and returns new future - template, RpcResponseFuture> - >::type* = nullptr> + template< + typename Func, + typename std::enable_if, RpcResponseFuture>>::type* = nullptr> QueuedFunction normalizeFunc(Func const& func) const { return [func](RpcResponseFuture const&) - { - return func(); - }; + { + return func(); + }; } // closure without return value ("auxiliary"), takes response and returns nothing -- internally we reuse the last future - template, void> - >::type* = nullptr> + template< + typename Func, + typename std::enable_if, void>>::type* = nullptr> QueuedFunction normalizeFunc(Func const& func) const { return [func](RpcResponseFuture const& r) - { - func(r.result()); - return r; - }; + { + func(r.result()); + return r; + }; } // closure without argument and return value, takes nothing and returns nothing -- next function will also get nothing - template, void> - >::type* = nullptr> + template, void>>::type* = nullptr> QueuedFunction normalizeFunc(Func const& func) const { return [func](RpcResponseFuture const& r) - { - func(); - return r; - }; + { + func(); + return r; + }; } // normal error handler, takes last response - template, void> - >::type* = nullptr> + template< + typename Func, + typename std::enable_if, void>>::type* = nullptr> ErrorHandlerFunction normalizeErrorHandler(Func const& func) const { return [func](RpcResponseFuture const& r) - { - func(r.result()); - }; + { + func(r.result()); + }; } // error handler without an argument, takes nothing - template, void> - >::type* = nullptr> + template, void>>::type* = nullptr> ErrorHandlerFunction normalizeErrorHandler(Func const& func) const { return [func](RpcResponseFuture const&) - { - func(); - }; + { + func(); + }; } Tag const tag_; diff --git a/qt/Session.cc b/qt/Session.cc index 4151b8aea..97f67937c 100644 --- a/qt/Session.cc +++ b/qt/Session.cc @@ -83,12 +83,10 @@ void Session::portTest() { auto* q = new RpcQueue(); - q->add([this]() - { - return exec("port-test", nullptr); - }); + q->add([this]() { return exec("port-test", nullptr); }); - q->add([this](RpcResponse const& r) + q->add( + [this](RpcResponse const& r) { bool is_open = false; @@ -109,7 +107,7 @@ void Session::portTest() void Session::copyMagnetLinkToClipboard(int torrent_id) { - auto constexpr MagnetLinkKey = std::string_view { "magnetLink" }; + auto constexpr MagnetLinkKey = std::string_view{ "magnetLink" }; auto constexpr Fields = std::array{ MagnetLinkKey }; tr_variant args; @@ -119,12 +117,10 @@ void Session::copyMagnetLinkToClipboard(int torrent_id) auto* q = new RpcQueue(); - q->add([this, &args]() - { - return exec(TR_KEY_torrent_get, &args); - }); + q->add([this, &args]() { return exec(TR_KEY_torrent_get, &args); }); - q->add([](RpcResponse const& r) + q->add( + [](RpcResponse const& r) { tr_variant* torrents; @@ -293,9 +289,9 @@ void Session::updatePref(int key) **** ***/ -Session::Session(QString config_dir, Prefs& prefs) : - config_dir_(std::move(config_dir)), - prefs_(prefs) +Session::Session(QString config_dir, Prefs& prefs) + : config_dir_(std::move(config_dir)) + , prefs_(prefs) { stats_ = {}; stats_.ratio = TR_RATIO_NA; @@ -396,7 +392,7 @@ bool Session::isLocal() const void Session::addOptionalIds(tr_variant* args, torrent_ids_t const& ids) const { - auto constexpr RecentlyActiveKey = std::string_view { "recently-active" }; + auto constexpr RecentlyActiveKey = std::string_view{ "recently-active" }; if (&ids == &RecentlyActiveIDs) { @@ -413,14 +409,8 @@ Session::Tag Session::torrentSetImpl(tr_variant* args) auto* const q = new RpcQueue(); auto const tag = q->tag(); - q->add([this, args]() - { - return rpc_.exec(TR_KEY_torrent_set, args); - }); - q->add([this, tag]() - { - emit sessionCalled(tag); - }); + q->add([this, args]() { return rpc_.exec(TR_KEY_torrent_set, args); }); + q->add([this, tag]() { emit sessionCalled(tag); }); q->setTolerateErrors(); q->run(); @@ -504,10 +494,8 @@ void Session::torrentRenamePath(torrent_ids_t const& ids, QString const& oldpath auto* q = new RpcQueue(); - q->add([this, &args]() - { - return exec("torrent-rename-path", &args); - }, + q->add( + [this, &args]() { return exec("torrent-rename-path", &args); }, [](RpcResponse const& r) { auto str = dictFind(r.args.get(), TR_KEY_path); @@ -515,18 +503,20 @@ void Session::torrentRenamePath(torrent_ids_t const& ids, QString const& oldpath str = dictFind(r.args.get(), TR_KEY_name); auto const name = str ? *str : QStringLiteral("(unknown)"); - auto* d = new QMessageBox(QMessageBox::Information, tr("Error Renaming Path"), - tr(R"(

Unable to rename "%1" as "%2": %3.

Please correct the errors and try again.

)"). - arg(path).arg(name).arg(r.result), QMessageBox::Close, + auto* d = new QMessageBox( + QMessageBox::Information, + tr("Error Renaming Path"), + tr(R"(

Unable to rename "%1" as "%2": %3.

Please correct the errors and try again.

)") + .arg(path) + .arg(name) + .arg(r.result), + QMessageBox::Close, QApplication::activeWindow()); QObject::connect(d, &QMessageBox::rejected, d, &QMessageBox::deleteLater); d->show(); }); - q->add([this, ids](RpcResponse const& /*r*/) - { - refreshTorrents(ids, TorrentProperties::Rename); - }); + q->add([this, ids](RpcResponse const& /*r*/) { refreshTorrents(ids, TorrentProperties::Rename); }); q->run(); } @@ -539,14 +529,14 @@ std::vector const& Session::getKeyNames(TorrentProperties prop { // unchanging fields needed by the main window static auto constexpr MainInfoKeys = std::array{ - TR_KEY_addedDate, - TR_KEY_downloadDir, - TR_KEY_file_count, - TR_KEY_hashString, - TR_KEY_name, - TR_KEY_primary_mime_type, - TR_KEY_totalSize, - TR_KEY_trackers, + TR_KEY_addedDate, // + TR_KEY_downloadDir, // + TR_KEY_file_count, // + TR_KEY_hashString, // + TR_KEY_name, // + TR_KEY_primary_mime_type, // + TR_KEY_totalSize, // + TR_KEY_trackers, // }; // changing fields needed by the main window @@ -575,55 +565,55 @@ std::vector const& Session::getKeyNames(TorrentProperties prop TR_KEY_sizeWhenDone, TR_KEY_status, TR_KEY_uploadedEver, - TR_KEY_webseedsSendingToUs + TR_KEY_webseedsSendingToUs, }; // unchanging fields needed by the details dialog static auto constexpr DetailInfoKeys = std::array{ - TR_KEY_comment, - TR_KEY_creator, - TR_KEY_dateCreated, - TR_KEY_files, - TR_KEY_isPrivate, - TR_KEY_pieceCount, - TR_KEY_pieceSize, - TR_KEY_trackers + TR_KEY_comment, // + TR_KEY_creator, // + TR_KEY_dateCreated, // + TR_KEY_files, // + TR_KEY_isPrivate, // + TR_KEY_pieceCount, // + TR_KEY_pieceSize, // + TR_KEY_trackers, // }; // changing fields needed by the details dialog static auto constexpr DetailStatKeys = std::array{ - TR_KEY_activityDate, - TR_KEY_bandwidthPriority, - TR_KEY_corruptEver, - TR_KEY_desiredAvailable, - TR_KEY_downloadedEver, - TR_KEY_downloadLimit, - TR_KEY_downloadLimited, - TR_KEY_fileStats, - TR_KEY_honorsSessionLimits, - TR_KEY_peer_limit, - TR_KEY_peers, - TR_KEY_seedIdleLimit, - TR_KEY_seedIdleMode, - TR_KEY_startDate, - TR_KEY_trackerStats, - TR_KEY_uploadLimit, - TR_KEY_uploadLimited + TR_KEY_activityDate, // + TR_KEY_bandwidthPriority, // + TR_KEY_corruptEver, // + TR_KEY_desiredAvailable, // + TR_KEY_downloadedEver, // + TR_KEY_downloadLimit, // + TR_KEY_downloadLimited, // + TR_KEY_fileStats, // + TR_KEY_honorsSessionLimits, // + TR_KEY_peer_limit, // + TR_KEY_peers, // + TR_KEY_seedIdleLimit, // + TR_KEY_seedIdleMode, // + TR_KEY_startDate, // + TR_KEY_trackerStats, // + TR_KEY_uploadLimit, // + TR_KEY_uploadLimited, // }; // keys needed after renaming a torrent static auto constexpr RenameKeys = std::array{ TR_KEY_fileStats, TR_KEY_files, - TR_KEY_name + TR_KEY_name, }; auto const append = [&names](tr_quark key) - { - size_t len = {}; - char const* str = tr_quark_get_string(key, &len); - names.emplace_back(str, len); - }; + { + size_t len = {}; + char const* str = tr_quark_get_string(key, &len); + names.emplace_back(str, len); + }; switch (props) { @@ -676,14 +666,12 @@ void Session::refreshTorrents(torrent_ids_t const& ids, TorrentProperties props) auto* q = new RpcQueue(); - q->add([this, &args]() - { - return exec(TR_KEY_torrent_get, &args); - }); + q->add([this, &args]() { return exec(TR_KEY_torrent_get, &args); }); bool const all_torrents = ids.empty(); - q->add([this, all_torrents](RpcResponse const& r) + q->add( + [this, all_torrents](RpcResponse const& r) { tr_variant* torrents; @@ -719,15 +707,9 @@ void Session::sendTorrentRequest(std::string_view request, torrent_ids_t const& auto* q = new RpcQueue(); - q->add([this, request, &args]() - { - return exec(request, &args); - }); + q->add([this, request, &args]() { return exec(request, &args); }); - q->add([this, ids]() - { - refreshTorrents(ids, TorrentProperties::MainStats); - }); + q->add([this, ids]() { refreshTorrents(ids, TorrentProperties::MainStats); }); q->run(); } @@ -789,15 +771,9 @@ void Session::refreshSessionStats() { auto* q = new RpcQueue(); - q->add([this]() - { - return exec("session-stats", nullptr); - }); + q->add([this]() { return exec("session-stats", nullptr); }); - q->add([this](RpcResponse const& r) - { - updateStats(r.args.get()); - }); + q->add([this](RpcResponse const& r) { updateStats(r.args.get()); }); q->run(); } @@ -806,15 +782,9 @@ void Session::refreshSessionInfo() { auto* q = new RpcQueue(); - q->add([this]() - { - return exec("session-get", nullptr); - }); + q->add([this]() { return exec("session-get", nullptr); }); - q->add([this](RpcResponse const& r) - { - updateInfo(r.args.get()); - }); + q->add([this](RpcResponse const& r) { updateInfo(r.args.get()); }); q->run(); } @@ -823,12 +793,10 @@ void Session::updateBlocklist() { auto* q = new RpcQueue(); - q->add([this]() - { - return exec("blocklist-update", nullptr); - }); + q->add([this]() { return exec("blocklist-update", nullptr); }); - q->add([this](RpcResponse const& r) + q->add( + [this](RpcResponse const& r) { auto const size = dictFind(r.args.get(), TR_KEY_blocklist_size); if (size) @@ -1086,20 +1054,22 @@ void Session::addTorrent(AddData const& add_me, tr_variant* args, bool trash_ori auto* q = new RpcQueue(); - q->add([this, args]() - { - return exec("torrent-add", args); - }, + q->add( + [this, args]() { return exec("torrent-add", args); }, [add_me](RpcResponse const& r) { - auto* d = new QMessageBox(QMessageBox::Warning, tr("Error Adding Torrent"), - QStringLiteral("

%1

%2

").arg(r.result).arg(add_me.readableName()), QMessageBox::Close, + auto* d = new QMessageBox( + QMessageBox::Warning, + tr("Error Adding Torrent"), + QStringLiteral("

%1

%2

").arg(r.result).arg(add_me.readableName()), + QMessageBox::Close, QApplication::activeWindow()); QObject::connect(d, &QMessageBox::rejected, d, &QMessageBox::deleteLater); d->show(); }); - q->add([this, add_me](RpcResponse const& r) + q->add( + [this, add_me](RpcResponse const& r) { tr_variant* dup; bool session_has_torrent = false; @@ -1128,7 +1098,8 @@ void Session::addTorrent(AddData const& add_me, tr_variant* args, bool trash_ori if (trash_original && add_me.type == AddData::FILENAME) { - q->add([add_me]() + q->add( + [add_me]() { QFile original(add_me.filename); original.setPermissions(QFile::ReadOwner | QFile::WriteOwner); @@ -1147,9 +1118,7 @@ void Session::onDuplicatesTimer() QStringList lines; for (auto it : duplicates) { - lines.push_back(tr("%1 (copy of %2)") - .arg(it.first) - .arg(it.second.left(7))); + lines.push_back(tr("%1 (copy of %2)").arg(it.first).arg(it.second.left(7))); } if (!lines.empty()) diff --git a/qt/Session.h b/qt/Session.h index 28fc46928..0b43a05f1 100644 --- a/qt/Session.h +++ b/qt/Session.h @@ -31,7 +31,7 @@ class Prefs; extern "C" { -struct tr_variant; + struct tr_variant; } class Session : public QObject diff --git a/qt/SessionDialog.cc b/qt/SessionDialog.cc index 4b0931359..574c11ff2 100644 --- a/qt/SessionDialog.cc +++ b/qt/SessionDialog.cc @@ -46,10 +46,10 @@ void SessionDialog::resensitize() const **** ***/ -SessionDialog::SessionDialog(Session& session, Prefs& prefs, QWidget* parent) : - BaseDialog(parent), - session_(session), - prefs_(prefs) +SessionDialog::SessionDialog(Session& session, Prefs& prefs, QWidget* parent) + : BaseDialog(parent) + , session_(session) + , prefs_(prefs) { ui_.setupUi(this); diff --git a/qt/Speed.h b/qt/Speed.h index b586d9ed0..5c02757cb 100644 --- a/qt/Speed.h +++ b/qt/Speed.h @@ -37,35 +37,35 @@ public: bytes_per_second_ = Bps; } - Speed& operator +=(Speed const& that) + Speed& operator+=(Speed const& that) { bytes_per_second_ += that.bytes_per_second_; return *this; } - [[nodiscard]] Speed operator +(Speed const& that) const + [[nodiscard]] Speed operator+(Speed const& that) const { return Speed{ getBps() + that.getBps() }; } - [[nodiscard]] bool operator <(Speed const& that) const + [[nodiscard]] bool operator<(Speed const& that) const { return getBps() < that.getBps(); } - [[nodiscard]] bool operator ==(Speed const& that) const + [[nodiscard]] bool operator==(Speed const& that) const { return getBps() == that.getBps(); } - [[nodiscard]] bool operator !=(Speed const& that) const + [[nodiscard]] bool operator!=(Speed const& that) const { return getBps() != that.getBps(); } private: - explicit Speed(int bytes_per_second) : - bytes_per_second_{bytes_per_second} + explicit Speed(int bytes_per_second) + : bytes_per_second_{ bytes_per_second } { } diff --git a/qt/SqueezeLabel.cc b/qt/SqueezeLabel.cc index e813536dd..ca928af29 100644 --- a/qt/SqueezeLabel.cc +++ b/qt/SqueezeLabel.cc @@ -45,13 +45,13 @@ #include "SqueezeLabel.h" -SqueezeLabel::SqueezeLabel(QString const& text, QWidget* parent) : - QLabel(text, parent) +SqueezeLabel::SqueezeLabel(QString const& text, QWidget* parent) + : QLabel(text, parent) { } -SqueezeLabel::SqueezeLabel(QWidget* parent) : - QLabel(parent) +SqueezeLabel::SqueezeLabel(QWidget* parent) + : QLabel(parent) { } diff --git a/qt/StatsDialog.cc b/qt/StatsDialog.cc index cde28276d..3287429ba 100644 --- a/qt/StatsDialog.cc +++ b/qt/StatsDialog.cc @@ -18,9 +18,9 @@ enum REFRESH_INTERVAL_MSEC = (15 * 1000) }; -StatsDialog::StatsDialog(Session& session, QWidget* parent) : - BaseDialog(parent), - session_(session) +StatsDialog::StatsDialog(Session& session, QWidget* parent) + : BaseDialog(parent) + , session_(session) { ui_.setupUi(this); diff --git a/qt/Torrent.cc b/qt/Torrent.cc index 0fac3438c..e22c0f42c 100644 --- a/qt/Torrent.cc +++ b/qt/Torrent.cc @@ -28,9 +28,9 @@ using ::trqt::variant_helpers::change; -Torrent::Torrent(Prefs const& prefs, int id) : - id_(id), - prefs_(prefs) +Torrent::Torrent(Prefs const& prefs, int id) + : id_(id) + , prefs_(prefs) { } @@ -186,10 +186,11 @@ Torrent::fields_t Torrent::update(tr_quark const* keys, tr_variant const* const* switch (key) { -#define HANDLE_KEY(key, field, bit) case TR_KEY_ ## key: \ - field_changed = change(field ## _, child); \ - changed.set(bit, field_changed); \ - break; +#define HANDLE_KEY(key, field, bit) \ + case TR_KEY_##key: \ + field_changed = change(field##_, child); \ + changed.set(bit, field_changed); \ + break; HANDLE_KEY(activityDate, activity_date, ACTIVITY_DATE) HANDLE_KEY(addedDate, added_date, ADDED_DATE) @@ -246,14 +247,15 @@ Torrent::fields_t Torrent::update(tr_quark const* keys, tr_variant const* const* HANDLE_KEY(webseedsSendingToUs, webseeds_sending_to_us, WEBSEEDS_SENDING_TO_US) #undef HANDLE_KEY -#define HANDLE_KEY(key, field, bit) case TR_KEY_ ## key: \ - field_changed = change(field ## _, child); \ - if (field_changed) \ - { \ - field ## _ = trApp->intern(field ## _); \ - } \ - changed.set(bit, field_changed); \ - break; +#define HANDLE_KEY(key, field, bit) \ + case TR_KEY_##key: \ + field_changed = change(field##_, child); \ + if (field_changed) \ + { \ + field##_ = trApp->intern(field##_); \ + } \ + changed.set(bit, field_changed); \ + break; HANDLE_KEY(comment, comment, COMMENT) HANDLE_KEY(creator, creator, CREATOR) diff --git a/qt/Torrent.h b/qt/Torrent.h index a9ea63570..4ebd9bc53 100644 --- a/qt/Torrent.h +++ b/qt/Torrent.h @@ -36,7 +36,7 @@ class Prefs; extern "C" { -struct tr_variant; + struct tr_variant; } struct Peer @@ -111,7 +111,9 @@ private: std::array data_ = {}; public: - TorrentHash() {} + TorrentHash() + { + } explicit TorrentHash(char const* str) { @@ -123,17 +125,17 @@ public: tr_hex_to_sha1(data_.data(), str.toUtf8().constData()); } - bool operator ==(TorrentHash const& that) const + bool operator==(TorrentHash const& that) const { return data_ == that.data_; } - bool operator !=(TorrentHash const& that) const + bool operator!=(TorrentHash const& that) const { return data_ != that.data_; } - bool operator <(TorrentHash const& that) const + bool operator<(TorrentHash const& that) const { return data_ < that.data_; } diff --git a/qt/TorrentDelegate.cc b/qt/TorrentDelegate.cc index e7a3339d1..082f09fc1 100644 --- a/qt/TorrentDelegate.cc +++ b/qt/TorrentDelegate.cc @@ -50,8 +50,15 @@ public: QRect bar_rect; QRect progress_rect; - ItemLayout(QString name_text, QString status_text, QString progress_text, QIcon const& emblem_icon, QFont const& base_font, - Qt::LayoutDirection direction, QPoint const& top_left, int width); + ItemLayout( + QString name_text, + QString status_text, + QString progress_text, + QIcon const& emblem_icon, + QFont const& base_font, + Qt::LayoutDirection direction, + QPoint const& top_left, + int width); [[nodiscard]] QSize size() const { @@ -80,14 +87,21 @@ private: } }; -ItemLayout::ItemLayout(QString name_text, QString status_text, QString progress_text, QIcon const& emblem_icon, - QFont const& base_font, Qt::LayoutDirection direction, QPoint const& top_left, int width) : - name_text_(std::move(name_text)), - status_text_(std::move(status_text)), - progress_text_(std::move(progress_text)), - name_font(base_font), - status_font(base_font), - progress_font(base_font) +ItemLayout::ItemLayout( + QString name_text, + QString status_text, + QString progress_text, + QIcon const& emblem_icon, + QFont const& base_font, + Qt::LayoutDirection direction, + QPoint const& top_left, + int width) + : name_text_(std::move(name_text)) + , status_text_(std::move(status_text)) + , progress_text_(std::move(progress_text)) + , name_font(base_font) + , status_font(base_font) + , progress_font(base_font) { QStyle const* style = QApplication::style(); int const icon_size(style->pixelMetric(QStyle::PM_LargeIconSize)); @@ -111,16 +125,22 @@ ItemLayout::ItemLayout(QString name_text, QString status_text, QString progress_ status_rect = name_rect.adjusted(0, name_rect.height() + 1, 0, status_size.height() + 1); bar_rect = status_rect.adjusted(0, status_rect.height() + 1, 0, BAR_HEIGHT + 1); progress_rect = bar_rect.adjusted(0, bar_rect.height() + 1, 0, progress_size.height() + 1); - icon_rect = QStyle::alignedRect(direction, Qt::AlignLeft | Qt::AlignVCenter, QSize(icon_size, icon_size), + icon_rect = QStyle::alignedRect( + direction, + Qt::AlignLeft | Qt::AlignVCenter, + QSize(icon_size, icon_size), QRect(top_left, QSize(width, progress_rect.bottom() - name_rect.top()))); - emblem_rect = QStyle::alignedRect(direction, Qt::AlignRight | Qt::AlignBottom, - emblem_icon.actualSize(icon_rect.size() / 2, QIcon::Normal, QIcon::On), icon_rect); + emblem_rect = QStyle::alignedRect( + direction, + Qt::AlignRight | Qt::AlignBottom, + emblem_icon.actualSize(icon_rect.size() / 2, QIcon::Normal, QIcon::On), + icon_rect); } } // namespace -TorrentDelegate::TorrentDelegate(QObject* parent) : - QStyledItemDelegate{parent} +TorrentDelegate::TorrentDelegate(QObject* parent) + : QStyledItemDelegate{ parent } { progress_bar_style_.minimum = 0; progress_bar_style_.maximum = 1000; @@ -151,8 +171,8 @@ QString TorrentDelegate::progressString(Torrent const& tor) { //: 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)); + str = tr("Magnetized transfer - retrieving metadata (%1%)") + .arg(Formatter::get().percentToString(tor.metadataPercentDone() * 100.0)); } else if (!is_done) // downloading { @@ -160,10 +180,10 @@ QString TorrentDelegate::progressString(Torrent const& tor) //: %1 is how much we've got, //: %2 is how much we'll have when done, //: %3 is a percentage of the two - str = - tr("%1 of %2 (%3%)").arg(Formatter::get().sizeToString(have_total)).arg(Formatter::get().sizeToString( - tor.sizeWhenDone())). - arg(Formatter::get().percentToString(tor.percentDone() * 100.0)); + str = tr("%1 of %2 (%3%)") + .arg(Formatter::get().sizeToString(have_total)) + .arg(Formatter::get().sizeToString(tor.sizeWhenDone())) + .arg(Formatter::get().percentToString(tor.percentDone() * 100.0)); } else if (!is_seed) // partial seed { @@ -176,11 +196,13 @@ QString TorrentDelegate::progressString(Torrent const& tor) //: %4 is how much we've uploaded, //: %5 is our upload-to-download ratio, //: %6 is the ratio we want to reach before we stop uploading - str = tr("%1 of %2 (%3%), uploaded %4 (Ratio: %5 Goal: %6)").arg(Formatter::get().sizeToString(have_total)). - arg(Formatter::get().sizeToString(tor.totalSize())). - arg(Formatter::get().percentToString(tor.percentComplete() * 100.0)). - arg(Formatter::get().sizeToString(tor.uploadedEver())).arg(Formatter::get().ratioToString(tor.ratio())). - arg(Formatter::get().ratioToString(seed_ratio)); + str = tr("%1 of %2 (%3%), uploaded %4 (Ratio: %5 Goal: %6)") + .arg(Formatter::get().sizeToString(have_total)) + .arg(Formatter::get().sizeToString(tor.totalSize())) + .arg(Formatter::get().percentToString(tor.percentComplete() * 100.0)) + .arg(Formatter::get().sizeToString(tor.uploadedEver())) + .arg(Formatter::get().ratioToString(tor.ratio())) + .arg(Formatter::get().ratioToString(seed_ratio)); } else { @@ -190,10 +212,12 @@ QString TorrentDelegate::progressString(Torrent const& tor) //: %3 is a percentage of the two, //: %4 is how much we've uploaded, //: %5 is our upload-to-download ratio - str = tr("%1 of %2 (%3%), uploaded %4 (Ratio: %5)").arg(Formatter::get().sizeToString(have_total)). - arg(Formatter::get().sizeToString(tor.totalSize())). - arg(Formatter::get().percentToString(tor.percentComplete() * 100.0)). - arg(Formatter::get().sizeToString(tor.uploadedEver())).arg(Formatter::get().ratioToString(tor.ratio())); + str = tr("%1 of %2 (%3%), uploaded %4 (Ratio: %5)") + .arg(Formatter::get().sizeToString(have_total)) + .arg(Formatter::get().sizeToString(tor.totalSize())) + .arg(Formatter::get().percentToString(tor.percentComplete() * 100.0)) + .arg(Formatter::get().sizeToString(tor.uploadedEver())) + .arg(Formatter::get().ratioToString(tor.ratio())); } } else // seeding @@ -205,9 +229,11 @@ QString TorrentDelegate::progressString(Torrent const& tor) //: %2 is how much we've uploaded, //: %3 is our upload-to-download ratio, //: %4 is the ratio we want to reach before we stop uploading - str = tr("%1, uploaded %2 (Ratio: %3 Goal: %4)").arg(Formatter::get().sizeToString(have_total)). - arg(Formatter::get().sizeToString(tor.uploadedEver())).arg(Formatter::get().ratioToString(tor.ratio())). - arg(Formatter::get().ratioToString(seed_ratio)); + str = tr("%1, uploaded %2 (Ratio: %3 Goal: %4)") + .arg(Formatter::get().sizeToString(have_total)) + .arg(Formatter::get().sizeToString(tor.uploadedEver())) + .arg(Formatter::get().ratioToString(tor.ratio())) + .arg(Formatter::get().ratioToString(seed_ratio)); } else // seeding w/o a ratio { @@ -215,8 +241,10 @@ QString TorrentDelegate::progressString(Torrent const& tor) //: %1 is the torrent's total size, //: %2 is how much we've uploaded, //: %3 is our upload-to-download ratio - str = tr("%1, uploaded %2 (Ratio: %3)").arg(Formatter::get().sizeToString(have_total)). - arg(Formatter::get().sizeToString(tor.uploadedEver())).arg(Formatter::get().ratioToString(tor.ratio())); + str = tr("%1, uploaded %2 (Ratio: %3)") + .arg(Formatter::get().sizeToString(have_total)) + .arg(Formatter::get().sizeToString(tor.uploadedEver())) + .arg(Formatter::get().ratioToString(tor.ratio())); } } @@ -273,8 +301,8 @@ QString TorrentDelegate::shortStatusString(Torrent const& tor) case TR_STATUS_DOWNLOAD: case TR_STATUS_SEED: - str = shortTransferString(tor) + QStringLiteral(" ") + tr("Ratio: %1").arg(Formatter::get().ratioToString( - tor.ratio())); + str = shortTransferString(tor) + QStringLiteral(" ") + + tr("Ratio: %1").arg(Formatter::get().ratioToString(tor.ratio())); break; default: @@ -308,8 +336,8 @@ QString TorrentDelegate::statusString(Torrent const& tor) case TR_STATUS_DOWNLOAD: if (!tor.hasMetadata()) { - str = tr("Downloading metadata from %Ln peer(s) (%1% done)", nullptr, tor.peersWeAreDownloadingFrom()). - arg(Formatter::get().percentToString(100.0 * tor.metadataPercentDone())); + str = tr("Downloading metadata from %Ln peer(s) (%1% done)", nullptr, tor.peersWeAreDownloadingFrom()) + .arg(Formatter::get().percentToString(100.0 * tor.metadataPercentDone())); } else { @@ -323,8 +351,8 @@ QString TorrentDelegate::statusString(Torrent const& tor) else { //: First part of phrase "Downloading from ... of ... connected peer(s) and ... web seed(s)" - str = tr("Downloading from %1 of %Ln connected peer(s)", nullptr, tor.connectedPeersAndWebseeds()). - arg(tor.peersWeAreDownloadingFrom()); + str = tr("Downloading from %1 of %Ln connected peer(s)", nullptr, tor.connectedPeersAndWebseeds()) + .arg(tor.peersWeAreDownloadingFrom()); } if (tor.webseedsWeAreDownloadingFrom()) @@ -344,8 +372,8 @@ QString TorrentDelegate::statusString(Torrent const& tor) } else { - str = tr("Seeding to %1 of %Ln connected peer(s)", nullptr, tor.connectedPeers()). - arg(tor.peersWeAreUploadingTo()); + str = tr("Seeding to %1 of %Ln connected peer(s)", nullptr, tor.connectedPeers()) + .arg(tor.peersWeAreUploadingTo()); } break; @@ -372,9 +400,15 @@ QString TorrentDelegate::statusString(Torrent const& tor) QSize TorrentDelegate::sizeHint(QStyleOptionViewItem const& option, Torrent const& tor) const { auto const m = QSize(margin(*QApplication::style())); - auto const layout = ItemLayout(tor.name(), progressString(tor), statusString(tor), - QIcon(), option.font, option.direction, - QPoint(0, 0), option.rect.width() - m.width() * 2); + auto const layout = ItemLayout( + tor.name(), + progressString(tor), + statusString(tor), + QIcon(), + option.font, + option.direction, + QPoint(0, 0), + option.rect.width() - m.width() * 2); return layout.size() + m * 2; } @@ -430,16 +464,18 @@ void TorrentDelegate::setProgressBarPercentDone(QStyleOptionViewItem const& opti if (tor.isSeeding() && tor.getSeedRatio(seed_ratio_limit)) { auto const seed_rate_ratio = tor.ratio() / seed_ratio_limit; - auto const scaled_progress = - static_cast(seed_rate_ratio * (progress_bar_style_.maximum - progress_bar_style_.minimum)); + auto const scaled_progress = static_cast( + seed_rate_ratio * (progress_bar_style_.maximum - progress_bar_style_.minimum)); progress_bar_style_.progress = progress_bar_style_.minimum + scaled_progress; } else { bool const is_magnet(!tor.hasMetadata()); progress_bar_style_.direction = option.direction; - progress_bar_style_.progress = static_cast(progress_bar_style_.minimum + (is_magnet ? tor.metadataPercentDone() : - tor.percentDone()) * (progress_bar_style_.maximum - progress_bar_style_.minimum)); + progress_bar_style_.progress = static_cast( + progress_bar_style_.minimum + + (is_magnet ? tor.metadataPercentDone() : tor.percentDone()) * + (progress_bar_style_.maximum - progress_bar_style_.minimum)); } } @@ -531,8 +567,15 @@ void TorrentDelegate::drawTorrent(QPainter* painter, QStyleOptionViewItem const& // layout QSize const m(margin(*style)); QRect const content_rect(option.rect.adjusted(m.width(), m.height(), -m.width(), -m.height())); - ItemLayout const layout(tor.name(), progressString(tor), statusString(tor), emblem_icon, option.font, option.direction, - content_rect.topLeft(), content_rect.width()); + ItemLayout const layout( + tor.name(), + progressString(tor), + statusString(tor), + emblem_icon, + option.font, + option.direction, + content_rect.topLeft(), + content_rect.width()); // render if (tor.hasError() && !is_item_selected) diff --git a/qt/TorrentDelegateMin.cc b/qt/TorrentDelegateMin.cc index a958c738a..4c7af012d 100644 --- a/qt/TorrentDelegateMin.cc +++ b/qt/TorrentDelegateMin.cc @@ -58,8 +58,14 @@ public: QRect status_rect; QRect bar_rect; - ItemLayout(QString name_text, QString status_text, QIcon const& emblem_icon, QFont const& base_font, - Qt::LayoutDirection direction, QPoint const& top_left, int width); + ItemLayout( + QString name_text, + QString status_text, + QIcon const& emblem_icon, + QFont const& base_font, + Qt::LayoutDirection direction, + QPoint const& top_left, + int width); [[nodiscard]] QSize size() const { @@ -86,12 +92,18 @@ private: } }; -ItemLayout::ItemLayout(QString name_text, QString status_text, QIcon const& emblem_icon, QFont const& base_font, - Qt::LayoutDirection direction, QPoint const& top_left, int width) : - name_font(base_font), - status_font(base_font), - name_text_(std::move(name_text)), - status_text_(std::move(status_text)) +ItemLayout::ItemLayout( + QString name_text, + QString status_text, + QIcon const& emblem_icon, + QFont const& base_font, + Qt::LayoutDirection direction, + QPoint const& top_left, + int width) + : name_font(base_font) + , status_font(base_font) + , name_text_(std::move(name_text)) + , status_text_(std::move(status_text)) { auto const* style = QApplication::style(); int const icon_size = style->pixelMetric(QStyle::PM_SmallIconSize); @@ -108,19 +120,26 @@ ItemLayout::ItemLayout(QString name_text, QString status_text, QIcon const& embl bar_style.maximum = 100; bar_style.progress = 100; bar_style.textVisible = true; - QSize const bar_size(bar_style.rect.width() * 2 - style->subElementRect(QStyle::SE_ProgressBarGroove, &bar_style).width(), + QSize const bar_size( + bar_style.rect.width() * 2 - style->subElementRect(QStyle::SE_ProgressBarGroove, &bar_style).width(), bar_style.rect.height()); - QRect base_rect(top_left, + QRect base_rect( + top_left, QSize(width, std::max({ icon_size, name_size.height(), status_size.height(), bar_size.height() }))); icon_rect = QStyle::alignedRect(direction, Qt::AlignLeft | Qt::AlignVCenter, QSize(icon_size, icon_size), base_rect); - emblem_rect = QStyle::alignedRect(direction, Qt::AlignRight | Qt::AlignBottom, emblem_icon.actualSize(icon_rect.size() / 2, - QIcon::Normal, QIcon::On), icon_rect); + emblem_rect = QStyle::alignedRect( + direction, + Qt::AlignRight | Qt::AlignBottom, + emblem_icon.actualSize(icon_rect.size() / 2, QIcon::Normal, QIcon::On), + icon_rect); bar_rect = QStyle::alignedRect(direction, Qt::AlignRight | Qt::AlignVCenter, bar_size, base_rect); Utils::narrowRect(base_rect, icon_rect.width() + GUI_PAD, bar_rect.width() + GUI_PAD, direction); - status_rect = QStyle::alignedRect(direction, Qt::AlignRight | Qt::AlignVCenter, QSize(status_size.width(), - base_rect.height()), + status_rect = QStyle::alignedRect( + direction, + Qt::AlignRight | Qt::AlignVCenter, + QSize(status_size.width(), base_rect.height()), base_rect); Utils::narrowRect(base_rect, 0, status_rect.width() + GUI_PAD, direction); name_rect = base_rect; @@ -132,8 +151,14 @@ QSize TorrentDelegateMin::sizeHint(QStyleOptionViewItem const& option, Torrent c { auto const is_magnet = bool(!tor.hasMetadata()); auto const m = QSize(margin(*QApplication::style())); - auto const layout = ItemLayout(is_magnet ? progressString(tor) : tor.name(), shortStatusString(tor), QIcon(), option.font, - option.direction, QPoint(0, 0), option.rect.width() - m.width() * 2); + auto const layout = ItemLayout( + is_magnet ? progressString(tor) : tor.name(), + shortStatusString(tor), + QIcon(), + option.font, + option.direction, + QPoint(0, 0), + option.rect.width() - m.width() * 2); return layout.size() + m * 2; } @@ -226,8 +251,14 @@ void TorrentDelegateMin::drawTorrent(QPainter* painter, QStyleOptionViewItem con // layout QSize const m(margin(*style)); QRect const content_rect(option.rect.adjusted(m.width(), m.height(), -m.width(), -m.height())); - ItemLayout const layout(is_magnet ? progressString(tor) : tor.name(), shortStatusString(tor), emblem_icon, option.font, - option.direction, content_rect.topLeft(), content_rect.width()); + ItemLayout const layout( + is_magnet ? progressString(tor) : tor.name(), + shortStatusString(tor), + emblem_icon, + option.font, + option.direction, + content_rect.topLeft(), + content_rect.width()); // render if (tor.hasError() && !is_item_selected) diff --git a/qt/TorrentDelegateMin.h b/qt/TorrentDelegateMin.h index e6082f260..c5ab38c19 100644 --- a/qt/TorrentDelegateMin.h +++ b/qt/TorrentDelegateMin.h @@ -17,8 +17,8 @@ class TorrentDelegateMin : public TorrentDelegate TR_DISABLE_COPY_MOVE(TorrentDelegateMin) public: - explicit TorrentDelegateMin(QObject* parent = nullptr) : - TorrentDelegate(parent) + explicit TorrentDelegateMin(QObject* parent = nullptr) + : TorrentDelegate(parent) { } diff --git a/qt/TorrentFilter.cc b/qt/TorrentFilter.cc index d67a0cbf3..b91747b7d 100644 --- a/qt/TorrentFilter.cc +++ b/qt/TorrentFilter.cc @@ -16,8 +16,8 @@ #include "TorrentModel.h" #include "Utils.h" -TorrentFilter::TorrentFilter(Prefs const& prefs) : - prefs_(prefs) +TorrentFilter::TorrentFilter(Prefs const& prefs) + : prefs_(prefs) { connect(&prefs_, &Prefs::changed, this, &TorrentFilter::onPrefChanged); connect(&refilter_timer_, &QTimer::timeout, this, &TorrentFilter::refilter); @@ -142,7 +142,8 @@ bool TorrentFilter::lessThan(QModelIndex const& left, QModelIndex const& right) if (val == 0) { - val = compare(a->peersWeAreUploadingTo() + a->webseedsWeAreDownloadingFrom(), + val = compare( + a->peersWeAreUploadingTo() + a->webseedsWeAreDownloadingFrom(), b->peersWeAreUploadingTo() + b->webseedsWeAreDownloadingFrom()); } diff --git a/qt/TorrentModel.cc b/qt/TorrentModel.cc index 3553bebdf..bbcca13c7 100644 --- a/qt/TorrentModel.cc +++ b/qt/TorrentModel.cc @@ -30,17 +30,17 @@ namespace struct TorrentIdLessThan { - bool operator ()(Torrent const* left, Torrent const* right) const + bool operator()(Torrent const* left, Torrent const* right) const { return left->id() < right->id(); } - bool operator ()(int left_id, Torrent const* right) const + bool operator()(int left_id, Torrent const* right) const { return left_id < right->id(); } - bool operator ()(Torrent const* left, int right_id) const + bool operator()(Torrent const* left, int right_id) const { return left->id() < right_id; } @@ -51,7 +51,7 @@ auto getIds(Iter it, Iter end) { torrent_ids_t ids; - for ( ; it != end; ++it) + for (; it != end; ++it) { ids.insert((*it)->id()); } @@ -65,8 +65,8 @@ auto getIds(Iter it, Iter end) **** ***/ -TorrentModel::TorrentModel(Prefs const& prefs) : - prefs_(prefs) +TorrentModel::TorrentModel(Prefs const& prefs) + : prefs_(prefs) { } @@ -162,11 +162,11 @@ void TorrentModel::updateTorrents(tr_variant* torrents, bool is_complete_list) auto const now = time(nullptr); auto const recently_added = [&now](auto const& tor) - { - static auto constexpr MaxAge = 60; - auto const date = tor->dateAdded(); - return (date != 0) && (difftime(now, date) < MaxAge); - }; + { + static auto constexpr MaxAge = 60; + auto const date = tor->dateAdded(); + return (date != 0) && (difftime(now, date) < MaxAge); + }; // build a list of the property keys tr_variant* const first_child = tr_variantListChild(torrents, 0); @@ -482,6 +482,9 @@ void TorrentModel::rowsRemove(torrents_t const& torrents) bool TorrentModel::hasTorrent(TorrentHash const& hash) const { - auto test = [hash](auto const& tor) { return tor->hash() == hash; }; + auto test = [hash](auto const& tor) + { + return tor->hash() == hash; + }; return std::any_of(torrents_.cbegin(), torrents_.cend(), test); } diff --git a/qt/TorrentModel.h b/qt/TorrentModel.h index 0e25ac6ff..f414fd31b 100644 --- a/qt/TorrentModel.h +++ b/qt/TorrentModel.h @@ -23,7 +23,7 @@ class Speed; extern "C" { -struct tr_variant; + struct tr_variant; } class TorrentModel : public QAbstractListModel @@ -47,7 +47,11 @@ public: Torrent const* getTorrentFromId(int id) const; using torrents_t = QVector; - torrents_t const& torrents() const { return torrents_; } + + torrents_t const& torrents() const + { + return torrents_; + } // QAbstractItemModel int rowCount(QModelIndex const& parent = QModelIndex()) const override; diff --git a/qt/TorrentView.cc b/qt/TorrentView.cc index 04909d679..e566ee571 100644 --- a/qt/TorrentView.cc +++ b/qt/TorrentView.cc @@ -15,8 +15,8 @@ class TorrentView::HeaderWidget : public QWidget { public: - explicit HeaderWidget(TorrentView* parent) : - QWidget(parent) + explicit HeaderWidget(TorrentView* parent) + : QWidget(parent) { setFont(QApplication::font("QMiniFont")); } @@ -63,9 +63,9 @@ private: QString text_; }; -TorrentView::TorrentView(QWidget* parent) : - QListView(parent), - header_widget_(new HeaderWidget(this)) +TorrentView::TorrentView(QWidget* parent) + : QListView(parent) + , header_widget_(new HeaderWidget(this)) { } diff --git a/qt/TrackerDelegate.cc b/qt/TrackerDelegate.cc index d9d2285c9..bff600338 100644 --- a/qt/TrackerDelegate.cc +++ b/qt/TrackerDelegate.cc @@ -55,7 +55,11 @@ private: QTextDocument text_document_; }; -ItemLayout::ItemLayout(QString const& text, bool suppress_colors, Qt::LayoutDirection direction, QPoint const& top_left, +ItemLayout::ItemLayout( + QString const& text, + bool suppress_colors, + Qt::LayoutDirection direction, + QPoint const& top_left, int width) { QSize const icon_size = FaviconCache::getIconSize(); @@ -137,12 +141,13 @@ void TrackerDelegate::drawTracker(QPainter* painter, QStyleOptionViewItem const& painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight)); } - tracker_icon.paint(painter, layout.icon_rect, Qt::AlignCenter, is_item_selected ? QIcon::Selected : QIcon::Normal, - QIcon::On); + tracker_icon + .paint(painter, layout.icon_rect, Qt::AlignCenter, is_item_selected ? QIcon::Selected : QIcon::Normal, QIcon::On); QAbstractTextDocumentLayout::PaintContext paint_context; paint_context.clip = layout.text_rect.translated(-layout.text_rect.topLeft()); - paint_context.palette.setColor(QPalette::Text, + paint_context.palette.setColor( + QPalette::Text, option.palette.color(is_item_selected ? QPalette::HighlightedText : QPalette::Text)); painter->translate(layout.text_rect.topLeft()); layout.textLayout()->draw(painter, paint_context); @@ -182,8 +187,14 @@ QString TrackerDelegate::getText(TrackerInfo const& inf) const auto const success_markup_end = QStringLiteral(""); auto const now = time(nullptr); - auto const time_until = [&now](auto t) { return timeToStringRounded(static_cast(t - now)); }; - auto const time_since = [&now](auto t) { return timeToStringRounded(static_cast(now - t)); }; + auto const time_until = [&now](auto t) + { + return timeToStringRounded(static_cast(t - now)); + }; + auto const time_since = [&now](auto t) + { + return timeToStringRounded(static_cast(now - t)); + }; // hostname str += inf.st.is_backup ? QStringLiteral("") : QStringLiteral(""); @@ -208,20 +219,27 @@ QString TrackerDelegate::getText(TrackerInfo const& inf) const if (inf.st.last_announce_succeeded) { //: %1 and %2 are replaced with HTML markup, %3 is duration - str += tr("Got a list of%1 %Ln peer(s)%2 %3 ago", nullptr, inf.st.last_announce_peer_count). - arg(success_markup_begin).arg(success_markup_end).arg(tstr); + str += tr("Got a list of%1 %Ln peer(s)%2 %3 ago", nullptr, inf.st.last_announce_peer_count) + .arg(success_markup_begin) + .arg(success_markup_end) + .arg(tstr); } else if (inf.st.last_announce_timed_out) { //: %1 and %2 are replaced with HTML markup, %3 is duration - str += tr("Peer list request %1timed out%2 %3 ago; will retry").arg(timeout_markup_begin). - arg(timeout_markup_end).arg(tstr); + str += tr("Peer list request %1timed out%2 %3 ago; will retry") + .arg(timeout_markup_begin) + .arg(timeout_markup_end) + .arg(tstr); } else { //: %1 and %3 are replaced with HTML markup, %2 is error message, %4 is duration - str += tr("Got an error %1\"%2\"%3 %4 ago").arg(err_markup_begin).arg(inf.st.last_announce_result). - arg(err_markup_end).arg(tstr); + str += tr("Got an error %1\"%2\"%3 %4 ago") + .arg(err_markup_begin) + .arg(inf.st.last_announce_result) + .arg(err_markup_end) + .arg(tstr); } } @@ -263,26 +281,34 @@ QString TrackerDelegate::getText(TrackerInfo const& inf) const if (!inf.st.last_scrape_succeeded) { //: %1 and %3 are replaced with HTML markup, %2 is error message, %4 is duration - str += tr("Got a scrape error %1\"%2\"%3 %4 ago").arg(err_markup_begin).arg(inf.st.last_scrape_result). - arg(err_markup_end).arg(tstr); + str += tr("Got a scrape error %1\"%2\"%3 %4 ago") + .arg(err_markup_begin) + .arg(inf.st.last_scrape_result) + .arg(err_markup_end) + .arg(tstr); } else if (inf.st.seeder_count >= 0 && inf.st.leecher_count >= 0) { //: 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); + 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", //: %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). - arg(success_markup_end).arg(tstr); + str += tr(" and%1 %Ln leecher(s)%2 %3 ago", nullptr, inf.st.leecher_count) + .arg(success_markup_begin) + .arg(success_markup_end) + .arg(tstr); } else { //: %1 and %2 are replaced with HTML markup, %3 is duration - str += tr("Tracker had %1no information%2 on peer counts %3 ago").arg(success_markup_begin). - arg(success_markup_end).arg(tstr); + str += tr("Tracker had %1no information%2 on peer counts %3 ago") + .arg(success_markup_begin) + .arg(success_markup_end) + .arg(tstr); } } diff --git a/qt/TrackerDelegate.h b/qt/TrackerDelegate.h index a3404b949..ddf0a5588 100644 --- a/qt/TrackerDelegate.h +++ b/qt/TrackerDelegate.h @@ -23,8 +23,8 @@ class TrackerDelegate : public QItemDelegate TR_DISABLE_COPY_MOVE(TrackerDelegate) public: - explicit TrackerDelegate(QObject* parent = nullptr) : - QItemDelegate(parent) + explicit TrackerDelegate(QObject* parent = nullptr) + : QItemDelegate(parent) { } diff --git a/qt/TrackerModel.cc b/qt/TrackerModel.cc index b5172a56d..a67abe36e 100644 --- a/qt/TrackerModel.cc +++ b/qt/TrackerModel.cc @@ -59,7 +59,7 @@ QVariant TrackerModel::data(QModelIndex const& index, int role) const struct CompareTrackers { - bool operator ()(TrackerInfo const& a, TrackerInfo const& b) const + bool operator()(TrackerInfo const& a, TrackerInfo const& b) const { if (a.torrent_id != b.torrent_id) { diff --git a/qt/TrackerModelFilter.cc b/qt/TrackerModelFilter.cc index 6b00f3788..7d838a3df 100644 --- a/qt/TrackerModelFilter.cc +++ b/qt/TrackerModelFilter.cc @@ -9,8 +9,8 @@ #include "TrackerModel.h" #include "TrackerModelFilter.h" -TrackerModelFilter::TrackerModelFilter(QObject* parent) : - QSortFilterProxyModel(parent) +TrackerModelFilter::TrackerModelFilter(QObject* parent) + : QSortFilterProxyModel(parent) { } diff --git a/qt/Utils.cc b/qt/Utils.cc index 457fc13dd..f35387837 100644 --- a/qt/Utils.cc +++ b/qt/Utils.cc @@ -92,8 +92,9 @@ int Utils::measureViewItem(QAbstractItemView const* view, QString const& text) option.textElideMode = Qt::ElideNone; option.font = view->font(); - return view->style()->sizeFromContents(QStyle::CT_ItemViewItem, &option, QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), view). - width(); + return view->style() + ->sizeFromContents(QStyle::CT_ItemViewItem, &option, QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), view) + .width(); } int Utils::measureHeaderItem(QHeaderView const* view, QString const& text) diff --git a/qt/Utils.h b/qt/Utils.h index 4e500e76e..032bac75e 100644 --- a/qt/Utils.h +++ b/qt/Utils.h @@ -30,7 +30,7 @@ namespace std template<> struct hash { - std::size_t operator ()(QString const& s) const + std::size_t operator()(QString const& s) const { return qHash(s); } @@ -107,8 +107,7 @@ public: static bool isUriWithSupportedScheme(QString const& s) { - return s.startsWith(QStringLiteral("ftp://")) || - s.startsWith(QStringLiteral("http://")) || + return s.startsWith(QStringLiteral("ftp://")) || s.startsWith(QStringLiteral("http://")) || s.startsWith(QStringLiteral("https://")); } }; diff --git a/qt/VariantHelpers.cc b/qt/VariantHelpers.cc index 4038df976..5eeef0f90 100644 --- a/qt/VariantHelpers.cc +++ b/qt/VariantHelpers.cc @@ -56,8 +56,10 @@ bool change(Peer& setme, tr_variant const* value) { switch (key) { -#define HANDLE_KEY(key, field) case TR_KEY_ ## key: \ - changed = change(setme.field, child) || changed; break; +#define HANDLE_KEY(key, field) \ + case TR_KEY_##key: \ + changed = change(setme.field, child) || changed; \ + break; HANDLE_KEY(address, address) HANDLE_KEY(clientIsChoked, client_is_choked) @@ -94,15 +96,19 @@ bool change(TorrentFile& setme, tr_variant const* value) { switch (key) { -#define HANDLE_KEY(key) case TR_KEY_ ## key: \ - changed = change(setme.key, child) || changed; break; +#define HANDLE_KEY(key) \ + case TR_KEY_##key: \ + changed = change(setme.key, child) || changed; \ + break; HANDLE_KEY(have) HANDLE_KEY(priority) HANDLE_KEY(wanted) #undef HANDLE_KEY -#define HANDLE_KEY(key, field) case TR_KEY_ ## key: \ - changed = change(setme.field, child) || changed; break; +#define HANDLE_KEY(key, field) \ + case TR_KEY_##key: \ + changed = change(setme.field, child) || changed; \ + break; HANDLE_KEY(bytesCompleted, have) HANDLE_KEY(length, size) @@ -129,8 +135,10 @@ bool change(TrackerStat& setme, tr_variant const* value) switch (key) { -#define HANDLE_KEY(key, field) case TR_KEY_ ## key: \ - field_changed = change(setme.field, child); break; +#define HANDLE_KEY(key, field) \ + case TR_KEY_##key: \ + field_changed = change(setme.field, child); \ + break; HANDLE_KEY(announce, announce) HANDLE_KEY(announceState, announce_state) HANDLE_KEY(downloadCount, download_count) diff --git a/qt/VariantHelpers.h b/qt/VariantHelpers.h index e0c8e77e7..c45e7d819 100644 --- a/qt/VariantHelpers.h +++ b/qt/VariantHelpers.h @@ -30,12 +30,11 @@ namespace trqt namespace variant_helpers { -template>::type* = nullptr> +template>::type* = nullptr> auto getValue(tr_variant const* variant) { std::optional ret; - auto value = T {}; + auto value = T{}; if (tr_variantGetBool(variant, &value)) { ret = value; @@ -44,15 +43,15 @@ auto getValue(tr_variant const* variant) return ret; } -template|| - std::is_same_v|| - std::is_same_v|| - std::is_same_v>::type* = nullptr> +template< + typename T, + typename std::enable_if< + std::is_same_v || std::is_same_v || std::is_same_v || + std::is_same_v>::type* = nullptr> auto getValue(tr_variant const* variant) { std::optional ret; - auto value = int64_t {}; + auto value = int64_t{}; if (tr_variantGetInt(variant, &value)) { ret = value; @@ -61,12 +60,11 @@ auto getValue(tr_variant const* variant) return ret; } -template>::type* = nullptr> +template>::type* = nullptr> auto getValue(tr_variant const* variant) { std::optional ret; - auto value = T {}; + auto value = T{}; if (tr_variantGetReal(variant, &value)) { ret = value; @@ -103,20 +101,18 @@ auto getValue(tr_variant const* variant) return ret; } -template|| - std::is_same_v>|| - std::is_same_v> - >::type* = nullptr - > + std::is_same_v || std::is_same_v> || std::is_same_v>>::type* = nullptr> auto getValue(tr_variant const* variant) { std::optional ret; if (tr_variantIsList(variant)) { - auto list = C {}; + auto list = C{}; for (size_t i = 0, n = tr_variantListSize(variant); i < n; ++i) { @@ -232,4 +228,4 @@ void dictAdd(tr_variant* dict, tr_quark key, T const& value) } // namespace variant_helpers -} // trqt +} // namespace trqt diff --git a/qt/WatchDir.cc b/qt/WatchDir.cc index 16e4ee2e4..ba3a5e5d8 100644 --- a/qt/WatchDir.cc +++ b/qt/WatchDir.cc @@ -20,8 +20,8 @@ **** ***/ -WatchDir::WatchDir(TorrentModel const& model) : - model_(model) +WatchDir::WatchDir(TorrentModel const& model) + : model_(model) { } @@ -86,7 +86,8 @@ void WatchDir::setPath(QString const& path, bool is_enabled) { watcher_ = std::make_unique(QStringList{ path }); connect(watcher_.get(), &QFileSystemWatcher::directoryChanged, this, &WatchDir::watcherActivated); - QTimer::singleShot(0, this, SLOT(rescanAllWatchedDirectories())); // trigger the watchdir for .torrent files in there already + // trigger the watchdir for .torrent files in there already + QTimer::singleShot(0, this, SLOT(rescanAllWatchedDirectories())); } } diff --git a/tests/libtransmission/bitfield-test.cc b/tests/libtransmission/bitfield-test.cc index 932f78c8f..a087fcb6f 100644 --- a/tests/libtransmission/bitfield-test.cc +++ b/tests/libtransmission/bitfield-test.cc @@ -35,8 +35,7 @@ TEST(Bitfield, countRange) do { end = tr_rand_int_weak(bit_count); - } - while (end == begin); + } while (end == begin); // ensure end <= begin if (end < begin) diff --git a/tests/libtransmission/crypto-test.cc b/tests/libtransmission/crypto-test.cc index c22766e6c..4b242e935 100644 --- a/tests/libtransmission/crypto-test.cc +++ b/tests/libtransmission/crypto-test.cc @@ -68,15 +68,15 @@ TEST(Crypto, encryptDecrypt) hash[i] = uint8_t(i); } - auto a = tr_crypto {}; + auto a = tr_crypto{}; tr_cryptoConstruct(&a, hash.data(), false); - auto b = tr_crypto_ {}; + auto b = tr_crypto_{}; tr_cryptoConstruct_(&b, hash.data(), true); auto public_key_length = int{}; EXPECT_TRUE(tr_cryptoComputeSecret(&a, tr_cryptoGetMyPublicKey_(&b, &public_key_length))); EXPECT_TRUE(tr_cryptoComputeSecret_(&b, tr_cryptoGetMyPublicKey(&a, &public_key_length))); - auto const input1 = std::string { "test1" }; + auto const input1 = std::string{ "test1" }; auto encrypted1 = std::array{}; auto decrypted1 = std::array{}; @@ -86,7 +86,7 @@ TEST(Crypto, encryptDecrypt) tr_cryptoDecrypt_(&b, input1.size(), encrypted1.data(), decrypted1.data()); EXPECT_EQ(input1, std::string(decrypted1.data(), input1.size())); - auto const input2 = std::string { "@#)C$@)#(*%bvkdjfhwbc039bc4603756VB3)" }; + auto const input2 = std::string{ "@#)C$@)#(*%bvkdjfhwbc039bc4603756VB3)" }; auto encrypted2 = std::array{}; auto decrypted2 = std::array{}; @@ -107,16 +107,16 @@ TEST(Crypto, sha1) EXPECT_TRUE(tr_sha1(hash1.data(), "test", 4, nullptr)); EXPECT_TRUE(tr_sha1_(hash2.data(), "test", 4, nullptr)); - EXPECT_EQ(0, - memcmp(hash1.data(), "\xa9\x4a\x8f\xe5\xcc\xb1\x9b\xa6\x1c\x4c\x08\x73\xd3\x91\xe9\x87\x98\x2f\xbb\xd3", - hash1.size())); + EXPECT_EQ( + 0, + memcmp(hash1.data(), "\xa9\x4a\x8f\xe5\xcc\xb1\x9b\xa6\x1c\x4c\x08\x73\xd3\x91\xe9\x87\x98\x2f\xbb\xd3", hash1.size())); EXPECT_EQ(0, memcmp(hash1.data(), hash2.data(), hash2.size())); EXPECT_TRUE(tr_sha1(hash1.data(), "1", 1, "22", 2, "333", 3, nullptr)); EXPECT_TRUE(tr_sha1_(hash2.data(), "1", 1, "22", 2, "333", 3, nullptr)); - EXPECT_EQ(0, - memcmp(hash1.data(), "\x1f\x74\x64\x8e\x50\xa6\xa6\x70\x8e\xc5\x4a\xb3\x27\xa1\x63\xd5\x53\x6b\x7c\xed", - hash1.size())); + EXPECT_EQ( + 0, + memcmp(hash1.data(), "\x1f\x74\x64\x8e\x50\xa6\xa6\x70\x8e\xc5\x4a\xb3\x27\xa1\x63\xd5\x53\x6b\x7c\xed", hash1.size())); EXPECT_EQ(0, memcmp(hash1.data(), hash2.data(), hash2.size())); } @@ -130,7 +130,7 @@ TEST(Crypto, ssha1) auto const tests = std::array{ LocalTest{ "test", "{15ad0621b259a84d24dcd4e75b09004e98a3627bAMbyRHJy" }, - { "QNY)(*#$B)!_X$B !_B#($^!)*&$%CV!#)&$C!@$(P*)", "{10e2d7acbb104d970514a147cd16d51dfa40fb3c0OSwJtOL" } + { "QNY)(*#$B)!_X$B !_B#($^!)*&$%CV!#)&$C!@$(P*)", "{10e2d7acbb104d970514a147cd16d51dfa40fb3c0OSwJtOL" }, }; auto constexpr HashCount = size_t{ 4 * 1024 }; @@ -221,7 +221,7 @@ TEST(Crypto, base64) EXPECT_EQ(strlen(out), len); EXPECT_TRUE(base64Eq("WU9ZTyE=", out)); auto* in = static_cast(tr_base64_decode_str(out, &len)); - EXPECT_EQ(decltype(len) { 5 }, len); + EXPECT_EQ(decltype(len){ 5 }, len); EXPECT_STREQ("YOYO!", in); tr_free(in); tr_free(out); diff --git a/tests/libtransmission/file-test.cc b/tests/libtransmission/file-test.cc index 987be46a0..67b05bcbf 100644 --- a/tests/libtransmission/file-test.cc +++ b/tests/libtransmission/file-test.cc @@ -711,9 +711,7 @@ TEST_F(FileTest, pathBasenameDirname) XnameTestData{ "/", "/" }, { "", "." }, #ifdef _WIN32 - { - "\\", "/" - }, + { "\\", "/" }, /* Invalid paths */ { "\\\\\\", nullptr }, { "123:", nullptr }, @@ -738,11 +736,9 @@ TEST_F(FileTest, pathBasenameDirname) { "c:\\a\\b\"c\\d", nullptr }, { "c:\\a\\b|c\\d", nullptr }, { "c:\\a\\b?c\\d", nullptr }, - { "c:\\a\\b*c\\d", nullptr } + { "c:\\a\\b*c\\d", nullptr }, #else - { - "////", "/" - } + { "////", "/" }, #endif }; @@ -756,9 +752,7 @@ TEST_F(FileTest, pathBasenameDirname) { "/a/b/c", "c" }, { "/a/b/c/", "c" }, #ifdef _WIN32 - { - "c:\\a\\b\\c", "c" - }, + { "c:\\a\\b\\c", "c" }, { "c:", "/" }, { "c:/", "/" }, { "c:\\", "/" }, @@ -770,7 +764,7 @@ TEST_F(FileTest, pathBasenameDirname) { "\\\\a", "a" }, { "\\\\1.2.3.4", "1.2.3.4" }, { "\\", "/" }, - { "\\a", "a" } + { "\\a", "a" }, #endif }; @@ -783,9 +777,7 @@ TEST_F(FileTest, pathBasenameDirname) { "a", "." }, { "a/", "." }, #ifdef _WIN32 - { - "C:\\a/b\\c", "C:\\a/b" - }, + { "C:\\a/b\\c", "C:\\a/b" }, { "C:\\a/b\\c\\", "C:\\a/b" }, { "C:\\a/b", "C:\\a" }, { "C:/a", "C:" }, @@ -802,7 +794,7 @@ TEST_F(FileTest, pathBasenameDirname) { "\\\\a", "\\\\" }, { "\\\\1.2.3.4", "\\\\" }, { "\\\\", "\\\\" }, - { "a/b\\c", "a/b" } + { "a/b\\c", "a/b" }, #endif }; @@ -982,8 +974,7 @@ TEST_F(FileTest, pathNativeSeparators) std::string expected_output; }; - auto const tests = std::array - { + auto const tests = std::array{ LocalTest{ "", "" }, { "a", TR_IF_WIN32("a", "a") }, { "/", TR_IF_WIN32("\\", "/") }, @@ -1069,7 +1060,7 @@ TEST_F(FileTest, fileOpen) EXPECT_NE(TR_BAD_SYS_FILE, fd); EXPECT_EQ(nullptr, err); tr_sys_file_write(fd, "s", 1, nullptr, nullptr); /* On *NIX, pointer is positioned on each write but not initially */ - auto n = uint64_t {}; + auto n = uint64_t{}; tr_sys_file_seek(fd, 0, TR_SEEK_CUR, &n, nullptr); EXPECT_EQ(5, n); tr_sys_file_close(fd, nullptr); @@ -1281,7 +1272,7 @@ TEST_F(FileTest, map) auto const test_dir = createTestDir(currentTestName()); auto* path1 = tr_buildPath(test_dir.data(), "a", nullptr); - auto const contents = std::string { "test" }; + auto const contents = std::string{ "test" }; createFileWithContents(path1, contents.data()); auto fd = tr_sys_file_open(path1, TR_SYS_FILE_READ | TR_SYS_FILE_WRITE, 0600, nullptr); @@ -1295,8 +1286,8 @@ TEST_F(FileTest, map) #ifdef HAVE_UNIFIED_BUFFER_CACHE - auto const contents_2 = std::string { "more" }; - auto n_written = uint64_t {}; + auto const contents_2 = std::string{ "more" }; + auto n_written = uint64_t{}; tr_sys_file_write_at(fd, contents_2.data(), contents_2.size(), 0, &n_written, &err); EXPECT_EQ(map_len, contents_2.size()); EXPECT_EQ(map_len, n_written); @@ -1320,7 +1311,7 @@ TEST_F(FileTest, fileUtilities) auto const test_dir = createTestDir(currentTestName()); auto* path1 = tr_buildPath(test_dir.data(), "a", nullptr); - auto const contents = std::string { "a\nbc\r\ndef\nghij\r\n\n\nklmno\r" }; + auto const contents = std::string{ "a\nbc\r\ndef\nghij\r\n\n\nklmno\r" }; createFileWithContents(path1, contents.data()); auto fd = tr_sys_file_open(path1, TR_SYS_FILE_READ, 0, nullptr); diff --git a/tests/libtransmission/getopt-test.cc b/tests/libtransmission/getopt-test.cc index 6522d5674..a7f97c96b 100644 --- a/tests/libtransmission/getopt-test.cc +++ b/tests/libtransmission/getopt-test.cc @@ -27,12 +27,16 @@ auto const Options = std::array{ { 0, nullptr, nullptr, nullptr, false, nullptr } }; -} // anonymous namespace +} // namespace class GetoptTest : public ::testing::Test { protected: - void runTest(int argc, char const* const* argv, int expected_n, int const* expected_c, + void runTest( // + int argc, + char const* const* argv, + int expected_n, + int const* expected_c, char const* const* expected_args) const { auto n = int{}; @@ -135,8 +139,9 @@ TEST_F(GetoptTest, missingArg) TEST_F(GetoptTest, lotsOfOptions) { - auto const args = - std::array{ "/some/path/tr-getopt-test", "--piecesize=4", "-c", "hello world", "-p", "--tracker=foo" }; + auto const args = std::array{ + "/some/path/tr-getopt-test", "--piecesize=4", "-c", "hello world", "-p", "--tracker=foo" + }; auto constexpr ExpectedN = 4; auto const expected_c = std::array{ 's', 'c', 'p', 't' }; auto const expected_opt_arg = std::array{ "4", "hello world", nullptr, "foo" }; diff --git a/tests/libtransmission/history-test.cc b/tests/libtransmission/history-test.cc index 314c555f9..521f8c45c 100644 --- a/tests/libtransmission/history-test.cc +++ b/tests/libtransmission/history-test.cc @@ -13,7 +13,7 @@ TEST(History, recentHistory) { - auto h = tr_recentHistory {}; + auto h = tr_recentHistory{}; tr_historyAdd(&h, 10000, 1); EXPECT_EQ(0, tr_historyGet(&h, 12000, 1000)); diff --git a/tests/libtransmission/json-test.cc b/tests/libtransmission/json-test.cc index 805f2720d..cb2f1cc92 100644 --- a/tests/libtransmission/json-test.cc +++ b/tests/libtransmission/json-test.cc @@ -34,7 +34,7 @@ protected: TEST_P(JSONTest, testElements) { - auto const in = std::string { + auto const in = std::string{ "{ \"string\": \"hello world\"," " \"escaped\": \"bell \\b formfeed \\f linefeed \\n carriage return \\r tab \\t\"," " \"int\": 5, " @@ -57,7 +57,7 @@ TEST_P(JSONTest, testElements) EXPECT_TRUE(tr_variantDictFindStr(&top, tr_quark_new("escaped", 7), &str, nullptr)); EXPECT_STREQ("bell \b formfeed \f linefeed \n carriage return \r tab \t", str); - auto i = int64_t {}; + auto i = int64_t{}; EXPECT_TRUE(tr_variantDictFindInt(&top, tr_quark_new("int", 3), &i)); EXPECT_EQ(5, i); @@ -83,7 +83,7 @@ TEST_P(JSONTest, testElements) TEST_P(JSONTest, testUtf8) { - auto in = std::string { "{ \"key\": \"Letöltések\" }" }; + auto in = std::string{ "{ \"key\": \"Letöltések\" }" }; tr_variant top; char const* str; char* json; @@ -101,7 +101,7 @@ TEST_P(JSONTest, testUtf8) tr_variantFree(&top); } - in = std::string { R"({ "key": "\u005C" })" }; + in = std::string{ R"({ "key": "\u005C" })" }; err = tr_variantFromJson(&top, in.data(), in.size()); EXPECT_EQ(0, err); EXPECT_TRUE(tr_variantIsDict(&top)); @@ -121,7 +121,7 @@ TEST_P(JSONTest, testUtf8) * 5. Dogfood that result back into the parser. * 6. Confirm that the result is UTF-8. */ - in = std::string { R"({ "key": "Let\u00f6lt\u00e9sek" })" }; + in = std::string{ R"({ "key": "Let\u00f6lt\u00e9sek" })" }; err = tr_variantFromJson(&top, in.data(), in.size()); EXPECT_EQ(0, err); EXPECT_TRUE(tr_variantIsDict(&top)); @@ -153,7 +153,7 @@ TEST_P(JSONTest, testUtf8) TEST_P(JSONTest, test1) { - auto const in = std::string { + auto const in = std::string{ "{\n" " \"headers\": {\n" " \"type\": \"request\",\n" @@ -204,7 +204,7 @@ TEST_P(JSONTest, test1) TEST_P(JSONTest, test2) { tr_variant top; - auto const in = std::string { " " }; + auto const in = std::string{ " " }; top.type = 0; int err = tr_variantFromJson(&top, in.data(), in.size()); @@ -215,7 +215,7 @@ TEST_P(JSONTest, test2) TEST_P(JSONTest, test3) { - auto const in = std::string { + auto const in = std::string{ "{ \"error\": 2," " \"errorString\": \"torrent not registered with this tracker 6UHsVW'*C\"," " \"eta\": 262792," @@ -237,7 +237,7 @@ TEST_P(JSONTest, test3) TEST_P(JSONTest, unescape) { tr_variant top; - auto const in = std::string { R"({ "string-1": "\/usr\/lib" })" }; + auto const in = std::string{ R"({ "string-1": "\/usr\/lib" })" }; int const err = tr_variantFromJson(&top, in.data(), in.size()); EXPECT_EQ(0, err); @@ -248,8 +248,11 @@ TEST_P(JSONTest, unescape) tr_variantFree(&top); } -INSTANTIATE_TEST_SUITE_P( +INSTANTIATE_TEST_SUITE_P( // JSON, JSONTest, - ::testing::Values("C", "da_DK.UTF-8", "fr_FR.UTF-8", "ru_RU.UTF-8") - ); + ::testing::Values( // + "C", + "da_DK.UTF-8", + "fr_FR.UTF-8", + "ru_RU.UTF-8")); diff --git a/tests/libtransmission/magnet-test.cc b/tests/libtransmission/magnet-test.cc index 29ebe2b33..3c2d43099 100644 --- a/tests/libtransmission/magnet-test.cc +++ b/tests/libtransmission/magnet-test.cc @@ -17,8 +17,8 @@ TEST(Magnet, magnetParse) { auto const expected_hash = std::array{ - 210, 53, 64, 16, 163, 202, 74, 222, 91, 116, - 39, 187, 9, 58, 98, 163, 137, 159, 243, 129 + 210, 53, 64, 16, 163, 202, 74, 222, 91, 116, // + 39, 187, 9, 58, 98, 163, 137, 159, 243, 129, // }; char const* const uri_hex = diff --git a/tests/libtransmission/makemeta-test.cc b/tests/libtransmission/makemeta-test.cc index ee9bf4d0f..c7a298d2d 100644 --- a/tests/libtransmission/makemeta-test.cc +++ b/tests/libtransmission/makemeta-test.cc @@ -28,8 +28,13 @@ namespace test class MakemetaTest : public SandboxedTest { protected: - void testSingleFileImpl(tr_tracker_info const* trackers, int const trackerCount, void const* payload, - size_t const payloadSize, char const* comment, bool isPrivate) + void testSingleFileImpl( + tr_tracker_info const* trackers, + int const trackerCount, + void const* payload, + size_t const payloadSize, + char const* comment, + bool isPrivate) { // char* sandbox; tr_info inf; @@ -83,8 +88,13 @@ protected: tr_metaInfoBuilderFree(builder); } - void testSingleDirectoryImpl(tr_tracker_info const* trackers, int const tracker_count, void const** payloads, - size_t const* payload_sizes, size_t const payload_count, char const* comment, + void testSingleDirectoryImpl( + tr_tracker_info const* trackers, + int const tracker_count, + void const** payloads, + size_t const* payload_sizes, + size_t const payload_count, + char const* comment, bool const is_private) { // create the top temp directory @@ -131,7 +141,10 @@ protected: EXPECT_STREQ(torrent_file, builder->outputFile); EXPECT_STREQ(comment, builder->comment); EXPECT_EQ(tracker_count, builder->trackerCount); - auto test = [&builder]() { return builder->isDone; }; + auto test = [&builder]() + { + return builder->isDone; + }; EXPECT_TRUE(waitFor(test, 5000)); sync(); @@ -162,8 +175,12 @@ protected: tr_free(top); } - void testSingleDirectoryRandomPayloadImpl(tr_tracker_info const* trackers, int const tracker_count, - size_t const max_file_count, size_t const max_file_size, char const* comment, + void testSingleDirectoryRandomPayloadImpl( + tr_tracker_info const* trackers, + int const tracker_count, + size_t const max_file_count, + size_t const max_file_size, + char const* comment, bool const is_private) { // build random payloads @@ -181,11 +198,13 @@ protected: // run the test testSingleDirectoryImpl( - trackers, tracker_count, + trackers, + tracker_count, const_cast(payloads), payload_sizes, payload_count, - comment, is_private); + comment, + is_private); // cleanup for (size_t i = 0; i < payload_count; i++) @@ -208,12 +227,10 @@ TEST_F(MakemetaTest, singleFile) trackers[tracker_count].tier = tracker_count; trackers[tracker_count].announce = const_cast("udp://tracker.publicbt.com:80"); ++tracker_count; - auto const payload = std::string { "Hello, World!\n" }; + auto const payload = std::string{ "Hello, World!\n" }; char const* const comment = "This is the comment"; bool const is_private = false; - testSingleFileImpl(trackers.data(), tracker_count, - payload.data(), payload.size(), - comment, is_private); + testSingleFileImpl(trackers.data(), tracker_count, payload.data(), payload.size(), comment, is_private); } TEST_F(MakemetaTest, singleDirectoryRandomPayload) @@ -234,10 +251,13 @@ TEST_F(MakemetaTest, singleDirectoryRandomPayload) for (size_t i = 0; i < 10; ++i) { - testSingleDirectoryRandomPayloadImpl(trackers.data(), tracker_count, + testSingleDirectoryRandomPayloadImpl( + trackers.data(), + tracker_count, DefaultMaxFileCount, DefaultMaxFileSize, - comment, is_private); + comment, + is_private); } } diff --git a/tests/libtransmission/metainfo-test.cc b/tests/libtransmission/metainfo-test.cc index 6fb3dab5c..f1fccbf68 100644 --- a/tests/libtransmission/metainfo-test.cc +++ b/tests/libtransmission/metainfo-test.cc @@ -78,7 +78,7 @@ TEST(Metainfo, bucket) { 0, TR_PARSE_OK, BEFORE_PATH "5:a.txt2:.." AFTER_PATH }, /* fail on empty string */ - { EILSEQ, TR_PARSE_ERR, "" } + { EILSEQ, TR_PARSE_ERR, "" }, }; tr_logSetLevel(TR_LOG_SILENT); @@ -143,7 +143,7 @@ TEST(Metainfo, sanitize) { "..foo", 5, "..foo", false }, { "foo.bar.baz", 11, "foo.bar.baz", false }, { "null", 4, "null", false }, - { "compass", 7, "compass", false } + { "compass", 7, "compass", false }, }; for (auto const& test : tests) diff --git a/tests/libtransmission/move-test.cc b/tests/libtransmission/move-test.cc index a14fab945..369f30aca 100644 --- a/tests/libtransmission/move-test.cc +++ b/tests/libtransmission/move-test.cc @@ -24,9 +24,9 @@ namespace libtransmission namespace test { -class IncompleteDirTest : - public SessionTest, - public ::testing::WithParamInterface> +class IncompleteDirTest + : public SessionTest + , public ::testing::WithParamInterface> { protected: void SetUp() override @@ -50,18 +50,19 @@ TEST_P(IncompleteDirTest, incompleteDir) // the test zero_torrent will be missing its first piece. auto* tor = zeroTorrentInit(); zeroTorrentPopulate(tor, false); - EXPECT_EQ(makeString(tr_strdup_printf("%s/%s.part", incomplete_dir, tor->info.files[0].name)), + EXPECT_EQ( + makeString(tr_strdup_printf("%s/%s.part", incomplete_dir, tor->info.files[0].name)), makeString(tr_torrentFindFile(tor, 0))); - EXPECT_EQ(makeString(tr_buildPath(incomplete_dir, tor->info.files[1].name, nullptr)), + EXPECT_EQ( + makeString(tr_buildPath(incomplete_dir, tor->info.files[1].name, nullptr)), makeString(tr_torrentFindFile(tor, 1))); EXPECT_EQ(tor->info.pieceSize, tr_torrentStat(tor)->leftUntilDone); // auto constexpr completeness_unset = tr_completeness { -1 }; // auto completeness = completeness_unset; int completeness = -1; - auto const zeroes_completeness_func = [] ( - tr_torrent* /*torrent*/, tr_completeness c, - bool /*was_running*/, void* vc) noexcept + auto const zeroes_completeness_func = + [](tr_torrent* /*torrent*/, tr_completeness c, bool /*was_running*/, void* vc) noexcept { *static_cast(vc) = c; }; @@ -78,7 +79,7 @@ TEST_P(IncompleteDirTest, incompleteDir) bool done = {}; }; - auto const test_incomplete_dir_threadfunc = [] (void* vdata)noexcept + auto const test_incomplete_dir_threadfunc = [](void* vdata) noexcept { auto* data = static_cast(vdata); tr_cacheWriteBlock(data->session->cache, data->tor, 0, data->offset, data->tor->blockSize, data->buf); @@ -107,7 +108,10 @@ TEST_P(IncompleteDirTest, incompleteDir) data.offset = data.block * tor->blockSize; tr_runInEventThread(session_, test_incomplete_dir_threadfunc, &data); - auto const test = [&data]() { return data.done; }; + auto const test = [&data]() + { + return data.done; + }; EXPECT_TRUE(waitFor(test, 1000)); } @@ -118,13 +122,17 @@ TEST_P(IncompleteDirTest, incompleteDir) blockingTorrentVerify(tor); EXPECT_EQ(0, tr_torrentStat(tor)->leftUntilDone); - auto test = [&completeness]() { return completeness != -1; }; + auto test = [&completeness]() + { + return completeness != -1; + }; EXPECT_TRUE(waitFor(test, 300)); EXPECT_EQ(TR_SEED, completeness); for (tr_file_index_t file_index = 0; file_index < tor->info.fileCount; ++file_index) { - EXPECT_EQ(makeString(tr_buildPath(download_dir, tor->info.files[file_index].name, nullptr)), + EXPECT_EQ( + makeString(tr_buildPath(download_dir, tor->info.files[file_index].name, nullptr)), makeString(tr_torrentFindFile(tor, file_index))); } @@ -136,14 +144,12 @@ INSTANTIATE_TEST_SUITE_P( IncompleteDir, IncompleteDirTest, ::testing::Values( - // what happens when incompleteDir is a subdir of downloadDir - std::make_pair(std::string{ "Downloads/Incomplete" }, std::string{ "Downloads" }), - // test what happens when downloadDir is a subdir of incompleteDir - std::make_pair(std::string{ "Downloads" }, std::string{ "Downloads/Complete" }), - // test what happens when downloadDir and incompleteDir are siblings - std::make_pair(std::string{ "Incomplete" }, std::string{ "Downloads" }) - ) - ); + // what happens when incompleteDir is a subdir of downloadDir + std::make_pair(std::string{ "Downloads/Incomplete" }, std::string{ "Downloads" }), + // test what happens when downloadDir is a subdir of incompleteDir + std::make_pair(std::string{ "Downloads" }, std::string{ "Downloads/Complete" }), + // test what happens when downloadDir and incompleteDir are siblings + std::make_pair(std::string{ "Incomplete" }, std::string{ "Downloads" }))); /*** **** @@ -165,7 +171,10 @@ TEST_F(MoveTest, setLocation) // now move it auto state = int{ -1 }; tr_torrentSetLocation(tor, target_dir.data(), true, nullptr, &state); - auto test = [&state]() { return state == TR_LOC_DONE; }; + auto test = [&state]() + { + return state == TR_LOC_DONE; + }; EXPECT_TRUE(waitFor(test, 300)); EXPECT_EQ(TR_LOC_DONE, state); @@ -177,7 +186,8 @@ TEST_F(MoveTest, setLocation) sync(); for (tr_file_index_t file_index = 0; file_index < tor->info.fileCount; ++file_index) { - EXPECT_EQ(makeString(tr_buildPath(target_dir.data(), tor->info.files[file_index].name, nullptr)), + EXPECT_EQ( + makeString(tr_buildPath(target_dir.data(), tor->info.files[file_index].name, nullptr)), makeString(tr_torrentFindFile(tor, file_index))); } diff --git a/tests/libtransmission/rename-test.cc b/tests/libtransmission/rename-test.cc index 45e060e51..baa2c24e7 100644 --- a/tests/libtransmission/rename-test.cc +++ b/tests/libtransmission/rename-test.cc @@ -37,9 +37,9 @@ protected: { tr_torrentRemove(tor, false, nullptr); auto const test = [this, expected_torrent_count]() - { - return tr_sessionCountTorrents(session_) == expected_torrent_count; - }; + { + return tr_sessionCountTorrents(session_) == expected_torrent_count; + }; EXPECT_TRUE(waitFor(test, MaxWaitMsec)); } @@ -121,17 +121,18 @@ protected: int torrentRenameAndWait(tr_torrent* tor, char const* oldpath, char const* newname) { - auto const on_rename_done = [] ( - tr_torrent* /*tor*/, char const* /*oldpath*/, - char const* /*newname*/, int error, - void* user_data) noexcept + auto const on_rename_done = + [](tr_torrent* /*tor*/, char const* /*oldpath*/, char const* /*newname*/, int error, void* user_data) noexcept { *static_cast(user_data) = error; }; int error = -1; tr_torrentRenamePath(tor, oldpath, newname, on_rename_done, &error); - auto test = [&error]() { return error != -1; }; + auto test = [&error]() + { + return error != -1; + }; EXPECT_TRUE(waitFor(test, MaxWaitMsec)); return error; } @@ -144,7 +145,8 @@ TEST_F(RenameTest, singleFilenameTorrent) // this is a single-file torrent whose file is hello-world.txt, holding the string "hello, world!" auto* ctor = tr_ctorNew(session_); - auto* tor = createTorrentFromBase64Metainfo(ctor, + auto* tor = createTorrentFromBase64Metainfo( + ctor, "ZDEwOmNyZWF0ZWQgYnkyNTpUcmFuc21pc3Npb24vMi42MSAoMTM0MDcpMTM6Y3JlYXRpb24gZGF0" "ZWkxMzU4NTQ5MDk4ZTg6ZW5jb2Rpbmc1OlVURi04NDppbmZvZDY6bGVuZ3RoaTE0ZTQ6bmFtZTE1" "OmhlbGxvLXdvcmxkLnR4dDEyOnBpZWNlIGxlbmd0aGkzMjc2OGU2OnBpZWNlczIwOukboJcrkFUY" @@ -212,7 +214,7 @@ TEST_F(RenameTest, singleFilenameTorrent) sync(); loaded = tr_torrentLoadResume(tor, ~0, ctor, nullptr); EXPECT_STREQ("foobar", tr_torrentName(tor)); - EXPECT_NE(decltype(loaded) { 0 }, (loaded & TR_FR_NAME)); + EXPECT_NE(decltype(loaded){ 0 }, (loaded & TR_FR_NAME)); /*** **** ...and rename it back again @@ -242,23 +244,22 @@ TEST_F(RenameTest, multifileTorrent) { char* str; auto constexpr TotalSize = size_t{ 67 }; - auto const expected_files = std::array - { + auto const expected_files = std::array{ "Felidae/Felinae/Acinonyx/Cheetah/Chester", "Felidae/Felinae/Felis/catus/Kyphi", "Felidae/Felinae/Felis/catus/Saffron", - "Felidae/Pantherinae/Panthera/Tiger/Tony" + "Felidae/Pantherinae/Panthera/Tiger/Tony", }; - auto const expected_contents = std::array - { + auto const expected_contents = std::array{ "It ain't easy bein' cheesy.\n", "Inquisitive\n", "Tough\n", - "They’re Grrrrreat!\n" + "They’re Grrrrreat!\n", }; auto* ctor = tr_ctorNew(session_); - auto* tor = createTorrentFromBase64Metainfo(ctor, + auto* tor = createTorrentFromBase64Metainfo( + ctor, "ZDEwOmNyZWF0ZWQgYnkyNTpUcmFuc21pc3Npb24vMi42MSAoMTM0MDcpMTM6Y3JlYXRpb24gZGF0" "ZWkxMzU4NTU1NDIwZTg6ZW5jb2Rpbmc1OlVURi04NDppbmZvZDU6ZmlsZXNsZDY6bGVuZ3RoaTI4" "ZTQ6cGF0aGw3OkZlbGluYWU4OkFjaW5vbnl4NzpDaGVldGFoNzpDaGVzdGVyZWVkNjpsZW5ndGhp" @@ -331,7 +332,7 @@ TEST_F(RenameTest, multifileTorrent) tr_free(files[1].name); tor->info.files[1].name = tr_strdup("gabba gabba hey"); auto const loaded = tr_torrentLoadResume(tor, ~0, ctor, nullptr); - EXPECT_NE(decltype(loaded) { 0 }, (loaded & TR_FR_FILENAMES)); + EXPECT_NE(decltype(loaded){ 0 }, (loaded & TR_FR_FILENAMES)); EXPECT_EQ(expected_files[0], files[0].name); EXPECT_STREQ("Felidae/Felinae/Felis/placeholder/Kyphi", files[1].name); EXPECT_STREQ("Felidae/Felinae/Felis/placeholder/Saffron", files[2].name); @@ -431,7 +432,8 @@ TEST_F(RenameTest, multifileTorrent) **/ ctor = tr_ctorNew(session_); - tor = createTorrentFromBase64Metainfo(ctor, + tor = createTorrentFromBase64Metainfo( + ctor, "ZDEwOmNyZWF0ZWQgYnkyNTpUcmFuc21pc3Npb24vMi42MSAoMTM0MDcpMTM6Y3JlYXRpb24gZGF0" "ZWkxMzU4NTU1NDIwZTg6ZW5jb2Rpbmc1OlVURi04NDppbmZvZDU6ZmlsZXNsZDY6bGVuZ3RoaTI4" "ZTQ6cGF0aGw3OkZlbGluYWU4OkFjaW5vbnl4NzpDaGVldGFoNzpDaGVzdGVyZWVkNjpsZW5ndGhp" @@ -474,8 +476,8 @@ TEST_F(RenameTest, multifileTorrent) TEST_F(RenameTest, partialFile) { - auto constexpr PieceCount = uint32_t { 33 }; - auto constexpr PieceSize = uint32_t { 32768 }; + auto constexpr PieceCount = uint32_t{ 33 }; + auto constexpr PieceSize = uint32_t{ 32768 }; auto const length = std::array{ 1048576, 4096, 512 }; auto const total_size = uint64_t(length[0]) + length[1] + length[2]; diff --git a/tests/libtransmission/rpc-test.cc b/tests/libtransmission/rpc-test.cc index 613a8efb5..477ea2c46 100644 --- a/tests/libtransmission/rpc-test.cc +++ b/tests/libtransmission/rpc-test.cc @@ -81,7 +81,7 @@ TEST_F(RpcTest, list) TEST_F(RpcTest, sessionGet) { - auto const rpc_response_func = [] (tr_session* /*session*/, tr_variant* response, void* setme) noexcept + auto const rpc_response_func = [](tr_session* /*session*/, tr_variant* response, void* setme) noexcept { *static_cast(setme) = *response; tr_variantInitBool(response, false); @@ -154,7 +154,7 @@ TEST_F(RpcTest, sessionGet) TR_KEY_trash_original_torrent_files, TR_KEY_units, TR_KEY_utp_enabled, - TR_KEY_version + TR_KEY_version, }; // what we got @@ -168,16 +168,22 @@ TEST_F(RpcTest, sessionGet) } auto missing_keys = std::vector{}; - std::set_difference(std::begin(expected_keys), std::end(expected_keys), - std::begin(actual_keys), std::end(actual_keys), + std::set_difference( + std::begin(expected_keys), + std::end(expected_keys), + std::begin(actual_keys), + std::end(actual_keys), std::inserter(missing_keys, std::begin(missing_keys))); - EXPECT_EQ(decltype(missing_keys) {}, missing_keys); + EXPECT_EQ(decltype(missing_keys){}, missing_keys); auto unexpected_keys = std::vector{}; - std::set_difference(std::begin(actual_keys), std::end(actual_keys), - std::begin(expected_keys), std::end(expected_keys), + std::set_difference( + std::begin(actual_keys), + std::end(actual_keys), + std::begin(expected_keys), + std::end(expected_keys), std::inserter(unexpected_keys, std::begin(unexpected_keys))); - EXPECT_EQ(decltype(unexpected_keys) {}, unexpected_keys); + EXPECT_EQ(decltype(unexpected_keys){}, unexpected_keys); // cleanup tr_variantFree(&response); diff --git a/tests/libtransmission/session-test.cc b/tests/libtransmission/session-test.cc index 68d96cb6e..ea5bea468 100644 --- a/tests/libtransmission/session-test.cc +++ b/tests/libtransmission/session-test.cc @@ -23,7 +23,7 @@ TEST(Session, peerId) { - auto const peer_id_prefix = std::string { PEERID_PREFIX }; + auto const peer_id_prefix = std::string{ PEERID_PREFIX }; for (int i = 0; i < 100000; ++i) { diff --git a/tests/libtransmission/subprocess-test.cc b/tests/libtransmission/subprocess-test.cc index 3c83d1c54..a7066758f 100644 --- a/tests/libtransmission/subprocess-test.cc +++ b/tests/libtransmission/subprocess-test.cc @@ -39,7 +39,7 @@ std::string getSelfPath() std::string getCmdSelfPath() { - auto const new_suffix = std::string { ".cmd" }; + auto const new_suffix = std::string{ ".cmd" }; auto exec = getSelfPath(); // replace ".exe" suffix with ".cmd" exec.resize(exec.size() - new_suffix.size()); @@ -47,9 +47,9 @@ std::string getCmdSelfPath() return exec; } -class SubprocessTest : - public ::testing::Test, - public testing::WithParamInterface +class SubprocessTest + : public ::testing::Test + , public testing::WithParamInterface { protected: Sandbox sandbox_; @@ -70,9 +70,9 @@ protected: return path; } - std::string const arg_dump_args_ { "--dump-args" }; - std::string const arg_dump_env_ { "--dump-env" }; - std::string const arg_dump_cwd_ { "--dump-cwd" }; + std::string const arg_dump_args_{ "--dump-args" }; + std::string const arg_dump_env_{ "--dump-env" }; + std::string const arg_dump_cwd_{ "--dump-cwd" }; std::string self_path_; @@ -93,9 +93,11 @@ protected: auto const& test_action = argv[2]; auto const tmp_result_path = result_path + ".tmp"; - auto fd = tr_sys_file_open(tmp_result_path.data(), // NOLINT + auto fd = tr_sys_file_open( + tmp_result_path.data(), // NOLINT TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE, - 0644, nullptr); + 0644, + nullptr); if (fd == TR_BAD_SYS_FILE) { @@ -137,7 +139,10 @@ protected: void waitForFileToExist(std::string const& path) { - auto const test = [path]() { return tr_sys_path_exists(path.data(), nullptr); }; + auto const test = [path]() + { + return tr_sys_path_exists(path.data(), nullptr); + }; EXPECT_TRUE(waitFor(test, 30000)); } @@ -150,7 +155,7 @@ protected: TEST_P(SubprocessTest, SpawnAsyncMissingExec) { - auto const missing_exe_path = std::string { TR_IF_WIN32("C:\\", "/") "tr-missing-test-exe" TR_IF_WIN32(".exe", "") }; + auto const missing_exe_path = std::string{ TR_IF_WIN32("C:\\", "/") "tr-missing-test-exe" TR_IF_WIN32(".exe", "") }; auto args = std::array{ // FIXME(ckerr): remove tr_strdup()s after https://github.com/transmission/transmission/issues/1384 @@ -173,10 +178,10 @@ TEST_P(SubprocessTest, SpawnAsyncArgs) auto const result_path = buildSandboxPath("result.txt"); bool const allow_batch_metachars = TR_IF_WIN32(false, true) || !tr_str_has_suffix(self_path_.c_str(), ".cmd"); - auto const test_arg1 = std::string { "arg1 " }; - auto const test_arg2 = std::string { " arg2" }; - auto const test_arg3 = std::string {}; - auto const test_arg4 = std::string { "\"arg3'^! $PATH %PATH% \\" }; + auto const test_arg1 = std::string{ "arg1 " }; + auto const test_arg2 = std::string{ " arg2" }; + auto const test_arg3 = std::string{}; + auto const test_arg4 = std::string{ "\"arg3'^! $PATH %PATH% \\" }; auto args = std::array{ // FIXME(ckerr): remove tr_strdup()s after https://github.com/transmission/transmission/issues/1384 @@ -226,31 +231,31 @@ TEST_P(SubprocessTest, SpawnAsyncEnv) { auto const result_path = buildSandboxPath("result.txt"); - auto const test_env_key1 = std::string { "VAR1" }; - auto const test_env_key2 = std::string { "_VAR_2_" }; - auto const test_env_key3 = std::string { "vAr#" }; - auto const test_env_key4 = std::string { "FOO" }; - auto const test_env_key5 = std::string { "ZOO" }; - auto const test_env_key6 = std::string { "TR_MISSING_TEST_ENV_KEY" }; + auto const test_env_key1 = std::string{ "VAR1" }; + auto const test_env_key2 = std::string{ "_VAR_2_" }; + auto const test_env_key3 = std::string{ "vAr#" }; + auto const test_env_key4 = std::string{ "FOO" }; + auto const test_env_key5 = std::string{ "ZOO" }; + auto const test_env_key6 = std::string{ "TR_MISSING_TEST_ENV_KEY" }; - auto const test_env_value1 = std::string { "value1 " }; - auto const test_env_value2 = std::string { " value2" }; - auto const test_env_value3 = std::string { " \"value3'^! $PATH %PATH% " }; - auto const test_env_value4 = std::string { "bar" }; - auto const test_env_value5 = std::string { "jar" }; + auto const test_env_value1 = std::string{ "value1 " }; + auto const test_env_value2 = std::string{ " value2" }; + auto const test_env_value3 = std::string{ " \"value3'^! $PATH %PATH% " }; + auto const test_env_value4 = std::string{ "bar" }; + auto const test_env_value5 = std::string{ "jar" }; auto args = std::array{ // FIXME(ckerr): remove tr_strdup()s after https://github.com/transmission/transmission/issues/1384 - tr_strdup(self_path_.c_str()), - tr_strdup(result_path.data()), - tr_strdup(arg_dump_env_.data()), - tr_strdup(test_env_key1.data()), - tr_strdup(test_env_key2.data()), - tr_strdup(test_env_key3.data()), - tr_strdup(test_env_key4.data()), - tr_strdup(test_env_key5.data()), - tr_strdup(test_env_key6.data()), - nullptr + tr_strdup(self_path_.c_str()), // + tr_strdup(result_path.data()), // + tr_strdup(arg_dump_env_.data()), // + tr_strdup(test_env_key1.data()), // + tr_strdup(test_env_key2.data()), // + tr_strdup(test_env_key3.data()), // + tr_strdup(test_env_key4.data()), // + tr_strdup(test_env_key5.data()), // + tr_strdup(test_env_key6.data()), // + nullptr, // }; auto env = std::array{ @@ -259,7 +264,7 @@ TEST_P(SubprocessTest, SpawnAsyncEnv) tr_strdup_printf("%s=%s", test_env_key2.data(), test_env_value2.data()), tr_strdup_printf("%s=%s", test_env_key3.data(), test_env_value3.data()), tr_strdup_printf("%s=%s", test_env_key5.data(), test_env_value5.data()), - nullptr + nullptr, }; setenv("FOO", "bar", true); // inherited @@ -330,7 +335,8 @@ TEST_P(SubprocessTest, SpawnAsyncCwdExplicit) auto buffer = std::array{}; EXPECT_TRUE(tr_sys_file_read_line(fd, buffer.data(), buffer.size(), nullptr)); - EXPECT_EQ(makeString(tr_sys_path_native_separators(tr_strdup(test_dir.c_str()))), + EXPECT_EQ( + makeString(tr_sys_path_native_separators(tr_strdup(test_dir.c_str()))), tr_sys_path_native_separators(&buffer.front())); EXPECT_FALSE(tr_sys_file_read_line(fd, buffer.data(), buffer.size(), nullptr)); @@ -390,17 +396,18 @@ TEST_P(SubprocessTest, SpawnAsyncCwdMissing) } #ifdef _WIN32 -INSTANTIATE_TEST_SUITE_P( +INSTANTIATE_TEST_SUITE_P( // Subprocess, SubprocessTest, - ::testing::Values(getSelfPath(), getCmdSelfPath()) - ); + ::testing::Values( // + getSelfPath(), + getCmdSelfPath())); #else -INSTANTIATE_TEST_SUITE_P( +INSTANTIATE_TEST_SUITE_P( // Subprocess, SubprocessTest, - ::testing::Values(getSelfPath()) - ); + ::testing::Values( // + getSelfPath())); #endif } // namespace test diff --git a/tests/libtransmission/test-fixtures.h b/tests/libtransmission/test-fixtures.h index 2e0108ef4..9bee2ef36 100644 --- a/tests/libtransmission/test-fixtures.h +++ b/tests/libtransmission/test-fixtures.h @@ -32,15 +32,15 @@ namespace test { auto const makeString = [](char*&& s) - { - auto const ret = std::string(s != nullptr ? s : ""); - tr_free(s); - return ret; - }; +{ + auto const ret = std::string(s != nullptr ? s : ""); + tr_free(s); + return ret; +}; bool waitFor(std::function const& test, int msec) { - auto const deadline = std::chrono::milliseconds { msec }; + auto const deadline = std::chrono::milliseconds{ msec }; auto const begin = std::chrono::steady_clock::now(); for (;;) @@ -62,9 +62,9 @@ bool waitFor(std::function const& test, int msec) class Sandbox { public: - Sandbox() : - parent_dir_{get_default_parent_dir()}, - sandbox_dir_{create_sandbox(parent_dir_, "transmission-test-XXXXXX")} + Sandbox() + : parent_dir_{ get_default_parent_dir() } + , sandbox_dir_{ create_sandbox(parent_dir_, "transmission-test-XXXXXX") } { } @@ -114,8 +114,7 @@ protected: std::vector ret; tr_sys_path_info info; - if (tr_sys_path_get_info(path.data(), 0, &info, nullptr) && - (info.type == TR_SYS_PATH_IS_DIRECTORY)) + if (tr_sys_path_get_info(path.data(), 0, &info, nullptr) && (info.type == TR_SYS_PATH_IS_DIRECTORY)) { auto const odir = tr_sys_dir_open(path.data(), nullptr); if (odir != TR_BAD_SYS_DIR) @@ -159,7 +158,10 @@ private: class SandboxedTest : public ::testing::Test { protected: - std::string sandboxDir() const { return sandbox_.path(); } + std::string sandboxDir() const + { + return sandbox_.path(); + } auto currentTestName() const { @@ -224,9 +226,11 @@ protected: buildParentDir(path); - auto const fd = tr_sys_file_open(path.c_str(), + auto const fd = tr_sys_file_open( + path.c_str(), TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE, - 0600, nullptr); + 0600, + nullptr); blockingFileWrite(fd, payload, n); tr_sys_file_close(fd, nullptr); sync(); @@ -274,7 +278,9 @@ void ensureFormattersInited() static std::once_flag flag; - std::call_once(flag, []() + std::call_once( + flag, + []() { tr_formatter_mem_init(MEM_K, MEM_K_STR, MEM_M_STR, MEM_G_STR, MEM_T_STR); tr_formatter_size_init(DISK_K, DISK_K_STR, DISK_M_STR, DISK_G_STR, DISK_T_STR); @@ -296,7 +302,7 @@ private: char const* str; auto q = TR_KEY_download_dir; auto const download_dir = tr_variantDictFindStr(settings, q, &str, &len) ? - makeString(tr_strdup_printf("%s/%*.*s", sandboxDir().data(), (int)len, (int)len, str)) : + makeString(tr_strdup_printf("%s/%*.*s", sandboxDir().data(), TR_ARG_TUPLE((int)len, (int)len, str))) : makeString(tr_buildPath(sandboxDir().data(), "Downloads", nullptr)); tr_sys_dir_create(download_dir.data(), TR_SYS_DIR_CREATE_PARENTS, 0700, nullptr); tr_variantDictAddStr(settings, q, download_dir.data()); @@ -304,7 +310,7 @@ private: // incomplete dir q = TR_KEY_incomplete_dir; auto const incomplete_dir = tr_variantDictFindStr(settings, q, &str, &len) ? - makeString(tr_strdup_printf("%s/%*.*s", sandboxDir().data(), (int)len, (int)len, str)) : + makeString(tr_strdup_printf("%s/%*.*s", sandboxDir().data(), TR_ARG_TUPLE((int)len, (int)len, str))) : makeString(tr_buildPath(sandboxDir().data(), "Incomplete", nullptr)); tr_variantDictAddStr(settings, q, incomplete_dir.data()); @@ -400,7 +406,10 @@ protected: auto const dirname = makeString(tr_sys_path_dirname(path.c_str(), nullptr)); tr_sys_dir_create(dirname.data(), TR_SYS_DIR_CREATE_PARENTS, 0700, nullptr); auto fd = tr_sys_file_open( - path.c_str(), TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE, 0600, nullptr); + path.c_str(), + TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE, + 0600, + nullptr); for (uint64_t j = 0; j < file.length; ++j) { @@ -433,14 +442,17 @@ protected: EXPECT_NE(nullptr, tor->session); EXPECT_FALSE(tr_amInEventThread(tor->session)); - auto constexpr onVerifyDone = [] (tr_torrent*, bool, void* done) noexcept + auto constexpr onVerifyDone = [](tr_torrent*, bool, void* done) noexcept { *static_cast(done) = true; }; bool done = false; tr_torrentVerify(tor, onVerifyDone, &done); - auto test = [&done]() { return done; }; + auto test = [&done]() + { + return done; + }; EXPECT_TRUE(waitFor(test, 2000)); } @@ -450,13 +462,13 @@ protected: { if (!settings_) { - auto* settings = new tr_variant {}; + auto* settings = new tr_variant{}; tr_variantInitDict(settings, 10); auto constexpr deleter = [](tr_variant* v) - { - tr_variantFree(v); - delete v; - }; + { + tr_variantFree(v); + delete v; + }; settings_.reset(settings, deleter); } diff --git a/tests/libtransmission/utils-test.cc b/tests/libtransmission/utils-test.cc index 7ec472282..1821565ef 100644 --- a/tests/libtransmission/utils-test.cc +++ b/tests/libtransmission/utils-test.cc @@ -180,7 +180,7 @@ int compareInts(void const* va, void const* vb) noexcept return a - b; } -} // unnamed namespace +} // namespace TEST_F(UtilsTest, lowerbound) { @@ -200,18 +200,18 @@ TEST_F(UtilsTest, lowerbound) TEST_F(UtilsTest, trQuickfindfirstk) { auto const run_test = [](size_t const k, size_t const n, int* buf, int range) - { - // populate buf with random ints - std::generate(buf, buf + n, [range]() { return tr_rand_int_weak(range); }); + { + // populate buf with random ints + std::generate(buf, buf + n, [range]() { return tr_rand_int_weak(range); }); - // find the best k - tr_quickfindFirstK(buf, n, sizeof(int), compareInts, k); + // find the best k + tr_quickfindFirstK(buf, n, sizeof(int), compareInts, k); - // confirm that the smallest K ints are in the first slots K slots in buf - auto const* highest_low = std::max_element(buf, buf + k); - auto const* lowest_high = std::min_element(buf + k, buf + n); - EXPECT_LE(highest_low, lowest_high); - }; + // confirm that the smallest K ints are in the first slots K slots in buf + auto const* highest_low = std::max_element(buf, buf + k); + auto const* lowest_high = std::min_element(buf + k, buf + n); + EXPECT_LE(highest_low, lowest_high); + }; auto constexpr K = size_t{ 10 }; auto constexpr NumTrials = size_t{ 1000 }; @@ -224,8 +224,8 @@ TEST_F(UtilsTest, trQuickfindfirstk) TEST_F(UtilsTest, trMemmem) { - auto const haystack = std::string { "abcabcabcabc" }; - auto const needle = std::string { "cab" }; + auto const haystack = std::string{ "abcabcabcabc" }; + auto const needle = std::string{ "cab" }; EXPECT_EQ(haystack, tr_memmem(haystack.data(), haystack.size(), haystack.data(), haystack.size())); EXPECT_EQ(haystack.substr(2), tr_memmem(haystack.data(), haystack.size(), needle.data(), needle.size())); @@ -234,12 +234,12 @@ TEST_F(UtilsTest, trMemmem) TEST_F(UtilsTest, trBinaryHex) { - auto const hex_in = std::string { "fb5ef5507427b17e04b69cef31fa3379b456735a" }; + auto const hex_in = std::string{ "fb5ef5507427b17e04b69cef31fa3379b456735a" }; auto binary = std::array{}; tr_hex_to_binary(hex_in.data(), binary.data(), hex_in.size() / 2); - auto hex_out = std::array{}; + auto hex_out = std::array{}; tr_binary_to_hex(binary.data(), hex_out.data(), 20); EXPECT_EQ(hex_in, reinterpret_cast(hex_out.data())); } @@ -313,7 +313,7 @@ TEST_F(UtilsTest, url) TEST_F(UtilsTest, trHttpUnescape) { - auto const url = std::string { "http%3A%2F%2Fwww.example.com%2F~user%2F%3Ftest%3D1%26test1%3D2" }; + auto const url = std::string{ "http%3A%2F%2Fwww.example.com%2F~user%2F%3Ftest%3D1%26test1%3D2" }; auto str = makeString(tr_http_unescape(url.data(), url.size())); EXPECT_EQ("http://www.example.com/~user/?test=1&test1=2", str); } @@ -368,7 +368,7 @@ char* testStrdupPrintfValist(char const* fmt, ...) return ret; } -} // unnamed namespace +} // namespace TEST_F(UtilsTest, trStrdupVprintf) { diff --git a/tests/libtransmission/variant-test.cc b/tests/libtransmission/variant-test.cc index 65545c944..f91f7dc4c 100644 --- a/tests/libtransmission/variant-test.cc +++ b/tests/libtransmission/variant-test.cc @@ -34,26 +34,24 @@ protected: auto bencParseInt(std::string const& in, uint8_t const** end, int64_t* val) { - return tr_bencParseInt(in.data(), - in.data() + in.size(), - end, val); + return tr_bencParseInt(in.data(), in.data() + in.size(), end, val); } }; #ifndef _WIN32 -# define STACK_SMASH_DEPTH (1 * 1000 * 1000) +#define STACK_SMASH_DEPTH (1 * 1000 * 1000) #else -# define STACK_SMASH_DEPTH (100 * 1000) +#define STACK_SMASH_DEPTH (100 * 1000) #endif TEST_F(VariantTest, parseInt) { - auto const in = std::string { "i64e" }; - auto constexpr InitVal = int64_t { 888 }; - auto constexpr ExpectVal = int64_t { 64 }; + auto const in = std::string{ "i64e" }; + auto constexpr InitVal = int64_t{ 888 }; + auto constexpr ExpectVal = int64_t{ 64 }; uint8_t const* end = {}; - auto val = int64_t { InitVal }; + auto val = int64_t{ InitVal }; auto const err = bencParseInt(in, &end, &val); EXPECT_EQ(0, err); EXPECT_EQ(ExpectVal, val); @@ -62,11 +60,11 @@ TEST_F(VariantTest, parseInt) TEST_F(VariantTest, parseIntWithMissingEnd) { - auto const in = std::string { "i64" }; - auto constexpr InitVal = int64_t { 888 }; + auto const in = std::string{ "i64" }; + auto constexpr InitVal = int64_t{ 888 }; uint8_t const* end = {}; - auto val = int64_t { InitVal }; + auto val = int64_t{ InitVal }; auto const err = bencParseInt(in, &end, &val); EXPECT_EQ(EILSEQ, err); EXPECT_EQ(InitVal, val); @@ -75,11 +73,11 @@ TEST_F(VariantTest, parseIntWithMissingEnd) TEST_F(VariantTest, parseIntEmptyBuffer) { - auto const in = std::string {}; - auto constexpr InitVal = int64_t { 888 }; + auto const in = std::string{}; + auto constexpr InitVal = int64_t{ 888 }; uint8_t const* end = {}; - auto val = int64_t { InitVal }; + auto val = int64_t{ InitVal }; auto const err = bencParseInt(in, &end, &val); EXPECT_EQ(EILSEQ, err); EXPECT_EQ(InitVal, val); @@ -88,11 +86,11 @@ TEST_F(VariantTest, parseIntEmptyBuffer) TEST_F(VariantTest, parseIntWithBadDigits) { - auto const in = std::string { "i6z4e" }; - auto constexpr InitVal = int64_t { 888 }; + auto const in = std::string{ "i6z4e" }; + auto constexpr InitVal = int64_t{ 888 }; uint8_t const* end = {}; - auto val = int64_t { InitVal }; + auto val = int64_t{ InitVal }; auto const err = bencParseInt(in, &end, &val); EXPECT_EQ(EILSEQ, err); EXPECT_EQ(InitVal, val); @@ -101,10 +99,10 @@ TEST_F(VariantTest, parseIntWithBadDigits) TEST_F(VariantTest, parseNegativeInt) { - auto const in = std::string { "i-3e" }; + auto const in = std::string{ "i-3e" }; uint8_t const* end = {}; - auto val = int64_t {}; + auto val = int64_t{}; auto const err = bencParseInt(in, &end, &val); EXPECT_EQ(0, err); EXPECT_EQ(-3, val); @@ -113,10 +111,10 @@ TEST_F(VariantTest, parseNegativeInt) TEST_F(VariantTest, parseIntZero) { - auto const in = std::string { "i0e" }; + auto const in = std::string{ "i0e" }; uint8_t const* end = {}; - auto val = int64_t {}; + auto val = int64_t{}; auto const err = bencParseInt(in, &end, &val); EXPECT_EQ(0, err); EXPECT_EQ(0, val); @@ -125,11 +123,11 @@ TEST_F(VariantTest, parseIntZero) TEST_F(VariantTest, parseIntWithLeadingZero) { - auto const in = std::string { "i04e" }; - auto constexpr InitVal = int64_t { 888 }; + auto const in = std::string{ "i04e" }; + auto constexpr InitVal = int64_t{ 888 }; uint8_t const* end = {}; - auto val = int64_t { InitVal }; + auto val = int64_t{ InitVal }; auto const err = bencParseInt(in, &end, &val); EXPECT_EQ(EILSEQ, err); // no leading zeroes allowed EXPECT_EQ(InitVal, val); @@ -248,7 +246,8 @@ TEST_F(VariantTest, parse) tr_variantFree(&val); } -TEST_F(VariantTest, bencParseAndReencode) { +TEST_F(VariantTest, bencParseAndReencode) +{ struct LocalTest { std::string benc; @@ -264,7 +263,7 @@ TEST_F(VariantTest, bencParseAndReencode) { { "d8:completei1e8:intervali1800e12:min intervali1800e5:peers0:e", true }, { "d1:ai0e1:be", false }, // odd number of children { "", false }, - { " ", false } + { " ", false }, }; for (auto const& test : tests) @@ -291,8 +290,8 @@ TEST_F(VariantTest, bencParseAndReencode) { TEST_F(VariantTest, bencSortWhenSerializing) { - auto const in = std::string { "lld1:bi32e1:ai64eeee" }; - auto const expected_out = std::string { "lld1:ai64e1:bi32eeee" }; + auto const in = std::string{ "lld1:bi32e1:ai64eeee" }; + auto const expected_out = std::string{ "lld1:ai64e1:bi32eeee" }; tr_variant val; char const* end; @@ -310,8 +309,8 @@ TEST_F(VariantTest, bencSortWhenSerializing) TEST_F(VariantTest, bencMalformedTooManyEndings) { - auto const in = std::string { "leee" }; - auto const expected_out = std::string { "le" }; + auto const in = std::string{ "leee" }; + auto const expected_out = std::string{ "le" }; tr_variant val; char const* end; @@ -329,14 +328,14 @@ TEST_F(VariantTest, bencMalformedTooManyEndings) TEST_F(VariantTest, bencMalformedNoEnding) { - auto const in = std::string { "l1:a1:b1:c" }; + auto const in = std::string{ "l1:a1:b1:c" }; tr_variant val; EXPECT_EQ(EILSEQ, tr_variantFromBenc(&val, in.data(), in.size())); } TEST_F(VariantTest, bencMalformedIncompleteString) { - auto const in = std::string { "1:" }; + auto const in = std::string{ "1:" }; tr_variant val; EXPECT_EQ(EILSEQ, tr_variantFromBenc(&val, in.data(), in.size())); } @@ -494,7 +493,7 @@ TEST_F(VariantTest, boolAndIntRecast) TEST_F(VariantTest, dictFindType) { - auto const expected_str = std::string { "this-is-a-string" }; + auto const expected_str = std::string{ "this-is-a-string" }; auto const expected_bool = bool{ true }; auto const expected_int = int{ 1234 }; auto const expected_real = double{ 0.3 }; @@ -539,7 +538,7 @@ TEST_F(VariantTest, dictFindType) EXPECT_EQ(std::lrint(expected_real * 100), std::lrint(d * 100)); // look up the keys as ints - auto i = int64_t {}; + auto i = int64_t{}; EXPECT_TRUE(tr_variantDictFindInt(&top, key_bool, &i)); EXPECT_EQ(expected_bool ? 1 : 0, i); EXPECT_FALSE(tr_variantDictFindInt(&top, key_real, &i)); diff --git a/tests/libtransmission/watchdir-test.cc b/tests/libtransmission/watchdir-test.cc index 1acb319fb..ba5c83a5a 100644 --- a/tests/libtransmission/watchdir-test.cc +++ b/tests/libtransmission/watchdir-test.cc @@ -25,20 +25,20 @@ extern "C" { -extern struct timeval tr_watchdir_generic_interval; -extern unsigned int tr_watchdir_retry_limit; -extern struct timeval tr_watchdir_retry_start_interval; -extern struct timeval tr_watchdir_retry_max_interval; + extern struct timeval tr_watchdir_generic_interval; + extern unsigned int tr_watchdir_retry_limit; + extern struct timeval tr_watchdir_retry_start_interval; + extern struct timeval tr_watchdir_retry_max_interval; } namespace { -auto constexpr FiftyMsec = timeval { 0, 50000 }; -auto constexpr OneHundredMsec = timeval { 0, 100000 }; -auto constexpr TwoHundredMsec = timeval { 0, 200000 }; +auto constexpr FiftyMsec = timeval{ 0, 50000 }; +auto constexpr OneHundredMsec = timeval{ 0, 100000 }; +auto constexpr TwoHundredMsec = timeval{ 0, 200000 }; -} +} // namespace namespace libtransmission { @@ -52,9 +52,9 @@ enum class WatchMode GENERIC }; -class WatchDirTest : - public SandboxedTest, - public ::testing::WithParamInterface +class WatchDirTest + : public SandboxedTest + , public ::testing::WithParamInterface { private: std::shared_ptr ev_base_; @@ -112,9 +112,11 @@ protected: struct CallbackData { - explicit CallbackData(tr_watchdir_status status = TR_WATCHDIR_ACCEPT) : - result{status} {} - tr_watchdir_status result {}; + explicit CallbackData(tr_watchdir_status status = TR_WATCHDIR_ACCEPT) + : result{ status } + { + } + tr_watchdir_status result{}; tr_watchdir_t wd = {}; std::string name = {}; @@ -167,7 +169,7 @@ TEST_P(WatchDirTest, initialScan) } // add a file - auto const base_name = std::string { "test.txt" }; + auto const base_name = std::string{ "test.txt" }; createFile(path, base_name); // confirm that a wd will pick up the file that @@ -198,7 +200,7 @@ TEST_P(WatchDirTest, watch) EXPECT_EQ("", wd_data.name); // test that a new file in an empty directory shows up - auto const file1 = std::string { "test1" }; + auto const file1 = std::string{ "test1" }; createFile(path, file1); processEvents(); EXPECT_EQ(wd, wd_data.wd); @@ -206,7 +208,7 @@ TEST_P(WatchDirTest, watch) // test that a new file in a nonempty directory shows up wd_data = CallbackData(TR_WATCHDIR_ACCEPT); - auto const file2 = std::string { "test2" }; + auto const file2 = std::string{ "test2" }; createFile(path, file2); processEvents(); EXPECT_EQ(wd, wd_data.wd); @@ -245,7 +247,7 @@ TEST_P(WatchDirTest, watchTwoDirs) // add a file into directory 1 and confirm it triggers // a callback with the right wd - auto const file1 = std::string { "test.txt" }; + auto const file1 = std::string{ "test.txt" }; createFile(dir1, file1); processEvents(); EXPECT_EQ(wd1, wd1_data.wd); @@ -257,7 +259,7 @@ TEST_P(WatchDirTest, watchTwoDirs) // a callback with the right wd wd1_data = CallbackData(TR_WATCHDIR_ACCEPT); wd2_data = CallbackData(TR_WATCHDIR_ACCEPT); - auto const file2 = std::string { "test2.txt" }; + auto const file2 = std::string{ "test2.txt" }; createFile(dir2, file2); processEvents(); EXPECT_EQ(nullptr, wd1_data.wd); @@ -270,8 +272,8 @@ TEST_P(WatchDirTest, watchTwoDirs) // be testing. wd1_data = CallbackData(TR_WATCHDIR_IGNORE); wd2_data = CallbackData(TR_WATCHDIR_IGNORE); - auto const file3 = std::string { "test3.txt" }; - auto const file4 = std::string { "test4.txt" }; + auto const file3 = std::string{ "test3.txt" }; + auto const file4 = std::string{ "test4.txt" }; createFile(dir1, file3); createFile(dir2, file4); processEvents(); @@ -285,7 +287,7 @@ TEST_P(WatchDirTest, watchTwoDirs) // and a new directory in directory 'b' wd1_data = CallbackData(TR_WATCHDIR_ACCEPT); wd2_data = CallbackData(TR_WATCHDIR_ACCEPT); - auto const file5 = std::string { "test5.txt" }; + auto const file5 = std::string{ "test5.txt" }; createFile(dir1, file5); createDir(dir2, file5); processEvents(); @@ -300,7 +302,7 @@ TEST_P(WatchDirTest, watchTwoDirs) // and a new directory in directory 'a' wd1_data = CallbackData(TR_WATCHDIR_ACCEPT); wd2_data = CallbackData(TR_WATCHDIR_ACCEPT); - auto const file6 = std::string { "test6.txt" }; + auto const file6 = std::string{ "test6.txt" }; createDir(dir1, file6); createFile(dir2, file6); processEvents(); @@ -313,8 +315,8 @@ TEST_P(WatchDirTest, watchTwoDirs) // watchdirs still triggers no callbacks wd1_data = CallbackData(TR_WATCHDIR_ACCEPT); wd2_data = CallbackData(TR_WATCHDIR_ACCEPT); - auto const file7 = std::string { "test7.txt" }; - auto const file8 = std::string { "test8.txt" }; + auto const file7 = std::string{ "test7.txt" }; + auto const file8 = std::string{ "test8.txt" }; createDir(dir1, file7); createDir(dir2, file8); processEvents(); @@ -349,7 +351,7 @@ TEST_P(WatchDirTest, retry) EXPECT_EQ(nullptr, wd_data.wd); EXPECT_EQ("", wd_data.name); - auto const test_file = std::string { "test" }; + auto const test_file = std::string{ "test" }; createFile(path, test_file); processEvents(); EXPECT_EQ(nullptr, wd_data.wd); @@ -363,11 +365,12 @@ TEST_P(WatchDirTest, retry) EXPECT_EQ(test_file, wd_data.name); } -INSTANTIATE_TEST_SUITE_P( +INSTANTIATE_TEST_SUITE_P( // WatchDir, WatchDirTest, - ::testing::Values(WatchMode::NATIVE, WatchMode::GENERIC) - ); + ::testing::Values( // + WatchMode::NATIVE, + WatchMode::GENERIC)); } // namespace test diff --git a/third-party/.clang-format b/third-party/.clang-format new file mode 100644 index 000000000..e871ed18b --- /dev/null +++ b/third-party/.clang-format @@ -0,0 +1,3 @@ +--- +DisableFormat: true +SortIncludes: false diff --git a/utils/create.c b/utils/create.c index 53c46a02a..66eaf198c 100644 --- a/utils/create.c +++ b/utils/create.c @@ -33,8 +33,7 @@ static char const* outfile = NULL; static char const* infile = NULL; static uint32_t piecesize_kib = 0; -static tr_option options[] = -{ +static tr_option options[] = { { 'p', "private", "Allow this torrent to only be used with the specified tracker(s)", "p", false, NULL }, { 'o', "outfile", "Save the generated .torrent to this filename", "o", true, "" }, { 's', "piecesize", "Set how many KiB each piece should be, overriding the preferred default", "s", true, "" }, @@ -204,9 +203,13 @@ int tr_main(int argc, char* argv[]) } char buf[128]; - printf(b->fileCount > 1 ? " %" PRIu32 " files, %s\n" : " %" PRIu32 " file, %s\n", b->fileCount, + printf( + b->fileCount > 1 ? " %" PRIu32 " files, %s\n" : " %" PRIu32 " file, %s\n", + b->fileCount, tr_formatter_size_B(buf, b->totalSize, sizeof(buf))); - printf(b->pieceCount > 1 ? " %" PRIu32 " pieces, %s each\n" : " %" PRIu32 " piece, %s\n", b->pieceCount, + printf( + b->pieceCount > 1 ? " %" PRIu32 " pieces, %s each\n" : " %" PRIu32 " piece, %s\n", + b->pieceCount, tr_formatter_size_B(buf, b->pieceSize, sizeof(buf))); tr_makeMetaInfo(b, outfile, trackers, trackerCount, comment, isPrivate); diff --git a/utils/edit.c b/utils/edit.c index cff2a30c1..f6dd24265 100644 --- a/utils/edit.c +++ b/utils/edit.c @@ -28,8 +28,7 @@ static char const* add = NULL; static char const* deleteme = NULL; static char const* replace[2] = { NULL, NULL }; -static tr_option options[] = -{ +static tr_option options[] = { { 'a', "add", "Add a tracker's announce URL", "a", true, "" }, { 'd', "delete", "Delete a tracker's announce URL", "d", true, "" }, { 'r', "replace", "Search and replace a substring in the announce URLs", "r", true, " " }, diff --git a/utils/remote.c b/utils/remote.c index 5ac48d297..94fa49736 100644 --- a/utils/remote.c +++ b/utils/remote.c @@ -235,7 +235,9 @@ enum static char const* getUsage(void) { - return MY_NAME " " LONG_VERSION_STRING "\n" + // clang-format off + return + MY_NAME " " LONG_VERSION_STRING "\n" "A fast and easy BitTorrent client\n" "https://transmissionbt.com/\n" "\n" @@ -245,6 +247,7 @@ static char const* getUsage(void) " " MY_NAME " [http(s?)://host:port/transmission/] [options]\n" "\n" "See the man page for detailed explanations and many examples."; + // clang-format on } /*** @@ -253,13 +256,12 @@ static char const* getUsage(void) **** ***/ -static tr_option opts[] = -{ +static tr_option opts[] = { { 'a', "add", "Add torrent files by filename or URL", "a", false, NULL }, { 970, "alt-speed", "Use the alternate Limits", "as", false, NULL }, { 971, "no-alt-speed", "Don't use the alternate Limits", "AS", false, NULL }, - { 972, "alt-speed-downlimit", "max alternate download speed (in "SPEED_K_STR ")", "asd", true, "" }, - { 973, "alt-speed-uplimit", "max alternate upload speed (in "SPEED_K_STR ")", "asu", true, "" }, + { 972, "alt-speed-downlimit", "max alternate download speed (in " SPEED_K_STR ")", "asd", true, "" }, + { 973, "alt-speed-uplimit", "max alternate upload speed (in " SPEED_K_STR ")", "asu", true, "" }, { 974, "alt-speed-scheduler", "Use the scheduled on/off times", "asc", false, NULL }, { 975, "no-alt-speed-scheduler", "Don't use the scheduled on/off times", "ASC", false, NULL }, { 976, "alt-speed-time-begin", "Time to start using the alt speed limits (in hhmm)", NULL, true, "