diff --git a/Transmission.xcodeproj/project.pbxproj b/Transmission.xcodeproj/project.pbxproj index 85bdb6a96..1b72b6d72 100644 --- a/Transmission.xcodeproj/project.pbxproj +++ b/Transmission.xcodeproj/project.pbxproj @@ -2180,7 +2180,8 @@ 29B97313FDCFA39411CA2CEA /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 0420; + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 0920; ORGANIZATIONNAME = "The Transmission Project"; TargetAttributes = { 8D1107260486CEB800E47090 = { @@ -3054,11 +3055,19 @@ ALWAYS_SEARCH_USER_PATHS = NO; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = "Accent Color"; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COMBINE_HIDPI_IMAGES = YES; @@ -3080,6 +3089,7 @@ ); GCC_UNROLL_LOOPS = YES; GCC_VERSION = com.apple.compilers.llvm.clang.1_0; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; @@ -3203,11 +3213,19 @@ ALWAYS_SEARCH_USER_PATHS = NO; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = "Accent Color"; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COMBINE_HIDPI_IMAGES = YES; @@ -3228,6 +3246,7 @@ ); GCC_UNROLL_LOOPS = YES; GCC_VERSION = com.apple.compilers.llvm.clang.1_0; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; @@ -3285,11 +3304,19 @@ ALWAYS_SEARCH_USER_PATHS = NO; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = "Accent Color"; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COMBINE_HIDPI_IMAGES = YES; @@ -3311,6 +3338,7 @@ ); GCC_UNROLL_LOOPS = YES; GCC_VERSION = com.apple.compilers.llvm.clang.1_0; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; diff --git a/macosx/AboutWindowController.h b/macosx/AboutWindowController.h index 610be4b74..b264569b0 100644 --- a/macosx/AboutWindowController.h +++ b/macosx/AboutWindowController.h @@ -30,7 +30,7 @@ IBOutlet NSPanel * fLicenseSheet; } -+ (AboutWindowController *) aboutController; +@property (nonatomic, class, readonly) AboutWindowController * aboutController; - (IBAction) showLicense: (id) sender; - (IBAction) hideLicense: (id) sender; diff --git a/macosx/AboutWindowController.m b/macosx/AboutWindowController.m index 740bbbc04..8f2af4ad6 100644 --- a/macosx/AboutWindowController.m +++ b/macosx/AboutWindowController.m @@ -36,29 +36,29 @@ AboutWindowController * fAboutBoxInstance = nil; - (void) awakeFromNib { - [fVersionField setStringValue: @(LONG_VERSION_STRING)]; + fVersionField.stringValue = @(LONG_VERSION_STRING); - [fCopyrightField setStringValue: [[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]); + const CGFloat oldButtonWidth = NSWidth(fLicenseButton.frame); - [fLicenseButton setTitle: NSLocalizedString(@"License", "About window -> license button")]; + fLicenseButton.title = NSLocalizedString(@"License", "About window -> license button"); [fLicenseButton sizeToFit]; - NSRect buttonFrame = [fLicenseButton frame]; + NSRect buttonFrame = fLicenseButton.frame; buttonFrame.size.width += 10.0; buttonFrame.origin.x -= NSWidth(buttonFrame) - oldButtonWidth; - [fLicenseButton setFrame: buttonFrame]; + fLicenseButton.frame = buttonFrame; } - (void) windowDidLoad { - [[self window] center]; + [self.window center]; } - (void) windowWillClose: (id) sender @@ -68,10 +68,10 @@ AboutWindowController * fAboutBoxInstance = nil; - (IBAction) showLicense: (id) sender { - NSString * licenseText = [NSString stringWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @"COPYING" ofType: nil] + NSString * licenseText = [NSString stringWithContentsOfFile: [NSBundle.mainBundle pathForResource: @"COPYING" ofType: nil] usedEncoding: nil error: NULL]; - [fLicenseView setString: licenseText]; - [fLicenseCloseButton setTitle: NSLocalizedString(@"OK", "About window -> license close button")]; + fLicenseView.string = licenseText; + fLicenseCloseButton.title = NSLocalizedString(@"OK", "About window -> license close button"); [self.window beginSheet: fLicenseSheet completionHandler:nil]; } diff --git a/macosx/AddMagnetWindowController.h b/macosx/AddMagnetWindowController.h index ac14c1608..1fad103a3 100644 --- a/macosx/AddMagnetWindowController.h +++ b/macosx/AddMagnetWindowController.h @@ -50,9 +50,9 @@ TorrentDeterminationType fGroupDeterminationType; } -- (id) initWithTorrent: (Torrent *) torrent destination: (NSString *) path controller: (Controller *) controller; +- (instancetype) initWithTorrent: (Torrent *) torrent destination: (NSString *) path controller: (Controller *) controller; -- (Torrent *) torrent; +@property (nonatomic, readonly) Torrent *torrent; - (void) setDestination: (id) sender; diff --git a/macosx/AddMagnetWindowController.m b/macosx/AddMagnetWindowController.m index 3ca9497dc..4951b2037 100644 --- a/macosx/AddMagnetWindowController.m +++ b/macosx/AddMagnetWindowController.m @@ -44,16 +44,16 @@ @implementation AddMagnetWindowController -- (id) initWithTorrent: (Torrent *) torrent destination: (NSString *) path controller: (Controller *) controller +- (instancetype) initWithTorrent: (Torrent *) torrent destination: (NSString *) path controller: (Controller *) controller { if ((self = [super initWithWindowNibName: @"AddMagnetWindow"])) { fTorrent = torrent; - fDestination = [path stringByExpandingTildeInPath]; + fDestination = path.stringByExpandingTildeInPath; fController = controller; - fGroupValue = [torrent groupValue]; + fGroupValue = torrent.groupValue; fGroupDeterminationType = TorrentDeterminationAutomatic; } return self; @@ -61,63 +61,63 @@ - (void) awakeFromNib { - [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateGroupMenu:) + [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateGroupMenu:) name: @"UpdateGroups" object: nil]; - NSString * name = [fTorrent name]; - [[self window] setTitle: name]; - [fNameField setStringValue: name]; - [fNameField setToolTip: name]; + NSString * name = fTorrent.name; + self.window.title = name; + fNameField.stringValue = name; + fNameField.toolTip = name; [self setGroupsMenu]; [fGroupPopUp selectItemWithTag: fGroupValue]; NSInteger priorityIndex; - switch ([fTorrent priority]) + 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]); + NSAssert1(NO, @"Unknown priority for adding torrent: %d", fTorrent.priority); priorityIndex = POPUP_PRIORITY_NORMAL; } [fPriorityPopUp selectItemAtIndex: priorityIndex]; - [fStartCheck setState: [[NSUserDefaults standardUserDefaults] boolForKey: @"AutoStartDownload"] ? NSOnState : NSOffState]; + fStartCheck.state = [NSUserDefaults.standardUserDefaults boolForKey: @"AutoStartDownload"] ? NSOnState : NSOffState; if (fDestination) [self setDestinationPath: fDestination determinationType: TorrentDeterminationAutomatic]; else { - [fLocationField setStringValue: @""]; - [fLocationImageView setImage: nil]; + fLocationField.stringValue = @""; + fLocationImageView.image = nil; } #warning when 10.7-only, switch to auto layout [fMagnetLinkLabel sizeToFit]; - const CGFloat downloadToLabelOldWidth = [fDownloadToLabel frame].size.width; + const CGFloat downloadToLabelOldWidth = fDownloadToLabel.frame.size.width; [fDownloadToLabel sizeToFit]; - const CGFloat changeDestOldWidth = [fChangeDestinationButton frame].size.width; + const CGFloat changeDestOldWidth = fChangeDestinationButton.frame.size.width; [fChangeDestinationButton sizeToFit]; - NSRect changeDestFrame = [fChangeDestinationButton frame]; + NSRect changeDestFrame = fChangeDestinationButton.frame; changeDestFrame.origin.x -= changeDestFrame.size.width - changeDestOldWidth; - [fChangeDestinationButton setFrame: changeDestFrame]; + fChangeDestinationButton.frame = changeDestFrame; - NSRect downloadToBoxFrame = [fDownloadToBox frame]; - const CGFloat downloadToBoxSizeDiff = ([fDownloadToLabel frame].size.width - downloadToLabelOldWidth) + (changeDestFrame.size.width - changeDestOldWidth); + NSRect downloadToBoxFrame = fDownloadToBox.frame; + const CGFloat downloadToBoxSizeDiff = (fDownloadToLabel.frame.size.width - downloadToLabelOldWidth) + (changeDestFrame.size.width - changeDestOldWidth); downloadToBoxFrame.size.width -= downloadToBoxSizeDiff; - downloadToBoxFrame.origin.x -= downloadToLabelOldWidth - [fDownloadToLabel frame].size.width; - [fDownloadToBox setFrame: downloadToBoxFrame]; + 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]); + NSRect groupPopUpFrame = fGroupPopUp.frame; + NSRect priorityPopUpFrame = fPriorityPopUp.frame; + const CGFloat popUpOffset = groupPopUpFrame.origin.x - NSMaxX(fGroupLabel.frame); [fGroupLabel sizeToFit]; [fPriorityLabel sizeToFit]; - NSRect groupLabelFrame = [fGroupLabel frame]; - NSRect priorityLabelFrame = [fPriorityLabel frame]; + NSRect groupLabelFrame = fGroupLabel.frame; + NSRect priorityLabelFrame = fPriorityLabel.frame; //first bring them both to the left edge groupLabelFrame.origin.x = MIN(groupLabelFrame.origin.x, priorityLabelFrame.origin.x); priorityLabelFrame.origin.x = MIN(groupLabelFrame.origin.x, priorityLabelFrame.origin.x); @@ -127,18 +127,18 @@ priorityLabelFrame.origin.x += labelWidth - priorityLabelFrame.size.width; groupPopUpFrame.origin.x = NSMaxX(groupLabelFrame) + popUpOffset; priorityPopUpFrame.origin.x = NSMaxX(priorityLabelFrame) + popUpOffset; - [fGroupLabel setFrame: groupLabelFrame]; - [fGroupPopUp setFrame: groupPopUpFrame]; - [fPriorityLabel setFrame: priorityLabelFrame]; - [fPriorityPopUp setFrame: priorityPopUpFrame]; + fGroupLabel.frame = groupLabelFrame; + fGroupPopUp.frame = groupPopUpFrame; + 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; + const CGFloat oldAddButtonWidth = fAddButton.bounds.size.width; + const CGFloat oldCancelButtonWidth = fCancelButton.bounds.size.width; [fAddButton sizeToFit]; [fCancelButton sizeToFit]; - NSRect addButtonFrame = [fAddButton frame]; - NSRect cancelButtonFrame = [fCancelButton frame]; + NSRect addButtonFrame = fAddButton.frame; + NSRect cancelButtonFrame = fCancelButton.frame; CGFloat buttonWidth = MAX(addButtonFrame.size.width, cancelButtonFrame.size.width); buttonWidth = MAX(buttonWidth, minButtonWidth); addButtonFrame.size.width = buttonWidth; @@ -146,8 +146,8 @@ const CGFloat addButtonWidthIncrease = buttonWidth - oldAddButtonWidth; addButtonFrame.origin.x -= addButtonWidthIncrease; cancelButtonFrame.origin.x -= addButtonWidthIncrease + (buttonWidth - oldCancelButtonWidth); - [fAddButton setFrame: addButtonFrame]; - [fCancelButton setFrame: cancelButtonFrame]; + fAddButton.frame = addButtonFrame; + fCancelButton.frame = cancelButtonFrame; [fStartCheck sizeToFit]; } @@ -161,7 +161,7 @@ - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; } - (Torrent *) torrent @@ -173,18 +173,18 @@ { NSOpenPanel * panel = [NSOpenPanel openPanel]; - [panel setPrompt: NSLocalizedString(@"Select", "Open torrent -> prompt")]; - [panel setAllowsMultipleSelection: NO]; - [panel setCanChooseFiles: NO]; - [panel setCanChooseDirectories: YES]; - [panel setCanCreateDirectories: YES]; + panel.prompt = NSLocalizedString(@"Select", "Open torrent -> prompt"); + panel.allowsMultipleSelection = NO; + panel.canChooseFiles = NO; + panel.canChooseDirectories = YES; + panel.canCreateDirectories = YES; - [panel setMessage: [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) @@ -195,22 +195,22 @@ - (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 setMessageText: NSLocalizedString(@"The destination directory and root data directory have the same name.", - "Add torrent -> same name -> title")]; - [alert setInformativeText: 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 setAlertStyle: NSWarningAlertStyle]; + 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 setShowsSuppressionButton: YES]; + alert.showsSuppressionButton = YES; - [alert beginSheetModalForWindow:[self window] completionHandler:^(NSModalResponse returnCode) { - if ([[alert suppressionButton] state] == NSOnState) - [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningFolderDataSameName"]; + [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { + if (alert.suppressionButton.state == NSOnState) + [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningFolderDataSameName"]; if (returnCode == NSAlertSecondButtonReturn) [self performSelectorOnMainThread: @selector(confirmAdd) withObject: nil waitUntilDone: NO]; @@ -222,7 +222,7 @@ - (void) cancelAdd: (id) sender { - [[self window] performClose: sender]; + [self.window performClose: sender]; } //only called on cancel @@ -244,7 +244,7 @@ NSAssert1(NO, @"Unknown priority tag for adding torrent: %ld", [sender tag]); priority = TR_PRI_NORMAL; } - [fTorrent setPriority: priority]; + fTorrent.priority = priority; } - (void) updateGroupMenu: (NSNotification *) notification @@ -266,7 +266,7 @@ { [fTorrent setGroupValue: fGroupValue determinationType: fGroupDeterminationType]; - if ([fStartCheck state] == NSOnState) + if (fStartCheck.state == NSOnState) [fTorrent startTransfer]; [self close]; @@ -275,7 +275,7 @@ - (void) setDestinationPath: (NSString *) destination determinationType: (TorrentDeterminationType) determinationType { - destination = [destination stringByExpandingTildeInPath]; + destination = destination.stringByExpandingTildeInPath; if (!fDestination || ![fDestination isEqualToString: destination]) { fDestination = destination; @@ -283,17 +283,17 @@ [fTorrent changeDownloadFolderBeforeUsing: fDestination determinationType: determinationType]; } - [fLocationField setStringValue: [fDestination stringByAbbreviatingWithTildeInPath]]; - [fLocationField setToolTip: fDestination]; + fLocationField.stringValue = fDestination.stringByAbbreviatingWithTildeInPath; + fLocationField.toolTip = fDestination; ExpandedPathToIconTransformer * iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; - [fLocationImageView setImage: [iconTransformer transformedValue: fDestination]]; + fLocationImageView.image = [iconTransformer transformedValue: fDestination]; } - (void) setGroupsMenu { - NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(changeGroupValue:) isSmall: NO]; - [fGroupPopUp setMenu: groupMenu]; + NSMenu * groupMenu = [GroupsController.groups groupMenuWithTarget: self action: @selector(changeGroupValue:) isSmall: NO]; + fGroupPopUp.menu = groupMenu; } - (void) changeGroupValue: (id) sender @@ -302,10 +302,10 @@ 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]; + 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; } diff --git a/macosx/AddWindowController.h b/macosx/AddWindowController.h index 6bb264618..0f2f0a40a 100644 --- a/macosx/AddWindowController.h +++ b/macosx/AddWindowController.h @@ -56,11 +56,11 @@ TorrentDeterminationType fGroupValueDetermination; } -- (id) initWithTorrent: (Torrent *) torrent destination: (NSString *) path lockDestination: (BOOL) lockDestination +- (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) -- (Torrent *) torrent; +@property (nonatomic, readonly) Torrent *torrent; - (void) setDestination: (id) sender; diff --git a/macosx/AddWindowController.m b/macosx/AddWindowController.m index c600702bf..4ab56a475 100644 --- a/macosx/AddWindowController.m +++ b/macosx/AddWindowController.m @@ -49,57 +49,57 @@ @implementation AddWindowController -- (id) initWithTorrent: (Torrent *) torrent destination: (NSString *) path lockDestination: (BOOL) lockDestination +- (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"])) { fTorrent = torrent; - fDestination = [path stringByExpandingTildeInPath]; + fDestination = path.stringByExpandingTildeInPath; fLockDestination = lockDestination; fController = controller; - fTorrentFile = [torrentFile stringByExpandingTildeInPath]; + fTorrentFile = torrentFile.stringByExpandingTildeInPath; fDeleteTorrentEnableInitially = deleteTorrent; fCanToggleDelete = canToggleDelete; - fGroupValue = [torrent groupValue]; + fGroupValue = torrent.groupValue; fGroupValueDetermination = TorrentDeterminationAutomatic; - [fVerifyIndicator setUsesThreadedAnimation: YES]; + fVerifyIndicator.usesThreadedAnimation = YES; } return self; } - (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]; - NSString * name = [fTorrent name]; - [[self window] setTitle: name]; - [fNameField setStringValue: name]; - [fNameField setToolTip: name]; + NSString * name = fTorrent.name; + self.window.title = name; + fNameField.stringValue = name; + fNameField.toolTip = name; - [fIconView setImage: [fTorrent icon]]; + fIconView.image = fTorrent.icon; - if (![fTorrent isFolder]) + if (!fTorrent.folder) { - [fFileFilterField setHidden: YES]; - [fCheckAllButton setHidden: YES]; - [fUncheckAllButton setHidden: YES]; + fFileFilterField.hidden = YES; + fCheckAllButton.hidden = YES; + fUncheckAllButton.hidden = YES; - NSRect scrollFrame = [fFileScrollView frame]; - const CGFloat diff = NSMinY([fFileScrollView frame]) - NSMinY([fFileFilterField frame]); + NSRect scrollFrame = fFileScrollView.frame; + const CGFloat diff = NSMinY(fFileScrollView.frame) - NSMinY(fFileFilterField.frame); scrollFrame.origin.y -= diff; scrollFrame.size.height += diff; - [fFileScrollView setFrame: scrollFrame]; + fFileScrollView.frame = scrollFrame; } else [self updateCheckButtons: nil]; @@ -108,28 +108,28 @@ [fGroupPopUp selectItemWithTag: fGroupValue]; NSInteger priorityIndex; - switch ([fTorrent priority]) + 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]); + NSAssert1(NO, @"Unknown priority for adding torrent: %d", fTorrent.priority); priorityIndex = POPUP_PRIORITY_NORMAL; } [fPriorityPopUp selectItemAtIndex: priorityIndex]; - [fStartCheck setState: [[NSUserDefaults standardUserDefaults] boolForKey: @"AutoStartDownload"] ? NSOnState : NSOffState]; + fStartCheck.state = [NSUserDefaults.standardUserDefaults boolForKey: @"AutoStartDownload"] ? NSOnState : NSOffState; - [fDeleteCheck setState: fDeleteTorrentEnableInitially ? NSOnState : NSOffState]; - [fDeleteCheck setEnabled: fCanToggleDelete]; + fDeleteCheck.state = fDeleteTorrentEnableInitially ? NSOnState : NSOffState; + fDeleteCheck.enabled = fCanToggleDelete; if (fDestination) [self setDestinationPath: fDestination determinationType: (fLockDestination ? TorrentDeterminationUserSpecified : TorrentDeterminationAutomatic)]; else { - [fLocationField setStringValue: @""]; - [fLocationImageView setImage: nil]; + fLocationField.stringValue = @""; + fLocationImageView.image = nil; } fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_SECONDS target: self @@ -146,7 +146,7 @@ - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; [fTimer invalidate]; } @@ -160,20 +160,20 @@ { NSOpenPanel * panel = [NSOpenPanel openPanel]; - [panel setPrompt: NSLocalizedString(@"Select", "Open torrent -> prompt")]; - [panel setAllowsMultipleSelection: NO]; - [panel setCanChooseFiles: NO]; - [panel setCanChooseDirectories: YES]; - [panel setCanCreateDirectories: YES]; + panel.prompt = NSLocalizedString(@"Select", "Open torrent -> prompt"); + panel.allowsMultipleSelection = NO; + panel.canChooseFiles = NO; + panel.canChooseDirectories = YES; + panel.canCreateDirectories = YES; - [panel setMessage: [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 { @@ -185,22 +185,22 @@ - (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 setMessageText: NSLocalizedString(@"The destination directory and root data directory have the same name.", - "Add torrent -> same name -> title")]; - [alert setInformativeText: 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 setAlertStyle: NSWarningAlertStyle]; + 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 setShowsSuppressionButton: YES]; + alert.showsSuppressionButton = YES; [alert beginSheetModalForWindow:[self window] completionHandler:^(NSModalResponse returnCode) { - if ([[alert suppressionButton] state] == NSOnState) - [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningFolderDataSameName"]; + if (alert.suppressionButton.state == NSOnState) + [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningFolderDataSameName"]; if (returnCode == NSAlertSecondButtonReturn) [self performSelectorOnMainThread: @selector(confirmAdd) withObject: nil waitUntilDone: NO]; @@ -212,7 +212,7 @@ - (void) cancelAdd: (id) sender { - [[self window] performClose: sender]; + [self.window performClose: sender]; } //only called on cancel @@ -260,23 +260,23 @@ NSAssert1(NO, @"Unknown priority tag for adding torrent: %ld", [sender tag]); priority = TR_PRI_NORMAL; } - [fTorrent setPriority: priority]; + fTorrent.priority = priority; } - (void) updateCheckButtons: (NSNotification *) notification { - NSString * statusString = [NSString stringForFileSize: [fTorrent size]]; - if ([fTorrent isFolder]) + 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])]]; - [fCheckAllButton setEnabled: filesCheckState != NSOnState]; //if anything is unchecked - [fUncheckAllButton setEnabled: ![fTorrent allDownloaded]]; //if there are any checked files that aren't finished + const NSInteger 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; - NSInteger count = [fTorrent fileCount]; + NSInteger count = fTorrent.fileCount; if (count != 1) fileString = [NSString stringWithFormat: NSLocalizedString(@"%@ files", "Add torrent -> info"), [NSString formattedUInteger: count]]; @@ -284,12 +284,12 @@ fileString = NSLocalizedString(@"1 file", "Add torrent -> info"); NSString * selectedString = [NSString stringWithFormat: NSLocalizedString(@"%@ selected", "Add torrent -> info"), - [NSString stringForFileSize: [fTorrent totalSizeSelected]]]; + [NSString stringForFileSize: fTorrent.totalSizeSelected]]; statusString = [NSString stringWithFormat: @"%@, %@ (%@)", fileString, statusString, selectedString]; } - [fStatusField setStringValue: statusString]; + fStatusField.stringValue = statusString; } - (void) updateGroupMenu: (NSNotification *) notification @@ -315,17 +315,17 @@ [self updateCheckButtons: nil]; //call in case button state changed by checking - if ([fTorrent isChecking]) + if (fTorrent.checking) { - const BOOL waiting = [fTorrent isCheckingWaiting]; - [fVerifyIndicator setIndeterminate: waiting]; + const BOOL waiting = fTorrent.checkingWaiting; + fVerifyIndicator.indeterminate = waiting; if (waiting) [fVerifyIndicator startAnimation: self]; else - [fVerifyIndicator setDoubleValue: [fTorrent checkingProgress]]; + fVerifyIndicator.doubleValue = fTorrent.checkingProgress; } else { - [fVerifyIndicator setIndeterminate: YES]; //we want to hide when stopped, which only applies when indeterminate + fVerifyIndicator.indeterminate = YES; //we want to hide when stopped, which only applies when indeterminate [fVerifyIndicator stopAnimation: self]; } } @@ -336,10 +336,10 @@ fTimer = nil; [fTorrent setGroupValue: fGroupValue determinationType: fGroupValueDetermination]; - if (fTorrentFile && fCanToggleDelete && [fDeleteCheck state] == NSOnState) + if (fTorrentFile && fCanToggleDelete && fDeleteCheck.state == NSOnState) [Torrent trashFile: fTorrentFile error: nil]; - if ([fStartCheck state] == NSOnState) + if (fStartCheck.state == NSOnState) [fTorrent startTransfer]; [fFileController setTorrent: nil]; //avoid a crash when window tries to update @@ -350,7 +350,7 @@ - (void) setDestinationPath: (NSString *) destination determinationType: (TorrentDeterminationType) determinationType { - destination = [destination stringByExpandingTildeInPath]; + destination = destination.stringByExpandingTildeInPath; if (!fDestination || ![fDestination isEqualToString: destination]) { fDestination = destination; @@ -358,17 +358,17 @@ [fTorrent changeDownloadFolderBeforeUsing: fDestination determinationType: determinationType]; } - [fLocationField setStringValue: [fDestination stringByAbbreviatingWithTildeInPath]]; - [fLocationField setToolTip: fDestination]; + fLocationField.stringValue = fDestination.stringByAbbreviatingWithTildeInPath; + fLocationField.toolTip = fDestination; ExpandedPathToIconTransformer * iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; - [fLocationImageView setImage: [iconTransformer transformedValue: fDestination]]; + fLocationImageView.image = [iconTransformer transformedValue: fDestination]; } - (void) setGroupsMenu { - NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(changeGroupValue:) isSmall: NO]; - [fGroupPopUp setMenu: groupMenu]; + NSMenu * groupMenu = [GroupsController.groups groupMenuWithTarget: self action: @selector(changeGroupValue:) isSmall: NO]; + fGroupPopUp.menu = groupMenu; } - (void) changeGroupValue: (id) sender @@ -379,10 +379,10 @@ 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]; + 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; } } diff --git a/macosx/BadgeView.h b/macosx/BadgeView.h index 7c8c0dff8..960fc5926 100644 --- a/macosx/BadgeView.h +++ b/macosx/BadgeView.h @@ -34,7 +34,7 @@ BOOL fQuitting; } -- (id) initWithLib: (tr_session *) lib; +- (instancetype) initWithLib: (tr_session *) lib; - (BOOL) setRatesWithDownload: (CGFloat) downloadRate upload: (CGFloat) uploadRate; - (void) setQuitting; diff --git a/macosx/BadgeView.m b/macosx/BadgeView.m index 73a952d1f..effe469ad 100644 --- a/macosx/BadgeView.m +++ b/macosx/BadgeView.m @@ -33,7 +33,7 @@ @implementation BadgeView -- (id) initWithLib: (tr_session *) lib +- (instancetype) initWithLib: (tr_session *) lib { if ((self = [super init])) { @@ -65,13 +65,13 @@ - (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]; + atHeight: (NSHeight(rect) - quitBadge.size.height) * 0.5 adjustForQuit: YES]; return; } @@ -83,7 +83,7 @@ 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 + bottom += uploadBadge.size.height + BETWEEN_PADDING; //download rate above upload rate } if (download) [self badge: [NSImage imageNamed: @"DownloadBadge"] string: [NSString stringForSpeedAbbrev: fDownloadRate] @@ -99,17 +99,17 @@ if (!fAttributes) { NSShadow * stringShadow = [[NSShadow alloc] init]; - [stringShadow setShadowOffset: NSMakeSize(2.0, -2.0)]; - [stringShadow setShadowBlurRadius: 4.0]; + stringShadow.shadowOffset = NSMakeSize(2.0, -2.0); + stringShadow.shadowBlurRadius = 4.0; fAttributes = [[NSMutableDictionary alloc] initWithCapacity: 3]; - fAttributes[NSForegroundColorAttributeName] = [NSColor whiteColor]; + fAttributes[NSForegroundColorAttributeName] = NSColor.whiteColor; fAttributes[NSShadowAttributeName] = stringShadow; } NSRect badgeRect; - badgeRect.size = [badge size]; + badgeRect.size = badge.size; badgeRect.origin.x = 0.0; badgeRect.origin.y = height; diff --git a/macosx/Badger.h b/macosx/Badger.h index e42d0110d..065e5ff28 100644 --- a/macosx/Badger.h +++ b/macosx/Badger.h @@ -33,7 +33,7 @@ NSMutableSet * fHashes; } -- (id) initWithLib: (tr_session *) lib; +- (instancetype) initWithLib: (tr_session *) lib; - (void) updateBadgeWithDownload: (CGFloat) downloadRate upload: (CGFloat) uploadRate; - (void) addCompletedTorrent: (Torrent *) torrent; diff --git a/macosx/Badger.m b/macosx/Badger.m index 520e662d2..e2f6b1459 100644 --- a/macosx/Badger.m +++ b/macosx/Badger.m @@ -27,14 +27,14 @@ @implementation Badger -- (id) initWithLib: (tr_session *) lib +- (instancetype) initWithLib: (tr_session *) lib { if ((self = [super init])) { fLib = lib; BadgeView * view = [[BadgeView alloc] initWithLib: lib]; - [[NSApp dockTile] setContentView: view]; + NSApp.dockTile.contentView = view; fHashes = [[NSMutableSet alloc] init]; } @@ -45,50 +45,50 @@ - (void) updateBadgeWithDownload: (CGFloat) downloadRate upload: (CGFloat) uploadRate { - const CGFloat displayDlRate = [[NSUserDefaults standardUserDefaults] boolForKey: @"BadgeDownloadRate"] + const CGFloat displayDlRate = [NSUserDefaults.standardUserDefaults boolForKey: @"BadgeDownloadRate"] ? downloadRate : 0.0; - const CGFloat displayUlRate = [[NSUserDefaults standardUserDefaults] boolForKey: @"BadgeUploadRate"] + const CGFloat 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]; + 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] setBadgeLabel: [NSString formattedUInteger: [fHashes count]]]; + [fHashes addObject: torrent.hashString]; + NSApp.dockTile.badgeLabel = [NSString formattedUInteger: fHashes.count]; } - (void) removeTorrent: (Torrent *) torrent { - if ([fHashes member: [torrent hashString]]) + if ([fHashes member: torrent.hashString]) { - [fHashes removeObject: [torrent hashString]]; - if ([fHashes count] > 0) - [[NSApp dockTile] setBadgeLabel: [NSString formattedUInteger: [fHashes count]]]; + [fHashes removeObject: torrent.hashString]; + if (fHashes.count > 0) + NSApp.dockTile.badgeLabel = [NSString formattedUInteger: fHashes.count]; else - [[NSApp dockTile] setBadgeLabel: @""]; + NSApp.dockTile.badgeLabel = @""; } } - (void) clearCompleted { - if ([fHashes count] > 0) + if (fHashes.count > 0) { [fHashes removeAllObjects]; - [[NSApp dockTile] setBadgeLabel: @""]; + NSApp.dockTile.badgeLabel = @""; } } - (void) setQuitting { [self clearCompleted]; - [(BadgeView *)[[NSApp dockTile] contentView] setQuitting]; - [[NSApp dockTile] display]; + [(BadgeView *)NSApp.dockTile.contentView setQuitting]; + [NSApp.dockTile display]; } @end diff --git a/macosx/BlocklistDownloader.h b/macosx/BlocklistDownloader.h index d739c9d30..d83944a45 100644 --- a/macosx/BlocklistDownloader.h +++ b/macosx/BlocklistDownloader.h @@ -24,12 +24,11 @@ @class BlocklistDownloaderViewController; -typedef enum -{ +typedef NS_ENUM(unsigned int, blocklistDownloadState) { BLOCKLIST_DL_START, BLOCKLIST_DL_DOWNLOADING, BLOCKLIST_DL_PROCESSING -} blocklistDownloadState; +}; @interface BlocklistDownloader : NSObject { @@ -45,7 +44,7 @@ typedef enum } + (BlocklistDownloader *) downloader; //starts download if not already occuring -+ (BOOL) isRunning; +@property (nonatomic, class, readonly) BOOL isRunning; - (void) setViewController: (BlocklistDownloaderViewController *) viewController; diff --git a/macosx/BlocklistDownloader.m b/macosx/BlocklistDownloader.m index 683e4dfbe..cc076806a 100644 --- a/macosx/BlocklistDownloader.m +++ b/macosx/BlocklistDownloader.m @@ -78,7 +78,7 @@ BlocklistDownloader * fBLDownloader = nil; [fDownload cancel]; - [[BlocklistScheduler scheduler] updateSchedule]; + [BlocklistScheduler.scheduler updateSchedule]; fBLDownloader = nil; } @@ -99,7 +99,7 @@ BlocklistDownloader * fBLDownloader = nil; fState = BLOCKLIST_DL_DOWNLOADING; fCurrentSize = 0; - fExpectedSize = [response expectedContentLength]; + fExpectedSize = response.expectedContentLength; [fViewController setStatusProgressForCurrentSize: fCurrentSize expectedSize: fExpectedSize]; } @@ -112,10 +112,10 @@ BlocklistDownloader * fBLDownloader = nil; - (void) download: (NSURLDownload *) download didFailWithError: (NSError *) error { - [fViewController setFailed: [error localizedDescription]]; + [fViewController setFailed: error.localizedDescription]; - [[NSUserDefaults standardUserDefaults] setObject: [NSDate date] forKey: @"BlocklistNewLastUpdate"]; - [[BlocklistScheduler scheduler] updateSchedule]; + [NSUserDefaults.standardUserDefaults setObject: [NSDate date] forKey: @"BlocklistNewLastUpdate"]; + [BlocklistScheduler.scheduler updateSchedule]; fBLDownloader = nil; } @@ -132,10 +132,10 @@ BlocklistDownloader * fBLDownloader = nil; [self decompressBlocklist]; dispatch_async(dispatch_get_main_queue(), ^{ - const int count = tr_blocklistSetContent([(Controller *)[NSApp delegate] sessionHandle], [fDestination UTF8String]); + const int 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]; @@ -145,11 +145,11 @@ BlocklistDownloader * fBLDownloader = nil; //update last updated date for schedule NSDate * date = [NSDate date]; - [[NSUserDefaults standardUserDefaults] setObject: date forKey: @"BlocklistNewLastUpdate"]; - [[NSUserDefaults standardUserDefaults] setObject: date forKey: @"BlocklistNewLastUpdateSuccess"]; - [[BlocklistScheduler scheduler] updateSchedule]; + [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; }); @@ -169,9 +169,9 @@ BlocklistDownloader * fBLDownloader = nil; { fState = BLOCKLIST_DL_START; - [[BlocklistScheduler scheduler] cancelSchedule]; + [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) @@ -185,28 +185,28 @@ BlocklistDownloader * fBLDownloader = nil; //.gz, .tar.gz, .tgz, and .bgz will be decompressed by NSURLDownload for us. However, we have to do .zip files manually. - (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]; - [unzip setLaunchPath: @"/usr/bin/unzip"]; - [unzip setCurrentDirectoryPath: workingDirectory]; - [unzip setArguments: @[ + unzip.launchPath = @"/usr/bin/unzip"; + unzip.currentDirectoryPath = workingDirectory; + unzip.arguments = @[ @"-o", /* overwrite */ @"-q", /* quiet! */ fDestination, /* source zip file */ @"-d", workingDirectory /*destination*/ - ]]; + ]; @try { [unzip launch]; [unzip waitUntilExit]; - if ([unzip terminationStatus] == 0) + if (unzip.terminationStatus == 0) success = YES; } @catch(id exc) @@ -219,27 +219,27 @@ BlocklistDownloader * fBLDownloader = nil; NSTask *zipinfo; zipinfo = [[NSTask alloc] init]; - [zipinfo setLaunchPath: @"/usr/bin/zipinfo"]; - [zipinfo setArguments: @[ + zipinfo.launchPath = @"/usr/bin/zipinfo"; + zipinfo.arguments = @[ @"-1", /* just the filename */ fDestination /* source zip file */ - ]]; - [zipinfo setStandardOutput: [NSPipe pipe]]; + ]; + 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]]; + 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; } diff --git a/macosx/BlocklistDownloaderViewController.m b/macosx/BlocklistDownloaderViewController.m index db2a4bdb3..533ff38a9 100644 --- a/macosx/BlocklistDownloaderViewController.m +++ b/macosx/BlocklistDownloaderViewController.m @@ -27,7 +27,7 @@ @interface BlocklistDownloaderViewController (Private) -- (id) initWithPrefsController: (PrefsController *) prefsController; +- (instancetype) initWithPrefsController: (PrefsController *) prefsController; - (void) startDownload; @end @@ -46,16 +46,16 @@ BlocklistDownloaderViewController * fBLViewController = nil; - (void) awakeFromNib { - [fButton setTitle: NSLocalizedString(@"Cancel", "Blocklist -> cancel button")]; + fButton.title = NSLocalizedString(@"Cancel", "Blocklist -> cancel button"); - const CGFloat oldWidth = NSWidth([fButton frame]); + const CGFloat oldWidth = NSWidth(fButton.frame); [fButton sizeToFit]; - NSRect buttonFrame = [fButton frame]; + NSRect buttonFrame = fButton.frame; buttonFrame.size.width += 12.0; //sizeToFit sizes a bit too small buttonFrame.origin.x -= NSWidth(buttonFrame) - oldWidth; - [fButton setFrame: buttonFrame]; + fButton.frame = buttonFrame; - [fProgressBar setUsesThreadedAnimation: YES]; + fProgressBar.usesThreadedAnimation = YES; [fProgressBar startAnimation: self]; } @@ -66,8 +66,8 @@ BlocklistDownloaderViewController * fBLViewController = nil; - (void) setStatusStarting { - [fTextField setStringValue: [NSLocalizedString(@"Connecting to site", "Blocklist -> message") stringByAppendingEllipsis]]; - [fProgressBar setIndeterminate: YES]; + fTextField.stringValue = [NSLocalizedString(@"Connecting to site", "Blocklist -> message") stringByAppendingEllipsis]; + fProgressBar.indeterminate = YES; } - (void) setStatusProgressForCurrentSize: (NSUInteger) currentSize expectedSize: (long long) expectedSize @@ -75,26 +75,26 @@ BlocklistDownloaderViewController * fBLViewController = nil; NSString * string = NSLocalizedString(@"Downloading blocklist", "Blocklist -> message"); if (expectedSize != NSURLResponseUnknownLength) { - [fProgressBar setIndeterminate: NO]; + fProgressBar.indeterminate = NO; NSString * substring = [NSString stringForFilePartialSize: currentSize fullSize: expectedSize]; string = [string stringByAppendingFormat: @" (%@)", substring]; - [fProgressBar setDoubleValue: (double)currentSize / expectedSize]; + fProgressBar.doubleValue = (double)currentSize / expectedSize; } else string = [string stringByAppendingFormat: @" (%@)", [NSString stringForFileSize: currentSize]]; - [fTextField setStringValue: string]; + fTextField.stringValue = string; } - (void) setStatusProcessing { //change to indeterminate while processing - [fProgressBar setIndeterminate: YES]; + fProgressBar.indeterminate = YES; [fProgressBar startAnimation: self]; - [fTextField setStringValue: [NSLocalizedString(@"Processing blocklist", "Blocklist -> message") stringByAppendingEllipsis]]; - [fButton setEnabled: NO]; + fTextField.stringValue = [NSLocalizedString(@"Processing blocklist", "Blocklist -> message") stringByAppendingEllipsis]; + fButton.enabled = NO; } - (void) setFinished @@ -112,13 +112,13 @@ BlocklistDownloaderViewController * fBLViewController = nil; NSAlert * alert = [[NSAlert alloc] init]; [alert addButtonWithTitle: NSLocalizedString(@"OK", "Blocklist -> button")]; - [alert setMessageText: NSLocalizedString(@"Download of the blocklist failed.", "Blocklist -> message")]; - [alert setAlertStyle: NSWarningAlertStyle]; + alert.messageText = NSLocalizedString(@"Download of the blocklist failed.", "Blocklist -> message"); + alert.alertStyle = NSWarningAlertStyle; - [alert setInformativeText: error]; + alert.informativeText = error; - [alert beginSheetModalForWindow:[fPrefsController window] completionHandler:^(NSModalResponse returnCode) { - [[alert window] orderOut: self]; + [alert beginSheetModalForWindow:fPrefsController.window completionHandler:^(NSModalResponse returnCode) { + [alert.window orderOut: self]; fBLViewController = nil; }]; @@ -128,7 +128,7 @@ BlocklistDownloaderViewController * fBLViewController = nil; @implementation BlocklistDownloaderViewController (Private) -- (id) initWithPrefsController: (PrefsController *) prefsController +- (instancetype) initWithPrefsController: (PrefsController *) prefsController { if ((self = [super init])) { @@ -141,7 +141,7 @@ BlocklistDownloaderViewController * fBLViewController = nil; - (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 diff --git a/macosx/BlocklistScheduler.h b/macosx/BlocklistScheduler.h index 2c80974ad..6da02617b 100644 --- a/macosx/BlocklistScheduler.h +++ b/macosx/BlocklistScheduler.h @@ -27,7 +27,7 @@ NSTimer * fTimer; } -+ (BlocklistScheduler *) scheduler; +@property (nonatomic, class, readonly) BlocklistScheduler * scheduler; - (void) updateSchedule; - (void) cancelSchedule; diff --git a/macosx/BlocklistScheduler.m b/macosx/BlocklistScheduler.m index 9ada52e8d..fa03066c0 100644 --- a/macosx/BlocklistScheduler.m +++ b/macosx/BlocklistScheduler.m @@ -48,19 +48,19 @@ BlocklistScheduler * fScheduler = nil; - (void) updateSchedule { - if ([BlocklistDownloader isRunning]) + if (BlocklistDownloader.isRunning) return; [self cancelSchedule]; NSString * blocklistURL; - if (![[NSUserDefaults standardUserDefaults] boolForKey: @"BlocklistNew"] - || !((blocklistURL = [[NSUserDefaults standardUserDefaults] stringForKey: @"BlocklistURL"]) && + if (![NSUserDefaults.standardUserDefaults boolForKey: @"BlocklistNew"] + || !((blocklistURL = [NSUserDefaults.standardUserDefaults stringForKey: @"BlocklistURL"]) && ![blocklistURL isEqualToString: @""]) - || ![[NSUserDefaults standardUserDefaults] boolForKey: @"BlocklistAutoUpdate"]) + || ![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]; @@ -70,7 +70,7 @@ BlocklistScheduler * fScheduler = nil; 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]; + NSRunLoop * loop = NSRunLoop.mainRunLoop; [loop addTimer: fTimer forMode: NSDefaultRunLoopMode]; [loop addTimer: fTimer forMode: NSModalPanelRunLoopMode]; [loop addTimer: fTimer forMode: NSEventTrackingRunLoopMode]; diff --git a/macosx/BonjourController.h b/macosx/BonjourController.h index e55b94ba6..e428f93dc 100644 --- a/macosx/BonjourController.h +++ b/macosx/BonjourController.h @@ -27,8 +27,8 @@ NSNetService * fService; } -+ (BonjourController *) defaultController; -+ (BOOL) defaultControllerExists; +@property (nonatomic, class, readonly) BonjourController * defaultController; +@property (nonatomic, class, readonly) BOOL defaultControllerExists; - (void) startWithPort: (int) port; - (void) stop; diff --git a/macosx/BonjourController.m b/macosx/BonjourController.m index e1c8810f6..78da7c777 100644 --- a/macosx/BonjourController.m +++ b/macosx/BonjourController.m @@ -47,12 +47,12 @@ BonjourController * fDefaultController = nil; { [self stop]; - 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)]; + 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)]; fService = [[NSNetService alloc] initWithDomain: @"" type: @"_http._tcp." name: serviceName port: port]; - [fService setDelegate: self]; + fService.delegate = self; [fService publish]; } @@ -65,12 +65,12 @@ BonjourController * fDefaultController = nil; - (void) netService: (NSNetService *) sender didNotPublish: (NSDictionary *) errorDict { - NSLog(@"Failed to publish the web interface service on port %ld, with error: %@", [sender port], errorDict); + NSLog(@"Failed to publish the web interface service on port %ld, with error: %@", sender.port, errorDict); } - (void) netService: (NSNetService *) sender didNotResolve: (NSDictionary *) errorDict { - NSLog(@"Failed to resolve the web interface service on port %ld, with error: %@", [sender port], errorDict); + NSLog(@"Failed to resolve the web interface service on port %ld, with error: %@", sender.port, errorDict); } @end diff --git a/macosx/ButtonToolbarItem.m b/macosx/ButtonToolbarItem.m index ba4c42316..49723a77a 100644 --- a/macosx/ButtonToolbarItem.m +++ b/macosx/ButtonToolbarItem.m @@ -26,14 +26,14 @@ - (void) validate { - [self setEnabled: [[self target] validateToolbarItem: self]]; + self.enabled = [self.target validateToolbarItem: self]; } - (NSMenuItem *) menuFormRepresentation { - NSMenuItem * menuItem = [[NSMenuItem alloc] initWithTitle: [self label] action: [self action] keyEquivalent: @""]; - [menuItem setTarget: [self target]]; - [menuItem setEnabled: [[self target] validateToolbarItem: self]]; + NSMenuItem * menuItem = [[NSMenuItem alloc] initWithTitle: self.label action: self.action keyEquivalent: @""]; + menuItem.target = self.target; + menuItem.enabled = [self.target validateToolbarItem: self]; return menuItem; } diff --git a/macosx/ColorTextField.m b/macosx/ColorTextField.m index fe2e7445b..2b52fde34 100644 --- a/macosx/ColorTextField.m +++ b/macosx/ColorTextField.m @@ -26,15 +26,15 @@ - (void) awakeFromNib { - [self setEnabled: [self isEnabled]]; + self.enabled = self.enabled; } - (void) setEnabled: (BOOL) flag { - [super setEnabled: flag]; + super.enabled = flag; - NSColor * color = flag ? [NSColor controlTextColor] : [NSColor disabledControlTextColor]; - [self setTextColor: color]; + NSColor * color = flag ? NSColor.controlTextColor : NSColor.disabledControlTextColor; + self.textColor = color; } @end diff --git a/macosx/Controller.h b/macosx/Controller.h index f294f26de..75abd5255 100644 --- a/macosx/Controller.h +++ b/macosx/Controller.h @@ -40,16 +40,15 @@ @class TorrentTableView; @class URLSheetWindowController; -typedef enum -{ +typedef NS_ENUM(unsigned int, addType) { ADD_MANUAL, ADD_AUTO, ADD_SHOW_OPTIONS, ADD_URL, ADD_CREATED -} addType; +}; -@interface Controller : NSObject +@interface Controller : NSObject { IBOutlet NSWindow * fWindow; IBOutlet TorrentTableView * fTableView; @@ -87,7 +86,7 @@ typedef enum - (void) openURL: (NSString *) urlString; - (void) openURLShowSheet: (id) sender; -- (tr_session *) sessionHandle; +@property (nonatomic, readonly) tr_session *sessionHandle; - (void) createFile: (id) sender; @@ -127,7 +126,7 @@ typedef enum - (void) verifySelectedTorrents: (id) sender; - (void) verifyTorrents: (NSArray *) torrents; -- (NSArray *)selectedTorrents; +@property (nonatomic, readonly) NSArray *selectedTorrents; @property (nonatomic, readonly) PrefsController * prefsController; - (void) showPreferenceWindow: (id) sender; @@ -199,10 +198,10 @@ typedef enum - (void) selectedToolbarClicked: (id) sender; - (void) setWindowSizeToFit; -- (NSRect) sizedWindowFrame; +@property (nonatomic, readonly) NSRect sizedWindowFrame; - (void) updateForAutoSize; - (void) setWindowMinMaxToCurrent; -- (CGFloat) minWindowContentSizeAllowed; +@property (nonatomic, readonly) CGFloat minWindowContentSizeAllowed; - (void) updateForExpandCollape; diff --git a/macosx/Controller.m b/macosx/Controller.m index 2a98c147d..0c021a5f2 100644 --- a/macosx/Controller.m +++ b/macosx/Controller.m @@ -81,11 +81,10 @@ #define TOOLBAR_QUICKLOOK @"Toolbar QuickLook" #define TOOLBAR_SHARE @"Toolbar Share" -typedef enum -{ +typedef NS_ENUM(unsigned int, toolbarGroupTag) { TOOLBAR_PAUSE_TAG = 0, TOOLBAR_RESUME_TAG = 1 -} toolbarGroupTag; +}; #define SORT_DATE @"Date" #define SORT_NAME @"Name" @@ -96,8 +95,7 @@ typedef enum #define SORT_ACTIVITY @"Activity" #define SORT_SIZE @"Size" -typedef enum -{ +typedef NS_ENUM(unsigned int, sortTag) { SORT_ORDER_TAG = 0, SORT_DATE_TAG = 1, SORT_NAME_TAG = 2, @@ -106,13 +104,12 @@ typedef enum SORT_TRACKER_TAG = 5, SORT_ACTIVITY_TAG = 6, SORT_SIZE_TAG = 7 -} sortTag; +}; -typedef enum -{ +typedef NS_ENUM(unsigned int, sortOrderTag) { SORT_ASC_TAG = 0, SORT_DESC_TAG = 1 -} sortOrderTag; +}; #define TORRENT_TABLE_VIEW_DATA_TYPE @"TorrentTableViewDataType" @@ -160,12 +157,12 @@ static void sleepCallback(void * controller, io_service_t y, natural_t messageTy // 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"]; - NSFileManager * fileManager = [NSFileManager defaultManager]; + NSFileManager * fileManager = NSFileManager.defaultManager; NSArray * krFilePaths = @[ krBinaryResourcePath ? krBinaryResourcePath : @"", @@ -178,7 +175,7 @@ static void removeKeRangerRansomware() BOOL foundKrFiles = NO; for (NSString * krFilePath in krFilePaths) { - if ([krFilePath length] == 0 || ![fileManager fileExistsAtPath: krFilePath]) + if (krFilePath.length == 0 || ![fileManager fileExistsAtPath: krFilePath]) continue; foundKrFiles = YES; @@ -194,20 +191,20 @@ static void removeKeRangerRansomware() { // The forgiving way: kill process which has the file opened NSTask * lsofTask = [[NSTask alloc] init]; - [lsofTask setLaunchPath: @"/usr/sbin/lsof"]; - [lsofTask setArguments: @[@"-F", @"pid", @"--", krLibraryKernelServicePath]]; - [lsofTask setStandardOutput: [NSPipe pipe]]; - [lsofTask setStandardInput: [NSPipe pipe]]; - [lsofTask setStandardError: [lsofTask standardOutput]]; + lsofTask.launchPath = @"/usr/sbin/lsof"; + 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"]) { if (![line hasPrefix: @"p"]) continue; - const pid_t krProcessId = [[line substringFromIndex: 1] intValue]; + const pid_t 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); } @@ -217,13 +214,13 @@ static void removeKeRangerRansomware() // The harsh way: kill all processes with matching name NSTask * killTask = [NSTask launchedTaskWithLaunchPath: @"/usr/bin/killall" arguments: @[@"-9", @"kernel_service"]]; [killTask waitUntilExit]; - if ([killTask terminationStatus] != 0) + 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) { - if ([krFilePath length] == 0 || ![fileManager fileExistsAtPath: krFilePath]) + if (krFilePath.length == 0 || ![fileManager fileExistsAtPath: krFilePath]) continue; if (![fileManager removeItemAtPath: krFilePath error: NULL]) @@ -281,16 +278,16 @@ static void removeKeRangerRansomware() removeKeRangerRansomware(); //make sure another Transmission.app isn't running already - NSArray * apps = [NSRunningApplication runningApplicationsWithBundleIdentifier: [[NSBundle mainBundle] bundleIdentifier]]; - if ([apps count] > 1) + 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 setMessageText: NSLocalizedString(@"Transmission is already running.", - "Transmission already running alert -> title")]; - [alert setInformativeText: 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 setAlertStyle: NSCriticalAlertStyle]; + 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]; @@ -298,8 +295,8 @@ 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]; @@ -309,30 +306,30 @@ static void removeKeRangerRansomware() [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")]; - [alert setMessageText: NSLocalizedString(@"Welcome to Transmission", "Legal alert -> title")]; - [alert setInformativeText: NSLocalizedString(@"Transmission is a file-sharing program." + 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.", - "Legal alert -> message")]; - [alert setAlertStyle: NSInformationalAlertStyle]; + "Legal alert -> message"); + alert.alertStyle = NSInformationalAlertStyle; if ([alert runModal] == NSAlertSecondButtonReturn) exit(0); - [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningLegal"]; + [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningLegal"]; } } -- (id) init +- (instancetype) init { if ((self = [super init])) { - fDefaults = [NSUserDefaults standardUserDefaults]; + fDefaults = NSUserDefaults.standardUserDefaults; //checks for old version speeds of -1 if ([fDefaults integerForKey: @"UploadLimit"] < 0) @@ -347,7 +344,7 @@ static void removeKeRangerRansomware() } //upgrading from versions < 2.40: clear recent items - [[NSDocumentController sharedDocumentController] clearRecentDocuments: nil]; + [NSDocumentController.sharedDocumentController clearRecentDocuments: nil]; tr_variant settings; tr_variantInitDict(&settings, 41); @@ -374,22 +371,20 @@ static void removeKeRangerRansomware() //hidden prefs if ([fDefaults objectForKey: @"BindAddressIPv4"]) - tr_variantDictAddStr(&settings, TR_KEY_bind_address_ipv4, [[fDefaults stringForKey: @"BindAddressIPv4"] UTF8String]); + 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_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_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_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_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); @@ -403,7 +398,7 @@ static void removeKeRangerRansomware() //hidden pref if ([fDefaults objectForKey: @"PeerSocketTOS"]) - tr_variantDictAddStr(&settings, TR_KEY_peer_socket_tos, [[fDefaults stringForKey: @"PeerSocketTOS"] UTF8String]); + 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"]); @@ -415,50 +410,50 @@ static void removeKeRangerRansomware() 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_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_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]); + tr_variantDictAddStr(&settings, TR_KEY_rpc_host_whitelist, [fDefaults stringForKey: @"RPCHostWhitelist"].UTF8String); NSByteCountFormatter * unitFormatter = [[NSByteCountFormatter alloc] init]; - [unitFormatter setIncludesCount: NO]; - [unitFormatter setAllowsNonnumericFormatting: NO]; + unitFormatter.includesCount = NO; + unitFormatter.allowsNonnumericFormatting = NO; - [unitFormatter setAllowedUnits: NSByteCountFormatterUseKB]; + 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) - [unitFormatter setAllowedUnits: NSByteCountFormatterUseMB]; + unitFormatter.allowedUnits = NSByteCountFormatterUseMB; NSString * mbString = [unitFormatter stringFromByteCount: 17]; - [unitFormatter setAllowedUnits: NSByteCountFormatterUseGB]; + unitFormatter.allowedUnits = NSByteCountFormatterUseGB; NSString * gbString = [unitFormatter stringFromByteCount: 17]; - [unitFormatter setAllowedUnits: NSByteCountFormatterUseTB]; + unitFormatter.allowedUnits = NSByteCountFormatterUseTB; 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"); fLib = tr_sessionInit(configDir, YES, &settings); @@ -466,7 +461,7 @@ static void removeKeRangerRansomware() fConfigDirectory = [[NSString alloc] initWithUTF8String: configDir]; - [NSApp setDelegate: self]; + NSApp.delegate = self; //register for magnet URLs (has to be in init) [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self andSelector: @selector(handleOpenContentsEvent:replyEvent:) @@ -479,7 +474,7 @@ static void removeKeRangerRansomware() //needs to be done before init-ing the prefs controller _fileWatcherQueue = [[VDKQueue alloc] init]; - [_fileWatcherQueue setDelegate: self]; + _fileWatcherQueue.delegate = self; _prefsController = [[PrefsController alloc] initWithHandle: fLib]; @@ -493,7 +488,7 @@ static void removeKeRangerRansomware() tr_sessionSetRPCCallback(fLib, rpcCallback, (__bridge void *)(self)); - [[SUUpdater sharedUpdater] setDelegate: self]; + [SUUpdater sharedUpdater].delegate = self; fQuitRequested = NO; fPauseOnLaunch = (GetCurrentKeyModifiers() & (optionKey | rightOptionKey)) != 0; @@ -504,27 +499,27 @@ static void removeKeRangerRansomware() - (void) awakeFromNib { NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"TRMainToolbar"]; - [toolbar setDelegate: self]; - [toolbar setAllowsUserCustomization: YES]; - [toolbar setAutosavesConfiguration: YES]; - [toolbar setDisplayMode: NSToolbarDisplayModeIconOnly]; - [fWindow setToolbar: toolbar]; + toolbar.delegate = self; + toolbar.allowsUserCustomization = YES; + toolbar.autosavesConfiguration = YES; + toolbar.displayMode = NSToolbarDisplayModeIconOnly; + fWindow.toolbar = toolbar; - [fWindow setDelegate: self]; //do manually to avoid placement issue + fWindow.delegate = self; //do manually to avoid placement issue [fWindow makeFirstResponder: fTableView]; - [fWindow setExcludedFromWindowsMenu: YES]; + fWindow.excludedFromWindowsMenu = YES; //set table size const BOOL small = [fDefaults boolForKey: @"SmallView"]; if (small) - [fTableView setRowHeight: ROW_HEIGHT_SMALL]; - [fTableView setUsesAlternatingRowBackgroundColors: !small]; + fTableView.rowHeight = ROW_HEIGHT_SMALL; + fTableView.usesAlternatingRowBackgroundColors = !small; - [fWindow setContentBorderThickness: NSMinY([[fTableView enclosingScrollView] frame]) forEdge: NSMinYEdge]; - [fWindow setMovableByWindowBackground: YES]; + [fWindow setContentBorderThickness: NSMinY(fTableView.enclosingScrollView.frame) forEdge: NSMinYEdge]; + fWindow.movableByWindowBackground = YES; - [[fTotalTorrentsField cell] setBackgroundStyle: NSBackgroundStyleRaised]; + fTotalTorrentsField.cell.backgroundStyle = NSBackgroundStyleRaised; //set up filter bar [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO]; @@ -532,17 +527,17 @@ static void removeKeRangerRansomware() //set up status bar [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO]; - [fActionButton setToolTip: NSLocalizedString(@"Shortcuts for changing global settings.", - "Main window -> 1st bottom left button (action) tooltip")]; - [fSpeedLimitButton setToolTip: NSLocalizedString(@"Speed Limit overrides the total bandwidth limits with its own limits.", - "Main window -> 2nd bottom left button (turtle) tooltip")]; + 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 setImage:[NSImage imageWithSystemSymbolName: @"gearshape.fill" accessibilityDescription: nil]]; - [fSpeedLimitButton setImage:[NSImage imageWithSystemSymbolName: @"tortoise.fill" accessibilityDescription: nil]]; + fActionButton.image = [NSImage imageWithSystemSymbolName: @"gearshape.fill" accessibilityDescription: nil]; + fSpeedLimitButton.image = [NSImage imageWithSystemSymbolName: @"tortoise.fill" accessibilityDescription: nil]; } - - [fClearCompletedButton setToolTip: NSLocalizedString(@"Remove all transfers that have completed seeding.", - "Main window -> 3rd bottom left button (remove all) tooltip")]; + 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]]; @@ -551,10 +546,10 @@ static void removeKeRangerRansomware() 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) + if (item.action == @selector(setSort:) && item.tag != SORT_ORDER_TAG) { [sortMenuItems addObject: item]; [fSortMenu removeItemAtIndex: sortMenuIndex]; @@ -600,7 +595,7 @@ static void removeKeRangerRansomware() if (history) { - NSMutableArray * waitToStartTorrents = [NSMutableArray arrayWithCapacity: (([history count] > 0 && !fPauseOnLaunch) ? [history count]-1 : 0)]; //theoretical max without doing a lot of work + NSMutableArray * waitToStartTorrents = [NSMutableArray arrayWithCapacity: ((history.count > 0 && !fPauseOnLaunch) ? history.count-1 : 0)]; //theoretical max without doing a lot of work for (NSDictionary * historyItem in history) { @@ -610,7 +605,7 @@ static void removeKeRangerRansomware() [fTorrents addObject: torrent]; NSNumber * waitToStart; - if (!fPauseOnLaunch && (waitToStart = historyItem[@"WaitToStart"]) && [waitToStart boolValue]) + if (!fPauseOnLaunch && (waitToStart = historyItem[@"WaitToStart"]) && waitToStart.boolValue) [waitToStartTorrents addObject: torrent]; } } @@ -622,10 +617,10 @@ static void removeKeRangerRansomware() fBadger = [[Badger alloc] initWithLib: fLib]; - [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate: self]; + NSUserNotificationCenter.defaultUserNotificationCenter.delegate = self; //observe notifications - NSNotificationCenter * nc = [NSNotificationCenter defaultCenter]; + NSNotificationCenter * nc = NSNotificationCenter.defaultCenter; [nc addObserver: self selector: @selector(updateUI) name: @"UpdateUI" object: nil]; @@ -680,8 +675,8 @@ static void removeKeRangerRansomware() [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]; + [NSRunLoop.currentRunLoop addTimer: fTimer forMode: NSModalPanelRunLoopMode]; + [NSRunLoop.currentRunLoop addTimer: fTimer forMode: NSEventTrackingRunLoopMode]; [self applyFilter]; @@ -693,14 +688,14 @@ static void removeKeRangerRansomware() - (void) applicationDidFinishLaunching: (NSNotification *) notification { - [NSApp setServicesProvider: self]; + 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]; //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]; @@ -709,7 +704,7 @@ static void removeKeRangerRansomware() //registering the Web UI to Bonjour if ([fDefaults boolForKey: @"RPC"] && [fDefaults boolForKey: @"RPCWebDiscovery"]) - [[BonjourController defaultController] startWithPort: [fDefaults integerForKey: @"RPCPort"]]; + [BonjourController.defaultController startWithPort: [fDefaults integerForKey: @"RPCPort"]]; //shamelessly ask for donations if ([fDefaults boolForKey: @"WarningDonate"]) @@ -719,14 +714,14 @@ static void removeKeRangerRansomware() const BOOL firstLaunch = stats.sessionCount <= 1; NSDate * lastDonateDate = [fDefaults objectForKey: @"DonateAskDate"]; - const BOOL timePassed = !lastDonateDate || (-1 * [lastDonateDate timeIntervalSinceNow]) >= DONATE_NAG_TIME; + const BOOL timePassed = !lastDonateDate || (-1 * lastDonateDate.timeIntervalSinceNow) >= DONATE_NAG_TIME; if (!firstLaunch && timePassed) { [fDefaults setObject: [NSDate date] forKey: @"DonateAskDate"]; NSAlert * alert = [[NSAlert alloc] init]; - [alert setMessageText: NSLocalizedString(@"Support open-source indie software", "Donation beg -> title")]; + 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." @@ -734,32 +729,32 @@ static void removeKeRangerRansomware() " 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 setInformativeText: donateMessage]; - [alert setAlertStyle: NSInformationalAlertStyle]; + alert.informativeText = donateMessage; + alert.alertStyle = NSInformationalAlertStyle; [alert addButtonWithTitle: [NSLocalizedString(@"Donate", "Donation beg -> button") stringByAppendingEllipsis]]; NSButton * noDonateButton = [alert addButtonWithTitle: NSLocalizedString(@"Nope", "Donation beg -> button")]; - [noDonateButton setKeyEquivalent: @"\e"]; //escape key + 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 - [alert setShowsSuppressionButton: allowNeverAgain]; + alert.showsSuppressionButton = allowNeverAgain; if (allowNeverAgain) - [[alert suppressionButton] setTitle: NSLocalizedString(@"Don't bug me about this ever again.", "Donation beg -> button")]; + alert.suppressionButton.title = NSLocalizedString(@"Don't bug me about this ever again.", "Donation beg -> button"); const NSInteger donateResult = [alert runModal]; if (donateResult == NSAlertFirstButtonReturn) [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 { - NSWindow * mainWindow = [NSApp mainWindow]; - if (!mainWindow || ![mainWindow isVisible]) + NSWindow * mainWindow = NSApp.mainWindow; + if (!mainWindow || !mainWindow.visible) [fWindow makeKeyAndOrderFront: nil]; return NO; @@ -771,10 +766,10 @@ static void removeKeRangerRansomware() { NSInteger active = 0, downloading = 0; for (Torrent * torrent in fTorrents) - if ([torrent isActive] && ![torrent isStalled]) + if (torrent.active && !torrent.stalled) { active++; - if (![torrent allDownloaded]) + if (!torrent.allDownloaded) downloading++; } @@ -807,21 +802,21 @@ static void removeKeRangerRansomware() fQuitting = YES; //stop the Bonjour service - if ([BonjourController defaultControllerExists]) - [[BonjourController defaultController] stop]; + if (BonjourController.defaultControllerExists) + [BonjourController.defaultController stop]; //stop blocklist download - if ([BlocklistDownloader isRunning]) + 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 isValid]) + if (fAutoImportTimer.valid) [fAutoImportTimer invalidate]; } @@ -838,12 +833,12 @@ static void removeKeRangerRansomware() } //remember window states and close all windows - [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"]; + [fDefaults setBool: fInfoController.window.visible forKey: @"InfoVisible"]; - if ([QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible]) + 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]; @@ -869,14 +864,14 @@ static void removeKeRangerRansomware() NSString * urlString = nil; NSAppleEventDescriptor * directObject = [event paramDescriptorForKeyword: keyDirectObject]; - if ([directObject descriptorType] == typeAEList) + if (directObject.descriptorType == typeAEList) { - for (NSInteger i = 1; i <= [directObject numberOfItems]; i++) - if ((urlString = [[directObject descriptorAtIndex: i] stringValue])) + for (NSInteger i = 1; i <= directObject.numberOfItems; i++) + if ((urlString = [directObject descriptorAtIndex: i].stringValue)) break; } else - urlString = [directObject stringValue]; + urlString = directObject.stringValue; if (urlString) [self openURL: urlString]; @@ -884,34 +879,34 @@ static void removeKeRangerRansomware() - (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]]; - if ([fPendingTorrentDownloads count] == 0) + [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]]; + [download.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]; NSAlert * alert = [[NSAlert alloc] init]; [alert addButtonWithTitle: NSLocalizedString(@"OK", "Download not a torrent -> button")]; - [alert setMessageText: NSLocalizedString(@"Torrent download failed", "Download not a torrent -> title")]; - [alert setInformativeText: message]; + alert.messageText = NSLocalizedString(@"Torrent download failed", "Download not a torrent -> title"); + alert.informativeText = message; [alert runModal]; } else - [download setDestination: [NSTemporaryDirectory() stringByAppendingPathComponent: [suggestedName lastPathComponent]] + [download setDestination: [NSTemporaryDirectory() stringByAppendingPathComponent: suggestedName.lastPathComponent] allowOverwrite: NO]; } -(void) download: (NSURLDownload *) download didCreateDestination: (NSString *) path { - NSMutableDictionary * dict = fPendingTorrentDownloads[[[download request] URL]]; + NSMutableDictionary * dict = fPendingTorrentDownloads[download.request.URL]; dict[@"Path"] = path; } @@ -919,17 +914,17 @@ static void removeKeRangerRansomware() { NSString * message = [NSString stringWithFormat: NSLocalizedString(@"The torrent could not be downloaded from %@: %@.", "Torrent download failed -> message"), - [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding], - [error localizedDescription]]; + [download.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding], + error.localizedDescription]; NSAlert * alert = [[NSAlert alloc] init]; [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent download failed -> button")]; - [alert setMessageText: NSLocalizedString(@"Torrent download failed", "Torrent download error -> title")]; - [alert setInformativeText: message]; + alert.messageText = NSLocalizedString(@"Torrent download failed", "Torrent download error -> title"); + alert.informativeText = message; [alert runModal]; - [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]]; - if ([fPendingTorrentDownloads count] == 0) + [fPendingTorrentDownloads removeObjectForKey: download.request.URL]; + if (fPendingTorrentDownloads.count == 0) { fPendingTorrentDownloads = nil; } @@ -937,15 +932,15 @@ static void removeKeRangerRansomware() - (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]; //delete the torrent file after opening - [[NSFileManager defaultManager] removeItemAtPath: path error: NULL]; + [NSFileManager.defaultManager removeItemAtPath: path error: NULL]; - [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]]; - if ([fPendingTorrentDownloads count] == 0) + [fPendingTorrentDownloads removeObjectForKey: download.request.URL]; + if (fPendingTorrentDownloads.count == 0) { fPendingTorrentDownloads = nil; } @@ -976,7 +971,7 @@ static void removeKeRangerRansomware() { //ensure torrent doesn't already exist tr_ctor * ctor = tr_ctorNew(fLib); - tr_ctorSetMetainfoFromFile(ctor, [torrentPath UTF8String]); + tr_ctorSetMetainfoFromFile(ctor, torrentPath.UTF8String); tr_info info; const tr_parse_result result = tr_torrentParse(ctor, &info); @@ -989,7 +984,7 @@ static void removeKeRangerRansomware() 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); @@ -1003,13 +998,13 @@ static void removeKeRangerRansomware() BOOL lockDestination = NO; //don't override the location with a group location if it has a hardcoded path if (path) { - location = [path stringByExpandingTildeInPath]; + location = path.stringByExpandingTildeInPath; lockDestination = YES; } else if ([fDefaults boolForKey: @"DownloadLocationConstant"]) - location = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath]; + location = [fDefaults stringForKey: @"DownloadFolder"].stringByExpandingTildeInPath; else if (type != ADD_URL) - location = [torrentPath stringByDeletingLastPathComponent]; + location = torrentPath.stringByDeletingLastPathComponent; else location = nil; @@ -1025,9 +1020,9 @@ static void removeKeRangerRansomware() 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]]; + location = [GroupsController.groups customDownloadLocationForIndex: torrent.groupValue]; [torrent changeDownloadFolderBeforeUsing: location determinationType: TorrentDeterminationAutomatic]; } @@ -1066,11 +1061,11 @@ static void removeKeRangerRansomware() - (void) askOpenConfirmed: (AddWindowController *) addController add: (BOOL) add { - Torrent * torrent = [addController torrent]; + Torrent * torrent = addController.torrent; if (add) { - [torrent setQueuePosition: [fTorrents count]]; + torrent.queuePosition = fTorrents.count; [torrent update]; [fTorrents addObject: torrent]; @@ -1087,7 +1082,7 @@ static void removeKeRangerRansomware() } [fAddWindows removeObject: addController]; - if ([fAddWindows count] == 0) + if (fAddWindows.count == 0) { fAddWindows = nil; } @@ -1096,7 +1091,7 @@ static void removeKeRangerRansomware() - (void) openMagnet: (NSString *) address { tr_torrent * duplicateTorrent; - if ((duplicateTorrent = tr_torrentFindFromMagnetLink(fLib, [address UTF8String]))) + if ((duplicateTorrent = tr_torrentFindFromMagnetLink(fLib, address.UTF8String))) { const tr_info * info = tr_torrentInfo(duplicateTorrent); NSString * name = (info != NULL && info->name != NULL) ? @(info->name) : nil; @@ -1107,7 +1102,7 @@ static void removeKeRangerRansomware() //determine download location NSString * location = nil; if ([fDefaults boolForKey: @"DownloadLocationConstant"]) - location = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath]; + location = [fDefaults stringForKey: @"DownloadFolder"].stringByExpandingTildeInPath; Torrent * torrent; if (!(torrent = [[Torrent alloc] initWithMagnetAddress: address location: location lib: fLib])) @@ -1117,9 +1112,9 @@ static void removeKeRangerRansomware() } //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]]; + location = [GroupsController.groups customDownloadLocationForIndex: torrent.groupValue]; [torrent changeDownloadFolderBeforeUsing: location determinationType: TorrentDeterminationAutomatic]; } @@ -1151,11 +1146,11 @@ static void removeKeRangerRansomware() - (void) askOpenMagnetConfirmed: (AddMagnetWindowController *) addController add: (BOOL) add { - Torrent * torrent = [addController torrent]; + Torrent * torrent = addController.torrent; if (add) { - [torrent setQueuePosition: [fTorrents count]]; + torrent.queuePosition = fTorrents.count; [torrent update]; [fTorrents addObject: torrent]; @@ -1172,7 +1167,7 @@ static void removeKeRangerRansomware() } [fAddWindows removeObject: addController]; - if ([fAddWindows count] == 0) + if (fAddWindows.count == 0) { fAddWindows = nil; } @@ -1180,7 +1175,7 @@ static void removeKeRangerRansomware() - (void) openCreatedFile: (NSNotification *) notification { - NSDictionary * dict = [notification userInfo]; + NSDictionary * dict = notification.userInfo; [self openFiles: @[dict[@"File"]] addType: ADD_CREATED forcePath: dict[@"Path"]]; } @@ -1200,23 +1195,21 @@ static void removeKeRangerRansomware() { NSOpenPanel * panel = [NSOpenPanel openPanel]; - [panel setAllowsMultipleSelection: YES]; - [panel setCanChooseFiles: YES]; - [panel setCanChooseDirectories: NO]; + panel.allowsMultipleSelection = YES; + panel.canChooseFiles = YES; + panel.canChooseDirectories = NO; - [panel setAllowedFileTypes: @[@"org.bittorrent.torrent", @"torrent"]]; + panel.allowedFileTypes = @[@"org.bittorrent.torrent", @"torrent"]; [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"]]; + NSDictionary * dictionary = [[NSDictionary alloc] initWithObjects: @[filenames, sender == fOpenIgnoreDownloadFolder ? @(ADD_SHOW_OPTIONS) : @(ADD_MANUAL)] + forKeys: @[@"Filenames", @"AddType"]]; [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO]; } }]; @@ -1228,16 +1221,16 @@ static void removeKeRangerRansomware() return; NSAlert * alert = [[NSAlert alloc] init]; - [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"\"%@\" is not a valid torrent file.", - "Open invalid alert -> title"), filename]]; - [alert setInformativeText: - NSLocalizedString(@"The torrent file cannot be opened because it contains invalid data.", - "Open invalid alert -> message")]; - [alert setAlertStyle: NSWarningAlertStyle]; + 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 runModal]; - if ([[alert suppressionButton] state] == NSOnState) + if (alert.suppressionButton.state == NSOnState) [fDefaults setBool: NO forKey: @"WarningInvalidOpen"]; } @@ -1247,14 +1240,14 @@ static void removeKeRangerRansomware() return; NSAlert * alert = [[NSAlert alloc] init]; - [alert setMessageText: NSLocalizedString(@"Adding magnetized transfer failed.", "Magnet link failed -> title")]; - [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"There was an error when adding the magnet link \"%@\"." - " The transfer will not occur.", "Magnet link failed -> message"), address]]; - [alert setAlertStyle: NSWarningAlertStyle]; + 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.alertStyle = NSWarningAlertStyle; [alert addButtonWithTitle: NSLocalizedString(@"OK", "Magnet link failed -> button")]; [alert runModal]; - if ([[alert suppressionButton] state] == NSOnState) + if (alert.suppressionButton.state == NSOnState) [fDefaults setBool: NO forKey: @"WarningInvalidOpen"]; } @@ -1264,17 +1257,17 @@ static void removeKeRangerRansomware() return; NSAlert * alert = [[NSAlert alloc] init]; - [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.", - "Open duplicate alert -> title"), name]]; - [alert setInformativeText: - NSLocalizedString(@"The transfer cannot be added because it is a duplicate of an already existing transfer.", - "Open duplicate alert -> message")]; - [alert setAlertStyle: NSWarningAlertStyle]; + 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 setShowsSuppressionButton: YES]; + alert.showsSuppressionButton = YES; [alert runModal]; - if ([[alert suppressionButton] state]) + if (alert.suppressionButton.state) [fDefaults setBool: NO forKey: @"WarningDuplicate"]; } @@ -1285,20 +1278,20 @@ static void removeKeRangerRansomware() NSAlert * alert = [[NSAlert alloc] init]; if (name) - [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.", - "Open duplicate magnet alert -> title"), name]]; + alert.messageText = [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.", + "Open duplicate magnet alert -> title"), name]; else - [alert setMessageText: NSLocalizedString(@"Magnet link is a duplicate of an existing transfer.", - "Open duplicate magnet alert -> title")]; - [alert setInformativeText: [NSString stringWithFormat: + 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 setAlertStyle: NSWarningAlertStyle]; + "Open duplicate magnet alert -> message"), address]; + alert.alertStyle = NSWarningAlertStyle; [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open duplicate magnet alert -> button")]; - [alert setShowsSuppressionButton: YES]; + alert.showsSuppressionButton = YES; [alert runModal]; - if ([[alert suppressionButton] state]) + if (alert.suppressionButton.state) [fDefaults setBool: NO forKey: @"WarningDuplicate"]; } @@ -1334,9 +1327,9 @@ static void removeKeRangerRansomware() NSURLRequest * request = [NSURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval: 60]; - if (fPendingTorrentDownloads[[request URL]]) + if (fPendingTorrentDownloads[request.URL]) { - NSLog(@"Already downloading %@", [request URL]); + NSLog(@"Already downloading %@", request.URL); return; } @@ -1345,7 +1338,7 @@ static void removeKeRangerRansomware() if (!fPendingTorrentDownloads) fPendingTorrentDownloads = [[NSMutableDictionary alloc] init]; NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithObject: download forKey: @"Download"]; - fPendingTorrentDownloads[[request URL]] = dict; + fPendingTorrentDownloads[request.URL] = dict; } } @@ -1375,15 +1368,15 @@ static void removeKeRangerRansomware() - (void) resumeSelectedTorrents: (id) sender { - [self resumeTorrents: [fTableView selectedTorrents]]; + [self resumeTorrents: fTableView.selectedTorrents]; } - (void) resumeAllTorrents: (id) sender { - NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]]; + NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: fTorrents.count]; for (Torrent * torrent in fTorrents) - if (![torrent isFinishedSeeding]) + if (!torrent.finishedSeeding) [torrents addObject: torrent]; [self resumeTorrents: torrents]; @@ -1399,15 +1392,15 @@ static void removeKeRangerRansomware() - (void) resumeSelectedTorrentsNoWait: (id) sender { - [self resumeTorrentsNoWait: [fTableView selectedTorrents]]; + [self resumeTorrentsNoWait: fTableView.selectedTorrents]; } - (void) resumeWaitingTorrents: (id) sender { - NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]]; + NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: fTorrents.count]; for (Torrent * torrent in fTorrents) - if ([torrent waitingToStart]) + if (torrent.waitingToStart) [torrents addObject: torrent]; [self resumeTorrentsNoWait: torrents]; @@ -1424,7 +1417,7 @@ static void removeKeRangerRansomware() - (void) stopSelectedTorrents: (id) sender { - [self stopTorrents: [fTableView selectedTorrents]]; + [self stopTorrents: fTableView.selectedTorrents]; } - (void) stopAllTorrents: (id) sender @@ -1436,7 +1429,7 @@ static void removeKeRangerRansomware() { //don't want any of these starting then stopping for (Torrent * torrent in torrents) - if ([torrent waitingToStart]) + if (torrent.waitingToStart) [torrent stopTransfer]; for (Torrent * torrent in torrents) @@ -1451,10 +1444,10 @@ static void removeKeRangerRansomware() { NSUInteger active = 0, downloading = 0; for (Torrent * torrent in torrents) - if ([torrent isActive]) + if (torrent.active) { ++active; - if (![torrent isSeeding]) + if (!torrent.seeding) ++downloading; } @@ -1462,10 +1455,10 @@ static void removeKeRangerRansomware() { NSString * title, * message; - const NSUInteger selected = [torrents count]; + const NSUInteger selected = torrents.count; if (selected == 1) { - NSString * torrentName = [(Torrent *)torrents[0] name]; + NSString * torrentName = ((Torrent *)torrents[0]).name; if (deleteData) title = [NSString stringWithFormat: @@ -1528,11 +1521,11 @@ static void removeKeRangerRansomware() for (Torrent * torrent in torrents) { //don't want any of these starting then stopping - if ([torrent waitingToStart]) + 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]; @@ -1542,12 +1535,12 @@ static void removeKeRangerRansomware() NSIndexSet * indexesToRemove = [torrents indexesOfObjectsWithOptions: NSEnumerationConcurrent passingTest: ^BOOL(Torrent * torrent, NSUInteger idx, BOOL * stop) { return [fTorrents indexOfObjectIdenticalTo: torrent] != NSNotFound; }]; - if ([torrents count] != [indexesToRemove count]) + if (torrents.count != indexesToRemove.count) { - NSLog(@"trying to remove %ld transfers, but %ld have already been removed", [torrents count], [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]; - if ([indexesToRemove count] == 0) + if (indexesToRemove.count == 0) { [self fullUpdateUI]; return; @@ -1564,17 +1557,17 @@ static void removeKeRangerRansomware() return [torrents containsObject: obj]; }]; - if ([indexes count] > 0) + if (indexes.count > 0) { if (!beganUpdate) { [NSAnimationContext beginGrouping]; //this has to be before we set the completion handler (#4874) //we can't closeRemoveTorrent: until it's no longer in the GUI at all - [[NSAnimationContext currentContext] setCompletionHandler: ^{ + NSAnimationContext.currentContext.completionHandler = ^{ for (Torrent * torrent in torrents) [torrent closeRemoveTorrent: deleteData]; - }]; + }; [fTableView beginUpdates]; beganUpdate = YES; @@ -1587,12 +1580,12 @@ static void removeKeRangerRansomware() }; //if not removed from the displayed torrents here, fullUpdateUI might cause a crash - if ([fDisplayedTorrents count] > 0) + if (fDisplayedTorrents.count > 0) { if ([fDisplayedTorrents[0] isKindOfClass: [TorrentGroup class]]) { for (TorrentGroup * group in fDisplayedTorrents) - doTableRemoval([group torrents], group); + doTableRemoval(group.torrents, group); } else doTableRemoval(fDisplayedTorrents, nil); @@ -1616,12 +1609,12 @@ static void removeKeRangerRansomware() - (void) removeNoDelete: (id) sender { - [self removeTorrents: [fTableView selectedTorrents] deleteData: NO]; + [self removeTorrents: fTableView.selectedTorrents deleteData: NO]; } - (void) removeDeleteData: (id) sender { - [self removeTorrents: [fTableView selectedTorrents] deleteData: YES]; + [self removeTorrents: fTableView.selectedTorrents deleteData: YES]; } - (void) clearCompleted: (id) sender @@ -1629,15 +1622,15 @@ static void removeKeRangerRansomware() NSMutableArray * torrents = [NSMutableArray array]; for (Torrent * torrent in fTorrents) - if ([torrent isFinishedSeeding]) + if (torrent.finishedSeeding) [torrents addObject: torrent]; if ([fDefaults boolForKey: @"WarningRemoveCompleted"]) { NSString * message, * info; - if ([torrents count] == 1) + if (torrents.count == 1) { - NSString * torrentName = [(Torrent *)torrents[0] name]; + 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]; @@ -1647,22 +1640,22 @@ static void removeKeRangerRansomware() 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]]]; + "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"); } NSAlert * alert = [[NSAlert alloc] init]; - [alert setMessageText: message]; - [alert setInformativeText: info]; - [alert setAlertStyle: NSWarningAlertStyle]; + 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 setShowsSuppressionButton: YES]; + alert.showsSuppressionButton = YES; const NSInteger returnCode = [alert runModal]; - if ([[alert suppressionButton] state]) + if (alert.suppressionButton.state) [fDefaults setBool: NO forKey: @"WarningRemoveCompleted"]; if (returnCode != NSAlertFirstButtonReturn) @@ -1674,61 +1667,61 @@ static void removeKeRangerRansomware() - (void) moveDataFilesSelected: (id) sender { - [self moveDataFiles: [fTableView selectedTorrents]]; + [self moveDataFiles: fTableView.selectedTorrents]; } - (void) moveDataFiles: (NSArray *) torrents { NSOpenPanel * panel = [NSOpenPanel openPanel]; - [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")]; - [panel setAllowsMultipleSelection: NO]; - [panel setCanChooseFiles: NO]; - [panel setCanChooseDirectories: YES]; - [panel setCanCreateDirectories: YES]; + panel.prompt = NSLocalizedString(@"Select", "Move torrent -> prompt"); + panel.allowsMultipleSelection = NO; + panel.canChooseFiles = NO; + panel.canChooseDirectories = YES; + panel.canCreateDirectories = YES; - NSInteger count = [torrents count]; + NSInteger count = torrents.count; if (count == 1) - [panel setMessage: [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 setMessage: [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) { if (result == NSFileHandlingPanelOKButton) { for (Torrent * torrent in torrents) - [torrent moveTorrentDataFileTo: [[panel URLs][0] path]]; + [torrent moveTorrentDataFileTo: panel.URLs[0].path]; } }]; } - (void) copyTorrentFiles: (id) sender { - [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: [fTableView selectedTorrents]]]; + [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: fTableView.selectedTorrents]]; } - (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents { - if ([torrents count] == 0) + if (torrents.count == 0) { return; } Torrent * torrent = torrents[0]; - if (![torrent isMagnet] && [[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]]) + if (!torrent.magnet && [NSFileManager.defaultManager fileExistsAtPath: torrent.torrentLocation]) { NSSavePanel * panel = [NSSavePanel savePanel]; - [panel setAllowedFileTypes: @[@"org.bittorrent.torrent", @"torrent"]]; - [panel setExtensionHidden: NO]; + panel.allowedFileTypes = @[@"org.bittorrent.torrent", @"torrent"]; + panel.extensionHidden = NO; - [panel setNameFieldStringValue: [torrent name]]; + panel.nameFieldStringValue = torrent.name; [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]; @@ -1736,16 +1729,16 @@ static void removeKeRangerRansomware() } else { - if (![torrent isMagnet]) + if (!torrent.magnet) { NSAlert * alert = [[NSAlert alloc] init]; [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")]; - [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created", - "Torrent file copy alert -> title"), [torrent name]]]; - [alert setInformativeText: [NSString stringWithFormat: + 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 setAlertStyle: NSWarningAlertStyle]; + torrent.torrentLocation]; + alert.alertStyle = NSWarningAlertStyle; [alert runModal]; } @@ -1757,41 +1750,41 @@ static void removeKeRangerRansomware() - (void) copyMagnetLinks: (id) sender { - NSArray * torrents = [fTableView selectedTorrents]; + NSArray * torrents = fTableView.selectedTorrents; - if ([torrents count] <= 0) + if (torrents.count <= 0) return; - NSMutableArray * links = [NSMutableArray arrayWithCapacity: [torrents count]]; + NSMutableArray * links = [NSMutableArray arrayWithCapacity: torrents.count]; for (Torrent * torrent in torrents) - [links addObject: [torrent magnetLink]]; + [links addObject: torrent.magnetLink]; NSString * text = [links componentsJoinedByString: @"\n"]; - NSPasteboard * pb = [NSPasteboard generalPasteboard]; + NSPasteboard * pb = NSPasteboard.generalPasteboard; [pb clearContents]; [pb writeObjects: @[text]]; } - (void) revealFile: (id) sender { - NSArray * selected = [fTableView selectedTorrents]; - NSMutableArray * paths = [NSMutableArray arrayWithCapacity: [selected count]]; + 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]]; } - if ([paths count] > 0) - [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: paths]; + if (paths.count > 0) + [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs: paths]; } - (IBAction) renameSelected: (id) sender { - NSArray * selected = [fTableView selectedTorrents]; - NSAssert([selected count] == 1, @"1 transfer needs to be selected to rename, but %ld are selected", [selected count]); + 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]; [FileRenameSheetController presentSheetForTorrent:torrent modalForWindow: fWindow completionHandler: ^(BOOL didRename) { @@ -1800,7 +1793,7 @@ static void removeKeRangerRansomware() 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 }]; }); } }]; @@ -1808,16 +1801,16 @@ static void removeKeRangerRansomware() - (void) announceSelectedTorrents: (id) sender { - for (Torrent * torrent in [fTableView selectedTorrents]) + for (Torrent * torrent in fTableView.selectedTorrents) { - if ([torrent canManualAnnounce]) + if (torrent.canManualAnnounce) [torrent manualAnnounce]; } } - (void) verifySelectedTorrents: (id) sender { - [self verifyTorrents: [fTableView selectedTorrents]]; + [self verifyTorrents: fTableView.selectedTorrents]; } - (void) verifyTorrents: (NSArray *) torrents @@ -1830,13 +1823,13 @@ static void removeKeRangerRansomware() - (NSArray *)selectedTorrents { - return [fTableView selectedTorrents]; + return fTableView.selectedTorrents; } - (void) showPreferenceWindow: (id) sender { - NSWindow * window = [_prefsController window]; - if (![window isVisible]) + NSWindow * window = _prefsController.window; + if (!window.visible) [window center]; [window makeKeyAndOrderFront: nil]; @@ -1844,30 +1837,30 @@ static void removeKeRangerRansomware() - (void) showAboutWindow: (id) sender { - [[AboutWindowController aboutController] showWindow: nil]; + [AboutWindowController.aboutController showWindow: nil]; } - (void) showInfo: (id) sender { - if ([[fInfoController window] isVisible]) + if (fInfoController.window.visible) [fInfoController close]; else { [fInfoController updateInfoStats]; - [[fInfoController window] orderFront: nil]; + [fInfoController.window orderFront: nil]; - if ([fInfoController canQuickLook] && [QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible]) + if (fInfoController.canQuickLook && [QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible) [[QLPreviewPanel sharedPreviewPanel] reloadData]; } - [[fWindow toolbar] validateVisibleItems]; + [fWindow.toolbar validateVisibleItems]; } - (void) resetInfo { - [fInfoController setInfoForTorrents: [fTableView selectedTorrents]]; + [fInfoController setInfoForTorrents: fTableView.selectedTorrents]; - if ([QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible]) + if ([QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible) [[QLPreviewPanel sharedPreviewPanel] reloadData]; } @@ -1889,12 +1882,12 @@ static void removeKeRangerRansomware() - (void) showMessageWindow: (id) sender { - [[self messageWindowController] showWindow: nil]; + [self.messageWindowController showWindow: nil]; } - (void) showStatsWindow: (id) sender { - [[StatsWindowController statsWindow] showWindow: nil]; + [StatsWindowController.statsWindow showWindow: nil]; } - (void) updateUI @@ -1906,25 +1899,25 @@ static void removeKeRangerRansomware() [torrent update]; //pull the upload and download speeds - most consistent by using current stats - dlRate += [torrent downloadRate]; - ulRate += [torrent uploadRate]; + dlRate += torrent.downloadRate; + ulRate += torrent.uploadRate; - anyCompleted |= [torrent isFinishedSeeding]; + anyCompleted |= torrent.finishedSeeding; } - if (![NSApp isHidden]) + if (!NSApp.hidden) { - if ([fWindow isVisible]) + if (fWindow.visible) { [self sortTorrents: NO]; [fStatusBar updateWithDownload: dlRate upload: ulRate]; - [fClearCompletedButton setHidden: !anyCompleted]; + fClearCompletedButton.hidden = !anyCompleted; } //update non-constant parts of info window - if ([[fInfoController window] isVisible]) + if (fInfoController.window.visible) [fInfoController updateInfoStats]; } @@ -1937,14 +1930,14 @@ static void removeKeRangerRansomware() { [self updateUI]; [self applyFilter]; - [[fWindow toolbar] validateVisibleItems]; + [fWindow.toolbar validateVisibleItems]; [self updateTorrentHistory]; } - (void) setBottomCountText: (BOOL) filtering { NSString * totalTorrentsString; - NSUInteger totalCount = [fTorrents count]; + NSUInteger totalCount = fTorrents.count; if (totalCount != 1) totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ transfers", "Status bar transfer count"), [NSString formattedUInteger: totalCount]]; @@ -1953,15 +1946,15 @@ static void removeKeRangerRansomware() if (filtering) { - NSUInteger count = [fTableView numberOfRows]; //have to factor in collapsed rows + NSUInteger count = fTableView.numberOfRows; //have to factor in collapsed rows if (count > 0 && ![fDisplayedTorrents[0] isKindOfClass: [Torrent class]]) - count -= [fDisplayedTorrents count]; + count -= fDisplayedTorrents.count; totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Status bar transfer count"), [NSString formattedUInteger: count], totalTorrentsString]; } - [fTotalTorrentsField setStringValue: totalTorrentsString]; + fTotalTorrentsField.stringValue = totalTorrentsString; } - (BOOL) userNotificationCenter: (NSUserNotificationCenter *) center shouldPresentNotification:(NSUserNotification *) notification @@ -1971,21 +1964,21 @@ static void removeKeRangerRansomware() - (void) userNotificationCenter: (NSUserNotificationCenter *) center didActivateNotification: (NSUserNotification *) notification { - if (![notification userInfo]) + if (!notification.userInfo) return; - if ([notification activationType] == NSUserNotificationActivationTypeActionButtonClicked) //reveal + 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"]; + location = notification.userInfo[@"Location"]; if (location) - [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: @[[NSURL fileURLWithPath: location]]]; + [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs: @[[NSURL fileURLWithPath: location]]]; } - else if ([notification activationType] == NSUserNotificationActivationTypeContentsClicked) + 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 @@ -1997,7 +1990,7 @@ static void removeKeRangerRansomware() { __block TorrentGroup * parent = nil; [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(TorrentGroup * group, NSUInteger idx, BOOL *stop) { - if ([[group torrents] containsObject: torrent]) + if ([group.torrents containsObject: torrent]) { parent = group; *stop = YES; @@ -2023,7 +2016,7 @@ static void removeKeRangerRansomware() { __block TorrentGroup * parent = nil; [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(TorrentGroup * group, NSUInteger idx, BOOL *stop) { - if ([[group torrents] containsObject: torrent]) + if ([group.torrents containsObject: torrent]) { parent = group; *stop = YES; @@ -2052,7 +2045,7 @@ static void removeKeRangerRansomware() __block Torrent * torrent = nil; [fTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id obj, NSUInteger idx, BOOL * stop) { - if ([[(Torrent *)obj hashString] isEqualToString: hash]) + if ([((Torrent *)obj).hashString isEqualToString: hash]) { torrent = obj; *stop = YES; @@ -2063,44 +2056,44 @@ static void removeKeRangerRansomware() - (void) torrentFinishedDownloading: (NSNotification *) notification { - Torrent * torrent = [notification object]; + Torrent * torrent = notification.object; - if ([[notification userInfo][@"WasRunning"] boolValue]) + if ([notification.userInfo[@"WasRunning"] boolValue]) { if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"]) { NSSound * sound; if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]])) { - [sound setDelegate: self]; + sound.delegate = self; fSoundPlaying = YES; [sound play]; } } - NSString * location = [torrent dataLocation]; + NSString * location = torrent.dataLocation; NSString * notificationTitle = NSLocalizedString(@"Download Complete", "notification title"); NSUserNotification * notification = [[NSUserNotification alloc] init]; - [notification setTitle: notificationTitle]; - [notification setInformativeText: [torrent name]]; + notification.title = notificationTitle; + notification.informativeText = torrent.name; - [notification setHasActionButton: YES]; - [notification setActionButtonTitle: NSLocalizedString(@"Show", "notification button")]; + 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 setUserInfo: userInfo]; + notification.userInfo = userInfo; - [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification: notification]; + [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification: notification]; - if (![fWindow isMainWindow]) + if (!fWindow.mainWindow) [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]; @@ -2113,47 +2106,47 @@ static void removeKeRangerRansomware() - (void) torrentFinishedSeeding: (NSNotification *) notification { - Torrent * torrent = [notification object]; + Torrent * torrent = notification.object; if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"]) { NSSound * sound; if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]])) { - [sound setDelegate: self]; + sound.delegate = self; fSoundPlaying = YES; [sound play]; } } - NSString * location = [torrent dataLocation]; + NSString * location = torrent.dataLocation; NSString * notificationTitle = NSLocalizedString(@"Seeding Complete", "notification title"); NSUserNotification * userNotification = [[NSUserNotification alloc] init]; - [userNotification setTitle: notificationTitle]; - [userNotification setInformativeText: [torrent name]]; + userNotification.title = notificationTitle; + userNotification.informativeText = torrent.name; - [userNotification setHasActionButton: YES]; - [userNotification setActionButtonTitle: NSLocalizedString(@"Show", "notification button")]; + 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 setUserInfo: userInfo]; + userNotification.userInfo = userInfo; - [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification: userNotification]; + [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification: userNotification]; //removing from the list calls fullUpdateUI - if ([torrent removeWhenFinishSeeding]) + if (torrent.removeWhenFinishSeeding) [self confirmRemoveTorrents: @[ torrent ] deleteData: NO]; else { - if (![fWindow isMainWindow]) + if (!fWindow.mainWindow) [fBadger addCompletedTorrent: torrent]; [self fullUpdateUI]; - if ([[fTableView selectedTorrents] containsObject: torrent]) + if ([fTableView.selectedTorrents containsObject: torrent]) { [fInfoController updateInfoStats]; [fInfoController updateOptions]; @@ -2163,10 +2156,10 @@ static void removeKeRangerRansomware() - (void) updateTorrentHistory { - NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]]; + NSMutableArray * history = [NSMutableArray arrayWithCapacity: fTorrents.count]; for (Torrent * torrent in fTorrents) - [history addObject: [torrent history]]; + [history addObject: torrent.history]; NSString * historyFile = [fConfigDirectory stringByAppendingPathComponent: TRANSFER_PLIST]; [history writeToFile: historyFile atomically: YES]; @@ -2175,7 +2168,8 @@ static void removeKeRangerRansomware() - (void) setSort: (id) sender { NSString * sortType; - switch ([(NSMenuItem *)sender tag]) + NSMenuItem *senderMenuItem = sender; + switch (senderMenuItem.tag) { case SORT_ORDER_TAG: sortType = SORT_ORDER; @@ -2203,7 +2197,7 @@ static void removeKeRangerRansomware() sortType = SORT_SIZE; break; default: - NSAssert1(NO, @"Unknown sort tag received: %ld", [(NSMenuItem *)sender tag]); + NSAssert1(NO, @"Unknown sort tag received: %ld", senderMenuItem.tag); return; } @@ -2222,7 +2216,7 @@ static void removeKeRangerRansomware() - (void) setSortReverse: (id) sender { - const BOOL setReverse = [(NSMenuItem *)sender tag] == SORT_DESC_TAG; + const BOOL setReverse = ((NSMenuItem *)sender).tag == SORT_DESC_TAG; if (setReverse != [fDefaults boolForKey: @"SortReverse"]) { [fDefaults setBool: setReverse forKey: @"SortReverse"]; @@ -2234,7 +2228,7 @@ static void removeKeRangerRansomware() { //actually sort [self sortTorrentsCallUpdates: YES includeQueueOrder: includeQueueOrder]; - [fTableView setNeedsDisplay: YES]; + fTableView.needsDisplay = YES; } - (void) sortTorrentsCallUpdates: (BOOL) callUpdates includeQueueOrder: (BOOL) includeQueueOrder @@ -2308,7 +2302,7 @@ static void removeKeRangerRansomware() if ([fDefaults boolForKey: @"SortByGroup"]) { for (TorrentGroup * group in fDisplayedTorrents) - [self rearrangeTorrentTableArray: [group torrents] forParent: group withSortDescriptors: descriptors beganTableUpdate: &beganTableUpdate]; + [self rearrangeTorrentTableArray: group.torrents forParent: group withSortDescriptors: descriptors beganTableUpdate: &beganTableUpdate]; } else [self rearrangeTorrentTableArray: fDisplayedTorrents forParent: nil withSortDescriptors: descriptors beganTableUpdate: &beganTableUpdate]; @@ -2322,7 +2316,7 @@ static void removeKeRangerRansomware() #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) + 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) { @@ -2371,21 +2365,21 @@ static void removeKeRangerRansomware() const NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"]; const BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG; - NSArray * searchStrings = [fFilterBar searchStrings]; - if (searchStrings && [searchStrings count] == 0) + 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 isActive] && ![torrent isCheckingWaiting]) + if (torrent.active && !torrent.checkingWaiting) { - const BOOL isActive = ![torrent isStalled]; + const BOOL isActive = !torrent.stalled; if (isActive) OSAtomicIncrement32(&active); - if ([torrent isSeeding]) + if (torrent.seeding) { OSAtomicIncrement32(&seeding); if (filterStatus && !((filterActive && isActive) || filterSeed)) @@ -2407,7 +2401,7 @@ static void removeKeRangerRansomware() //checkGroup if (filterGroup) - if ([torrent groupValue] != groupFilterValue) + if (torrent.groupValue != groupFilterValue) return NO; //check text field @@ -2416,7 +2410,7 @@ static void removeKeRangerRansomware() __block BOOL removeTextField = NO; if (filterTracker) { - NSArray * trackers = [torrent allTrackersFlat]; + 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) { @@ -2438,7 +2432,7 @@ static void removeKeRangerRansomware() else { [searchStrings enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id searchString, NSUInteger idx, BOOL * stop) { - if ([[torrent name] rangeOfString: searchString options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound) + if ([torrent.name rangeOfString: searchString options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound) { removeTextField = YES; *stop = YES; @@ -2457,26 +2451,26 @@ static void removeKeRangerRansomware() //set button tooltips if (fFilterBar) - [fFilterBar setCountAll: [fTorrents count] active: active downloading: downloading seeding: seeding paused: paused]; + [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; + 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) + 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 setPreviousFinishedPieces: nil]; + torrent.previousFinishedPieces = nil; }; if (wasGroupRows) [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id obj, NSUInteger idx, BOOL * stop) { - [[(TorrentGroup *)obj torrents] enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: removePreviousFinishedPieces]; + [((TorrentGroup *)obj).torrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: removePreviousFinishedPieces]; }]; else [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: removePreviousFinishedPieces]; @@ -2487,7 +2481,7 @@ static void removeKeRangerRansomware() //don't animate torrents when first launching static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - [[NSAnimationContext currentContext] setDuration: 0]; + NSAnimationContext.currentContext.duration = 0; }); [NSAnimationContext beginGrouping]; @@ -2495,7 +2489,7 @@ static void removeKeRangerRansomware() if (!groupRows && !wasGroupRows) { NSMutableIndexSet * addIndexes = [NSMutableIndexSet indexSet], - * removePreviousIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fDisplayedTorrents count])]; + * 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) { @@ -2508,20 +2502,20 @@ static void removeKeRangerRansomware() [removePreviousIndexes removeIndex: currentIndex]; }]; - if ([addIndexes count] > 0 || [removePreviousIndexes count] > 0) + if (addIndexes.count > 0 || removePreviousIndexes.count > 0) { beganUpdates = YES; [fTableView beginUpdates]; //remove torrents we didn't find - if ([removePreviousIndexes count] > 0) + if (removePreviousIndexes.count > 0) { [fDisplayedTorrents removeObjectsAtIndexes: removePreviousIndexes]; [fTableView removeItemsAtIndexes: removePreviousIndexes inParent: nil withAnimation: NSTableViewAnimationSlideDown]; } //add new torrents - if ([addIndexes count] > 0) + if (addIndexes.count > 0) { //slide new torrents in differently if (fAddingTransfers) @@ -2533,11 +2527,11 @@ static void removeKeRangerRansomware() [addIndexes removeIndexes: newAddIndexes]; [fDisplayedTorrents addObjectsFromArray: [allTorrents objectsAtIndexes: newAddIndexes]]; - [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange([fDisplayedTorrents count] - [newAddIndexes count], [newAddIndexes count])] inParent: nil withAnimation: NSTableViewAnimationSlideLeft]; + [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]; + [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(fDisplayedTorrents.count - addIndexes.count, addIndexes.count)] inParent: nil withAnimation: NSTableViewAnimationSlideDown]; } } } @@ -2549,13 +2543,13 @@ static void removeKeRangerRansomware() beganUpdates = YES; [fTableView beginUpdates]; - NSMutableIndexSet * unusedAllTorrentsIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [allTorrents count])]; + NSMutableIndexSet * unusedAllTorrentsIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, allTorrents.count)]; - NSMutableDictionary * groupsByIndex = [NSMutableDictionary dictionaryWithCapacity: [fDisplayedTorrents count]]; + NSMutableDictionary * groupsByIndex = [NSMutableDictionary dictionaryWithCapacity: fDisplayedTorrents.count]; for (TorrentGroup * group in fDisplayedTorrents) - groupsByIndex[@([group groupIndex])] = group; + groupsByIndex[@(group.groupIndex)] = group; - const NSUInteger originalGroupCount = [fDisplayedTorrents count]; + const NSUInteger originalGroupCount = fDisplayedTorrents.count; for (NSUInteger index = 0; index < originalGroupCount; ++index) { TorrentGroup * group = fDisplayedTorrents[index]; @@ -2563,9 +2557,9 @@ static void removeKeRangerRansomware() NSMutableIndexSet * removeIndexes = [NSMutableIndexSet indexSet]; //needs to be a signed integer - for (NSUInteger indexInGroup = 0; indexInGroup < [[group torrents] count]; ++indexInGroup) + for (NSUInteger indexInGroup = 0; indexInGroup < group.torrents.count; ++indexInGroup) { - Torrent * torrent = [group torrents][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); }]; @@ -2575,8 +2569,8 @@ static void removeKeRangerRansomware() { BOOL markTorrentAsUsed = YES; - const NSInteger groupValue = [torrent groupValue]; - if (groupValue != [group groupIndex]) + const NSInteger groupValue = torrent.groupValue; + if (groupValue != group.groupIndex) { TorrentGroup * newGroup = groupsByIndex[@(groupValue)]; if (!newGroup) @@ -2585,7 +2579,7 @@ static void removeKeRangerRansomware() groupsByIndex[@(groupValue)] = newGroup; [fDisplayedTorrents addObject: newGroup]; - [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: [fDisplayedTorrents count]-1] inParent: nil withAnimation: NSTableViewAnimationEffectFade]; + [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 @@ -2595,10 +2589,10 @@ static void removeKeRangerRansomware() markTorrentAsUsed = NO; } - [[group torrents] removeObjectAtIndex: indexInGroup]; - [[newGroup torrents] addObject: torrent]; + [group.torrents removeObjectAtIndex: indexInGroup]; + [newGroup.torrents addObject: torrent]; - [fTableView moveItemAtIndex: indexInGroup inParent: group toIndex: [[newGroup torrents] count]-1 inParent: newGroup]; + [fTableView moveItemAtIndex: indexInGroup inParent: group toIndex: newGroup.torrents.count-1 inParent: newGroup]; --indexInGroup; } @@ -2608,9 +2602,9 @@ static void removeKeRangerRansomware() } } - if ([removeIndexes count] > 0) + if (removeIndexes.count > 0) { - [[group torrents] removeObjectsAtIndexes: removeIndexes]; + [group.torrents removeObjectsAtIndexes: removeIndexes]; [fTableView removeItemsAtIndexes: removeIndexes inParent: group withAnimation: NSTableViewAnimationEffectFade]; } } @@ -2618,7 +2612,7 @@ static void removeKeRangerRansomware() //add remaining new torrents for (Torrent * torrent in [allTorrents objectsAtIndexes: unusedAllTorrentsIndexes]) { - const NSInteger groupValue = [torrent groupValue]; + const NSInteger groupValue = torrent.groupValue; TorrentGroup * group = groupsByIndex[@(groupValue)]; if (!group) { @@ -2626,22 +2620,22 @@ static void removeKeRangerRansomware() groupsByIndex[@(groupValue)] = group; [fDisplayedTorrents addObject: group]; - [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: [fDisplayedTorrents count]-1] inParent: nil withAnimation: NSTableViewAnimationEffectFade]; + [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: fDisplayedTorrents.count-1] inParent: nil withAnimation: NSTableViewAnimationEffectFade]; [fTableView isGroupCollapsed: groupValue] ? [fTableView collapseItem: group] : [fTableView expandItem: group]; } - [[group torrents] addObject: torrent]; + [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]; + [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; + return ((TorrentGroup *)obj).torrents.count == 0; }]; - if ([removeGroupIndexes count] > 0) + if (removeGroupIndexes.count > 0) { [fDisplayedTorrents removeObjectsAtIndexes: removeGroupIndexes]; [fTableView removeItemsAtIndexes: removeGroupIndexes inParent: nil withAnimation: NSTableViewAnimationEffectFade]; @@ -2660,20 +2654,20 @@ static void removeKeRangerRansomware() //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]; + NSArray * selectedValues = fTableView.selectedValues; beganUpdates = YES; [fTableView beginUpdates]; - [fTableView removeItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fDisplayedTorrents count])] inParent: nil withAnimation: NSTableViewAnimationSlideDown]; + [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]]; + NSMutableDictionary * groupsByIndex = [NSMutableDictionary dictionaryWithCapacity: GroupsController.groups.numberOfGroups]; for (Torrent * torrent in allTorrents) { - const NSInteger groupValue = [torrent groupValue]; + const NSInteger groupValue = torrent.groupValue; TorrentGroup * group = groupsByIndex[@(groupValue)]; if (!group) { @@ -2681,10 +2675,10 @@ static void removeKeRangerRansomware() groupsByIndex[@(groupValue)] = group; } - [[group torrents] addObject: torrent]; + [group.torrents addObject: torrent]; } - [fDisplayedTorrents setArray: [groupsByIndex allValues]]; + [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]; @@ -2693,7 +2687,7 @@ static void removeKeRangerRansomware() else [fDisplayedTorrents setArray: allTorrents]; - [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fDisplayedTorrents count])] inParent: nil withAnimation: NSTableViewAnimationEffectFade]; + [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fDisplayedTorrents.count)] inParent: nil withAnimation: NSTableViewAnimationEffectFade]; if (groupRows) { @@ -2711,7 +2705,7 @@ static void removeKeRangerRansomware() if (beganUpdates) [fTableView endUpdates]; - [fTableView setNeedsDisplay: YES]; + fTableView.needsDisplay = YES; [NSAnimationContext endGrouping]; @@ -2738,12 +2732,13 @@ static void removeKeRangerRansomware() return; NSPopover * popover = [[NSPopover alloc] init]; - [popover setBehavior: NSPopoverBehaviorTransient]; + popover.behavior = NSPopoverBehaviorTransient; GlobalOptionsPopoverViewController * viewController = [[GlobalOptionsPopoverViewController alloc] initWithHandle: fLib]; - [popover setContentViewController: viewController]; - [popover setDelegate: self]; + popover.contentViewController = viewController; + popover.delegate = self; - [popover showRelativeToRect: [sender frame] ofView: sender preferredEdge: NSMaxYEdge]; + NSView *senderView = sender; + [popover showRelativeToRect: senderView.frame ofView: senderView preferredEdge: NSMaxYEdge]; } //don't show multiple popovers when clicking the gear button repeatedly @@ -2761,12 +2756,12 @@ static void removeKeRangerRansomware() { if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu) { - for (NSInteger i = [menu numberOfItems]-1; i >= 0; i--) + for (NSInteger i = menu.numberOfItems-1; i >= 0; i--) [menu removeItemAtIndex: i]; - NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO]; + NSMenu * groupMenu = [GroupsController.groups groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO]; - const NSInteger groupMenuCount = [groupMenu numberOfItems]; + const NSInteger groupMenuCount = groupMenu.numberOfItems; for (NSInteger i = 0; i < groupMenuCount; i++) { NSMenuItem * item = [groupMenu itemAtIndex: 0]; @@ -2777,7 +2772,7 @@ static void removeKeRangerRansomware() else if (menu == fShareMenu || menu == fShareContextMenu) { [menu removeAllItems]; - for (NSMenuItem * item in [[ShareTorrentFileHelper sharedHelper] menuItems]) + for (NSMenuItem * item in ShareTorrentFileHelper.sharedHelper.menuItems) { [menu addItem:item]; } @@ -2787,11 +2782,11 @@ static void removeKeRangerRansomware() - (void) setGroup: (id) sender { - for (Torrent * torrent in [fTableView selectedTorrents]) + for (Torrent * torrent in fTableView.selectedTorrents) { - [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group + [fTableView removeCollapsedGroup: torrent.groupValue]; //remove old collapsed group - [torrent setGroupValue: [(NSMenuItem *)sender tag] determinationType: TorrentDeterminationUserSpecified]; + [torrent setGroupValue: ((NSMenuItem *)sender).tag determinationType: TorrentDeterminationUserSpecified]; } [self applyFilter]; @@ -2824,7 +2819,7 @@ static void removeKeRangerRansomware() notification.informativeText = NSLocalizedString(@"Bandwidth settings changed", "notification description"); notification.hasActionButton = NO; - [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification]; + [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification:notification]; } } @@ -2840,7 +2835,7 @@ static void removeKeRangerRansomware() if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"]) return; - if ([fAutoImportTimer isValid]) + if (fAutoImportTimer.valid) [fAutoImportTimer invalidate]; //check again in 10 seconds in case torrent file wasn't complete @@ -2852,7 +2847,7 @@ static void removeKeRangerRansomware() - (void) changeAutoImport { - if ([fAutoImportTimer isValid]) + if (fAutoImportTimer.valid) [fAutoImportTimer invalidate]; fAutoImportTimer = nil; @@ -2867,10 +2862,10 @@ static void removeKeRangerRansomware() if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"])) return; - path = [path stringByExpandingTildeInPath]; + path = path.stringByExpandingTildeInPath; NSArray * importedNames; - if (!(importedNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: path error: NULL])) + if (!(importedNames = [NSFileManager.defaultManager contentsOfDirectoryAtPath: path error: NULL])) return; //only check files that have not been checked yet @@ -2889,12 +2884,12 @@ static void removeKeRangerRansomware() NSString * fullFile = [path stringByAppendingPathComponent: file]; - if (!([[[NSWorkspace sharedWorkspace] typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"] - || [[fullFile pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)) + 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]); + tr_ctorSetMetainfoFromFile(ctor, fullFile.UTF8String); switch (tr_torrentParse(ctor, NULL)) { @@ -2903,12 +2898,12 @@ static void removeKeRangerRansomware() NSString * notificationTitle = NSLocalizedString(@"Torrent File Auto Added", "notification title"); NSUserNotification* notification = [[NSUserNotification alloc] init]; - [notification setTitle: notificationTitle]; - [notification setInformativeText: file]; + notification.title = notificationTitle; + notification.informativeText = file; - [notification setHasActionButton: NO]; + notification.hasActionButton = NO; - [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification: notification]; + [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification: notification]; break; } case TR_PARSE_ERR: @@ -2928,26 +2923,26 @@ static void removeKeRangerRansomware() if (![fDefaults boolForKey: @"AutoImport"]) return; - NSString * location = [(NSURL *)[notification object] path], + NSString * location = ((NSURL *)notification.object).path, * path = [fDefaults stringForKey: @"AutoImportDirectory"]; - if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath] - isEqualToString: [path stringByExpandingTildeInPath]]) - [fAutoImportedNames addObject: [location lastPathComponent]]; + if (location && path && [location.stringByDeletingLastPathComponent.stringByExpandingTildeInPath + isEqualToString: path.stringByExpandingTildeInPath]) + [fAutoImportedNames addObject: location.lastPathComponent]; } - (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item { if (item) - return [[item torrents] count]; + return ((TorrentGroup *)item).torrents.count; else - return [fDisplayedTorrents count]; + return fDisplayedTorrents.count; } - (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item { if (item) - return [item torrents][index]; + return ((TorrentGroup *)item).torrents[index]; else return fDisplayedTorrents[index]; } @@ -2962,21 +2957,22 @@ static void removeKeRangerRansomware() if ([item isKindOfClass: [Torrent class]]) { if (tableColumn) return nil; - return [item hashString]; + return ((Torrent *)item).hashString; } else { - NSString * ident = [tableColumn identifier]; + NSString * ident = tableColumn.identifier; + TorrentGroup * group = (TorrentGroup *)item; if ([ident isEqualToString: @"Group"]) { - NSInteger group = [item groupIndex]; - return group != -1 ? [[GroupsController groups] nameForIndex: group] + NSInteger groupIndex = group.groupIndex; + return groupIndex != -1 ? [GroupsController.groups nameForIndex: groupIndex] : NSLocalizedString(@"No Group", "Group table row"); } else if ([ident isEqualToString: @"Color"]) { - NSInteger group = [item groupIndex]; - return [[GroupsController groups] imageForIndex: group]; + NSInteger groupIndex = group.groupIndex; + return [GroupsController.groups imageForIndex: groupIndex]; } else if ([ident isEqualToString: @"DL Image"]) return [NSImage imageNamed: @"DownArrowGroupTemplate"]; @@ -2985,13 +2981,11 @@ static void removeKeRangerRansomware() ? @"YingYangGroupTemplate" : @"UpArrowGroupTemplate"]; else { - TorrentGroup * group = (TorrentGroup *)item; - if ([fDefaults boolForKey: @"DisplayGroupRowRatio"]) - return [NSString stringForRatio: [group ratio]]; + return [NSString stringForRatio: group.ratio]; else { - CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate]; + CGFloat rate = [ident isEqualToString: @"UL"] ? group.uploadRate : group.downloadRate; return [NSString stringForSpeed: rate]; } } @@ -3022,8 +3016,8 @@ static void removeKeRangerRansomware() - (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]) + NSPasteboard * pasteboard = info.draggingPasteboard; + if ([pasteboard.types containsObject: TORRENT_TABLE_VIEW_DATA_TYPE]) { if ([fDefaults boolForKey: @"SortByGroup"]) { @@ -3035,7 +3029,7 @@ static void removeKeRangerRansomware() if ([item isKindOfClass: [Torrent class]]) { TorrentGroup * group = [fTableView parentForItem: item]; - index = [[group torrents] indexOfObject: item] + 1; + index = [group.torrents indexOfObject: item] + 1; item = group; } } @@ -3067,14 +3061,14 @@ static void removeKeRangerRansomware() - (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]) + 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]) + 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]; @@ -3083,7 +3077,8 @@ static void removeKeRangerRansomware() //change groups if (item) { - const NSInteger groupIndex = [item groupIndex]; + TorrentGroup * group = (TorrentGroup *)item; + const NSInteger groupIndex = group.groupIndex; for (Torrent * torrent in movingTorrents) [torrent setGroupValue: groupIndex determinationType: TorrentDeterminationUserSpecified]; @@ -3092,8 +3087,9 @@ static void removeKeRangerRansomware() //reorder queue order if (newRow != NSOutlineViewDropOnItemIndex) { + TorrentGroup * group = (TorrentGroup *)item; //find torrent to place under - NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents; + NSArray * groupTorrents = group ? group.torrents : fDisplayedTorrents; Torrent * topTorrent = nil; for (NSInteger i = newRow-1; i >= 0; i--) { @@ -3110,14 +3106,14 @@ static void removeKeRangerRansomware() //insert objects at new location const NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0; - NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])]; + 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 setQueuePosition: i++]; + torrent.queuePosition = i++; [torrent update]; } @@ -3129,7 +3125,7 @@ static void removeKeRangerRansomware() for (Torrent * torrent in movingTorrents) { TorrentGroup * oldParent = item ? [fTableView parentForItem: torrent] : nil; - NSMutableArray * oldTorrents = oldParent ? [oldParent torrents] : fDisplayedTorrents; + NSMutableArray * oldTorrents = oldParent ? oldParent.torrents : fDisplayedTorrents; const NSUInteger oldIndex = [oldTorrents indexOfObject: torrent]; if (item == oldParent) @@ -3142,7 +3138,7 @@ static void removeKeRangerRansomware() { NSAssert(item && oldParent, @"Expected to be dragging between group rows"); - NSMutableArray * newTorrents = [(TorrentGroup *)item torrents]; + NSMutableArray * newTorrents = ((TorrentGroup *)item).torrents; [newTorrents insertObject: torrent atIndex: insertDisplayIndex]; [oldTorrents removeObjectAtIndex: oldIndex]; } @@ -3164,25 +3160,25 @@ static void removeKeRangerRansomware() - (void) torrentTableViewSelectionDidChange: (NSNotification *) notification { [self resetInfo]; - [[fWindow toolbar] validateVisibleItems]; + [fWindow.toolbar validateVisibleItems]; } - (NSDragOperation) draggingEntered: (id ) info { - NSPasteboard * pasteboard = [info draggingPasteboard]; - if ([[pasteboard types] containsObject: NSFilenamesPboardType]) + 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) + 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]); + tr_ctorSetMetainfoFromFile(ctor, file.UTF8String); if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK) { if (!fOverlayWindow) @@ -3196,7 +3192,7 @@ static void removeKeRangerRansomware() } //create a torrent file if a single file - if (!torrent && [files count] == 1) + if (!torrent && files.count == 1) { if (!fOverlayWindow) fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow]; @@ -3205,11 +3201,11 @@ static void removeKeRangerRansomware() return NSDragOperationCopy; } } - else if ([[pasteboard types] containsObject: NSURLPboardType]) + else if ([pasteboard.types containsObject: NSURLPboardType]) { if (!fOverlayWindow) fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow]; - [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]]; + [fOverlayWindow setURL: [NSURL URLFromPasteboard: pasteboard].relativeString]; return NSDragOperationCopy; } @@ -3229,33 +3225,33 @@ static void removeKeRangerRansomware() if (fOverlayWindow) [fOverlayWindow fadeOut]; - NSPasteboard * pasteboard = [info draggingPasteboard]; - if ([[pasteboard types] containsObject: NSFilenamesPboardType]) + 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]]; + 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) + 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]); + tr_ctorSetMetainfoFromFile(ctor, file.UTF8String); if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK) [filesToOpen addObject: file]; tr_ctorFree(ctor); } } - if ([filesToOpen count] > 0) + if (filesToOpen.count > 0) [self application: NSApp openFiles: filesToOpen]; else { - if (!torrent && [files count] == 1) + if (!torrent && files.count == 1) [CreatorWindowController createTorrentFile: fLib forFile: [NSURL fileURLWithPath: files[0]]]; else accept = NO; @@ -3263,12 +3259,12 @@ static void removeKeRangerRansomware() return accept; } - else if ([[pasteboard types] containsObject: NSURLPboardType]) + else if ([pasteboard.types containsObject: NSURLPboardType]) { NSURL * url; if ((url = [NSURL URLFromPasteboard: pasteboard])) { - [self openURL: [url absoluteString]]; + [self openURL: url.absoluteString]; return YES; } } @@ -3282,27 +3278,27 @@ static void removeKeRangerRansomware() BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"]; [fDefaults setBool: makeSmall forKey: @"SmallView"]; - [fTableView setUsesAlternatingRowBackgroundColors: !makeSmall]; + fTableView.usesAlternatingRowBackgroundColors = !makeSmall; - [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR]; + fTableView.rowHeight = makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR; [fTableView beginUpdates]; - [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]]; + [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; + const NSSize contentSize = fWindow.contentView.frame.size; - NSSize contentMinSize = [fWindow contentMinSize]; - contentMinSize.height = [self minWindowContentSizeAllowed]; - [fWindow setContentMinSize: contentMinSize]; + 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]; + NSRect frame = fWindow.frame; CGFloat heightChange = contentMinSize.height - contentSize.height; frame.size.height += heightChange; frame.origin.y -= heightChange; @@ -3328,27 +3324,27 @@ static void removeKeRangerRansomware() - (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check { - NSScrollView * scrollView = [fTableView enclosingScrollView]; + NSScrollView * scrollView = fTableView.enclosingScrollView; //convert pixels to points - NSRect windowFrame = [fWindow frame]; + 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 + 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]; + NSScreen * screen = fWindow.screen; if (screen) { - NSSize maxSize = [scrollView convertSize: [screen visibleFrame].size fromView: nil]; + NSSize maxSize = [scrollView convertSize: screen.visibleFrame.size fromView: nil]; if (!fStatusBar) maxSize.height -= STATUS_BAR_HEIGHT; if (!fFilterBar) @@ -3385,18 +3381,18 @@ static void removeKeRangerRansomware() { fStatusBar = [[StatusBarController alloc] initWithLib: fLib]; - NSView * contentView = [fWindow contentView]; - const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil]; + NSView * contentView = fWindow.contentView; + const NSSize windowSize = [contentView convertSize: fWindow.frame.size fromView: nil]; - NSRect statusBarFrame = [[fStatusBar view] frame]; + NSRect statusBarFrame = fStatusBar.view.frame; statusBarFrame.size.width = windowSize.width; - [[fStatusBar view] setFrame: statusBarFrame]; + fStatusBar.view.frame = statusBarFrame; - [contentView addSubview: [fStatusBar view]]; - [[fStatusBar view] setFrameOrigin: NSMakePoint(0.0, NSMaxY([contentView frame]))]; + [contentView addSubview: fStatusBar.view]; + [fStatusBar.view setFrameOrigin: NSMakePoint(0.0, NSMaxY(contentView.frame))]; } - CGFloat heightChange = [[fStatusBar view] frame].size.height; + CGFloat heightChange = fStatusBar.view.frame.size.height; if (!show) heightChange *= -1; @@ -3405,13 +3401,13 @@ static void removeKeRangerRansomware() { NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO]; - NSScreen * screen = [fWindow screen]; + NSScreen * screen = fWindow.screen; if (screen) { - CGFloat change = [screen visibleFrame].size.height - frame.size.height; + CGFloat change = screen.visibleFrame.size.height - frame.size.height; if (change < 0.0) { - frame = [fWindow frame]; + frame = fWindow.frame; frame.size.height += change; frame.origin.y -= change; [fWindow setFrame: frame display: NO animate: NO]; @@ -3421,32 +3417,32 @@ static void removeKeRangerRansomware() [self updateUI]; - NSScrollView * scrollView = [fTableView enclosingScrollView]; + NSScrollView * scrollView = fTableView.enclosingScrollView; //set views to not autoresize - const NSUInteger statsMask = [[fStatusBar view] autoresizingMask]; - [[fStatusBar view] setAutoresizingMask: NSViewNotSizable]; + const NSUInteger statsMask = fStatusBar.view.autoresizingMask; + fStatusBar.view.autoresizingMask = NSViewNotSizable; NSUInteger filterMask; if (fFilterBar) { - filterMask = [[fFilterBar view] autoresizingMask]; - [[fFilterBar view] setAutoresizingMask: NSViewNotSizable]; + filterMask = fFilterBar.view.autoresizingMask; + fFilterBar.view.autoresizingMask = NSViewNotSizable; } - const NSUInteger scrollMask = [scrollView autoresizingMask]; - [scrollView setAutoresizingMask: 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] setAutoresizingMask: statsMask]; + fStatusBar.view.autoresizingMask = statsMask; if (fFilterBar) - [[fFilterBar view] setAutoresizingMask: filterMask]; - [scrollView setAutoresizingMask: scrollMask]; + fFilterBar.view.autoresizingMask = filterMask; + scrollView.autoresizingMask = scrollMask; if (!show) { - [[fStatusBar view] removeFromSuperviewWithoutNeedingDisplay]; + [fStatusBar.view removeFromSuperviewWithoutNeedingDisplay]; fStatusBar = nil; } @@ -3455,9 +3451,9 @@ static void removeKeRangerRansomware() else { //change min size - NSSize minSize = [fWindow contentMinSize]; + NSSize minSize = fWindow.contentMinSize; minSize.height += heightChange; - [fWindow setContentMinSize: minSize]; + fWindow.contentMinSize = minSize; } } @@ -3471,7 +3467,7 @@ static void removeKeRangerRansomware() [self showFilterBar: show animate: YES]; [fDefaults setBool: show forKey: @"FilterBar"]; - [[fWindow toolbar] validateVisibleItems]; + [fWindow.toolbar validateVisibleItems]; [self applyFilter]; //do even if showing to ensure tooltips are updated } @@ -3487,24 +3483,24 @@ static void removeKeRangerRansomware() { fFilterBar = [[FilterBarController alloc] init]; - NSView * contentView = [fWindow contentView]; - const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil]; + NSView * contentView = fWindow.contentView; + const NSSize windowSize = [contentView convertSize: fWindow.frame.size fromView: nil]; - NSRect filterBarFrame = [[fFilterBar view] frame]; + NSRect filterBarFrame = fFilterBar.view.frame; filterBarFrame.size.width = windowSize.width; - [[fFilterBar view] setFrame: filterBarFrame]; + fFilterBar.view.frame = filterBarFrame; if (fStatusBar) - [contentView addSubview: [fFilterBar view] positioned: NSWindowBelow relativeTo: [fStatusBar view]]; + [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)]; + [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]); + CGFloat heightChange = NSHeight(fFilterBar.view.frame); if (!show) heightChange *= -1; @@ -3513,13 +3509,13 @@ static void removeKeRangerRansomware() { NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO]; - NSScreen * screen = [fWindow screen]; + NSScreen * screen = fWindow.screen; if (screen) { - CGFloat change = [screen visibleFrame].size.height - frame.size.height; + CGFloat change = screen.visibleFrame.size.height - frame.size.height; if (change < 0.0) { - frame = [fWindow frame]; + frame = fWindow.frame; frame.size.height += change; frame.origin.y -= change; [fWindow setFrame: frame display: NO animate: NO]; @@ -3527,24 +3523,24 @@ static void removeKeRangerRansomware() } } - NSScrollView * scrollView = [fTableView enclosingScrollView]; + NSScrollView * scrollView = fTableView.enclosingScrollView; //set views to not autoresize - const NSUInteger filterMask = [[fFilterBar view] autoresizingMask]; - const NSUInteger scrollMask = [scrollView autoresizingMask]; - [[fFilterBar view] setAutoresizingMask: NSViewNotSizable]; - [scrollView setAutoresizingMask: NSViewNotSizable]; + 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] setAutoresizingMask: filterMask]; - [scrollView setAutoresizingMask: scrollMask]; + fFilterBar.view.autoresizingMask = filterMask; + scrollView.autoresizingMask = scrollMask; if (!show) { - [[fFilterBar view] removeFromSuperviewWithoutNeedingDisplay]; + [fFilterBar.view removeFromSuperviewWithoutNeedingDisplay]; fFilterBar = nil; } @@ -3553,9 +3549,9 @@ static void removeKeRangerRansomware() else { //change min size - NSSize minSize = [fWindow contentMinSize]; + NSSize minSize = fWindow.contentMinSize; minSize.height += heightChange; - [fWindow setContentMinSize: minSize]; + fWindow.contentMinSize = minSize; } } @@ -3574,8 +3570,8 @@ static void removeKeRangerRansomware() - (void) beginPreviewPanelControl: (QLPreviewPanel *) panel { fPreviewPanel = panel; - [fPreviewPanel setDelegate: self]; - [fPreviewPanel setDataSource: self]; + fPreviewPanel.delegate = self; + fPreviewPanel.dataSource = self; } - (void) endPreviewPanelControl: (QLPreviewPanel *) panel @@ -3585,11 +3581,11 @@ static void removeKeRangerRansomware() - (NSArray *) quickLookableTorrents { - NSArray * selectedTorrents = [fTableView selectedTorrents]; - NSMutableArray * qlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]]; + NSArray * selectedTorrents = fTableView.selectedTorrents; + NSMutableArray * qlArray = [NSMutableArray arrayWithCapacity: selectedTorrents.count]; for (Torrent * torrent in selectedTorrents) - if (([torrent isFolder] || [torrent isComplete]) && [torrent dataLocation]) + if ((torrent.folder || torrent.complete) && torrent.dataLocation) [qlArray addObject: torrent]; return qlArray; @@ -3597,16 +3593,16 @@ static void removeKeRangerRansomware() - (NSInteger) numberOfPreviewItemsInPreviewPanel: (QLPreviewPanel *) panel { - if ([fInfoController canQuickLook]) - return [[fInfoController quickLookURLs] count]; + if (fInfoController.canQuickLook) + return fInfoController.quickLookURLs.count; else - return [[self quickLookableTorrents] count]; + return [self quickLookableTorrents].count; } - (id ) previewPanel: (QLPreviewPanel *) panel previewItemAtIndex: (NSInteger) index { - if ([fInfoController canQuickLook]) - return [fInfoController quickLookURLs][index]; + if (fInfoController.canQuickLook) + return fInfoController.quickLookURLs[index]; else return [self quickLookableTorrents][index]; } @@ -3624,11 +3620,11 @@ static void removeKeRangerRansomware() - (NSRect) previewPanel: (QLPreviewPanel *) panel sourceFrameOnScreenForPreviewItem: (id ) item { - if ([fInfoController canQuickLook]) + if (fInfoController.canQuickLook) return [fInfoController quickLookSourceFrameForPreviewItem: item]; else { - if (![fWindow isVisible]) + if (!fWindow.visible) return NSZeroRect; const NSInteger row = [fTableView rowForItem: item]; @@ -3637,7 +3633,7 @@ static void removeKeRangerRansomware() NSRect frame = [fTableView iconRectForRow: row]; - if (!NSIntersectsRect([fTableView visibleRect], frame)) + if (!NSIntersectsRect(fTableView.visibleRect, frame)) return NSZeroRect; frame.origin = [fTableView convertPoint: frame.origin toView: nil]; @@ -3650,11 +3646,12 @@ static void removeKeRangerRansomware() - (void) showToolbarShare: (id) sender { NSParameterAssert([sender isKindOfClass:[NSButton class]]); - - NSSharingServicePicker * picker = [[NSSharingServicePicker alloc] initWithItems: [[ShareTorrentFileHelper sharedHelper] shareTorrentURLs]]; + NSButton *senderButton = sender; + + NSSharingServicePicker * picker = [[NSSharingServicePicker alloc] initWithItems: ShareTorrentFileHelper.sharedHelper.shareTorrentURLs]; picker.delegate = self; - [picker showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMinYEdge]; + [picker showRelativeToRect:senderButton.bounds ofView:senderButton preferredEdge:NSMinYEdge]; } - (id)sharingServicePicker:(NSSharingServicePicker *)sharingServicePicker delegateForSharingService:(NSSharingService *)sharingService @@ -3677,17 +3674,17 @@ static void removeKeRangerRansomware() ButtonToolbarItem * item = [[class alloc] initWithItemIdentifier: ident]; NSButton * button = [[NSButton alloc] init]; - [button setBezelStyle: NSTexturedRoundedBezelStyle]; - [button setStringValue: @""]; + button.bezelStyle = NSTexturedRoundedBezelStyle; + button.stringValue = @""; - [item setView: button]; + item.view = button; if (@available(macOS 11.0, *)) { // not needed } else { const NSSize buttonSize = NSMakeSize(36.0, 25.0); - [item setMinSize: buttonSize]; - [item setMaxSize: buttonSize]; + item.minSize = buttonSize; + item.maxSize = buttonSize; } return item; @@ -3699,17 +3696,17 @@ static void removeKeRangerRansomware() { ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")]; - [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")]; - [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")]; + 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 setImage: [NSImage imageWithSystemSymbolName: @"doc.badge.plus" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"doc.badge.plus" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate"]]; + item.image = [NSImage imageNamed: @"ToolbarCreateTemplate"]; } - [item setTarget: self]; - [item setAction: @selector(createFile:)]; - [item setAutovalidates: NO]; + item.target = self; + item.action = @selector(createFile:); + item.autovalidates = NO; return item; } @@ -3717,17 +3714,17 @@ static void removeKeRangerRansomware() { ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")]; - [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")]; - [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")]; + 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 setImage: [NSImage imageWithSystemSymbolName: @"folder" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"folder" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate"]]; + item.image = [NSImage imageNamed: @"ToolbarOpenTemplate"]; } - [item setTarget: self]; - [item setAction: @selector(openShowSheet:)]; - [item setAutovalidates: NO]; + item.target = self; + item.action = @selector(openShowSheet:); + item.autovalidates = NO; return item; } @@ -3735,18 +3732,17 @@ static void removeKeRangerRansomware() { ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")]; - [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")]; - [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")]; - [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate"]]; + 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 setImage: [NSImage imageWithSystemSymbolName: @"globe" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"globe" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate"]]; + item.image = [NSImage imageNamed: @"ToolbarOpenWebTemplate"]; } - [item setTarget: self]; - [item setAction: @selector(openURLShowSheet:)]; - [item setAutovalidates: NO]; + item.target = self; + item.action = @selector(openURLShowSheet:); + item.autovalidates = NO; return item; } @@ -3754,35 +3750,35 @@ static void removeKeRangerRansomware() { ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")]; - [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")]; - [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")]; + 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 setImage: [NSImage imageWithSystemSymbolName: @"nosign" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"nosign" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate"]]; + item.image = [NSImage imageNamed: @"ToolbarRemoveTemplate"]; } - [item setTarget: self]; - [item setAction: @selector(removeNoDelete:)]; - [item setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh]; + item.target = self; + item.action = @selector(removeNoDelete:); + item.visibilityPriority = NSToolbarItemVisibilityPriorityHigh; return item; } else if ([ident isEqualToString: TOOLBAR_INFO]) { ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled + ((NSButtonCell *)((NSButton *)item.view).cell).showsStateBy = NSContentsCellMask; //blue when enabled - [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")]; - [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")]; - [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")]; + 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 setImage: [NSImage imageWithSystemSymbolName: @"info.circle" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"info.circle" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate"]]; + item.image = [NSImage imageNamed: @"ToolbarInfoTemplate"]; } - [item setTarget: self]; - [item setAction: @selector(showInfo:)]; + item.target = self; + item.action = @selector(showInfo:); return item; } @@ -3791,26 +3787,26 @@ static void removeKeRangerRansomware() GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident]; NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect]; - [segmentedControl setCell: [[ToolbarSegmentedCell alloc] init]]; - [groupItem setView: segmentedControl]; - NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell]; + segmentedControl.cell = [[ToolbarSegmentedCell alloc] init]; + groupItem.view = segmentedControl; + NSSegmentedCell * segmentedCell = (NSSegmentedCell *)segmentedControl.cell; segmentedControl.segmentStyle = NSSegmentStyleSeparated; - [segmentedControl setSegmentCount: 2]; - [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary]; + segmentedControl.segmentCount = 2; + segmentedCell.trackingMode = NSSegmentSwitchTrackingMomentary; if (@available(macOS 11.0, *)) { // not needed } else { const NSSize groupSize = NSMakeSize(72.0, 25.0); - [groupItem setMinSize: groupSize]; - [groupItem setMaxSize: groupSize]; + groupItem.minSize = groupSize; + groupItem.maxSize = groupSize; } - [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")]; - [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")]; - [groupItem setTarget: self]; - [groupItem setAction: @selector(allToolbarClicked:)]; + 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]]; @@ -3837,7 +3833,7 @@ static void removeKeRangerRansomware() NSLocalizedString(@"Resume All", "All toolbar item -> label")]]; - [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh]; + groupItem.visibilityPriority = NSToolbarItemVisibilityPriorityHigh; return groupItem; } @@ -3846,26 +3842,25 @@ static void removeKeRangerRansomware() GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident]; NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect]; - [segmentedControl setCell: [[ToolbarSegmentedCell alloc] init]]; - [groupItem setView: segmentedControl]; - NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell]; - segmentedControl.segmentStyle = NSSegmentStyleSeparated; + segmentedControl.cell = [[ToolbarSegmentedCell alloc] init]; + groupItem.view = segmentedControl; + NSSegmentedCell * segmentedCell = (NSSegmentedCell *)segmentedControl.cell; - [segmentedControl setSegmentCount: 2]; - [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary]; + segmentedControl.segmentCount = 2; + segmentedCell.trackingMode = NSSegmentSwitchTrackingMomentary; if (@available(macOS 11.0, *)) { // not needed } else { const NSSize groupSize = NSMakeSize(72.0, 25.0); - [groupItem setMinSize: groupSize]; - [groupItem setMaxSize: groupSize]; + groupItem.minSize = groupSize; + groupItem.maxSize = groupSize; } - [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")]; - [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")]; - [groupItem setTarget: self]; - [groupItem setAction: @selector(selectedToolbarClicked:)]; + 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]]; @@ -3891,40 +3886,40 @@ static void removeKeRangerRansomware() NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label")]]; - [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh]; + groupItem.visibilityPriority = NSToolbarItemVisibilityPriorityHigh; return groupItem; } else if ([ident isEqualToString: TOOLBAR_FILTER]) { ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled + ((NSButtonCell *)((NSButton *)item.view).cell).showsStateBy = NSContentsCellMask; //blue when enabled - [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")]; - [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")]; - [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")]; + 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 setImage: [NSImage imageWithSystemSymbolName: @"magnifyingglass" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"magnifyingglass" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate"]]; + item.image = [NSImage imageNamed: @"ToolbarFilterTemplate"]; } - [item setTarget: self]; - [item setAction: @selector(toggleFilterBar:)]; + item.target = self; + item.action = @selector(toggleFilterBar:); return item; } else if ([ident isEqualToString: TOOLBAR_QUICKLOOK]) { ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident]; - [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled + ((NSButtonCell *)((NSButton *)item.view).cell).showsStateBy = NSContentsCellMask; //blue when enabled - [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")]; - [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")]; - [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")]; - [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]]; - [item setTarget: self]; - [item setAction: @selector(toggleQuickLook:)]; - [item setVisibilityPriority: NSToolbarItemVisibilityPriorityLow]; + 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; } @@ -3932,15 +3927,15 @@ static void removeKeRangerRansomware() { ShareToolbarItem * item = [self toolbarButtonWithIdentifier: ident forToolbarButtonClass: [ShareToolbarItem class]]; - [item setLabel: NSLocalizedString(@"Share", "Share toolbar item -> label")]; - [item setPaletteLabel: NSLocalizedString(@"Share", "Share toolbar item -> palette label")]; - [item setToolTip: NSLocalizedString(@"Share torrent file", "Share toolbar item -> tooltip")]; - [item setImage: [NSImage imageNamed: NSImageNameShareTemplate]]; - [item setVisibilityPriority: NSToolbarItemVisibilityPriorityLow]; + 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 setTarget: self]; - [itemButton setAction: @selector(showToolbarShare:)]; + NSButton *itemButton = (NSButton *)item.view; + itemButton.target = self; + itemButton.action = @selector(showToolbarShare:); [itemButton sendActionOn:NSLeftMouseDownMask]; return item; @@ -3952,7 +3947,7 @@ static void removeKeRangerRansomware() - (void) allToolbarClicked: (id) sender { NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]] - ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [(NSControl *)sender tag]; + ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : ((NSControl *)sender).tag; switch (tagValue) { case TOOLBAR_PAUSE_TAG: @@ -3967,7 +3962,7 @@ static void removeKeRangerRansomware() - (void) selectedToolbarClicked: (id) sender { NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]] - ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [(NSControl *)sender tag]; + ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : ((NSControl *)sender).tag; switch (tagValue) { case TOOLBAR_PAUSE_TAG: @@ -3997,17 +3992,17 @@ static void removeKeRangerRansomware() - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem { - NSString * ident = [toolbarItem itemIdentifier]; + NSString * ident = toolbarItem.itemIdentifier; //enable remove item if ([ident isEqualToString: TOOLBAR_REMOVE]) - return [fTableView numberOfSelectedRows] > 0; + return fTableView.numberOfSelectedRows > 0; //enable pause all item if ([ident isEqualToString: TOOLBAR_PAUSE_ALL]) { for (Torrent * torrent in fTorrents) - if ([torrent isActive] || [torrent waitingToStart]) + if (torrent.active || torrent.waitingToStart) return YES; return NO; } @@ -4016,7 +4011,7 @@ static void removeKeRangerRansomware() if ([ident isEqualToString: TOOLBAR_RESUME_ALL]) { for (Torrent * torrent in fTorrents) - if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding]) + if (!torrent.active && !torrent.waitingToStart && !torrent.finishedSeeding) return YES; return NO; } @@ -4024,8 +4019,8 @@ static void removeKeRangerRansomware() //enable pause item if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED]) { - for (Torrent * torrent in [fTableView selectedTorrents]) - if ([torrent isActive] || [torrent waitingToStart]) + for (Torrent * torrent in fTableView.selectedTorrents) + if (torrent.active || torrent.waitingToStart) return YES; return NO; } @@ -4033,8 +4028,8 @@ static void removeKeRangerRansomware() //enable resume item if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED]) { - for (Torrent * torrent in [fTableView selectedTorrents]) - if (![torrent isActive] && ![torrent waitingToStart]) + for (Torrent * torrent in fTableView.selectedTorrents) + if (!torrent.active && !torrent.waitingToStart) return YES; return NO; } @@ -4042,53 +4037,53 @@ static void removeKeRangerRansomware() //set info item if ([ident isEqualToString: TOOLBAR_INFO]) { - [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]]; + ((NSButton *)toolbarItem.view).state = fInfoController.window.visible; return YES; } //set filter item if ([ident isEqualToString: TOOLBAR_FILTER]) { - [(NSButton *)[toolbarItem view] setState: fFilterBar != nil]; + ((NSButton *)toolbarItem.view).state = fFilterBar != nil; return YES; } //set quick look item if ([ident isEqualToString: TOOLBAR_QUICKLOOK]) { - [(NSButton *)[toolbarItem view] setState: [QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible]]; + ((NSButton *)toolbarItem.view).state = [QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible; return YES; } //enable share item if ([ident isEqualToString: TOOLBAR_SHARE]) - return [fTableView numberOfSelectedRows] > 0; + return fTableView.numberOfSelectedRows > 0; return YES; } - (BOOL) validateMenuItem: (NSMenuItem *) menuItem { - SEL action = [menuItem action]; + SEL action = menuItem.action; if (action == @selector(toggleSpeedLimit:)) { - [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState]; + 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 isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu]; + BOOL canUseTable = fWindow.keyWindow || menuItem.menu.supermenu != NSApp.mainMenu; //enable open items if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:)) - return [fWindow attachedSheet] == nil; + return fWindow.attachedSheet == nil; //enable sort options if (action == @selector(setSort:)) { NSString * sortType; - switch ([menuItem tag]) + switch (menuItem.tag) { case SORT_ORDER_TAG: sortType = SORT_ORDER; @@ -4119,66 +4114,66 @@ static void removeKeRangerRansomware() sortType = SORT_ORDER; } - [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState]; - return [fWindow isVisible]; + menuItem.state = [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState; + return fWindow.visible; } if (action == @selector(setGroup:)) { BOOL checked = NO; - NSInteger index = [menuItem tag]; - for (Torrent * torrent in [fTableView selectedTorrents]) - if (index == [torrent groupValue]) + NSInteger index = menuItem.tag; + for (Torrent * torrent in fTableView.selectedTorrents) + if (index == torrent.groupValue) { checked = YES; break; } - [menuItem setState: checked ? NSOnState : NSOffState]; - return canUseTable && [fTableView numberOfSelectedRows] > 0; + menuItem.state = checked ? NSOnState : NSOffState; + return canUseTable && fTableView.numberOfSelectedRows > 0; } if (action == @selector(toggleSmallView:)) { - [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState]; - return [fWindow isVisible]; + menuItem.state = [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState; + return fWindow.visible; } if (action == @selector(togglePiecesBar:)) { - [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState]; - return [fWindow isVisible]; + menuItem.state = [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState; + return fWindow.visible; } if (action == @selector(toggleAvailabilityBar:)) { - [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState]; - return [fWindow isVisible]; + menuItem.state = [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState; + return fWindow.visible; } //enable show info if (action == @selector(showInfo:)) { - NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector") + NSString * title = fInfoController.window.visible ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector") : NSLocalizedString(@"Show Inspector", "View menu -> Inspector"); - [menuItem setTitle: title]; + menuItem.title = title; return YES; } //enable prev/next inspector tab if (action == @selector(setInfoTab:)) - return [[fInfoController window] isVisible]; + 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"); - [menuItem setTitle: title]; + menuItem.title = title; - return [fWindow isVisible]; + return fWindow.visible; } //enable toggle filter bar @@ -4186,33 +4181,33 @@ static void removeKeRangerRansomware() { NSString * title = !fFilterBar ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar") : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar"); - [menuItem setTitle: title]; + menuItem.title = title; - return [fWindow isVisible]; + return fWindow.visible; } //enable prev/next filter button if (action == @selector(switchFilter:)) - return [fWindow isVisible] && fFilterBar; + return fWindow.visible && fFilterBar; //enable reveal in finder if (action == @selector(revealFile:)) - return canUseTable && [fTableView numberOfSelectedRows] > 0; + return canUseTable && fTableView.numberOfSelectedRows > 0; //enable renaming file/folder if (action == @selector(renameSelected:)) - return canUseTable && [fTableView numberOfSelectedRows] == 1; + 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 isActive]) + if (torrent.active) { - if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? ![torrent isSeeding] : YES) + if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? !torrent.seeding : YES) { warning = YES; break; @@ -4221,39 +4216,39 @@ static void removeKeRangerRansomware() } //append or remove ellipsis when needed - NSString * title = [menuItem title], * ellipsis = [NSString ellipsis]; + NSString * title = menuItem.title, * ellipsis = NSString.ellipsis; if (warning && [fDefaults boolForKey: @"CheckRemove"]) { if (![title hasSuffix: ellipsis]) - [menuItem setTitle: [title stringByAppendingEllipsis]]; + menuItem.title = [title stringByAppendingEllipsis]; } else { if ([title hasSuffix: ellipsis]) - [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]]; + menuItem.title = [title substringToIndex: [title rangeOfString: ellipsis].location]; } - return canUseTable && [fTableView numberOfSelectedRows] > 0; + return canUseTable && fTableView.numberOfSelectedRows > 0; } //remove all completed transfers item if (action == @selector(clearCompleted:)) { //append or remove ellipsis when needed - NSString * title = [menuItem title], * ellipsis = [NSString ellipsis]; + NSString * title = menuItem.title, * ellipsis = NSString.ellipsis; if ([fDefaults boolForKey: @"WarningRemoveCompleted"]) { if (![title hasSuffix: ellipsis]) - [menuItem setTitle: [title stringByAppendingEllipsis]]; + menuItem.title = [title stringByAppendingEllipsis]; } else { if ([title hasSuffix: ellipsis]) - [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]]; + menuItem.title = [title substringToIndex: [title rangeOfString: ellipsis].location]; } for (Torrent * torrent in fTorrents) - if ([torrent isFinishedSeeding]) + if (torrent.finishedSeeding) return YES; return NO; } @@ -4262,7 +4257,7 @@ static void removeKeRangerRansomware() if (action == @selector(stopAllTorrents:)) { for (Torrent * torrent in fTorrents) - if ([torrent isActive] || [torrent waitingToStart]) + if (torrent.active || torrent.waitingToStart) return YES; return NO; } @@ -4271,7 +4266,7 @@ static void removeKeRangerRansomware() if (action == @selector(resumeAllTorrents:)) { for (Torrent * torrent in fTorrents) - if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding]) + if (!torrent.active && !torrent.waitingToStart && !torrent.finishedSeeding) return YES; return NO; } @@ -4283,7 +4278,7 @@ static void removeKeRangerRansomware() return NO; for (Torrent * torrent in fTorrents) - if ([torrent waitingToStart]) + if (torrent.waitingToStart) return YES; return NO; } @@ -4294,8 +4289,8 @@ static void removeKeRangerRansomware() if (!canUseTable) return NO; - for (Torrent * torrent in [fTableView selectedTorrents]) - if (![torrent isActive]) + for (Torrent * torrent in fTableView.selectedTorrents) + if (!torrent.active) return YES; return NO; } @@ -4306,8 +4301,8 @@ static void removeKeRangerRansomware() if (!canUseTable) return NO; - for (Torrent * torrent in [fTableView selectedTorrents]) - if ([torrent isActive] || [torrent waitingToStart]) + for (Torrent * torrent in fTableView.selectedTorrents) + if (torrent.active || torrent.waitingToStart) return YES; return NO; } @@ -4318,8 +4313,8 @@ static void removeKeRangerRansomware() if (!canUseTable) return NO; - for (Torrent * torrent in [fTableView selectedTorrents]) - if (![torrent isActive] && ![torrent waitingToStart]) + for (Torrent * torrent in fTableView.selectedTorrents) + if (!torrent.active && !torrent.waitingToStart) return YES; return NO; } @@ -4330,8 +4325,8 @@ static void removeKeRangerRansomware() if (!canUseTable) return NO; - for (Torrent * torrent in [fTableView selectedTorrents]) - if ([torrent canManualAnnounce]) + for (Torrent * torrent in fTableView.selectedTorrents) + if (torrent.canManualAnnounce) return YES; return NO; } @@ -4342,15 +4337,15 @@ static void removeKeRangerRansomware() if (!canUseTable) return NO; - for (Torrent * torrent in [fTableView selectedTorrents]) - if (![torrent isMagnet]) + 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; + return canUseTable && fTableView.numberOfSelectedRows > 0; //enable copy torrent file item if (action == @selector(copyTorrentFiles:)) @@ -4358,38 +4353,38 @@ static void removeKeRangerRansomware() if (!canUseTable) return NO; - for (Torrent * torrent in [fTableView selectedTorrents]) - if (![torrent isMagnet]) + 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; + return canUseTable && fTableView.numberOfSelectedRows > 0; //enable reverse sort item if (action == @selector(setSortReverse:)) { - const BOOL isReverse = [menuItem tag] == SORT_DESC_TAG; - [menuItem setState: (isReverse == [fDefaults boolForKey: @"SortReverse"]) ? NSOnState : NSOffState]; + const BOOL 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 setState: [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] isVisible]; + const BOOL 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"); - [menuItem setTitle: title]; + menuItem.title = title; return YES; } @@ -4407,7 +4402,7 @@ static void removeKeRangerRansomware() BOOL anyActive = NO; for (Torrent * torrent in fTorrents) { - if ([torrent isActive]) + if (torrent.active) anyActive = YES; [torrent sleep]; //have to call on all, regardless if they are active } @@ -4427,7 +4422,7 @@ static void removeKeRangerRansomware() { //prevent idle sleep unless no torrents are active for (Torrent * torrent in fTorrents) - if ([torrent isActive] && ![torrent isStalled] && ![torrent isError]) + if (torrent.active && !torrent.stalled && !torrent.error) { IOCancelPowerChange(fRootPort, (long) messageArgument); return; @@ -4453,9 +4448,9 @@ static void removeKeRangerRansomware() NSUInteger seeding = 0, downloading = 0; for (Torrent * torrent in fTorrents) { - if ([torrent isSeeding]) + if (torrent.seeding) seeding++; - else if ([torrent isActive]) + else if (torrent.active) downloading++; else; } @@ -4488,9 +4483,9 @@ static void removeKeRangerRansomware() - (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; } @@ -4498,11 +4493,11 @@ static void removeKeRangerRansomware() { if ([fDefaults boolForKey: @"AutoSize"]) { - NSScrollView * scrollView = [fTableView enclosingScrollView]; + NSScrollView * scrollView = fTableView.enclosingScrollView; - [scrollView setHasVerticalScroller: NO]; - [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES]; - [scrollView setHasVerticalScroller: YES]; + scrollView.hasVerticalScroller = NO; + [fWindow setFrame: self.sizedWindowFrame display: YES animate: YES]; + scrollView.hasVerticalScroller = YES; [self setWindowMinMaxToCurrent]; } @@ -4510,12 +4505,12 @@ static void removeKeRangerRansomware() - (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]; } @@ -4526,34 +4521,34 @@ static void removeKeRangerRansomware() [self setWindowSizeToFit]; else { - NSSize contentMinSize = [fWindow contentMinSize]; - contentMinSize.height = [self minWindowContentSizeAllowed]; + NSSize contentMinSize = fWindow.contentMinSize; + contentMinSize.height = self.minWindowContentSizeAllowed; - [fWindow setContentMinSize: contentMinSize]; + fWindow.contentMinSize = contentMinSize; - NSSize contentMaxSize = [fWindow contentMaxSize]; + NSSize contentMaxSize = fWindow.contentMaxSize; contentMaxSize.height = FLT_MAX; - [fWindow setContentMaxSize: contentMaxSize]; + fWindow.contentMaxSize = contentMaxSize; } } - (void) setWindowMinMaxToCurrent { - const CGFloat height = NSHeight([[fWindow contentView] frame]); + const CGFloat 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; - [fWindow setContentMinSize: minSize]; - [fWindow setContentMaxSize: maxSize]; + fWindow.contentMinSize = minSize; + fWindow.contentMaxSize = maxSize; } - (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; } @@ -4581,7 +4576,7 @@ static void removeKeRangerRansomware() - (void) toggleQuickLook: (id) sender { - if ([[QLPreviewPanel sharedPreviewPanel] isVisible]) + if ([QLPreviewPanel sharedPreviewPanel].visible) [[QLPreviewPanel sharedPreviewPanel] orderOut: nil]; else [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront: nil]; @@ -4589,22 +4584,22 @@ static void removeKeRangerRansomware() - (void) linkHomepage: (id) sender { - [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]]; + [NSWorkspace.sharedWorkspace openURL: [NSURL URLWithString: WEBSITE_URL]]; } - (void) linkForums: (id) sender { - [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]]; + [NSWorkspace.sharedWorkspace openURL: [NSURL URLWithString: FORUM_URL]]; } - (void) linkGitHub: (id) sender { - [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: GITHUB_URL]]; + [NSWorkspace.sharedWorkspace openURL: [NSURL URLWithString: GITHUB_URL]]; } - (void) linkDonate: (id) sender { - [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]]; + [NSWorkspace.sharedWorkspace openURL: [NSURL URLWithString: DONATE_URL]]; } - (void) updaterWillRelaunchApplication: (SUUpdater *) updater @@ -4621,7 +4616,7 @@ static void removeKeRangerRansomware() 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]) + if (torrentStruct == checkTorrent.torrentStruct) { torrent = checkTorrent; *stop = YES; @@ -4692,9 +4687,9 @@ static void removeKeRangerRansomware() 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]]; + location = [GroupsController.groups customDownloadLocationForIndex: torrent.groupValue]; [torrent changeDownloadFolderBeforeUsing: location determinationType: TorrentDeterminationAutomatic]; } @@ -4726,7 +4721,7 @@ static void removeKeRangerRansomware() { [torrent update]; - if ([[fTableView selectedTorrents] containsObject: torrent]) + if ([fTableView.selectedTorrents containsObject: torrent]) { [fInfoController updateInfoStats]; //this will reload the file table [fInfoController updateOptions]; @@ -4738,7 +4733,7 @@ static void removeKeRangerRansomware() [torrent update]; [torrent updateTimeMachineExclude]; - if ([[fTableView selectedTorrents] containsObject: torrent]) + if ([fTableView.selectedTorrents containsObject: torrent]) [fInfoController updateInfoStats]; } diff --git a/macosx/CreatorWindowController.h b/macosx/CreatorWindowController.h index ae246459e..90e8a52ae 100644 --- a/macosx/CreatorWindowController.h +++ b/macosx/CreatorWindowController.h @@ -50,7 +50,7 @@ + (CreatorWindowController *) createTorrentFile: (tr_session *) handle; + (CreatorWindowController *) createTorrentFile: (tr_session *) handle forFile: (NSURL *) file; -- (id) initWithHandle: (tr_session *) handle path: (NSURL *) path; +- (instancetype) initWithHandle: (tr_session *) handle path: (NSURL *) path; - (IBAction) setLocation: (id) sender; - (IBAction) create: (id) sender; diff --git a/macosx/CreatorWindowController.m b/macosx/CreatorWindowController.m index 4d6900747..8e5773d90 100644 --- a/macosx/CreatorWindowController.m +++ b/macosx/CreatorWindowController.m @@ -63,7 +63,7 @@ NSMutableSet *creatorWindowControllerSet = nil; return creator; } -- (id) initWithHandle: (tr_session *) handle path: (NSURL *) path +- (instancetype) initWithHandle: (tr_session *) handle path: (NSURL *) path { if ((self = [super initWithWindowNibName: @"Creator"])) { @@ -74,17 +74,17 @@ NSMutableSet *creatorWindowControllerSet = nil; fStarted = NO; fPath = path; - fInfo = tr_metaInfoBuilderCreate([[fPath path] UTF8String]); + fInfo = tr_metaInfoBuilderCreate(fPath.path.UTF8String); if (fInfo->fileCount == 0) { NSAlert * alert = [[NSAlert alloc] init]; [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> no files -> button")]; - [alert setMessageText: NSLocalizedString(@"This folder contains no files.", - "Create torrent -> no files -> title")]; - [alert setInformativeText: NSLocalizedString(@"There must be at least one file in a folder to create a torrent file.", - "Create torrent -> no files -> warning")]; - [alert setAlertStyle: NSWarningAlertStyle]; + 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; [alert runModal]; @@ -94,18 +94,18 @@ NSMutableSet *creatorWindowControllerSet = nil; { NSAlert * alert = [[NSAlert alloc] init]; [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> zero size -> button")]; - [alert setMessageText: NSLocalizedString(@"The total file size is zero bytes.", - "Create torrent -> zero size -> title")]; - [alert setInformativeText: NSLocalizedString(@"A torrent file cannot be created for files with no size.", - "Create torrent -> zero size -> warning")]; - [alert setAlertStyle: NSWarningAlertStyle]; + 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]; return nil; } - fDefaults = [NSUserDefaults standardUserDefaults]; + fDefaults = NSUserDefaults.standardUserDefaults; //get list of trackers if (!(fTrackers = [[fDefaults arrayForKey: @"CreatorTrackers"] mutableCopy])) @@ -126,7 +126,7 @@ NSMutableSet *creatorWindowControllerSet = nil; } //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]; @@ -139,21 +139,21 @@ NSMutableSet *creatorWindowControllerSet = nil; - (void) awakeFromNib { - [[self window] setRestorationClass: [self class]]; + self.window.restorationClass = [self class]; - NSString * name = [fPath lastPathComponent]; + NSString * name = fPath.lastPathComponent; - [[self window] setTitle: name]; + self.window.title = name; - [fNameField setStringValue: name]; - [fNameField setToolTip: [fPath path]]; + fNameField.stringValue = name; + fNameField.toolTip = fPath.path; const BOOL multifile = fInfo->isFolder; - NSImage * icon = [[NSWorkspace sharedWorkspace] iconForFileType: multifile - ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) : [fPath pathExtension]]; - [icon setSize: [fIconView frame].size]; - [fIconView setImage: icon]; + NSImage * icon = [NSWorkspace.sharedWorkspace iconForFileType: multifile + ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) : fPath.pathExtension]; + icon.size = fIconView.frame.size; + fIconView.image = icon; NSString * statusString = [NSString stringForFileSize: fInfo->totalSize]; if (multifile) @@ -167,14 +167,14 @@ NSMutableSet *creatorWindowControllerSet = nil; fileString = NSLocalizedString(@"1 file", "Create torrent -> info"); statusString = [NSString stringWithFormat: @"%@, %@", fileString, statusString]; } - [fStatusField setStringValue: statusString]; + fStatusField.stringValue = statusString; if (fInfo->pieceCount == 1) - [fPiecesField setStringValue: [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 setStringValue: [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"]]; if (!fLocation) @@ -182,15 +182,15 @@ NSMutableSet *creatorWindowControllerSet = nil; //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"]]]; + fLocation = [[NSURL alloc] initFileURLWithPath: [location.stringByExpandingTildeInPath stringByAppendingPathComponent: [name stringByAppendingPathExtension: @"torrent"]]]; } [self updateLocationField]; //set previously saved values if ([fDefaults objectForKey: @"CreatorPrivate"]) - [fPrivateCheck setState: [fDefaults boolForKey: @"CreatorPrivate"] ? NSOnState : NSOffState]; + fPrivateCheck.state = [fDefaults boolForKey: @"CreatorPrivate"] ? NSOnState : NSOffState; - [fOpenCheck setState: [fDefaults boolForKey: @"CreatorOpen"] ? NSOnState : NSOffState]; + fOpenCheck.state = [fDefaults boolForKey: @"CreatorOpen"] ? NSOnState : NSOffState; } - (void) dealloc @@ -210,7 +210,7 @@ NSMutableSet *creatorWindowControllerSet = 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); } @@ -219,9 +219,9 @@ NSMutableSet *creatorWindowControllerSet = nil; [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 encodeInteger: fOpenCheck.state forKey: @"TRCreatorOpenCheck"]; + [state encodeInteger: fPrivateCheck.state forKey: @"TRCreatorPrivateCheck"]; + [state encodeObject: fCommentView.string forKey: @"TRCreatorPrivateComment"]; } - (void) window: (NSWindow *) window didDecodeRestorableState: (NSCoder *) coder @@ -232,29 +232,29 @@ NSMutableSet *creatorWindowControllerSet = nil; fTrackers = [coder decodeObjectForKey: @"TRCreatorTrackers"]; [fTrackerTable reloadData]; - [fOpenCheck setState: [coder decodeIntegerForKey: @"TRCreatorOpenCheck"]]; - [fPrivateCheck setState: [coder decodeIntegerForKey: @"TRCreatorPrivateCheck"]]; - [fCommentView setString: [coder decodeObjectForKey: @"TRCreatorPrivateComment"]]; + fOpenCheck.state = [coder decodeIntegerForKey: @"TRCreatorOpenCheck"]; + fPrivateCheck.state = [coder decodeIntegerForKey: @"TRCreatorPrivateCheck"]; + fCommentView.string = [coder decodeObjectForKey: @"TRCreatorPrivateComment"]; } - (IBAction) setLocation: (id) sender { NSSavePanel * panel = [NSSavePanel savePanel]; - [panel setPrompt: NSLocalizedString(@"Select", "Create torrent -> location sheet -> button")]; - [panel setMessage: NSLocalizedString(@"Select the name and location for the torrent file.", - "Create torrent -> location sheet -> message")]; + 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 setAllowedFileTypes: @[@"org.bittorrent.torrent", @"torrent"]]; - [panel setCanSelectHiddenExtension: YES]; + panel.allowedFileTypes = @[@"org.bittorrent.torrent", @"torrent"]; + panel.canSelectHiddenExtension = YES; - [panel setDirectoryURL: [fLocation URLByDeletingLastPathComponent]]; - [panel setNameFieldStringValue: [fLocation lastPathComponent]]; + 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]; + fLocation = panel.URL; [self updateLocationField]; } }]; @@ -263,15 +263,15 @@ NSMutableSet *creatorWindowControllerSet = nil; - (IBAction) create: (id) sender { //make sure the trackers are no longer being verified - if ([fTrackerTable editedRow] != -1) - [[self window] endEditingFor: fTrackerTable]; + if (fTrackerTable.editedRow != -1) + [self.window endEditingFor: fTrackerTable]; - const BOOL isPrivate = [fPrivateCheck state] == NSOnState; - if ([fTrackers count] == 0 + const BOOL isPrivate = fPrivateCheck.state == NSOnState; + if (fTrackers.count == 0 && [fDefaults boolForKey: isPrivate ? @"WarningCreatorPrivateBlankAddress" : @"WarningCreatorBlankAddress"]) { NSAlert * alert = [[NSAlert alloc] init]; - [alert setMessageText: NSLocalizedString(@"There are no tracker addresses.", "Create torrent -> blank address -> title")]; + 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." @@ -281,17 +281,17 @@ NSMutableSet *creatorWindowControllerSet = nil; " non-tracker peer discovery methods such as PEX and DHT to download and seed.", "Create torrent -> blank address -> message"); - [alert setInformativeText: infoString]; + alert.informativeText = infoString; [alert addButtonWithTitle: NSLocalizedString(@"Create", "Create torrent -> blank address -> button")]; [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Create torrent -> blank address -> button")]; - [alert setShowsSuppressionButton: YES]; + alert.showsSuppressionButton = YES; - [alert beginSheetModalForWindow:[self window] completionHandler:^(NSModalResponse returnCode) { - if ([[alert suppressionButton] state] == NSOnState) + [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { + if (alert.suppressionButton.state == NSOnState) { - [[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: @"WarningCreatorBlankAddress"]; //set regardless of private/public + if (fPrivateCheck.state == NSOnState) + [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningCreatorPrivateBlankAddress"]; } if (returnCode == NSAlertFirstButtonReturn) @@ -304,7 +304,7 @@ NSMutableSet *creatorWindowControllerSet = nil; - (IBAction) cancelCreateWindow: (id) sender { - [[self window] close]; + [self.window close]; } - (void) windowWillClose: (NSNotification *) notification @@ -320,7 +320,7 @@ NSMutableSet *creatorWindowControllerSet = nil; - (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView { - return [fTrackers count]; + return fTrackers.count; } - (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row @@ -331,12 +331,12 @@ NSMutableSet *creatorWindowControllerSet = nil; - (IBAction) addRemoveTracker: (id) sender { //don't allow add/remove when currently adding - it leads to weird results - if ([fTrackerTable editedRow] != -1) + if (fTrackerTable.editedRow != -1) return; if ([[sender cell] tagForSegment: [sender selectedSegment]] == TRACKER_REMOVE_TAG) { - [fTrackers removeObjectsAtIndexes: [fTrackerTable selectedRowIndexes]]; + [fTrackers removeObjectsAtIndexes: fTrackerTable.selectedRowIndexes]; [fTrackerTable deselectAll: self]; [fTrackerTable reloadData]; @@ -346,7 +346,7 @@ NSMutableSet *creatorWindowControllerSet = nil; [fTrackers addObject: @""]; [fTrackerTable reloadData]; - const NSInteger row = [fTrackers count] - 1; + const NSInteger row = fTrackers.count - 1; [fTrackerTable selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; [fTrackerTable editColumn: 0 row: row withEvent: nil select: YES]; } @@ -357,12 +357,12 @@ NSMutableSet *creatorWindowControllerSet = nil; { NSString * tracker = (NSString *)object; - tracker = [tracker stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; + tracker = [tracker stringByTrimmingCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; if ([tracker rangeOfString: @"://"].location == NSNotFound) tracker = [@"http://" stringByAppendingString: tracker]; - if (!tr_urlIsValidTracker([tracker UTF8String])) + if (!tr_urlIsValidTracker(tracker.UTF8String)) { NSBeep(); [fTrackers removeObjectAtIndex: row]; @@ -376,29 +376,29 @@ NSMutableSet *creatorWindowControllerSet = nil; - (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 { - NSArray * addresses = [fTrackers objectsAtIndexes: [fTrackerTable selectedRowIndexes]]; + NSArray * addresses = [fTrackers objectsAtIndexes: fTrackerTable.selectedRowIndexes]; NSString * text = [addresses componentsJoinedByString: @"\n"]; - NSPasteboard * pb = [NSPasteboard generalPasteboard]; + NSPasteboard * pb = NSPasteboard.generalPasteboard; [pb clearContents]; [pb writeObjects: @[text]]; } - (BOOL) validateMenuItem: (NSMenuItem *) menuItem { - const SEL action = [menuItem action]; + const SEL action = menuItem.action; if (action == @selector(copy:)) - return [[self window] firstResponder] == fTrackerTable && [fTrackerTable numberOfSelectedRows] > 0; + 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; } @@ -407,7 +407,7 @@ NSMutableSet *creatorWindowControllerSet = nil; { 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) @@ -420,12 +420,12 @@ NSMutableSet *creatorWindowControllerSet = nil; 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 (tr_urlIsValidTracker([tracker UTF8String])) + if (tr_urlIsValidTracker(tracker.UTF8String)) { [fTrackers addObject: tracker]; added = YES; @@ -447,73 +447,73 @@ NSMutableSet *creatorWindowControllerSet = nil; - (void) updateLocationField { - NSString * pathString = [fLocation path]; - [fLocationField setStringValue: [pathString stringByAbbreviatingWithTildeInPath]]; - [fLocationField setToolTip: pathString]; + NSString * pathString = fLocation.path; + fLocationField.stringValue = pathString.stringByAbbreviatingWithTildeInPath; + fLocationField.toolTip = pathString; } + (NSURL *) chooseFile { NSOpenPanel * panel = [NSOpenPanel openPanel]; - [panel setTitle: NSLocalizedString(@"Create Torrent File", "Create torrent -> select file")]; - [panel setPrompt: NSLocalizedString(@"Select", "Create torrent -> select file")]; - [panel setAllowsMultipleSelection: NO]; - [panel setCanChooseFiles: YES]; - [panel setCanChooseDirectories: YES]; - [panel setCanCreateDirectories: NO]; + panel.title = NSLocalizedString(@"Create Torrent File", "Create torrent -> select file"); + panel.prompt = NSLocalizedString(@"Select", "Create torrent -> select file"); + panel.allowsMultipleSelection = NO; + panel.canChooseFiles = YES; + panel.canChooseDirectories = YES; + panel.canCreateDirectories = NO; - [panel setMessage: NSLocalizedString(@"Select a file or folder for the torrent file.", "Create torrent -> select file")]; + panel.message = NSLocalizedString(@"Select a file or folder for the torrent file.", "Create torrent -> select file"); BOOL success = [panel runModal] == NSModalResponseOK; - return success ? [panel URLs][0] : nil; + return success ? panel.URLs[0] : nil; } - (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 setMessageText: NSLocalizedString(@"The chosen torrent file location does not exist.", - "Create torrent -> directory doesn't exist warning -> title")]; - [alert setInformativeText: [NSString stringWithFormat: + 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 setAlertStyle: NSWarningAlertStyle]; + fLocation.URLByDeletingLastPathComponent.path]; + alert.alertStyle = NSWarningAlertStyle; - [alert beginSheetModalForWindow:[self window] completionHandler:nil]; + [alert beginSheetModalForWindow:self.window completionHandler:nil]; return; } //check if a file with the same name and location already exists if ([fLocation checkResourceIsReachableAndReturnError: NULL]) { - NSArray * pathComponents = [fLocation pathComponents]; - NSInteger count = [pathComponents count]; + 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 setMessageText: NSLocalizedString(@"A torrent file with this name and directory cannot be created.", - "Create torrent -> file already exists warning -> title")]; - [alert setInformativeText: [NSString stringWithFormat: + 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 setAlertStyle: NSWarningAlertStyle]; + pathComponents[count-1], pathComponents[count-2]]; + alert.alertStyle = NSWarningAlertStyle; - [alert beginSheetModalForWindow:[self window] completionHandler:nil]; + [alert beginSheetModalForWindow:self.window completionHandler:nil]; return; } //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++) + for (NSUInteger i = 0; i < fTrackers.count; i++) { trackerInfo[i].announce = (char *)[fTrackers[i] UTF8String]; trackerInfo[i].tier = i; @@ -521,15 +521,15 @@ NSMutableSet *creatorWindowControllerSet = nil; //store values [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 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"]; - [[self window] setRestorable: NO]; + 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]; @@ -548,71 +548,68 @@ NSMutableSet *creatorWindowControllerSet = nil; case TR_MAKEMETA_OK: if (fOpenWhenCreated) { - NSDictionary * dict = [[NSDictionary alloc] initWithObjects: @[ - [fLocation path], - [[fPath URLByDeletingLastPathComponent] path]] - forKeys: @[@"File", @"Path"]]; - [[NSNotificationCenter defaultCenter] postNotificationName: @"OpenCreatedTorrentFile" object: self userInfo: dict]; + NSDictionary * dict = @{@"File": fLocation.path, @"Path": fPath.URLByDeletingLastPathComponent.path}; + [NSNotificationCenter.defaultCenter postNotificationName: @"OpenCreatedTorrentFile" object: self userInfo: dict]; } - [[self window] close]; + [self.window close]; break; case TR_MAKEMETA_CANCELLED: - [[self window] close]; + [self.window close]; break; default: alert = [[NSAlert alloc] init]; [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> failed -> button")]; - [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Creation of \"%@\" failed.", - "Create torrent -> failed -> title"), [fLocation lastPathComponent]]]; - [alert setAlertStyle: NSWarningAlertStyle]; + 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 setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"Could not read \"%s\": %s.", - "Create torrent -> failed -> warning"), fInfo->errfile, strerror(fInfo->my_errno)]]; + 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 setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"Could not write \"%s\": %s.", - "Create torrent -> failed -> warning"), fInfo->errfile, strerror(fInfo->my_errno)]]; + 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 setInformativeText: [NSString stringWithFormat: @"%@ (%d)", - NSLocalizedString(@"An unknown error has occurred.", "Create torrent -> failed -> warning"), fInfo->result]]; + 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]; + [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { + [alert.window orderOut: nil]; + [self.window close]; }]; } } else { - [fProgressIndicator setDoubleValue: (double)fInfo->pieceIndex / fInfo->pieceCount]; + fProgressIndicator.doubleValue = (double)fInfo->pieceIndex / fInfo->pieceCount; if (!fStarted) { fStarted = YES; - [fProgressView setHidden: YES]; + fProgressView.hidden = YES; - NSWindow * window = [self window]; - [window setFrameAutosaveName: @""]; + NSWindow * window = self.window; + window.frameAutosaveName = @""; - NSRect windowRect = [window frame]; - CGFloat difference = [fProgressView frame].size.height - [[window contentView] frame].size.height; + NSRect windowRect = window.frame; + CGFloat difference = fProgressView.frame.size.height - window.contentView.frame.size.height; windowRect.origin.y -= difference; windowRect.size.height += difference; //don't allow vertical resizing CGFloat height = windowRect.size.height; - [window setMinSize: NSMakeSize([window minSize].width, height)]; - [window setMaxSize: NSMakeSize([window maxSize].width, height)]; + window.minSize = NSMakeSize(window.minSize.width, height); + window.maxSize = NSMakeSize(window.maxSize.width, height); - [window setContentView: fProgressView]; + window.contentView = fProgressView; [window setFrame: windowRect display: YES animate: YES]; - [fProgressView setHidden: NO]; + fProgressView.hidden = NO; - [[window standardWindowButton: NSWindowCloseButton] setEnabled: NO]; + [window standardWindowButton: NSWindowCloseButton].enabled = NO; } } } diff --git a/macosx/DragOverlayView.m b/macosx/DragOverlayView.m index 8e9e44aa2..123d1386c 100644 --- a/macosx/DragOverlayView.m +++ b/macosx/DragOverlayView.m @@ -27,30 +27,26 @@ @implementation DragOverlayView -- (id) initWithFrame: (NSRect) frame +- (instancetype) initWithFrame: (NSRect) frame { if ((self = [super initWithFrame: frame])) { //create attributes NSShadow * stringShadow = [[NSShadow alloc] init]; - [stringShadow setShadowOffset: NSMakeSize(2.0, -2.0)]; - [stringShadow setShadowBlurRadius: 4.0]; + stringShadow.shadowOffset = NSMakeSize(2.0, -2.0); + stringShadow.shadowBlurRadius = 4.0; NSFont * bigFont = [NSFont boldSystemFontOfSize: 18.0], * smallFont = [NSFont systemFontOfSize: 14.0]; - NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; - [paragraphStyle setLineBreakMode: NSLineBreakByTruncatingMiddle]; + NSMutableParagraphStyle * paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + paragraphStyle.lineBreakMode = NSLineBreakByTruncatingMiddle; - fMainLineAttributes = [[NSDictionary alloc] initWithObjects: @[[NSColor whiteColor], - bigFont, stringShadow, paragraphStyle] - forKeys: @[NSForegroundColorAttributeName, NSFontAttributeName, - NSShadowAttributeName, NSParagraphStyleAttributeName]]; + fMainLineAttributes = @{NSForegroundColorAttributeName: NSColor.whiteColor, NSFontAttributeName: bigFont, + NSShadowAttributeName: stringShadow, NSParagraphStyleAttributeName: paragraphStyle}; - fSubLineAttributes = [[NSDictionary alloc] initWithObjects: @[[NSColor whiteColor], - smallFont, stringShadow, paragraphStyle] - forKeys: @[NSForegroundColorAttributeName, NSFontAttributeName, - NSShadowAttributeName, NSParagraphStyleAttributeName]]; + fSubLineAttributes = @{NSForegroundColorAttributeName: NSColor.whiteColor, NSFontAttributeName: smallFont, + NSShadowAttributeName: stringShadow, NSParagraphStyleAttributeName: paragraphStyle}; } return self; @@ -90,15 +86,15 @@ [fBadge unlockFocus]; - [self setNeedsDisplay: YES]; + self.needsDisplay = YES; } -(void) drawRect: (NSRect) rect { if (fBadge) { - const NSRect frame = [self frame]; - const NSSize imageSize = [fBadge size]; + 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]; } } diff --git a/macosx/DragOverlayWindow.h b/macosx/DragOverlayWindow.h index 1636e180d..923997591 100644 --- a/macosx/DragOverlayWindow.h +++ b/macosx/DragOverlayWindow.h @@ -31,7 +31,7 @@ NSViewAnimation * fFadeInAnimation, * fFadeOutAnimation; } -- (id) initWithLib: (tr_session *) lib forWindow: (NSWindow *) window; +- (instancetype) initWithLib: (tr_session *) lib forWindow: (NSWindow *) window; - (void) setTorrents: (NSArray *) files; - (void) setFile: (NSString *) file; diff --git a/macosx/DragOverlayWindow.m b/macosx/DragOverlayWindow.m index 987aa027c..cb128ce02 100644 --- a/macosx/DragOverlayWindow.m +++ b/macosx/DragOverlayWindow.m @@ -32,41 +32,41 @@ @implementation DragOverlayWindow -- (id) initWithLib: (tr_session *) lib forWindow: (NSWindow *) window +- (instancetype) initWithLib: (tr_session *) lib forWindow: (NSWindow *) window { - if ((self = ([super initWithContentRect: [window frame] styleMask: NSBorderlessWindowMask + if ((self = ([super initWithContentRect: window.frame styleMask: NSBorderlessWindowMask backing: NSBackingStoreBuffered defer: NO]))) { fLib = lib; - [self setBackgroundColor: [NSColor colorWithCalibratedWhite: 0.0 alpha: 0.5]]; - [self setAlphaValue: 0.0]; - [self setOpaque: NO]; - [self setHasShadow: NO]; + 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]]; - [self setContentView: view]; + DragOverlayView * view = [[DragOverlayView alloc] initWithFrame: self.frame]; + self.contentView = view; - [self setReleasedWhenClosed: NO]; - [self setIgnoresMouseEvents: YES]; + self.releasedWhenClosed = NO; + self.ignoresMouseEvents = YES; fFadeInAnimation = [[NSViewAnimation alloc] initWithViewAnimations: @[ @{NSViewAnimationTargetKey: self, NSViewAnimationEffectKey: NSViewAnimationFadeInEffect} ]]; - [fFadeInAnimation setDuration: 0.15]; - [fFadeInAnimation setAnimationBlockingMode: NSAnimationNonblockingThreaded]; + fFadeInAnimation.duration = 0.15; + fFadeInAnimation.animationBlockingMode = NSAnimationNonblockingThreaded; fFadeOutAnimation = [[NSViewAnimation alloc] initWithViewAnimations: @[ @{NSViewAnimationTargetKey: self, NSViewAnimationEffectKey: NSViewAnimationFadeOutEffect} ]]; - [fFadeOutAnimation setDuration: 0.5]; - [fFadeOutAnimation setAnimationBlockingMode: NSAnimationNonblockingThreaded]; + fFadeOutAnimation.duration = 0.5; + fFadeOutAnimation.animationBlockingMode = NSAnimationNonblockingThreaded; [window addChildWindow: self ordered: NSWindowAbove]; - [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(resizeWindow) + [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(resizeWindow) name: NSWindowDidResizeNotification object: window]; } return self; @@ -74,7 +74,7 @@ - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; } - (void) setTorrents: (NSArray *) files @@ -88,11 +88,11 @@ 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_ctorSetMetainfoFromFile(ctor, [file UTF8String]); + tr_ctorSetMetainfoFromFile(ctor, file.UTF8String); tr_info info; if (tr_torrentParse(ctor, &info) == TR_PARSE_OK) { @@ -130,7 +130,7 @@ 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"), @@ -139,20 +139,20 @@ 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 { - [[self contentView] setOverlay: [NSImage imageNamed: @"CreateLarge"] + [self.contentView setOverlay: [NSImage imageNamed: @"CreateLarge"] mainLine: NSLocalizedString(@"Create a Torrent File", "Drag overlay -> file") subLine: file]; [self fadeIn]; } - (void) setURL: (NSString *) url { - [[self contentView] setOverlay: [NSImage imageNamed: @"Globe"] + [self.contentView setOverlay: [NSImage imageNamed: @"Globe"] mainLine: NSLocalizedString(@"Web Address", "Drag overlay -> url") subLine: url]; [self fadeIn]; } @@ -160,10 +160,10 @@ - (void) fadeIn { //stop other animation and set to same progress - if ([fFadeOutAnimation isAnimating]) + if (fFadeOutAnimation.animating) { [fFadeOutAnimation stopAnimation]; - [fFadeInAnimation setCurrentProgress: 1.0 - [fFadeOutAnimation currentProgress]]; + fFadeInAnimation.currentProgress = 1.0 - fFadeOutAnimation.currentProgress; } [fFadeInAnimation startAnimation]; } @@ -171,12 +171,12 @@ - (void) fadeOut { //stop other animation and set to same progress - if ([fFadeInAnimation isAnimating]) + if (fFadeInAnimation.animating) { [fFadeInAnimation stopAnimation]; - [fFadeOutAnimation setCurrentProgress: 1.0 - [fFadeInAnimation currentProgress]]; + fFadeOutAnimation.currentProgress = 1.0 - fFadeInAnimation.currentProgress; } - if ([self alphaValue] > 0.0) + if (self.alphaValue > 0.0) [fFadeOutAnimation startAnimation]; } @@ -186,7 +186,7 @@ - (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 3dff06aa2..5ba26d553 100644 --- a/macosx/ExpandedPathToIconTransformer.m +++ b/macosx/ExpandedPathToIconTransformer.m @@ -44,14 +44,14 @@ 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 setSize: NSMakeSize(16.0, 16.0)]; + icon.size = NSMakeSize(16.0, 16.0); return icon; } -@end \ No newline at end of file +@end diff --git a/macosx/ExpandedPathToPathTransformer.m b/macosx/ExpandedPathToPathTransformer.m index 6d8baa275..d112c0177 100644 --- a/macosx/ExpandedPathToPathTransformer.m +++ b/macosx/ExpandedPathToPathTransformer.m @@ -36,7 +36,7 @@ - (id) transformedValue: (id) value { - return value == nil ? nil : [[NSFileManager defaultManager] displayNameAtPath: value]; + return value == nil ? nil : [NSFileManager.defaultManager displayNameAtPath: value]; } -@end \ No newline at end of file +@end diff --git a/macosx/FileListNode.h b/macosx/FileListNode.h index f8825718a..79dc757bc 100644 --- a/macosx/FileListNode.h +++ b/macosx/FileListNode.h @@ -26,25 +26,25 @@ @interface FileListNode : NSObject -@property (nonatomic, copy, readonly) NSString * name; -@property (nonatomic, copy, readonly) NSString * path; +@property (nonatomic, readonly) NSString * name; +@property (nonatomic, readonly) NSString * path; @property (nonatomic, weak, readonly) Torrent * torrent; @property (nonatomic, readonly) uint64_t size; -@property (nonatomic, strong, readonly) NSImage * icon; +@property (nonatomic, readonly) NSImage * icon; @property (nonatomic, readonly) BOOL isFolder; -@property (nonatomic, strong, readonly) NSMutableArray * children; +@property (nonatomic, readonly) NSMutableArray * children; -@property (nonatomic, strong, readonly) NSIndexSet * indexes; +@property (nonatomic, readonly) NSIndexSet * indexes; -- (id) initWithFolderName: (NSString *) name path: (NSString *) path torrent: (Torrent *) torrent; -- (id) 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; -- (NSString *) description; +@property (nonatomic, readonly) NSString *description; - (BOOL) updateFromOldName: (NSString *) oldName toNewName: (NSString *) newName inPath: (NSString *) path; diff --git a/macosx/FileListNode.m b/macosx/FileListNode.m index da91f400a..749196f1c 100644 --- a/macosx/FileListNode.m +++ b/macosx/FileListNode.m @@ -24,7 +24,7 @@ @interface FileListNode (Private) -- (id) 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 @@ -35,7 +35,7 @@ NSMutableArray * _children; } -- (id) 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])) { @@ -46,7 +46,7 @@ return self; } -- (id) 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])) { @@ -82,7 +82,7 @@ - (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]; } @@ -90,8 +90,8 @@ - (NSImage *) icon { if (!_icon) - _icon = [[NSWorkspace sharedWorkspace] iconForFileType: _isFolder ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) - : [_name pathExtension]]; + _icon = [NSWorkspace.sharedWorkspace iconForFileType: _isFolder ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) + : _name.pathExtension]; return _icon; } @@ -113,8 +113,8 @@ 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 { @@ -125,7 +125,7 @@ return YES; } } - else if ([lookupPathComponents count] < [thesePathComponents count]) //what's being renamed is part of this node's path + 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) { @@ -137,7 +137,7 @@ 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 +149,7 @@ @implementation FileListNode (Private) -- (id) 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.m b/macosx/FileNameCell.m index b69e71a08..d0b29ff4c 100644 --- a/macosx/FileNameCell.m +++ b/macosx/FileNameCell.m @@ -43,26 +43,26 @@ - (NSRect) rectForTitleWithString: (NSAttributedString *) string inBounds: (NSRect) bounds; - (NSRect) rectForStatusWithString: (NSAttributedString *) string withTitleRect: (NSRect) titleRect inBounds: (NSRect) bounds; -- (NSAttributedString *) attributedTitle; -- (NSAttributedString *) attributedStatus; +@property (nonatomic, readonly) NSAttributedString *attributedTitle; +@property (nonatomic, readonly) NSAttributedString *attributedStatus; @end @implementation FileNameCell -- (id) init +- (instancetype) init { if ((self = [super init])) { - NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; - [paragraphStyle setLineBreakMode: NSLineBreakByTruncatingMiddle]; + NSMutableParagraphStyle * paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + paragraphStyle.lineBreakMode = NSLineBreakByTruncatingMiddle; fTitleAttributes = [[NSMutableDictionary alloc] initWithObjectsAndKeys: [NSFont messageFontOfSize: 12.0], NSFontAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil]; - NSMutableParagraphStyle * statusParagraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; - [statusParagraphStyle setLineBreakMode: NSLineBreakByTruncatingTail]; + NSMutableParagraphStyle * statusParagraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + statusParagraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; fStatusAttributes = [[NSMutableDictionary alloc] initWithObjectsAndKeys: [NSFont messageFontOfSize: 9.0], NSFontAttributeName, @@ -85,8 +85,8 @@ - (NSImage *) image { - FileListNode * node = (FileListNode *)[self objectValue]; - return [node icon]; + FileListNode * node = (FileListNode *)self.objectValue; + return node.icon; } - (NSRect) imageRectForBounds: (NSRect) bounds @@ -95,7 +95,7 @@ result.origin.x += PADDING_HORIZONAL; - const CGFloat IMAGE_SIZE = [(FileListNode *)[self objectValue] isFolder] ? IMAGE_FOLDER_SIZE : IMAGE_ICON_SIZE; + const CGFloat 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); @@ -105,40 +105,41 @@ - (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; - if ([self backgroundStyle] == NSBackgroundStyleDark) - titleColor = statusColor = [NSColor whiteColor]; - else if ([[(FileListNode *)[self objectValue] torrent] checkForFiles: [(FileListNode *)[self objectValue] indexes]] == NSOffState) - titleColor = statusColor = [NSColor disabledControlTextColor]; + FileListNode * node = self.objectValue; + if (self.backgroundStyle == NSBackgroundStyleDark) + titleColor = statusColor = NSColor.whiteColor; + else if ([node.torrent checkForFiles: node.indexes] == NSOffState) + titleColor = statusColor = NSColor.disabledControlTextColor; else { - titleColor = [NSColor controlTextColor]; - statusColor = [NSColor secondaryLabelColor]; + titleColor = NSColor.controlTextColor; + statusColor = NSColor.secondaryLabelColor; } fTitleAttributes[NSForegroundColorAttributeName] = titleColor; fStatusAttributes[NSForegroundColorAttributeName] = statusColor; //title - NSAttributedString * titleString = [self attributedTitle]; + NSAttributedString * titleString = self.attributedTitle; NSRect titleRect = [self rectForTitleWithString: titleString inBounds: cellFrame]; [titleString drawInRect: titleRect]; //status - NSAttributedString * statusString = [self attributedStatus]; + NSAttributedString * statusString = self.attributedStatus; NSRect statusRect = [self rectForStatusWithString: statusString withTitleRect: titleRect inBounds: cellFrame]; [statusString drawInRect: statusRect]; } - (NSRect) expansionFrameWithFrame: (NSRect) cellFrame inView: (NSView *) view { - NSAttributedString * titleString = [self attributedTitle]; + 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 isFlipped])) + && 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); @@ -152,8 +153,8 @@ cellFrame.origin.x += PADDING_EXPANSION_FRAME; cellFrame.origin.y += PADDING_EXPANSION_FRAME; - fTitleAttributes[NSForegroundColorAttributeName] = [NSColor controlTextColor]; - NSAttributedString * titleString = [self attributedTitle]; + fTitleAttributes[NSForegroundColorAttributeName] = NSColor.controlTextColor; + NSAttributedString * titleString = self.attributedTitle; [titleString drawInRect: cellFrame]; } @@ -167,7 +168,7 @@ //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; @@ -189,7 +190,7 @@ const NSSize 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; @@ -208,20 +209,20 @@ - (NSAttributedString *) attributedTitle { - NSString * title = [(FileListNode *)[self objectValue] name]; + NSString * title = ((FileListNode *)self.objectValue).name; return [[NSAttributedString alloc] initWithString: title attributes: fTitleAttributes]; } - (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]; NSString * status = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", - "Inspector -> Files tab -> file status string"), percentString, [NSString stringForFileSize: [node size]]]; + "Inspector -> Files tab -> file status string"), percentString, [NSString stringForFileSize: node.size]]; return [[NSAttributedString alloc] initWithString: status attributes: fStatusAttributes]; } diff --git a/macosx/FileOutlineController.h b/macosx/FileOutlineController.h index f8882b45a..99a6d7c04 100644 --- a/macosx/FileOutlineController.h +++ b/macosx/FileOutlineController.h @@ -35,7 +35,7 @@ NSString * fFilterText; } -- (FileOutlineView *) outlineView; +@property (nonatomic, readonly) FileOutlineView *outlineView; - (void) setTorrent: (Torrent *) torrent; diff --git a/macosx/FileOutlineController.m b/macosx/FileOutlineController.m index 4294b4f46..ed8760595 100644 --- a/macosx/FileOutlineController.m +++ b/macosx/FileOutlineController.m @@ -34,22 +34,20 @@ #define ROW_SMALL_HEIGHT 18.0 -typedef enum -{ +typedef NS_ENUM(unsigned int, fileCheckMenuTag) { FILE_CHECK_TAG, FILE_UNCHECK_TAG -} fileCheckMenuTag; +}; -typedef enum -{ +typedef NS_ENUM(unsigned int, filePriorityMenuTag) { FILE_PRIORITY_HIGH_TAG, FILE_PRIORITY_NORMAL_TAG, FILE_PRIORITY_LOW_TAG -} filePriorityMenuTag; +}; @interface FileOutlineController (Private) -- (NSMenu *) menu; +@property (nonatomic, readonly) NSMenu *menu; - (NSUInteger) findFileNode: (FileListNode *) node inList: (NSArray *) list atIndexes: (NSIndexSet *) range currentParent: (FileListNode *) currentParent finalParent: (FileListNode **) parent; @@ -61,14 +59,14 @@ typedef enum { fFileList = [[NSMutableArray alloc] init]; - [fOutline setDoubleAction: @selector(revealFile:)]; - [fOutline setTarget: self]; + fOutline.doubleAction = @selector(revealFile:); + fOutline.target = self; //set table header tool tips - [[fOutline tableColumnWithIdentifier: @"Check"] setHeaderToolTip: NSLocalizedString(@"Download", "file table -> header tool tip")]; - [[fOutline tableColumnWithIdentifier: @"Priority"] setHeaderToolTip: 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 setMenu: [self menu]]; + fOutline.menu = self.menu; [self setTorrent: nil]; } @@ -83,7 +81,7 @@ typedef enum { fTorrent = torrent; - [fFileList setArray: [fTorrent fileList]]; + [fFileList setArray: fTorrent.fileList]; fFilterText = nil; @@ -93,8 +91,8 @@ typedef enum - (void) setFilterText: (NSString *) text { - NSArray * components = [text betterComponentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; - if (!components || [components count] == 0) + NSArray * components = [text betterComponentsSeparatedByCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; + if (!components || components.count == 0) { text = nil; components = nil; @@ -111,14 +109,14 @@ typedef enum NSMutableDictionary * removedIndexesForParents = nil; //ugly, but we can't modify the actual file nodes - NSArray * tempList = !text ? [fTorrent fileList] : [fTorrent flatFileList]; + 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) + if ([item.name rangeOfString: (NSString *)obj options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound) { filter = YES; *stop = YES; @@ -129,7 +127,7 @@ typedef enum 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; + 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) { @@ -178,9 +176,9 @@ typedef enum } //remove trailing items - those are the unused - if (currentIndex < [fFileList count]) + if (currentIndex < fFileList.count) { - const NSRange removeRange = NSMakeRange(currentIndex, [fFileList count]-currentIndex); + const NSRange removeRange = NSMakeRange(currentIndex, fFileList.count-currentIndex); [fFileList removeObjectsInRange: removeRange]; [fOutline removeItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: removeRange] inParent: nil withAnimation: NSTableViewAnimationSlideDown]; } @@ -198,54 +196,54 @@ typedef enum { [fTorrent updateFileStat]; - [fOutline setNeedsDisplay: YES]; + fOutline.needsDisplay = YES; } - (void) outlineViewSelectionDidChange: (NSNotification *) notification { - if ([QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible]) + if ([QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible) [[QLPreviewPanel sharedPreviewPanel] reloadData]; } - (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item { if (!item) - return fFileList ? [fFileList count] : 0; + return fFileList ? fFileList.count : 0; else { FileListNode * node = (FileListNode *)item; - return [node isFolder] ? [[node children] count] : 0; + return node.isFolder ? node.children.count : 0; } } - (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 { - return (item ? [(FileListNode *)item children] : fFileList)[index]; + return (item ? ((FileListNode *)item).children : fFileList)[index]; } - (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item { - if ([[tableColumn identifier] isEqualToString: @"Check"]) - return @([fTorrent checkForFiles: [(FileListNode *)item indexes]]); + 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]; + NSString * identifier = tableColumn.identifier; if ([identifier isEqualToString: @"Check"]) - [cell setEnabled: [fTorrent canChangeDownloadCheckForFiles: [(FileListNode *)item indexes]]]; + [cell setEnabled: [fTorrent canChangeDownloadCheckForFiles: ((FileListNode *)item).indexes]]; else if ([identifier isEqualToString: @"Priority"]) { [cell setRepresentedObject: item]; - NSInteger hoveredRow = [fOutline hoveredRow]; + NSInteger hoveredRow = fOutline.hoveredRow; [(FilePriorityCell *)cell setHovered: hoveredRow != -1 && hoveredRow == [fOutline rowForItem: item]]; } else; @@ -253,41 +251,43 @@ typedef enum - (void) outlineView: (NSOutlineView *) outlineView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn byItem: (id) item { - NSString * identifier = [tableColumn identifier]; + NSString * identifier = tableColumn.identifier; if ([identifier isEqualToString: @"Check"]) { NSIndexSet * indexSet; - if ([NSEvent modifierFlags] & NSAlternateKeyMask) - indexSet = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTorrent fileCount])]; + if (NSEvent.modifierFlags & NSAlternateKeyMask) + 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]; - [fOutline setNeedsDisplay: YES]; + 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 { - 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 * ident = [tableColumn identifier]; + NSString * ident = tableColumn.identifier; if ([ident isEqualToString: @"Name"]) { NSString * path = [fTorrent fileLocation: item]; - if (!path) - path = [[(FileListNode *)item path] stringByAppendingPathComponent: [(FileListNode *)item name]]; + if (!path) { + FileListNode * node = (FileListNode *)item; + path = [node.path stringByAppendingPathComponent: node.name]; + } return path; } else if ([ident isEqualToString: @"Check"]) { - switch ([cell state]) + switch (cell.state) { case NSOffState: return NSLocalizedString(@"Don't Download", "files tab -> tooltip"); @@ -299,8 +299,8 @@ typedef enum } else if ([ident isEqualToString: @"Priority"]) { - NSSet * priorities = [fTorrent filePrioritiesForIndexes: [(FileListNode *)item indexes]]; - switch ([priorities count]) + NSSet * priorities = [fTorrent filePrioritiesForIndexes: ((FileListNode *)item).indexes]; + switch (priorities.count) { case 0: return NSLocalizedString(@"Priority Not Available", "files tab -> tooltip"); @@ -326,53 +326,59 @@ typedef enum - (CGFloat) outlineView: (NSOutlineView *) outlineView heightOfRowByItem: (id) item { - if ([(FileListNode *)item isFolder]) + if (((FileListNode *)item).isFolder) return ROW_SMALL_HEIGHT; else - return [outlineView rowHeight]; + return outlineView.rowHeight; } - (void) setCheck: (id) sender { NSInteger state = [sender tag] == FILE_UNCHECK_TAG ? NSOffState : NSOnState; - NSIndexSet * indexSet = [fOutline selectedRowIndexes]; + NSIndexSet * indexSet = fOutline.selectedRowIndexes; NSMutableIndexSet * itemIndexes = [NSMutableIndexSet indexSet]; - for (NSInteger i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) - [itemIndexes addIndexes: [[fOutline itemAtRow: i] indexes]]; + for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) + { + FileListNode * item = [fOutline itemAtRow: i]; + [itemIndexes addIndexes: item.indexes]; + } [fTorrent setFileCheckState: state forIndexes: itemIndexes]; - [fOutline setNeedsDisplay: YES]; + fOutline.needsDisplay = YES; } - (void) setOnlySelectedCheck: (id) sender { - NSIndexSet * indexSet = [fOutline selectedRowIndexes]; + NSIndexSet * indexSet = fOutline.selectedRowIndexes; NSMutableIndexSet * itemIndexes = [NSMutableIndexSet indexSet]; - for (NSInteger i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) - [itemIndexes addIndexes: [[fOutline itemAtRow: i] indexes]]; + for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) + { + FileListNode * item = [fOutline itemAtRow: i]; + [itemIndexes addIndexes: item.indexes]; + } [fTorrent setFileCheckState: NSOnState forIndexes: itemIndexes]; - NSMutableIndexSet * remainingItemIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTorrent fileCount])]; + NSMutableIndexSet * remainingItemIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTorrent.fileCount)]; [remainingItemIndexes removeIndexes: itemIndexes]; [fTorrent setFileCheckState: NSOffState forIndexes: remainingItemIndexes]; - [fOutline setNeedsDisplay: YES]; + fOutline.needsDisplay = YES; } - (void) checkAll { - NSIndexSet * indexSet = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTorrent fileCount])]; + NSIndexSet * indexSet = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTorrent.fileCount)]; [fTorrent setFileCheckState: NSOnState forIndexes: indexSet]; - [fOutline setNeedsDisplay: YES]; + fOutline.needsDisplay = YES; } - (void) uncheckAll { - NSIndexSet * indexSet = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTorrent fileCount])]; + NSIndexSet * indexSet = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTorrent.fileCount)]; [fTorrent setFileCheckState: NSOffState forIndexes: indexSet]; - [fOutline setNeedsDisplay: YES]; + fOutline.needsDisplay = YES; } - (void) setPriority: (id) sender @@ -390,53 +396,56 @@ typedef enum priority = TR_PRI_LOW; } - NSIndexSet * indexSet = [fOutline selectedRowIndexes]; + NSIndexSet * indexSet = fOutline.selectedRowIndexes; NSMutableIndexSet * itemIndexes = [NSMutableIndexSet indexSet]; - for (NSInteger i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) - [itemIndexes addIndexes: [[fOutline itemAtRow: i] indexes]]; + for (NSInteger i = indexSet.firstIndex; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) + { + FileListNode * item = [fOutline itemAtRow: i]; + [itemIndexes addIndexes: item.indexes]; + } [fTorrent setFilePriority: priority forIndexes: itemIndexes]; - [fOutline setNeedsDisplay: YES]; + fOutline.needsDisplay = YES; } - (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]]; if (path) [paths addObject: [NSURL fileURLWithPath: path]]; } - if ([paths count] > 0) - [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: paths]; + if (paths.count > 0) + [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs: paths]; } - (void) renameSelected: (id) sender { - NSIndexSet * indexes = [fOutline selectedRowIndexes]; - NSAssert([indexes count] == 1, @"1 file needs to be selected to rename, but %ld are selected", [indexes count]); + 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]; - if (![torrent isFolder]) + 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) { + [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 }]; }]; } } @@ -447,12 +456,12 @@ typedef enum if (!fTorrent) return NO; - SEL action = [menuItem action]; + SEL action = menuItem.action; if (action == @selector(revealFile:)) { - NSIndexSet * indexSet = [fOutline selectedRowIndexes]; - for (NSInteger i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) + 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; @@ -460,43 +469,49 @@ typedef enum if (action == @selector(setCheck:)) { - if ([fOutline numberOfSelectedRows] == 0) + if (fOutline.numberOfSelectedRows == 0) return NO; - NSIndexSet * indexSet = [fOutline selectedRowIndexes]; + NSIndexSet * indexSet = fOutline.selectedRowIndexes; NSMutableIndexSet * itemIndexes = [NSMutableIndexSet indexSet]; - for (NSInteger i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) - [itemIndexes addIndexes: [[fOutline itemAtRow: i] indexes]]; + 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; + NSInteger state = (menuItem.tag == FILE_CHECK_TAG) ? NSOnState : NSOffState; return [fTorrent checkForFiles: itemIndexes] != state && [fTorrent canChangeDownloadCheckForFiles: itemIndexes]; } if (action == @selector(setOnlySelectedCheck:)) { - if ([fOutline numberOfSelectedRows] == 0) + if (fOutline.numberOfSelectedRows == 0) return NO; - NSIndexSet * indexSet = [fOutline selectedRowIndexes]; + NSIndexSet * indexSet = fOutline.selectedRowIndexes; NSMutableIndexSet * itemIndexes = [NSMutableIndexSet indexSet]; - for (NSInteger i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i]) - [itemIndexes addIndexes: [[fOutline itemAtRow: i] indexes]]; + 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:)) { - if ([fOutline numberOfSelectedRows] == 0) + if (fOutline.numberOfSelectedRows == 0) { - [menuItem setState: NSOffState]; + menuItem.state = NSOffState; return NO; } //determine which priorities are checked - NSIndexSet * indexSet = [fOutline selectedRowIndexes]; + NSIndexSet * indexSet = fOutline.selectedRowIndexes; tr_priority_t priority; - switch ([menuItem tag]) + switch (menuItem.tag) { case FILE_PRIORITY_HIGH_TAG: priority = TR_PRI_HIGH; @@ -510,9 +525,10 @@ typedef enum } 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]) { - NSIndexSet * fileIndexSet = [[fOutline itemAtRow: i] indexes]; + FileListNode * node = [fOutline itemAtRow: i]; + NSIndexSet * fileIndexSet = node.indexes; if (![fTorrent canChangeDownloadCheckForFiles: fileIndexSet]) continue; @@ -524,13 +540,13 @@ typedef enum } } - [menuItem setState: current ? NSOnState : NSOffState]; + menuItem.state = current ? NSOnState : NSOffState; return canChange; } if (action == @selector(renameSelected:)) { - return [fOutline numberOfSelectedRows] == 1; + return fOutline.numberOfSelectedRows == 1; } return YES; @@ -547,20 +563,20 @@ typedef enum //check and uncheck NSMenuItem * item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Check Selected", "File Outline -> Menu") action: @selector(setCheck:) keyEquivalent: @""]; - [item setTarget: self]; - [item setTag: FILE_CHECK_TAG]; + item.target = self; + item.tag = FILE_CHECK_TAG; [menu addItem: item]; item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Uncheck Selected", "File Outline -> Menu") action: @selector(setCheck:) keyEquivalent: @""]; - [item setTarget: self]; - [item setTag: FILE_UNCHECK_TAG]; + item.target = self; + item.tag = FILE_UNCHECK_TAG; [menu addItem: item]; //only check selected item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Only Check Selected", "File Outline -> Menu") action: @selector(setOnlySelectedCheck:) keyEquivalent: @""]; - [item setTarget: self]; + item.target = self; [menu addItem: item]; [menu addItem: [NSMenuItem separatorItem]]; @@ -568,28 +584,28 @@ typedef enum //priority item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Priority", "File Outline -> Menu") action: NULL keyEquivalent: @""]; NSMenu * priorityMenu = [[NSMenu alloc] initWithTitle: @"File Priority Menu"]; - [item setSubmenu: priorityMenu]; + item.submenu = priorityMenu; [menu addItem: item]; item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"High", "File Outline -> Priority Menu") action: @selector(setPriority:) keyEquivalent: @""]; - [item setTarget: self]; - [item setTag: FILE_PRIORITY_HIGH_TAG]; - [item setImage: [NSImage imageNamed: @"PriorityHighTemplate"]]; + item.target = self; + item.tag = FILE_PRIORITY_HIGH_TAG; + item.image = [NSImage imageNamed: @"PriorityHighTemplate"]; [priorityMenu addItem: item]; item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Normal", "File Outline -> Priority Menu") action: @selector(setPriority:) keyEquivalent: @""]; - [item setTarget: self]; - [item setTag: FILE_PRIORITY_NORMAL_TAG]; - [item setImage: [NSImage imageNamed: @"PriorityNormalTemplate"]]; + item.target = self; + item.tag = FILE_PRIORITY_NORMAL_TAG; + item.image = [NSImage imageNamed: @"PriorityNormalTemplate"]; [priorityMenu addItem: item]; item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Low", "File Outline -> Priority Menu") action: @selector(setPriority:) keyEquivalent: @""]; - [item setTarget: self]; - [item setTag: FILE_PRIORITY_LOW_TAG]; - [item setImage: [NSImage imageNamed: @"PriorityLowTemplate"]]; + item.target = self; + item.tag = FILE_PRIORITY_LOW_TAG; + item.image = [NSImage imageNamed: @"PriorityLowTemplate"]; [priorityMenu addItem: item]; @@ -598,7 +614,7 @@ typedef enum //reveal in finder item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"Show in Finder", "File Outline -> Menu") action: @selector(revealFile:) keyEquivalent: @""]; - [item setTarget: self]; + item.target = self; [menu addItem: item]; [menu addItem: [NSMenuItem separatorItem]]; @@ -606,22 +622,22 @@ typedef enum //rename item = [[NSMenuItem alloc] initWithTitle: [NSLocalizedString(@"Rename File", "File Outline -> Menu") stringByAppendingEllipsis] action: @selector(renameSelected:) keyEquivalent: @""]; - [item setTarget: self]; + item.target = self; [menu addItem: item]; return menu; } -- (NSUInteger) findFileNode: (FileListNode *) node inList: (NSArray *) list atIndexes: (NSIndexSet *) indexes currentParent: (FileListNode *) currentParent finalParent: (FileListNode **) 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!"); + 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.indexes containsIndex: node.indexes.firstIndex]) { - if (![checkNode isFolder]) + if (!checkNode.isFolder) { NSAssert2([checkNode isEqualTo: node], @"Expected file nodes to be equal: %@ %@", checkNode, node); @@ -630,7 +646,7 @@ typedef enum } else { - const NSUInteger subIndex = [self findFileNode: node inList: [checkNode children] atIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [[checkNode children] count])] currentParent: checkNode finalParent: parent]; + 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; } diff --git a/macosx/FileOutlineView.h b/macosx/FileOutlineView.h index 5ba9c33b6..d3f28d9e8 100644 --- a/macosx/FileOutlineView.h +++ b/macosx/FileOutlineView.h @@ -31,6 +31,6 @@ - (NSRect) iconRectForRow: (int) row; -- (NSInteger) hoveredRow; +@property (nonatomic, readonly) NSInteger hoveredRow; @end diff --git a/macosx/FileOutlineView.m b/macosx/FileOutlineView.m index e225f1849..28bdb0e9c 100644 --- a/macosx/FileOutlineView.m +++ b/macosx/FileOutlineView.m @@ -32,13 +32,13 @@ - (void) awakeFromNib { FileNameCell * nameCell = [[FileNameCell alloc] init]; - [[self tableColumnWithIdentifier: @"Name"] setDataCell: nameCell]; + [self tableColumnWithIdentifier: @"Name"].dataCell = nameCell; FilePriorityCell * priorityCell = [[FilePriorityCell alloc] init]; - [[self tableColumnWithIdentifier: @"Priority"] setDataCell: priorityCell]; + [self tableColumnWithIdentifier: @"Priority"].dataCell = priorityCell; - [self setAutoresizesOutlineColumn: NO]; - [self setIndentationPerLevel: 14.0]; + self.autoresizesOutlineColumn = NO; + self.indentationPerLevel = 14.0; fMouseRow = -1; } @@ -46,13 +46,13 @@ - (void) mouseDown: (NSEvent *) event { - [[self window] makeKeyWindow]; + [self.window makeKeyWindow]; [super mouseDown: event]; } - (NSMenu *) menuForEvent: (NSEvent *) event { - const NSInteger row = [self rowAtPoint: [self convertPoint: [event locationInWindow] fromView: nil]]; + const NSInteger row = [self rowAtPoint: [self convertPoint: event.locationInWindow fromView: nil]]; if (row >= 0) { @@ -62,7 +62,7 @@ else [self deselectAll: self]; - return [self menu]; + return self.menu; } - (NSRect) iconRectForRow: (int) row @@ -70,7 +70,7 @@ 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; } @@ -78,17 +78,17 @@ { [super updateTrackingAreas]; - for (NSTrackingArea * area in [self trackingAreas]) + for (NSTrackingArea * area in self.trackingAreas) { - if ([area owner] == self && [area userInfo][@"Row"]) + if (area.owner == self && area.userInfo[@"Row"]) [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]; + NSPoint mouseLocation = [self convertPoint: self.window.mouseLocationOutsideOfEventStream fromView: nil]; for (NSInteger row = visibleRows.location, col = [self columnWithIdentifier: @"Priority"]; (NSUInteger)row < NSMaxRange(visibleRows); row++) { @@ -108,9 +108,9 @@ - (void) mouseEntered: (NSEvent *) event { NSNumber * row; - if ((row = ((NSDictionary *)[event userData])[@"Row"])) + if ((row = ((NSDictionary *)event.userData)[@"Row"])) { - fMouseRow = [row intValue]; + fMouseRow = row.intValue; [self setNeedsDisplayInRect: [self frameOfCellAtColumn: [self columnWithIdentifier: @"Priority"] row: fMouseRow]]; } } @@ -118,9 +118,9 @@ - (void) mouseExited: (NSEvent *) event { NSNumber * row; - if ((row = ((NSDictionary *)[event userData])[@"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.m b/macosx/FilePriorityCell.m index 1e161bffe..acf5a5966 100644 --- a/macosx/FilePriorityCell.m +++ b/macosx/FilePriorityCell.m @@ -30,15 +30,15 @@ @implementation FilePriorityCell -- (id) init +- (instancetype) init { if ((self = [super init])) { - [self setTrackingMode: NSSegmentSwitchTrackingSelectAny]; - [self setControlSize: NSMiniControlSize]; - [self setSegmentCount: 3]; + self.trackingMode = NSSegmentSwitchTrackingSelectAny; + self.controlSize = NSMiniControlSize; + self.segmentCount = 3; - for (NSInteger i = 0; i < [self segmentCount]; i++) + 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 @@ -56,7 +56,7 @@ - (id) copyWithZone: (NSZone *) zone { id value = [super copyWithZone: zone]; - [value setRepresentedObject: [self representedObject]]; + [value setRepresentedObject: self.representedObject]; return value; } @@ -79,11 +79,12 @@ break; } - Torrent * torrent = [(FileListNode *)[self representedObject] torrent]; - [torrent setFilePriority: priority forIndexes: [(FileListNode *)[self representedObject] indexes]]; + FileListNode * node = self.representedObject; + Torrent * torrent = node.torrent; + [torrent setFilePriority: priority forIndexes: node.indexes]; - FileOutlineView * controlView = (FileOutlineView *)[self controlView]; - [controlView setNeedsDisplay: YES]; + FileOutlineView * controlView = (FileOutlineView *)self.controlView; + controlView.needsDisplay = YES; } - (void) addTrackingAreasForView: (NSView *) controlView inRect: (NSRect) cellFrame withUserInfo: (NSDictionary *) userInfo @@ -91,7 +92,7 @@ { NSTrackingAreaOptions options = NSTrackingEnabledDuringMouseDrag | NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways; - if (NSMouseInRect(mouseLocation, cellFrame, [controlView isFlipped])) + if (NSMouseInRect(mouseLocation, cellFrame, controlView.flipped)) { options |= NSTrackingAssumeInside; [controlView setNeedsDisplayInRect: cellFrame]; @@ -108,11 +109,11 @@ - (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]; + const NSUInteger count = priorities.count; if (fHoverRow && count > 0) { [super setSelected: [priorities containsObject: @(TR_PRI_LOW)] forSegment: 0]; @@ -130,33 +131,33 @@ { //if ([self backgroundStyle] != NSBackgroundStyleDark) { - NSImage * image = [[NSImage imageNamed: @"PriorityNormalTemplate"] imageWithColor: [NSColor lightGrayColor]]; + NSImage * image = [[NSImage imageNamed: @"PriorityNormalTemplate"] imageWithColor: NSColor.lightGrayColor]; [images addObject: image]; - totalWidth = [image size].width; + 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)]) { NSImage * image = [[NSImage imageNamed: @"PriorityLowTemplate"] imageWithColor: priorityColor]; [images addObject: image]; - totalWidth += [image size].width; + totalWidth += image.size.width; } if ([priorities containsObject: @(TR_PRI_NORMAL)]) { NSImage * image = [[NSImage imageNamed: @"PriorityNormalTemplate"] imageWithColor: priorityColor]; [images addObject: image]; - totalWidth += [image size].width; + totalWidth += image.size.width; } if ([priorities containsObject: @(TR_PRI_HIGH)]) { NSImage * image = [[NSImage imageNamed: @"PriorityHighTemplate"] imageWithColor: priorityColor]; [images addObject: image]; - totalWidth += [image size].width; + totalWidth += image.size.width; } } @@ -167,7 +168,7 @@ for (NSImage * image in images) { - const NSSize imageSize = [image size]; + const NSSize imageSize = image.size; const NSRect 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]; diff --git a/macosx/FileRenameSheetController.m b/macosx/FileRenameSheetController.m index 29b2a929f..08dafaa41 100644 --- a/macosx/FileRenameSheetController.m +++ b/macosx/FileRenameSheetController.m @@ -14,8 +14,8 @@ typedef void (^CompletionBlock)(BOOL); @interface FileRenameSheetController () -@property (nonatomic, strong) Torrent * torrent; -@property (nonatomic, strong) FileListNode * node; +@property (nonatomic) Torrent * torrent; +@property (nonatomic) FileListNode * node; @property (nonatomic, copy) CompletionBlock completionHandler; @property (nonatomic, copy) NSString * originalName; @@ -34,7 +34,7 @@ typedef void (^CompletionBlock)(BOOL); 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 @@ -44,11 +44,11 @@ typedef void (^CompletionBlock)(BOOL); FileRenameSheetController * renamer = [[FileRenameSheetController alloc] initWithWindowNibName: @"FileRenameSheetController"]; - renamer.torrent = [node torrent]; + 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 @@ -66,45 +66,45 @@ typedef void (^CompletionBlock)(BOOL); { [super windowDidLoad]; - self.originalName = [self.node name] ?: [self.torrent name]; + self.originalName = self.node.name ?: self.torrent.name; NSString * label = [NSString stringWithFormat: NSLocalizedString(@"Rename the file \"%@\":", "rename sheet label"), self.originalName]; - [self.labelField setStringValue: label]; + self.labelField.stringValue = label; - [self.inputField setStringValue: self.originalName]; - [self.renameButton setEnabled: NO]; + 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]; + const NSRect oldRenameFrame = self.renameButton.frame; + const NSRect 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]); + const CGFloat extra = NSWidth(oldRenameFrame) - NSWidth(self.renameButton.frame); - [self.renameButton setTitle: NSLocalizedString(@"Rename", "rename sheet button")]; - [self.cancelButton setTitle: NSLocalizedString(@"Cancel", "rename sheet button")]; + self.renameButton.title = NSLocalizedString(@"Rename", "rename sheet button"); + self.cancelButton.title = NSLocalizedString(@"Cancel", "rename sheet button"); [self.renameButton sizeToFit]; [self.cancelButton sizeToFit]; - NSRect newRenameFrame = [self.renameButton frame]; - NSRect newCancelFrame = [self.cancelButton frame]; + NSRect newRenameFrame = self.renameButton.frame; + NSRect newCancelFrame = self.cancelButton.frame; 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); newRenameFrame.origin.x -= renameWidthIncrease; - [self.renameButton setFrame:newRenameFrame]; + self.renameButton.frame = newRenameFrame; const CGFloat cancelWidthIncrease = NSWidth(newCancelFrame) - NSWidth(oldCancelFrame); newCancelFrame.origin.x -= renameWidthIncrease + cancelWidthIncrease; - [self.cancelButton setFrame:newCancelFrame]; + self.cancelButton.frame = newCancelFrame; } - (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 @@ -113,19 +113,19 @@ typedef void (^CompletionBlock)(BOOL); }; 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 { - [NSApp endSheet: [self window] returnCode: NSCancelButton]; + [NSApp endSheet: self.window returnCode: NSCancelButton]; } - (void) controlTextDidChange: (NSNotification *) notification { - [self.renameButton setEnabled: ![[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 e2bc232b8..1191a549a 100644 --- a/macosx/FilterBarController.h +++ b/macosx/FilterBarController.h @@ -45,7 +45,7 @@ IBOutlet NSPopUpButton * fGroupsButton; } -- (id) init; +- (instancetype) init; - (void) setFilter: (id) sender; - (void) switchFilter: (BOOL) right; @@ -54,7 +54,7 @@ - (void) setGroupFilter: (id) sender; - (void) reset: (BOOL) updateUI; -- (NSArray *) searchStrings; +@property (nonatomic, readonly) NSArray *searchStrings; - (void) focusSearchField; - (void) setCountAll: (NSUInteger) all active: (NSUInteger) active downloading: (NSUInteger) downloading diff --git a/macosx/FilterBarController.m b/macosx/FilterBarController.m index 7ddac1200..c8a2b869f 100644 --- a/macosx/FilterBarController.m +++ b/macosx/FilterBarController.m @@ -41,7 +41,7 @@ @implementation FilterBarController -- (id) init +- (instancetype) init { return (self = [super initWithNibName: @"FilterBar" bundle: nil]); } @@ -49,30 +49,30 @@ - (void) awakeFromNib { //localizations - [fNoFilterButton setTitle: NSLocalizedString(@"All", "Filter Bar -> filter button")]; - [fActiveFilterButton setTitle: NSLocalizedString(@"Active", "Filter Bar -> filter button")]; - [fDownloadFilterButton setTitle: NSLocalizedString(@"Downloading", "Filter Bar -> filter button")]; - [fSeedFilterButton setTitle: NSLocalizedString(@"Seeding", "Filter Bar -> filter button")]; - [fPauseFilterButton setTitle: NSLocalizedString(@"Paused", "Filter Bar -> filter button")]; + fNoFilterButton.title = NSLocalizedString(@"All", "Filter Bar -> filter button"); + fActiveFilterButton.title = NSLocalizedString(@"Active", "Filter Bar -> filter button"); + fDownloadFilterButton.title = NSLocalizedString(@"Downloading", "Filter Bar -> filter button"); + fSeedFilterButton.title = NSLocalizedString(@"Seeding", "Filter Bar -> filter button"); + fPauseFilterButton.title = NSLocalizedString(@"Paused", "Filter Bar -> filter button"); - [[fNoFilterButton cell] setBackgroundStyle: NSBackgroundStyleRaised]; - [[fActiveFilterButton cell] setBackgroundStyle: NSBackgroundStyleRaised]; - [[fDownloadFilterButton cell] setBackgroundStyle: NSBackgroundStyleRaised]; - [[fSeedFilterButton cell] setBackgroundStyle: NSBackgroundStyleRaised]; - [[fPauseFilterButton cell] setBackgroundStyle: NSBackgroundStyleRaised]; + fNoFilterButton.cell.backgroundStyle = NSBackgroundStyleRaised; + fActiveFilterButton.cell.backgroundStyle = NSBackgroundStyleRaised; + fDownloadFilterButton.cell.backgroundStyle = NSBackgroundStyleRaised; + fSeedFilterButton.cell.backgroundStyle = NSBackgroundStyleRaised; + fPauseFilterButton.cell.backgroundStyle = NSBackgroundStyleRaised; - [[[[fSearchField cell] searchMenuTemplate] itemWithTag: FILTER_TYPE_TAG_NAME] setTitle: - NSLocalizedString(@"Name", "Filter Bar -> filter menu")]; - [[[[fSearchField cell] searchMenuTemplate] itemWithTag: FILTER_TYPE_TAG_TRACKER] setTitle: - 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] setTitle: - 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]) @@ -87,49 +87,49 @@ { //safety if (![filterType isEqualToString: FILTER_NONE]) - [[NSUserDefaults standardUserDefaults] setObject: FILTER_NONE forKey: @"Filter"]; + [NSUserDefaults.standardUserDefaults setObject: FILTER_NONE forKey: @"Filter"]; currentFilterButton = fNoFilterButton; } - [currentFilterButton setState: NSOnState]; + currentFilterButton.state = NSOnState; //set filter search type - NSString * filterSearchType = [[NSUserDefaults standardUserDefaults] stringForKey: @"FilterSearchType"]; + NSString * filterSearchType = [NSUserDefaults.standardUserDefaults stringForKey: @"FilterSearchType"]; - NSMenu * filterSearchMenu = [[fSearchField cell] searchMenuTemplate]; + NSMenu * filterSearchMenu = fSearchField.searchMenuTemplate; NSString * filterSearchTypeTitle; if ([filterSearchType isEqualToString: FILTER_TYPE_TRACKER]) - filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_TRACKER] title]; + 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]; + [NSUserDefaults.standardUserDefaults setObject: FILTER_TYPE_NAME forKey: @"FilterSearchType"]; + filterSearchTypeTitle = [filterSearchMenu itemWithTag: FILTER_TYPE_TAG_NAME].title; } - [[fSearchField cell] setPlaceholderString: filterSearchTypeTitle]; + fSearchField.placeholderString = filterSearchTypeTitle; NSString * searchString; - if ((searchString = [[NSUserDefaults standardUserDefaults] stringForKey: @"FilterSearchString"])) - [fSearchField setStringValue: 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:) + [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateGroups:) name: @"UpdateGroups" object: nil]; } - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; } - (void) setFilter: (id) sender { - NSString * oldFilterType = [[NSUserDefaults standardUserDefaults] stringForKey: @"Filter"]; + NSString * oldFilterType = [NSUserDefaults.standardUserDefaults stringForKey: @"Filter"]; NSButton * prevFilterButton; if ([oldFilterType isEqualToString: FILTER_PAUSE]) @@ -145,7 +145,7 @@ if (sender != prevFilterButton) { - [prevFilterButton setState: NSOffState]; + prevFilterButton.state = NSOffState; [sender setState: NSOnState]; NSString * filterType; @@ -160,17 +160,17 @@ else filterType = FILTER_NONE; - [[NSUserDefaults standardUserDefaults] setObject: filterType forKey: @"Filter"]; + [NSUserDefaults.standardUserDefaults setObject: filterType forKey: @"Filter"]; } else [sender setState: NSOnState]; - [[NSNotificationCenter defaultCenter] postNotificationName: @"ApplyFilter" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName: @"ApplyFilter" object: nil]; } - (void) switchFilter: (BOOL) right { - NSString * filterType = [[NSUserDefaults standardUserDefaults] stringForKey: @"Filter"]; + NSString * filterType = [NSUserDefaults.standardUserDefaults stringForKey: @"Filter"]; NSButton * button; if ([filterType isEqualToString: FILTER_NONE]) @@ -191,18 +191,18 @@ - (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 { - [[[self view] window] makeFirstResponder: fSearchField]; + [self.view.window makeFirstResponder: fSearchField]; } - (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]) @@ -218,25 +218,25 @@ else filterType = FILTER_TYPE_NAME; - [[NSUserDefaults standardUserDefaults] setObject: filterType forKey: @"FilterSearchType"]; + [NSUserDefaults.standardUserDefaults setObject: filterType forKey: @"FilterSearchType"]; - [[fSearchField cell] setPlaceholderString: [sender title]]; + fSearchField.placeholderString = [sender title]; } - [[NSNotificationCenter defaultCenter] postNotificationName: @"ApplyFilter" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName: @"ApplyFilter" object: nil]; } - (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 { - [[NSUserDefaults standardUserDefaults] setInteger: GROUP_FILTER_ALL_TAG forKey: @"FilterGroup"]; + [NSUserDefaults.standardUserDefaults setInteger: GROUP_FILTER_ALL_TAG forKey: @"FilterGroup"]; if (updateUI) { @@ -244,19 +244,19 @@ [self setFilter: fNoFilterButton]; - [fSearchField setStringValue: @""]; + fSearchField.stringValue = @""; [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 { - return [[fSearchField stringValue] betterComponentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; + return [fSearchField.stringValue betterComponentsSeparatedByCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; } - (void) setCountAll: (NSUInteger) all active: (NSUInteger) active downloading: (NSUInteger) downloading @@ -271,14 +271,14 @@ - (void) menuNeedsUpdate: (NSMenu *) menu { - if (menu == [fGroupsButton menu]) + if (menu == fGroupsButton.menu) { - for (NSInteger i = [menu numberOfItems]-1; i >= 3; 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]; + const NSInteger groupMenuCount = groupMenu.numberOfItems; for (NSInteger i = 0; i < groupMenuCount; i++) { NSMenuItem * item = [groupMenu itemAtIndex: 0]; @@ -290,27 +290,27 @@ - (BOOL) validateMenuItem: (NSMenuItem *) menuItem { - const SEL action = [menuItem action]; + const SEL 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) + if (menuItem.tag == FILTER_TYPE_TAG_TRACKER) state = [filterType isEqualToString: FILTER_TYPE_TRACKER]; else state = [filterType isEqualToString: FILTER_TYPE_NAME]; - [menuItem setState: state ? NSOnState : NSOffState]; + menuItem.state = state ? NSOnState : NSOffState; return YES; } if (action == @selector(setGroupFilter:)) { - [menuItem setState: [menuItem tag] == [[NSUserDefaults standardUserDefaults] integerForKey: @"FilterGroup"] - ? NSOnState : NSOffState]; + menuItem.state = menuItem.tag == [NSUserDefaults.standardUserDefaults integerForKey: @"FilterGroup"] + ? NSOnState : NSOffState; return YES; } @@ -330,16 +330,16 @@ [fSeedFilterButton sizeToFit]; [fPauseFilterButton sizeToFit]; - NSRect allRect = [fNoFilterButton frame]; - NSRect activeRect = [fActiveFilterButton frame]; - NSRect downloadRect = [fDownloadFilterButton frame]; - NSRect seedRect = [fSeedFilterButton frame]; - NSRect pauseRect = [fPauseFilterButton frame]; + NSRect allRect = fNoFilterButton.frame; + NSRect activeRect = fActiveFilterButton.frame; + NSRect downloadRect = fDownloadFilterButton.frame; + NSRect seedRect = fSeedFilterButton.frame; + NSRect pauseRect = fPauseFilterButton.frame; //size search filter to not overlap buttons - NSRect searchFrame = [fSearchField frame]; + NSRect searchFrame = fSearchField.frame; searchFrame.origin.x = NSMaxX(pauseRect) + 5.0; - searchFrame.size.width = NSWidth([[self view] frame]) - searchFrame.origin.x - 5.0; + searchFrame.size.width = NSWidth(self.view.frame) - searchFrame.origin.x - 5.0; //make sure it is not too long if (NSWidth(searchFrame) > SEARCH_MAX_WIDTH) @@ -372,18 +372,18 @@ seedRect.origin.x = NSMaxX(downloadRect) + 1.0; pauseRect.origin.x = NSMaxX(seedRect) + 1.0; - [fNoFilterButton setFrame: allRect]; - [fActiveFilterButton setFrame: activeRect]; - [fDownloadFilterButton setFrame: downloadRect]; - [fSeedFilterButton setFrame: seedRect]; - [fPauseFilterButton setFrame: pauseRect]; + fNoFilterButton.frame = allRect; + fActiveFilterButton.frame = activeRect; + fDownloadFilterButton.frame = downloadRect; + fSeedFilterButton.frame = seedRect; + fPauseFilterButton.frame = pauseRect; - [fSearchField setFrame: searchFrame]; + fSearchField.frame = searchFrame; } - (void) updateGroupsButton { - const NSInteger groupIndex = [[NSUserDefaults standardUserDefaults] integerForKey: @"FilterGroup"]; + const NSInteger groupIndex = [NSUserDefaults.standardUserDefaults integerForKey: @"FilterGroup"]; NSImage * icon; NSString * toolTip; @@ -394,14 +394,14 @@ } else { - icon = [[GroupsController groups] imageForIndex: groupIndex]; - NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex] + 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] setImage: icon]; - [fGroupsButton setToolTip: toolTip]; + [fGroupsButton.menu itemAtIndex: 0].image = icon; + fGroupsButton.toolTip = toolTip; } - (void) updateGroups: (NSNotification *) notification diff --git a/macosx/FilterBarView.m b/macosx/FilterBarView.m index 6d6aca727..886f77e9c 100644 --- a/macosx/FilterBarView.m +++ b/macosx/FilterBarView.m @@ -37,13 +37,13 @@ - (void) drawRect: (NSRect) rect { - [[NSColor windowBackgroundColor] setFill]; + [NSColor.windowBackgroundColor setFill]; NSRectFill(rect); const NSRect lineBorderRect = NSMakeRect(NSMinX(rect), 0.0, NSWidth(rect), 1.0); if (NSIntersectsRect(lineBorderRect, rect)) { - [[NSColor gridColor] setFill]; + [NSColor.gridColor setFill]; NSRectFill(lineBorderRect); } } diff --git a/macosx/FilterButton.m b/macosx/FilterButton.m index 1a0c6e5a3..cb967d6b8 100644 --- a/macosx/FilterButton.m +++ b/macosx/FilterButton.m @@ -25,7 +25,7 @@ @implementation FilterButton -- (id) initWithCoder: (NSCoder *) coder +- (instancetype) initWithCoder: (NSCoder *) coder { if ((self = [super initWithCoder: coder])) { @@ -41,9 +41,9 @@ fCount = count; - [self setToolTip: fCount == 1 ? NSLocalizedString(@"1 transfer", "Filter Button -> tool tip") + self.toolTip = fCount == 1 ? NSLocalizedString(@"1 transfer", "Filter Button -> tool tip") : [NSString stringWithFormat: NSLocalizedString(@"%@ transfers", "Filter Bar Button -> tool tip"), - [NSString formattedUInteger: fCount]]]; + [NSString formattedUInteger: fCount]]; } @end diff --git a/macosx/GlobalOptionsPopoverViewController.h b/macosx/GlobalOptionsPopoverViewController.h index 70979201c..a9aac3a89 100644 --- a/macosx/GlobalOptionsPopoverViewController.h +++ b/macosx/GlobalOptionsPopoverViewController.h @@ -36,7 +36,7 @@ NSString * fInitialString; } -- (id) initWithHandle: (tr_session *) handle; +- (instancetype) initWithHandle: (tr_session *) handle; - (IBAction) updatedDisplayString: (id) sender; diff --git a/macosx/GlobalOptionsPopoverViewController.m b/macosx/GlobalOptionsPopoverViewController.m index 769927567..86e422798 100644 --- a/macosx/GlobalOptionsPopoverViewController.m +++ b/macosx/GlobalOptionsPopoverViewController.m @@ -24,13 +24,13 @@ @implementation GlobalOptionsPopoverViewController -- (id) initWithHandle: (tr_session *) handle +- (instancetype) initWithHandle: (tr_session *) handle { if ((self = [super initWithNibName: @"GlobalOptionsPopover" bundle: nil])) { fHandle = handle; - fDefaults = [NSUserDefaults standardUserDefaults]; + fDefaults = NSUserDefaults.standardUserDefaults; } return self; @@ -38,25 +38,25 @@ - (void) awakeFromNib { - [fUploadLimitField setIntValue: [fDefaults integerForKey: @"UploadLimit"]]; - [fDownloadLimitField setIntValue: [fDefaults integerForKey: @"DownloadLimit"]]; + fUploadLimitField.intValue = [fDefaults integerForKey: @"UploadLimit"]; + fDownloadLimitField.intValue = [fDefaults integerForKey: @"DownloadLimit"]; - [fRatioStopField setFloatValue: [fDefaults floatForKey: @"RatioLimit"]]; - [fIdleStopField setIntegerValue: [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 { - [[NSNotificationCenter defaultCenter] postNotificationName: @"RefreshTorrentTable" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName: @"RefreshTorrentTable" object: nil]; } - (IBAction) setDownSpeedSetting: (id) sender { tr_sessionLimitSpeed(fHandle, TR_DOWN, [fDefaults boolForKey: @"CheckDownload"]); - [[NSNotificationCenter defaultCenter] postNotificationName: @"SpeedLimitUpdate" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName: @"SpeedLimitUpdate" object: nil]; } - (IBAction) setDownSpeedLimit: (id) sender @@ -65,16 +65,16 @@ [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 { 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 @@ -83,7 +83,7 @@ [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 @@ -91,10 +91,10 @@ 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 @@ -103,13 +103,13 @@ [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 @@ -117,10 +117,10 @@ 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 @@ -129,18 +129,18 @@ [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 { - fInitialString = [control stringValue]; + fInitialString = control.stringValue; return YES; } @@ -150,7 +150,7 @@ NSBeep(); if (fInitialString) { - [control setStringValue: fInitialString]; + control.stringValue = fInitialString; fInitialString = nil; } return NO; diff --git a/macosx/GroupToolbarItem.m b/macosx/GroupToolbarItem.m index df8f8f76c..65aefce7e 100644 --- a/macosx/GroupToolbarItem.m +++ b/macosx/GroupToolbarItem.m @@ -32,42 +32,42 @@ - (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: + for (NSInteger i = 0; i < control.segmentCount; i++) + [control setEnabled: [self.target validateToolbarItem: [[NSToolbarItem alloc] initWithItemIdentifier: fIdentifiers[i]]] forSegment: i]; } - (void) createMenu: (NSArray *) labels { - NSMenuItem * menuItem = [[NSMenuItem alloc] initWithTitle: [self label] action: NULL keyEquivalent: @""]; - NSMenu * menu = [[NSMenu alloc] initWithTitle: [self label]]; - [menuItem setSubmenu: menu]; + NSMenuItem * menuItem = [[NSMenuItem alloc] initWithTitle: self.label action: NULL keyEquivalent: @""]; + NSMenu * menu = [[NSMenu alloc] initWithTitle: self.label]; + menuItem.submenu = menu; - [menu setAutoenablesItems: NO]; + menu.autoenablesItems = NO; - const NSInteger count = [(NSSegmentedControl *)[self view] segmentCount]; + const NSInteger count = ((NSSegmentedControl *)self.view).segmentCount; for (NSInteger i = 0; i < count; i++) { - NSMenuItem * addItem = [[NSMenuItem alloc] initWithTitle: labels[i] action: [self action] keyEquivalent: @""]; - [addItem setTarget: [self target]]; - [addItem setTag: i]; + NSMenuItem * addItem = [[NSMenuItem alloc] initWithTitle: labels[i] action: self.action keyEquivalent: @""]; + addItem.target = self.target; + addItem.tag = i; [menu addItem: addItem]; } - [self setMenuFormRepresentation: menuItem]; + self.menuFormRepresentation = menuItem; } - (NSMenuItem *) menuFormRepresentation { - NSMenuItem * menuItem = [super menuFormRepresentation]; + NSMenuItem * menuItem = super.menuFormRepresentation; - const NSInteger count = [(NSSegmentedControl *)[self view] segmentCount]; + const NSInteger count = ((NSSegmentedControl *)self.view).segmentCount; for (NSInteger i = 0; i < count; i++) - [[[menuItem submenu] itemAtIndex: i] setEnabled: [[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 37f97b0af..1766b1ece 100644 --- a/macosx/GroupsController.h +++ b/macosx/GroupsController.h @@ -29,9 +29,9 @@ NSMutableArray * fGroups; } -+ (GroupsController *) groups; +@property (nonatomic, class, readonly) GroupsController * groups; -- (NSInteger) numberOfGroups; +@property (nonatomic, readonly) NSInteger numberOfGroups; - (NSInteger) rowValueForIndex: (NSInteger) index; - (NSInteger) indexForRow: (NSInteger) row; diff --git a/macosx/GroupsController.m b/macosx/GroupsController.m index cf7785adf..856cc468f 100644 --- a/macosx/GroupsController.m +++ b/macosx/GroupsController.m @@ -46,54 +46,54 @@ GroupsController * fGroupsInstance = nil; return fGroupsInstance; } -- (id) init +- (instancetype) init { if ((self = [super init])) { NSData * data; - if ((data = [[NSUserDefaults standardUserDefaults] dataForKey: @"GroupDicts"])) + if ((data = [NSUserDefaults.standardUserDefaults dataForKey: @"GroupDicts"])) fGroups = [NSKeyedUnarchiver unarchiveObjectWithData: data]; - else if ((data = [[NSUserDefaults standardUserDefaults] dataForKey: @"Groups"])) //handle old groups + else if ((data = [NSUserDefaults.standardUserDefaults dataForKey: @"Groups"])) //handle old groups { fGroups = [NSUnarchiver unarchiveObjectWithData: data]; - [[NSUserDefaults standardUserDefaults] removeObjectForKey: @"Groups"]; + [NSUserDefaults.standardUserDefaults removeObjectForKey: @"Groups"]; [self saveGroups]; } else { //default groups NSMutableDictionary * red = [NSMutableDictionary dictionaryWithObjectsAndKeys: - [NSColor redColor], @"Color", + NSColor.redColor, @"Color", NSLocalizedString(@"Red", "Groups -> Name"), @"Name", @0, @"Index", nil]; NSMutableDictionary * orange = [NSMutableDictionary dictionaryWithObjectsAndKeys: - [NSColor orangeColor], @"Color", + NSColor.orangeColor, @"Color", NSLocalizedString(@"Orange", "Groups -> Name"), @"Name", @1, @"Index", nil]; NSMutableDictionary * yellow = [NSMutableDictionary dictionaryWithObjectsAndKeys: - [NSColor yellowColor], @"Color", + NSColor.yellowColor, @"Color", NSLocalizedString(@"Yellow", "Groups -> Name"), @"Name", @2, @"Index", nil]; NSMutableDictionary * green = [NSMutableDictionary dictionaryWithObjectsAndKeys: - [NSColor greenColor], @"Color", + NSColor.greenColor, @"Color", NSLocalizedString(@"Green", "Groups -> Name"), @"Name", @3, @"Index", nil]; NSMutableDictionary * blue = [NSMutableDictionary dictionaryWithObjectsAndKeys: - [NSColor blueColor], @"Color", + NSColor.blueColor, @"Color", NSLocalizedString(@"Blue", "Groups -> Name"), @"Name", @4, @"Index", nil]; NSMutableDictionary * purple = [NSMutableDictionary dictionaryWithObjectsAndKeys: - [NSColor purpleColor], @"Color", + NSColor.purpleColor, @"Color", NSLocalizedString(@"Purple", "Groups -> Name"), @"Name", @5, @"Index", nil]; NSMutableDictionary * gray = [NSMutableDictionary dictionaryWithObjectsAndKeys: - [NSColor grayColor], @"Color", + NSColor.grayColor, @"Color", NSLocalizedString(@"Gray", "Groups -> Name"), @"Name", @6, @"Index", nil]; @@ -108,14 +108,14 @@ GroupsController * fGroupsInstance = nil; - (NSInteger) numberOfGroups { - return [fGroups count]; + return fGroups.count; } - (NSInteger) rowValueForIndex: (NSInteger) index { if (index != -1) { - for (NSUInteger i = 0; i < [fGroups count]; i++) + for (NSUInteger i = 0; i < fGroups.count; i++) if (index == [fGroups[i][@"Index"] integerValue]) return i; } @@ -139,7 +139,7 @@ GroupsController * fGroupsInstance = nil; fGroups[orderIndex][@"Name"] = name; [self saveGroups]; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateGroups" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGroups" object: self]; } - (NSImage *) imageForIndex: (NSInteger) index @@ -162,8 +162,8 @@ GroupsController * fGroupsInstance = nil; dict[@"Color"] = color; - [[GroupsController groups] saveGroups]; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateGroups" object: self]; + [GroupsController.groups saveGroups]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGroups" object: self]; } - (BOOL) usesCustomDownloadLocationForIndex: (NSInteger) index @@ -181,7 +181,7 @@ GroupsController * fGroupsInstance = nil; dict[@"UsesCustomDownloadLocation"] = @(useCustomLocation); - [[GroupsController groups] saveGroups]; + [GroupsController.groups saveGroups]; } - (NSString *) customDownloadLocationForIndex: (NSInteger) index @@ -195,7 +195,7 @@ GroupsController * fGroupsInstance = nil; NSMutableDictionary * dict = fGroups[[self rowValueForIndex: index]]; dict[@"CustomDownloadLocation"] = location; - [[GroupsController groups] saveGroups]; + [GroupsController.groups saveGroups]; } - (BOOL) usesAutoAssignRulesForIndex: (NSInteger) index @@ -205,7 +205,7 @@ GroupsController * fGroupsInstance = nil; return NO; NSNumber * assignRules = fGroups[orderIndex][@"UsesAutoGroupRules"]; - return assignRules && [assignRules boolValue]; + return assignRules && assignRules.boolValue; } - (void) setUsesAutoAssignRules: (BOOL) useAutoAssignRules forIndex: (NSInteger) index @@ -214,7 +214,7 @@ GroupsController * fGroupsInstance = nil; dict[@"UsesAutoGroupRules"] = @(useAutoAssignRules); - [[GroupsController groups] saveGroups]; + [GroupsController.groups saveGroups]; } - (NSPredicate *) autoAssignRulesForIndex: (NSInteger) index @@ -233,7 +233,7 @@ GroupsController * fGroupsInstance = nil; if (predicate) { dict[@"AutoGroupRules"] = predicate; - [[GroupsController groups] saveGroups]; + [GroupsController.groups saveGroups]; } else { @@ -245,16 +245,16 @@ GroupsController * fGroupsInstance = nil; - (void) addNewGroup { //find the lowest index - NSMutableIndexSet * candidates = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fGroups count]+1)]; + NSMutableIndexSet * candidates = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fGroups.count+1)]; for (NSDictionary * dict in fGroups) [candidates removeIndex: [dict[@"Index"] integerValue]]; - const NSInteger index = [candidates firstIndex]; + const NSInteger 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]]; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateGroups" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateGroups" object: self]; [self saveGroups]; } @@ -263,13 +263,13 @@ GroupsController * fGroupsInstance = nil; NSInteger index = [fGroups[row][@"Index"] integerValue]; [fGroups removeObjectAtIndex: row]; - [[NSNotificationCenter defaultCenter] postNotificationName: @"GroupValueRemoved" object: self userInfo: + [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]; } @@ -278,7 +278,7 @@ GroupsController * fGroupsInstance = nil; [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 @@ -287,39 +287,39 @@ GroupsController * fGroupsInstance = nil; NSMenuItem * item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"None", "Groups -> Menu") action: action keyEquivalent: @""]; - [item setTarget: target]; - [item setTag: -1]; + item.target = target; + item.tag = -1; NSImage * icon = [NSImage imageNamed: @"GroupsNoneTemplate"]; if (small) { icon = [icon copy]; - [icon setSize: NSMakeSize(ICON_WIDTH_SMALL, ICON_WIDTH_SMALL)]; + icon.size = NSMakeSize(ICON_WIDTH_SMALL, ICON_WIDTH_SMALL); - [item setImage: icon]; + item.image = icon; } else - [item setImage: icon]; + item.image = icon; [menu addItem: item]; for (NSMutableDictionary * dict in fGroups) { item = [[NSMenuItem alloc] initWithTitle: dict[@"Name"] action: action keyEquivalent: @""]; - [item setTarget: target]; + item.target = target; - [item setTag: [dict[@"Index"] integerValue]]; + item.tag = [dict[@"Index"] integerValue]; NSImage * icon = [self imageForGroup: dict]; if (small) { icon = [icon copy]; - [icon setSize: NSMakeSize(ICON_WIDTH_SMALL, ICON_WIDTH_SMALL)]; + icon.size = NSMakeSize(ICON_WIDTH_SMALL, ICON_WIDTH_SMALL); - [item setImage: icon]; + item.image = icon; } else - [item setImage: icon]; + item.image = icon; [menu addItem: item]; } @@ -345,7 +345,7 @@ GroupsController * fGroupsInstance = nil; - (void) saveGroups { //don't archive the icon - NSMutableArray * groups = [NSMutableArray arrayWithCapacity: [fGroups count]]; + NSMutableArray * groups = [NSMutableArray arrayWithCapacity: fGroups.count]; for (NSDictionary * dict in fGroups) { NSMutableDictionary * tempDict = [dict mutableCopy]; @@ -353,7 +353,7 @@ GroupsController * fGroupsInstance = nil; [groups addObject: tempDict]; } - [[NSUserDefaults standardUserDefaults] setObject: [NSKeyedArchiver archivedDataWithRootObject: groups] forKey: @"GroupDicts"]; + [NSUserDefaults.standardUserDefaults setObject: [NSKeyedArchiver archivedDataWithRootObject: groups] forKey: @"GroupDicts"]; } - (NSImage *) imageForGroup: (NSMutableDictionary *) dict @@ -373,13 +373,13 @@ GroupsController * fGroupsInstance = nil; //border NSGradient * gradient = [[NSGradient alloc] initWithStartingColor: [color blendedColorWithFraction: 0.45 ofColor: - [NSColor whiteColor]] endingColor: color]; + 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 = [[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]; diff --git a/macosx/GroupsPrefsController.m b/macosx/GroupsPrefsController.m index f48b188ba..1e8ac1a02 100644 --- a/macosx/GroupsPrefsController.m +++ b/macosx/GroupsPrefsController.m @@ -33,7 +33,7 @@ @interface GroupsPrefsController () -@property (nonatomic, strong) IBOutlet NSWindow * groupRulesSheetWindow; +@property (nonatomic) IBOutlet NSWindow * groupRulesSheetWindow; @property (nonatomic, weak) IBOutlet NSPredicateEditor * ruleEditor; @property (nonatomic, weak) IBOutlet NSLayoutConstraint * ruleEditorHeightConstraint; @@ -63,15 +63,15 @@ - (NSInteger) numberOfRowsInTableView: (NSTableView *) tableview { - return [[GroupsController groups] numberOfGroups]; + return GroupsController.groups.numberOfGroups; } - (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row { - GroupsController * groupsController = [GroupsController groups]; + GroupsController * groupsController = GroupsController.groups; NSInteger groupsIndex = [groupsController indexForRow: row]; - NSString * identifier = [tableColumn identifier]; + NSString * identifier = tableColumn.identifier; if ([identifier isEqualToString: @"Color"]) return [groupsController imageForIndex: groupsIndex]; else @@ -85,21 +85,21 @@ - (void) observeValueForKeyPath: (NSString *) keyPath ofObject: (id) object change: (NSDictionary *) change context: (void *) context { - if (object == fSelectedColorView && [fTableView numberOfSelectedRows] == 1) + if (object == fSelectedColorView && fTableView.numberOfSelectedRows == 1) { - NSInteger index = [[GroupsController groups] indexForRow: [fTableView selectedRow]]; - [[GroupsController groups] setColor: [fSelectedColorView color] forIndex: index]; - [fTableView setNeedsDisplay: YES]; + NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; + [GroupsController.groups setColor: fSelectedColorView.color forIndex: index]; + fTableView.needsDisplay = YES; } } - (void) controlTextDidEndEditing: (NSNotification *) notification { - if ([notification object] == fSelectedColorNameField) + if (notification.object == fSelectedColorNameField) { - NSInteger index = [[GroupsController groups] indexForRow: [fTableView selectedRow]]; - [[GroupsController groups] setName: [fSelectedColorNameField stringValue] forIndex: index]; - [fTableView setNeedsDisplay: YES]; + NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; + [GroupsController.groups setName: fSelectedColorNameField.stringValue forIndex: index]; + fTableView.needsDisplay = YES; } } @@ -113,8 +113,8 @@ - (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]; return NSDragOperationGeneric; @@ -126,18 +126,18 @@ - (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]]; - NSInteger oldRow = [indexes firstIndex]; + 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 endUpdates]; @@ -148,8 +148,8 @@ - (void) addRemoveGroup: (id) sender { - if ([NSColorPanel sharedColorPanelExists]) - [[NSColorPanel sharedColorPanel] close]; + if (NSColorPanel.sharedColorPanelExists) + [NSColorPanel.sharedColorPanel close]; NSInteger row; @@ -158,9 +158,9 @@ 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]; @@ -168,24 +168,24 @@ [fTableView selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; [fTableView scrollRowToVisible: row]; - [[fSelectedColorNameField window] makeFirstResponder: fSelectedColorNameField]; + [fSelectedColorNameField.window makeFirstResponder: fSelectedColorNameField]; break; case REMOVE_TAG: - row = [fTableView selectedRow]; + row = fTableView.selectedRow; [fTableView beginUpdates]; - [[GroupsController groups] removeGroupWithRowIndex: row]; + [GroupsController.groups removeGroupWithRowIndex: row]; [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]; @@ -201,24 +201,24 @@ { NSOpenPanel * panel = [NSOpenPanel openPanel]; - [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")]; - [panel setAllowsMultipleSelection: NO]; - [panel setCanChooseFiles: NO]; - [panel setCanChooseDirectories: YES]; - [panel setCanCreateDirectories: YES]; + panel.prompt = NSLocalizedString(@"Select", "Preferences -> Open panel prompt"); + panel.allowsMultipleSelection = NO; + panel.canChooseFiles = NO; + 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) { + const NSInteger 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]; @@ -229,18 +229,18 @@ - (IBAction) toggleUseCustomDownloadLocation: (id) sender { - NSInteger index = [[GroupsController groups] indexForRow: [fTableView selectedRow]]; - if ([fCustomLocationEnableCheck state] == NSOnState) + 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]; } else - [[GroupsController groups] setUsesCustomDownloadLocation: NO forIndex: index]; + [GroupsController.groups setUsesCustomDownloadLocation: NO forIndex: index]; - [fCustomLocationPopUp setEnabled: ([fCustomLocationEnableCheck state] == NSOnState)]; + fCustomLocationPopUp.enabled = (fCustomLocationEnableCheck.state == NSOnState); } #pragma mark - @@ -248,30 +248,30 @@ - (IBAction) toggleUseAutoAssignRules: (id) sender { - NSInteger index = [[GroupsController groups] indexForRow: [fTableView selectedRow]]; - if ([fAutoAssignRulesEnableCheck state] == NSOnState) + 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]; } else - [[GroupsController groups] setUsesAutoAssignRules: NO forIndex: index]; + [GroupsController.groups setUsesAutoAssignRules: NO forIndex: index]; - [fAutoAssignRulesEditButton setEnabled: [fAutoAssignRulesEnableCheck state] == NSOnState]; + fAutoAssignRulesEditButton.enabled = fAutoAssignRulesEnableCheck.state == NSOnState; } - (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]; - [self.ruleEditor setObjectValue: predicate]; + NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; + NSPredicate *predicate = [GroupsController.groups autoAssignRulesForIndex: index]; + self.ruleEditor.objectValue = predicate; - if ([self.ruleEditor numberOfRows] == 0) + if (self.ruleEditor.numberOfRows == 0) [self.ruleEditor addRow: nil]; [fTableView.window beginSheet:self.groupRulesSheetWindow completionHandler:nil]; @@ -282,12 +282,12 @@ [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]; - [fAutoAssignRulesEnableCheck setState: NO]; - [fAutoAssignRulesEditButton setEnabled: NO]; + [GroupsController.groups setUsesAutoAssignRules: NO forIndex: index]; + fAutoAssignRulesEnableCheck.state = NO; + fAutoAssignRulesEditButton.enabled = NO; } } @@ -296,28 +296,28 @@ [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 setState: [[GroupsController groups] usesAutoAssignRulesForIndex: index]]; - [fAutoAssignRulesEditButton setEnabled: [fAutoAssignRulesEnableCheck state] == NSOnState]; + fAutoAssignRulesEnableCheck.state = [GroupsController.groups usesAutoAssignRulesForIndex: index]; + fAutoAssignRulesEditButton.enabled = fAutoAssignRulesEnableCheck.state == NSOnState; } - (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; + const CGFloat rowHeight = self.ruleEditor.rowHeight; + const CGFloat 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); + const CGFloat requiredRowCount = self.ruleEditor.numberOfRows; + const CGFloat maxVisibleRowCount = (long)((NSHeight(self.ruleEditor.window.screen.visibleFrame) * 2 / 3) / rowHeight); - [self.ruleEditorHeightConstraint setConstant: MIN(requiredRowCount, maxVisibleRowCount) * rowHeight + bordersHeight]; - [ruleEditorScrollView setHasVerticalScroller: requiredRowCount > maxVisibleRowCount]; + self.ruleEditorHeightConstraint.constant = MIN(requiredRowCount, maxVisibleRowCount) * rowHeight + bordersHeight; + ruleEditorScrollView.hasVerticalScroller = requiredRowCount > maxVisibleRowCount; } @end @@ -326,55 +326,55 @@ - (void) updateSelectedGroup { - [fAddRemoveControl setEnabled: [fTableView numberOfSelectedRows] > 0 forSegment: REMOVE_TAG]; - if ([fTableView numberOfSelectedRows] == 1) + [fAddRemoveControl setEnabled: fTableView.numberOfSelectedRows > 0 forSegment: REMOVE_TAG]; + if (fTableView.numberOfSelectedRows == 1) { - const NSInteger index = [[GroupsController groups] indexForRow: [fTableView selectedRow]]; - [fSelectedColorView setColor: [[GroupsController groups] colorForIndex: index]]; - [fSelectedColorView setEnabled: YES]; - [fSelectedColorNameField setStringValue: [[GroupsController groups] nameForIndex: index]]; - [fSelectedColorNameField setEnabled: YES]; + const NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; + fSelectedColorView.color = [GroupsController.groups colorForIndex: index]; + fSelectedColorView.enabled = YES; + fSelectedColorNameField.stringValue = [GroupsController.groups nameForIndex: index]; + fSelectedColorNameField.enabled = YES; [self refreshCustomLocationWithSingleGroup]; - [fAutoAssignRulesEnableCheck setState: [[GroupsController groups] usesAutoAssignRulesForIndex: index]]; - [fAutoAssignRulesEnableCheck setEnabled: YES]; - [fAutoAssignRulesEditButton setEnabled: ([fAutoAssignRulesEnableCheck state] == NSOnState)]; + fAutoAssignRulesEnableCheck.state = [GroupsController.groups usesAutoAssignRulesForIndex: index]; + fAutoAssignRulesEnableCheck.enabled = YES; + fAutoAssignRulesEditButton.enabled = (fAutoAssignRulesEnableCheck.state == NSOnState); } else { - [fSelectedColorView setColor: [NSColor whiteColor]]; - [fSelectedColorView setEnabled: NO]; - [fSelectedColorNameField setStringValue: @""]; - [fSelectedColorNameField setEnabled: NO]; - [fCustomLocationEnableCheck setEnabled: NO]; - [fCustomLocationPopUp setEnabled: NO]; - [fAutoAssignRulesEnableCheck setEnabled: NO]; - [fAutoAssignRulesEditButton setEnabled: NO]; + fSelectedColorView.color = NSColor.whiteColor; + fSelectedColorView.enabled = NO; + fSelectedColorNameField.stringValue = @""; + fSelectedColorNameField.enabled = NO; + fCustomLocationEnableCheck.enabled = NO; + fCustomLocationPopUp.enabled = NO; + fAutoAssignRulesEnableCheck.enabled = NO; + fAutoAssignRulesEditButton.enabled = NO; } } - (void) refreshCustomLocationWithSingleGroup { - const NSInteger index = [[GroupsController groups] indexForRow: [fTableView selectedRow]]; + const NSInteger index = [GroupsController.groups indexForRow: fTableView.selectedRow]; - const BOOL hasCustomLocation = [[GroupsController groups] usesCustomDownloadLocationForIndex: index]; - [fCustomLocationEnableCheck setState: hasCustomLocation]; - [fCustomLocationEnableCheck setEnabled: YES]; - [fCustomLocationPopUp setEnabled: hasCustomLocation]; + const BOOL 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] setTitle: [pathTransformer transformedValue: location]]; + [fCustomLocationPopUp itemAtIndex: 0].title = [pathTransformer transformedValue: location]; ExpandedPathToIconTransformer * iconTransformer = [[ExpandedPathToIconTransformer alloc] init]; - [[fCustomLocationPopUp itemAtIndex: 0] setImage: [iconTransformer transformedValue: location]]; + [fCustomLocationPopUp itemAtIndex: 0].image = [iconTransformer transformedValue: location]; } else { - [[fCustomLocationPopUp itemAtIndex: 0] setTitle: @""]; - [[fCustomLocationPopUp itemAtIndex: 0] setImage: nil]; + [fCustomLocationPopUp itemAtIndex: 0].title = @""; + [fCustomLocationPopUp itemAtIndex: 0].image = nil; } } diff --git a/macosx/InfoActivityViewController.m b/macosx/InfoActivityViewController.m index 3fbcc12eb..21ef9579f 100644 --- a/macosx/InfoActivityViewController.m +++ b/macosx/InfoActivityViewController.m @@ -40,11 +40,11 @@ @implementation InfoActivityViewController -- (id) init +- (instancetype) init { if ((self = [super initWithNibName: @"InfoActivityView" bundle: nil])) { - [self setTitle: NSLocalizedString(@"Activity", "Inspector view -> title")]; + self.title = NSLocalizedString(@"Activity", "Inspector view -> title"); } return self; @@ -61,7 +61,7 @@ CGFloat oldMaxWidth = 0.0, originX, newMaxWidth = 0.0; for (NSTextField * label in labels) { - const NSRect oldFrame = [label frame]; + const NSRect oldFrame = label.frame; if (oldFrame.size.width > oldMaxWidth) { oldMaxWidth = oldFrame.size.width; @@ -69,37 +69,37 @@ } [label sizeToFit]; - const CGFloat newWidth = [label bounds].size.width; + const CGFloat newWidth = label.bounds.size.width; if (newWidth > newMaxWidth) newMaxWidth = newWidth; } for (NSTextField * label in labels) { - NSRect frame = [label frame]; + NSRect frame = label.frame; frame.origin.x = originX + (newMaxWidth - frame.size.width); - [label setFrame: frame]; + label.frame = frame; } 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) { - NSRect frame = [field frame]; + NSRect frame = field.frame; frame.origin.x += widthIncrease; frame.size.width -= widthIncrease; - [field setFrame: frame]; + field.frame = frame; } //set the click action of the pieces view #warning after 2.8 just hook this up in the xib - [fPiecesView setAction:@selector(updatePiecesView:)]; - [fPiecesView setTarget:self]; + fPiecesView.action = @selector(updatePiecesView:); + fPiecesView.target = self; } - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; } - (void) setInfoForTorrents: (NSArray *) torrents @@ -115,7 +115,7 @@ if (!fSet) [self setupInfo]; - const NSInteger numberSelected = [fTorrents count]; + const NSInteger numberSelected = fTorrents.count; if (numberSelected == 0) return; @@ -123,61 +123,61 @@ NSDate * lastActivity = nil; for (Torrent * torrent in fTorrents) { - have += [torrent haveTotal]; - haveVerified += [torrent haveVerified]; - downloadedTotal += [torrent downloadedTotal]; - uploadedTotal += [torrent uploadedTotal]; - failedHash += [torrent failedHash]; + have += torrent.haveTotal; + haveVerified += torrent.haveVerified; + downloadedTotal += torrent.downloadedTotal; + uploadedTotal += torrent.uploadedTotal; + failedHash += torrent.failedHash; NSDate * nextLastActivity; - if ((nextLastActivity = [torrent dateActivity])) + if ((nextLastActivity = torrent.dateActivity)) lastActivity = lastActivity ? [lastActivity laterDate: nextLastActivity] : nextLastActivity; } if (have == 0) - [fHaveField setStringValue: [NSString stringForFileSize: 0]]; + fHaveField.stringValue = [NSString stringForFileSize: 0]; else { NSString * verifiedString = [NSString stringWithFormat: NSLocalizedString(@"%@ verified", "Inspector -> Activity tab -> have"), [NSString stringForFileSize: haveVerified]]; if (have == haveVerified) - [fHaveField setStringValue: verifiedString]; + fHaveField.stringValue = verifiedString; else - [fHaveField setStringValue: [NSString stringWithFormat: @"%@ (%@)", [NSString stringForFileSize: have], verifiedString]]; + fHaveField.stringValue = [NSString stringWithFormat: @"%@ (%@)", [NSString stringForFileSize: have], verifiedString]; } - [fDownloadedTotalField setStringValue: [NSString stringForFileSize: downloadedTotal]]; - [fUploadedTotalField setStringValue: [NSString stringForFileSize: uploadedTotal]]; - [fFailedHashField setStringValue: [NSString stringForFileSize: failedHash]]; + fDownloadedTotalField.stringValue = [NSString stringForFileSize: downloadedTotal]; + fUploadedTotalField.stringValue = [NSString stringForFileSize: uploadedTotal]; + fFailedHashField.stringValue = [NSString stringForFileSize: failedHash]; - [fDateActivityField setObjectValue: lastActivity]; + fDateActivityField.objectValue = lastActivity; if (numberSelected == 1) { Torrent * torrent = fTorrents[0]; - [fStateField setStringValue: [torrent stateString]]; + fStateField.stringValue = torrent.stateString; - NSString * progressString = [NSString percentString: [torrent progress] longDecimals: YES]; - if ([torrent isFolder]) + 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]]; + [NSString percentString: torrent.progressDone longDecimals: YES]]; progressString = [progressString stringByAppendingFormat: @" (%@)", progressSelectedString]; } - [fProgressField setStringValue: progressString]; + fProgressField.stringValue = progressString; - [fRatioField setStringValue: [NSString stringForRatio: [torrent ratio]]]; + fRatioField.stringValue = [NSString stringForRatio: torrent.ratio]; - NSString * errorMessage = [torrent errorMessage]; - if (![errorMessage isEqualToString: [fErrorMessageView string]]) - [fErrorMessageView setString: errorMessage]; + NSString * errorMessage = torrent.errorMessage; + if (![errorMessage isEqualToString: fErrorMessageView.string]) + fErrorMessageView.string = errorMessage; - [fDateCompletedField setObjectValue: [torrent dateCompleted]]; + fDateCompletedField.objectValue = torrent.dateCompleted; //uses a relative date, so can't be set once - [fDateAddedField setObjectValue: [torrent dateAdded]]; + fDateAddedField.objectValue = torrent.dateAdded; static NSDateComponentsFormatter *timeFormatter; static dispatch_once_t onceToken; @@ -188,14 +188,14 @@ timeFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropLeading; }); - [fDownloadTimeField setStringValue: [timeFormatter stringFromTimeInterval:[torrent secondsDownloading]]]; - [fSeedTimeField setStringValue: [timeFormatter stringFromTimeInterval:[torrent secondsSeeding]]]; + fDownloadTimeField.stringValue = [timeFormatter stringFromTimeInterval:torrent.secondsDownloading]; + fSeedTimeField.stringValue = [timeFormatter stringFromTimeInterval:torrent.secondsSeeding]; [fPiecesView updateView]; } else if (numberSelected > 1) { - [fRatioField setStringValue: [NSString stringForRatio: tr_getRatio(uploadedTotal, downloadedTotal)]]; + fRatioField.stringValue = [NSString stringForRatio: tr_getRatio(uploadedTotal, downloadedTotal)]; } else; } @@ -203,14 +203,14 @@ - (void) setPiecesView: (id) sender { const BOOL availability = [sender selectedSegment] == PIECES_CONTROL_AVAILABLE; - [[NSUserDefaults standardUserDefaults] setBool: availability forKey: @"PiecesViewShowAvailability"]; + [NSUserDefaults.standardUserDefaults setBool: availability forKey: @"PiecesViewShowAvailability"]; [self updatePiecesView:nil]; } - (void) updatePiecesView: (id) sender { - const BOOL piecesAvailableSegment = [[NSUserDefaults standardUserDefaults] boolForKey: @"PiecesViewShowAvailability"]; + const BOOL piecesAvailableSegment = [NSUserDefaults.standardUserDefaults boolForKey: @"PiecesViewShowAvailability"]; [fPiecesControl setSelected: piecesAvailableSegment forSegment: PIECES_CONTROL_AVAILABLE]; [fPiecesControl setSelected: !piecesAvailableSegment forSegment: PIECES_CONTROL_PROGRESS]; @@ -229,44 +229,44 @@ - (void) setupInfo { - const NSUInteger count = [fTorrents count]; + const NSUInteger count = fTorrents.count; if (count != 1) { if (count == 0) { - [fHaveField setStringValue: @""]; - [fDownloadedTotalField setStringValue: @""]; - [fUploadedTotalField setStringValue: @""]; - [fFailedHashField setStringValue: @""]; - [fDateActivityField setObjectValue: @""]; //using [field setStringValue: @""] causes "December 31, 1969 7:00 PM" to be displayed, at least on 10.7.3 - [fRatioField setStringValue: @""]; + fHaveField.stringValue = @""; + fDownloadedTotalField.stringValue = @""; + fUploadedTotalField.stringValue = @""; + fFailedHashField.stringValue = @""; + fDateActivityField.objectValue = @""; //using [field setStringValue: @""] causes "December 31, 1969 7:00 PM" to be displayed, at least on 10.7.3 + fRatioField.stringValue = @""; } - [fStateField setStringValue: @""]; - [fProgressField setStringValue: @""]; + fStateField.stringValue = @""; + fProgressField.stringValue = @""; - [fErrorMessageView setString: @""]; + fErrorMessageView.string = @""; //using [field setStringValue: @""] causes "December 31, 1969 7:00 PM" to be displayed, at least on 10.7.3 - [fDateAddedField setObjectValue: @""]; - [fDateCompletedField setObjectValue: @""]; + fDateAddedField.objectValue = @""; + fDateCompletedField.objectValue = @""; - [fDownloadTimeField setStringValue: @""]; - [fSeedTimeField setStringValue: @""]; + fDownloadTimeField.stringValue = @""; + fSeedTimeField.stringValue = @""; [fPiecesControl setSelected: NO forSegment: PIECES_CONTROL_AVAILABLE]; [fPiecesControl setSelected: NO forSegment: PIECES_CONTROL_PROGRESS]; - [fPiecesControl setEnabled: NO]; + fPiecesControl.enabled = NO; [fPiecesView setTorrent: nil]; } else { Torrent * torrent = fTorrents[0]; - const BOOL piecesAvailableSegment = [[NSUserDefaults standardUserDefaults] boolForKey: @"PiecesViewShowAvailability"]; + const BOOL piecesAvailableSegment = [NSUserDefaults.standardUserDefaults boolForKey: @"PiecesViewShowAvailability"]; [fPiecesControl setSelected: piecesAvailableSegment forSegment: PIECES_CONTROL_AVAILABLE]; [fPiecesControl setSelected: !piecesAvailableSegment forSegment: PIECES_CONTROL_PROGRESS]; - [fPiecesControl setEnabled: YES]; + fPiecesControl.enabled = YES; [fPiecesView setTorrent: torrent]; } diff --git a/macosx/InfoFileViewController.h b/macosx/InfoFileViewController.h index 3e313fcd8..68cb4ff7a 100644 --- a/macosx/InfoFileViewController.h +++ b/macosx/InfoFileViewController.h @@ -48,8 +48,8 @@ - (IBAction) checkAll: (id) sender; - (IBAction) uncheckAll: (id) sender; -- (NSArray *) quickLookURLs; -- (BOOL) canQuickLook; +@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 bffdd34c3..86642ff3f 100644 --- a/macosx/InfoFileViewController.m +++ b/macosx/InfoFileViewController.m @@ -36,11 +36,11 @@ @implementation InfoFileViewController -- (id) init +- (instancetype) init { if ((self = [super initWithNibName: @"InfoFileView" bundle: nil])) { - [self setTitle: NSLocalizedString(@"Files", "Inspector view -> title")]; + self.title = NSLocalizedString(@"Files", "Inspector view -> title"); } return self; @@ -48,38 +48,38 @@ - (void) awakeFromNib { - const CGFloat height = [[NSUserDefaults standardUserDefaults] floatForKey: @"InspectorContentHeightFiles"]; + const CGFloat height = [NSUserDefaults.standardUserDefaults floatForKey: @"InspectorContentHeightFiles"]; if (height != 0.0) { - NSRect viewRect = [[self view] frame]; + NSRect viewRect = self.view.frame; viewRect.size.height = height; - [[self view] setFrame: viewRect]; + 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 setTitle: NSLocalizedString(@"All", "inspector -> check all")]; - [fUncheckAllButton setTitle: NSLocalizedString(@"None", "inspector -> check all")]; + fCheckAllButton.title = NSLocalizedString(@"All", "inspector -> check all"); + fUncheckAllButton.title = NSLocalizedString(@"None", "inspector -> check all"); - NSRect checkAllFrame = [fCheckAllButton frame]; - NSRect uncheckAllFrame = [fUncheckAllButton frame]; + NSRect checkAllFrame = fCheckAllButton.frame; + NSRect uncheckAllFrame = fUncheckAllButton.frame; const CGFloat oldAllWidth = checkAllFrame.size.width; const CGFloat oldNoneWidth = uncheckAllFrame.size.width; [fCheckAllButton sizeToFit]; [fUncheckAllButton sizeToFit]; - const CGFloat newWidth = MAX([fCheckAllButton bounds].size.width, [fUncheckAllButton bounds].size.width); + const CGFloat newWidth = MAX(fCheckAllButton.bounds.size.width, fUncheckAllButton.bounds.size.width); const CGFloat uncheckAllChange = newWidth - oldNoneWidth; uncheckAllFrame.size.width = newWidth; uncheckAllFrame.origin.x -= uncheckAllChange; - [fUncheckAllButton setFrame: uncheckAllFrame]; + fUncheckAllButton.frame = uncheckAllFrame; const CGFloat checkAllChange = newWidth - oldAllWidth; checkAllFrame.size.width = newWidth; checkAllFrame.origin.x -= (checkAllChange + uncheckAllChange); - [fCheckAllButton setFrame: checkAllFrame]; + fCheckAllButton.frame = checkAllFrame; } @@ -96,24 +96,24 @@ if (!fSet) [self setupInfo]; - if ([fTorrents count] == 1) + if (fTorrents.count == 1) { [fFileController refresh]; #warning use TorrentFileCheckChange notification as well Torrent * torrent = fTorrents[0]; - if ([torrent isFolder]) + if (torrent.folder) { - const NSInteger filesCheckState = [torrent checkForFiles: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [torrent fileCount])]]; - [fCheckAllButton setEnabled: filesCheckState != NSOnState]; //if anything is unchecked - [fUncheckAllButton setEnabled: ![torrent allDownloaded]]; //if there are any checked files that aren't finished + const NSInteger 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 { - [[NSUserDefaults standardUserDefaults] setFloat: NSHeight([[self view] frame]) forKey: @"InspectorContentHeightFiles"]; + [NSUserDefaults.standardUserDefaults setFloat: NSHeight(self.view.frame) forKey: @"InspectorContentHeightFiles"]; } - (void) setFileFilterText: (id) sender @@ -133,12 +133,12 @@ - (NSArray *) quickLookURLs { - FileOutlineView * fileOutlineView = [fFileController outlineView]; + FileOutlineView * fileOutlineView = fFileController.outlineView; Torrent * torrent = fTorrents[0]; - NSIndexSet * indexes = [fileOutlineView selectedRowIndexes]; - NSMutableArray * urlArray = [NSMutableArray arrayWithCapacity: [indexes count]]; + 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]) @@ -150,17 +150,17 @@ - (BOOL) canQuickLook { - if ([fTorrents count] != 1) + if (fTorrents.count != 1) return NO; Torrent * torrent = fTorrents[0]; - if (![torrent isFolder]) + 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]) + for (NSUInteger i = indexes.firstIndex; i != NSNotFound; i = [indexes indexGreaterThanIndex: i]) if ([self canQuickLookFile: [fileOutlineView itemAtRow: i]]) return YES; @@ -169,11 +169,11 @@ - (NSRect) quickLookSourceFrameForPreviewItem: (id ) item { - FileOutlineView * fileOutlineView = [fFileController outlineView]; + FileOutlineView * fileOutlineView = fFileController.outlineView; - NSString * fullPath = [(NSURL *)item path]; + NSString * fullPath = ((NSURL *)item).path; Torrent * torrent = fTorrents[0]; - NSRange visibleRows = [fileOutlineView rowsInRect: [fileOutlineView bounds]]; + NSRange visibleRows = [fileOutlineView rowsInRect: fileOutlineView.bounds]; for (NSUInteger row = visibleRows.location; row < NSMaxRange(visibleRows); row++) { @@ -182,11 +182,11 @@ { NSRect frame = [fileOutlineView iconRectForRow: row]; - if (!NSIntersectsRect([fileOutlineView visibleRect], frame)) + if (!NSIntersectsRect(fileOutlineView.visibleRect, frame)) return NSZeroRect; frame.origin = [fileOutlineView convertPoint: frame.origin toView: nil]; - frame = [[[self view] window] convertRectToScreen: frame]; + frame = [self.view.window convertRectToScreen: frame]; frame.origin.y -= frame.size.height; return frame; } @@ -201,31 +201,31 @@ - (void) setupInfo { - [fFileFilterField setStringValue: @""]; + fFileFilterField.stringValue = @""; - if ([fTorrents count] == 1) + if (fTorrents.count == 1) { Torrent * torrent = fTorrents[0]; [fFileController setTorrent: torrent]; - const BOOL isFolder = [torrent isFolder]; - [fFileFilterField setEnabled: isFolder]; + const BOOL isFolder = torrent.folder; + fFileFilterField.enabled = isFolder; if (!isFolder) { - [fCheckAllButton setEnabled: NO]; - [fUncheckAllButton setEnabled: NO]; + fCheckAllButton.enabled = NO; + fUncheckAllButton.enabled = NO; } } else { [fFileController setTorrent: nil]; - [fFileFilterField setEnabled: NO]; + fFileFilterField.enabled = NO; - [fCheckAllButton setEnabled: NO]; - [fUncheckAllButton setEnabled: NO]; + fCheckAllButton.enabled = NO; + fUncheckAllButton.enabled = NO; } fSet = YES; @@ -234,7 +234,7 @@ - (BOOL) canQuickLookFile: (FileListNode *) item { Torrent * torrent = fTorrents[0]; - return ([item isFolder] || [torrent fileProgress: item] >= 1.0) && [torrent fileLocation: item]; + return (item.isFolder || [torrent fileProgress: item] >= 1.0) && [torrent fileLocation: item]; } @end diff --git a/macosx/InfoGeneralViewController.m b/macosx/InfoGeneralViewController.m index 8e63a5a9a..26f081faa 100644 --- a/macosx/InfoGeneralViewController.m +++ b/macosx/InfoGeneralViewController.m @@ -32,11 +32,11 @@ @implementation InfoGeneralViewController -- (id) init +- (instancetype) init { if ((self = [super initWithNibName: @"InfoGeneralView" bundle: nil])) { - [self setTitle: NSLocalizedString(@"General Info", "Inspector view -> title")]; + self.title = NSLocalizedString(@"General Info", "Inspector view -> title"); } return self; @@ -54,7 +54,7 @@ CGFloat oldMaxWidth = 0.0, originX, newMaxWidth = 0.0; for (NSTextField * label in labels) { - const NSRect oldFrame = [label frame]; + const NSRect oldFrame = label.frame; if (oldFrame.size.width > oldMaxWidth) { oldMaxWidth = oldFrame.size.width; @@ -62,26 +62,26 @@ } [label sizeToFit]; - const CGFloat newWidth = [label bounds].size.width; + const CGFloat newWidth = label.bounds.size.width; if (newWidth > newMaxWidth) newMaxWidth = newWidth; } for (NSTextField * label in labels) { - NSRect frame = [label frame]; + NSRect frame = label.frame; frame.origin.x = originX + (newMaxWidth - frame.size.width); - [label setFrame: frame]; + label.frame = frame; } NSArray * fields = @[ fPiecesField, fHashField, fSecureField, fCreatorField, fDateCreatedField, fCommentScrollView, fDataLocationField ]; const CGFloat widthIncrease = newMaxWidth - oldMaxWidth; for (NSView * field in fields) { - NSRect frame = [field frame]; + NSRect frame = field.frame; frame.origin.x += widthIncrease; frame.size.width -= widthIncrease; - [field setFrame: frame]; + field.frame = frame; } } @@ -98,27 +98,27 @@ if (!fSet) [self setupInfo]; - if ([fTorrents count] != 1) + if (fTorrents.count != 1) return; Torrent * torrent = fTorrents[0]; - NSString * location = [torrent dataLocation]; - [fDataLocationField setStringValue: location ? [location stringByAbbreviatingWithTildeInPath] : @""]; - [fDataLocationField setToolTip: location ? location : @""]; + NSString * location = torrent.dataLocation; + fDataLocationField.stringValue = location ? location.stringByAbbreviatingWithTildeInPath : @""; + fDataLocationField.toolTip = location ? location : @""; - [fRevealDataButton setHidden: !location]; + fRevealDataButton.hidden = !location; } - (void) revealDataFile: (id) sender { Torrent * torrent = fTorrents[0]; - NSString * location = [torrent dataLocation]; + NSString * location = torrent.dataLocation; if (!location) return; NSURL * file = [NSURL fileURLWithPath: location]; - [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: @[file]]; + [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs: @[file]]; } @end @@ -127,44 +127,44 @@ - (void) setupInfo { - if ([fTorrents count] == 1) + if (fTorrents.count == 1) { Torrent * torrent = fTorrents[0]; #warning candidate for localizedStringWithFormat (although then we'll get two commas) - NSString * piecesString = ![torrent isMagnet] ? [NSString stringWithFormat: @"%ld, %@", [torrent pieceCount], - [NSString stringForFileSize: [torrent pieceSize]]] : @""; - [fPiecesField setStringValue: piecesString]; + NSString * piecesString = !torrent.magnet ? [NSString stringWithFormat: @"%ld, %@", torrent.pieceCount, + [NSString stringForFileSize: torrent.pieceSize]] : @""; + fPiecesField.stringValue = piecesString; - NSString * hashString = [torrent hashString]; - [fHashField setStringValue: hashString]; - [fHashField setToolTip: hashString]; - [fSecureField setStringValue: [torrent privateTorrent] + 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")]; + : NSLocalizedString(@"Public Torrent", "Inspector -> private torrent"); - NSString * commentString = [torrent comment]; - [fCommentView setString: commentString]; + NSString * commentString = torrent.comment; + fCommentView.string = commentString; - NSString * creatorString = [torrent creator]; - [fCreatorField setStringValue: creatorString]; - [fDateCreatedField setObjectValue: [torrent dateCreated]]; + NSString * creatorString = torrent.creator; + fCreatorField.stringValue = creatorString; + fDateCreatedField.objectValue = torrent.dateCreated; } else { - [fPiecesField setStringValue: @""]; - [fHashField setStringValue: @""]; - [fHashField setToolTip: nil]; - [fSecureField setStringValue: @""]; - [fCommentView setString: @""]; + fPiecesField.stringValue = @""; + fHashField.stringValue = @""; + fHashField.toolTip = nil; + fSecureField.stringValue = @""; + fCommentView.string = @""; - [fCreatorField setStringValue: @""]; - [fDateCreatedField setStringValue: @""]; + fCreatorField.stringValue = @""; + fDateCreatedField.stringValue = @""; - [fDataLocationField setStringValue: @""]; - [fDataLocationField setToolTip: nil]; + fDataLocationField.stringValue = @""; + fDataLocationField.toolTip = nil; - [fRevealDataButton setHidden: YES]; + fRevealDataButton.hidden = YES; } fSet = YES; diff --git a/macosx/InfoOptionsViewController.m b/macosx/InfoOptionsViewController.m index 85af3fc5b..efba95fb9 100644 --- a/macosx/InfoOptionsViewController.m +++ b/macosx/InfoOptionsViewController.m @@ -44,11 +44,11 @@ @implementation InfoOptionsViewController -- (id) init +- (instancetype) init { if ((self = [super initWithNibName: @"InfoOptionsView" bundle: nil])) { - [self setTitle: NSLocalizedString(@"Options", "Inspector view -> title")]; + self.title = NSLocalizedString(@"Options", "Inspector view -> title"); } return self; @@ -58,13 +58,13 @@ { [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 { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; } - (void) setInfoForTorrents: (NSArray *) torrents @@ -85,7 +85,7 @@ - (void) updateOptions { - if ([fTorrents count] == 0) + if (fTorrents.count == 0) return; //get bandwidth info @@ -96,7 +96,7 @@ uploadSpeedLimit = [torrent speedLimit: YES], downloadUseSpeedLimit = [torrent usesSpeedLimit: NO] ? NSOnState : NSOffState, downloadSpeedLimit = [torrent speedLimit: NO], - globalUseSpeedLimit = [torrent usesGlobalSpeedLimit] ? NSOnState : NSOffState; + globalUseSpeedLimit = torrent.usesGlobalSpeedLimit ? NSOnState : NSOffState; while ((torrent = [enumerator nextObject]) && (uploadUseSpeedLimit != NSMixedState || uploadSpeedLimit != INVALID @@ -115,61 +115,61 @@ if (downloadSpeedLimit != INVALID && downloadSpeedLimit != [torrent speedLimit: NO]) downloadSpeedLimit = INVALID; - if (globalUseSpeedLimit != NSMixedState && globalUseSpeedLimit != ([torrent usesGlobalSpeedLimit] ? NSOnState : NSOffState)) + if (globalUseSpeedLimit != NSMixedState && globalUseSpeedLimit != (torrent.usesGlobalSpeedLimit ? NSOnState : NSOffState)) globalUseSpeedLimit = NSMixedState; } //set upload view - [fUploadLimitCheck setState: uploadUseSpeedLimit]; - [fUploadLimitCheck setEnabled: YES]; + fUploadLimitCheck.state = uploadUseSpeedLimit; + fUploadLimitCheck.enabled = YES; - [fUploadLimitLabel setEnabled: uploadUseSpeedLimit == NSOnState]; - [fUploadLimitField setEnabled: uploadUseSpeedLimit == NSOnState]; + fUploadLimitLabel.enabled = uploadUseSpeedLimit == NSOnState; + fUploadLimitField.enabled = uploadUseSpeedLimit == NSOnState; if (uploadSpeedLimit != INVALID) - [fUploadLimitField setIntValue: uploadSpeedLimit]; + fUploadLimitField.intValue = uploadSpeedLimit; else - [fUploadLimitField setStringValue: @""]; + fUploadLimitField.stringValue = @""; //set download view - [fDownloadLimitCheck setState: downloadUseSpeedLimit]; - [fDownloadLimitCheck setEnabled: YES]; + fDownloadLimitCheck.state = downloadUseSpeedLimit; + fDownloadLimitCheck.enabled = YES; - [fDownloadLimitLabel setEnabled: downloadUseSpeedLimit == NSOnState]; - [fDownloadLimitField setEnabled: downloadUseSpeedLimit == NSOnState]; + fDownloadLimitLabel.enabled = downloadUseSpeedLimit == NSOnState; + fDownloadLimitField.enabled = downloadUseSpeedLimit == NSOnState; if (downloadSpeedLimit != INVALID) - [fDownloadLimitField setIntValue: downloadSpeedLimit]; + fDownloadLimitField.intValue = downloadSpeedLimit; else - [fDownloadLimitField setStringValue: @""]; + fDownloadLimitField.stringValue = @""; //set global check - [fGlobalLimitCheck setState: globalUseSpeedLimit]; - [fGlobalLimitCheck setEnabled: YES]; + fGlobalLimitCheck.state = globalUseSpeedLimit; + fGlobalLimitCheck.enabled = YES; //get ratio and idle info enumerator = [fTorrents objectEnumerator]; torrent = [enumerator nextObject]; //first torrent - NSInteger checkRatio = [torrent ratioSetting], checkIdle = [torrent idleSetting], - removeWhenFinishSeeding = [torrent removeWhenFinishSeeding] ? NSOnState : NSOffState; - CGFloat ratioLimit = [torrent ratioLimit]; - NSUInteger idleLimit = [torrent idleLimitMinutes]; + NSInteger checkRatio = torrent.ratioSetting, checkIdle = torrent.idleSetting, + 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)) { - if (checkRatio != INVALID && checkRatio != [torrent ratioSetting]) + if (checkRatio != INVALID && checkRatio != torrent.ratioSetting) checkRatio = INVALID; - if (ratioLimit != INVALID && ratioLimit != [torrent ratioLimit]) + if (ratioLimit != INVALID && ratioLimit != torrent.ratioLimit) ratioLimit = INVALID; - if (checkIdle != INVALID && checkIdle != [torrent idleSetting]) + if (checkIdle != INVALID && checkIdle != torrent.idleSetting) checkIdle = INVALID; - if (idleLimit != INVALID && idleLimit != [torrent idleLimitMinutes]) + if (idleLimit != INVALID && idleLimit != torrent.idleLimitMinutes) idleLimit = INVALID; - if (removeWhenFinishSeeding != NSMixedState && removeWhenFinishSeeding != ([torrent removeWhenFinishSeeding] ? NSOnState : NSOffState)) + if (removeWhenFinishSeeding != NSMixedState && removeWhenFinishSeeding != (torrent.removeWhenFinishSeeding ? NSOnState : NSOffState)) removeWhenFinishSeeding = NSMixedState; } @@ -184,15 +184,15 @@ else index = -1; [fRatioPopUp selectItemAtIndex: index]; - [fRatioPopUp setEnabled: YES]; + fRatioPopUp.enabled = YES; - [fRatioLimitField setHidden: checkRatio != TR_RATIOLIMIT_SINGLE]; + fRatioLimitField.hidden = checkRatio != TR_RATIOLIMIT_SINGLE; if (ratioLimit != INVALID) - [fRatioLimitField setFloatValue: ratioLimit]; + fRatioLimitField.floatValue = ratioLimit; else - [fRatioLimitField setStringValue: @""]; + fRatioLimitField.stringValue = @""; - [fRatioLimitGlobalLabel setHidden: checkRatio != TR_RATIOLIMIT_GLOBAL]; + fRatioLimitGlobalLabel.hidden = checkRatio != TR_RATIOLIMIT_GLOBAL; //set idle view if (checkIdle == TR_IDLELIMIT_SINGLE) @@ -204,30 +204,30 @@ else index = -1; [fIdlePopUp selectItemAtIndex: index]; - [fIdlePopUp setEnabled: YES]; + fIdlePopUp.enabled = YES; - [fIdleLimitField setHidden: checkIdle != TR_IDLELIMIT_SINGLE]; + fIdleLimitField.hidden = checkIdle != TR_IDLELIMIT_SINGLE; if (idleLimit != INVALID) - [fIdleLimitField setIntegerValue: idleLimit]; + fIdleLimitField.integerValue = idleLimit; else - [fIdleLimitField setStringValue: @""]; - [fIdleLimitLabel setHidden: checkIdle != TR_IDLELIMIT_SINGLE]; + fIdleLimitField.stringValue = @""; + fIdleLimitLabel.hidden = checkIdle != TR_IDLELIMIT_SINGLE; - [fIdleLimitGlobalLabel setHidden: checkIdle != TR_IDLELIMIT_GLOBAL]; + fIdleLimitGlobalLabel.hidden = checkIdle != TR_IDLELIMIT_GLOBAL; //set remove transfer when seeding finishes - [fRemoveSeedingCompleteCheck setState: removeWhenFinishSeeding]; - [fRemoveSeedingCompleteCheck setEnabled: YES]; + fRemoveSeedingCompleteCheck.state = removeWhenFinishSeeding; + fRemoveSeedingCompleteCheck.enabled = YES; //get priority info enumerator = [fTorrents objectEnumerator]; torrent = [enumerator nextObject]; //first torrent - NSInteger priority = [torrent priority]; + NSInteger priority = torrent.priority; while ((torrent = [enumerator nextObject]) && priority != INVALID) { - if (priority != INVALID && priority != [torrent priority]) + if (priority != INVALID && priority != torrent.priority) priority = INVALID; } @@ -241,17 +241,17 @@ else index = -1; [fPriorityPopUp selectItemAtIndex: index]; - [fPriorityPopUp setEnabled: YES]; + fPriorityPopUp.enabled = YES; //get peer info enumerator = [fTorrents objectEnumerator]; torrent = [enumerator nextObject]; //first torrent - NSInteger maxPeers = [torrent maxPeerConnect]; + NSInteger maxPeers = torrent.maxPeerConnect; while ((torrent = [enumerator nextObject])) { - if (maxPeers != [torrent maxPeerConnect]) + if (maxPeers != torrent.maxPeerConnect) { maxPeers = INVALID; break; @@ -259,49 +259,49 @@ } //set peer view - [fPeersConnectField setEnabled: YES]; - [fPeersConnectLabel setEnabled: YES]; + fPeersConnectField.enabled = YES; + fPeersConnectLabel.enabled = YES; if (maxPeers != INVALID) - [fPeersConnectField setIntValue: maxPeers]; + fPeersConnectField.intValue = maxPeers; else - [fPeersConnectField setStringValue: @""]; + fPeersConnectField.stringValue = @""; } - (void) setUseSpeedLimit: (id) sender { const BOOL upload = sender == fUploadLimitCheck; - if ([(NSButton *)sender state] == NSMixedState) + if (((NSButton *)sender).state == NSMixedState) [sender setState: NSOnState]; - const BOOL limit = [(NSButton *)sender state] == NSOnState; + const BOOL limit = ((NSButton *)sender).state == NSOnState; for (Torrent * torrent in fTorrents) [torrent setUseSpeedLimit: limit upload: upload]; NSTextField * field = upload ? fUploadLimitField : fDownloadLimitField; - [field setEnabled: limit]; + field.enabled = limit; if (limit) { [field selectText: self]; - [[[self view] window] makeKeyAndOrderFront: self]; + [self.view.window makeKeyAndOrderFront: self]; } NSTextField * label = upload ? fUploadLimitLabel : fDownloadLimitLabel; - [label setEnabled: limit]; + label.enabled = limit; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; } - (void) setUseGlobalSpeedLimit: (id) sender { - if ([(NSButton *)sender state] == NSMixedState) + if (((NSButton *)sender).state == NSMixedState) [sender setState: NSOnState]; - const BOOL limit = [(NSButton *)sender state] == NSOnState; + const BOOL limit = ((NSButton *)sender).state == NSOnState; for (Torrent * torrent in fTorrents) - [torrent setUseGlobalSpeedLimit: limit]; + torrent.usesGlobalSpeedLimit = limit; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; } - (void) setSpeedLimit: (id) sender @@ -312,7 +312,7 @@ 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 @@ -337,18 +337,18 @@ } for (Torrent * torrent in fTorrents) - [torrent setRatioSetting: setting]; + torrent.ratioSetting = setting; - [fRatioLimitField setHidden: !single]; + fRatioLimitField.hidden = !single; if (single) { [fRatioLimitField selectText: self]; - [[[self view] window] makeKeyAndOrderFront: self]; + [self.view.window makeKeyAndOrderFront: self]; } - [fRatioLimitGlobalLabel setHidden: setting != TR_RATIOLIMIT_GLOBAL]; + fRatioLimitGlobalLabel.hidden = setting != TR_RATIOLIMIT_GLOBAL; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; } - (void) setRatioLimit: (id) sender @@ -356,9 +356,9 @@ const CGFloat limit = [sender floatValue]; for (Torrent * torrent in fTorrents) - [torrent setRatioLimit: limit]; + torrent.ratioLimit = limit; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; } - (void) setIdleSetting: (id) sender @@ -383,19 +383,19 @@ } for (Torrent * torrent in fTorrents) - [torrent setIdleSetting: setting]; + torrent.idleSetting = setting; - [fIdleLimitField setHidden: !single]; - [fIdleLimitLabel setHidden: !single]; + fIdleLimitField.hidden = !single; + fIdleLimitLabel.hidden = !single; if (single) { [fIdleLimitField selectText: self]; - [[[self view] window] makeKeyAndOrderFront: self]; + [self.view.window makeKeyAndOrderFront: self]; } - [fIdleLimitGlobalLabel setHidden: setting != TR_IDLELIMIT_GLOBAL]; + fIdleLimitGlobalLabel.hidden = setting != TR_IDLELIMIT_GLOBAL; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; } - (void) setIdleLimit: (id) sender @@ -403,21 +403,21 @@ const NSUInteger limit = [sender integerValue]; for (Torrent * torrent in fTorrents) - [torrent setIdleLimitMinutes: limit]; + torrent.idleLimitMinutes = limit; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; } - (IBAction) setRemoveWhenSeedingCompletes: (id) sender { - if ([(NSButton *)sender state] == NSMixedState) + if (((NSButton *)sender).state == NSMixedState) [sender setState: NSOnState]; - const BOOL enable = [(NSButton *)sender state] == NSOnState; + const BOOL enable = ((NSButton *)sender).state == NSOnState; for (Torrent * torrent in fTorrents) - [torrent setRemoveWhenFinishSeeding: enable]; + torrent.removeWhenFinishSeeding = enable; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; } - (void) setPriority: (id) sender @@ -440,11 +440,11 @@ } for (Torrent * torrent in fTorrents) - [torrent setPriority: priority]; + 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 @@ -452,14 +452,14 @@ NSInteger limit = [sender intValue]; for (Torrent * torrent in fTorrents) - [torrent setMaxPeerConnect: limit]; + torrent.maxPeerConnect = limit; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptionsNotification" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptionsNotification" object: self]; } - (BOOL) control: (NSControl *) control textShouldBeginEditing: (NSText *) fieldEditor { - fInitialString = [control stringValue]; + fInitialString = control.stringValue; return YES; } @@ -469,7 +469,7 @@ NSBeep(); if (fInitialString) { - [control setStringValue: fInitialString]; + control.stringValue = fInitialString; fInitialString = nil; } return NO; @@ -481,45 +481,45 @@ - (void) setupInfo { - if ([fTorrents count] == 0) + if (fTorrents.count == 0) { - [fUploadLimitCheck setEnabled: NO]; - [fUploadLimitCheck setState: NSOffState]; - [fUploadLimitField setEnabled: NO]; - [fUploadLimitLabel setEnabled: NO]; - [fUploadLimitField setStringValue: @""]; + fUploadLimitCheck.enabled = NO; + fUploadLimitCheck.state = NSOffState; + fUploadLimitField.enabled = NO; + fUploadLimitLabel.enabled = NO; + fUploadLimitField.stringValue = @""; - [fDownloadLimitCheck setEnabled: NO]; - [fDownloadLimitCheck setState: NSOffState]; - [fDownloadLimitField setEnabled: NO]; - [fDownloadLimitLabel setEnabled: NO]; - [fDownloadLimitField setStringValue: @""]; + fDownloadLimitCheck.enabled = NO; + fDownloadLimitCheck.state = NSOffState; + fDownloadLimitField.enabled = NO; + fDownloadLimitLabel.enabled = NO; + fDownloadLimitField.stringValue = @""; - [fGlobalLimitCheck setEnabled: NO]; - [fGlobalLimitCheck setState: NSOffState]; + fGlobalLimitCheck.enabled = NO; + fGlobalLimitCheck.state = NSOffState; - [fPriorityPopUp setEnabled: NO]; + fPriorityPopUp.enabled = NO; [fPriorityPopUp selectItemAtIndex: -1]; - [fRatioPopUp setEnabled: NO]; + fRatioPopUp.enabled = NO; [fRatioPopUp selectItemAtIndex: -1]; - [fRatioLimitField setHidden: YES]; - [fRatioLimitField setStringValue: @""]; - [fRatioLimitGlobalLabel setHidden: YES]; + fRatioLimitField.hidden = YES; + fRatioLimitField.stringValue = @""; + fRatioLimitGlobalLabel.hidden = YES; - [fIdlePopUp setEnabled: NO]; + fIdlePopUp.enabled = NO; [fIdlePopUp selectItemAtIndex: -1]; - [fIdleLimitField setHidden: YES]; - [fIdleLimitField setStringValue: @""]; - [fIdleLimitLabel setHidden: YES]; - [fIdleLimitGlobalLabel setHidden: YES]; + fIdleLimitField.hidden = YES; + fIdleLimitField.stringValue = @""; + fIdleLimitLabel.hidden = YES; + fIdleLimitGlobalLabel.hidden = YES; - [fRemoveSeedingCompleteCheck setEnabled: NO]; - [fRemoveSeedingCompleteCheck setState: NSOffState]; + fRemoveSeedingCompleteCheck.enabled = NO; + fRemoveSeedingCompleteCheck.state = NSOffState; - [fPeersConnectField setEnabled: NO]; - [fPeersConnectField setStringValue: @""]; - [fPeersConnectLabel setEnabled: NO]; + fPeersConnectField.enabled = NO; + fPeersConnectField.stringValue = @""; + fPeersConnectLabel.enabled = NO; } else [self updateOptions]; @@ -527,27 +527,27 @@ - (void) setGlobalLabels { - NSString * global = [[NSUserDefaults standardUserDefaults] boolForKey: @"RatioCheck"] - ? [NSString stringForRatio: [[NSUserDefaults standardUserDefaults] floatForKey: @"RatioLimit"]] + NSString * global = [NSUserDefaults.standardUserDefaults boolForKey: @"RatioCheck"] + ? [NSString stringForRatio: [NSUserDefaults.standardUserDefaults floatForKey: @"RatioLimit"]] : NSLocalizedString(@"disabled", "Info options -> global setting"); - [fRatioLimitGlobalLabel setStringValue: global]; + fRatioLimitGlobalLabel.stringValue = global; //idle field NSString * globalIdle; - if ([[NSUserDefaults standardUserDefaults] boolForKey: @"IdleLimitCheck"]) + if ([NSUserDefaults.standardUserDefaults boolForKey: @"IdleLimitCheck"]) { - const NSInteger globalMin = [[NSUserDefaults standardUserDefaults] integerForKey: @"IdleLimitMinutes"]; + 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]; } else globalIdle = NSLocalizedString(@"disabled", "Info options -> global setting"); - [fIdleLimitGlobalLabel setStringValue: globalIdle]; + fIdleLimitGlobalLabel.stringValue = globalIdle; } - (void) updateOptionsNotification: (NSNotification *) notification { - if ([notification object] != self) + if (notification.object != self) [self updateOptions]; } diff --git a/macosx/InfoPeersViewController.h b/macosx/InfoPeersViewController.h index 4874c0c99..686a7d981 100644 --- a/macosx/InfoPeersViewController.h +++ b/macosx/InfoPeersViewController.h @@ -26,7 +26,7 @@ @class WebSeedTableView; -@interface InfoPeersViewController : NSViewController +@interface InfoPeersViewController : NSViewController { NSArray * fTorrents; diff --git a/macosx/InfoPeersViewController.m b/macosx/InfoPeersViewController.m index eb274a0f7..2c7dfd97a 100644 --- a/macosx/InfoPeersViewController.m +++ b/macosx/InfoPeersViewController.m @@ -33,22 +33,22 @@ #define ANIMATION_ID_KEY @"animationId" #define WEB_SEED_ANIMATION_ID @"webSeed" -@interface InfoPeersViewController (Private) +@interface InfoPeersViewController (Private) - (void) setupInfo; - (void) setWebSeedTableHidden: (BOOL) hide animate: (BOOL) animate; -- (NSArray *) peerSortDescriptors; +@property (nonatomic, readonly) NSArray *peerSortDescriptors; @end @implementation InfoPeersViewController -- (id) init +- (instancetype) init { if ((self = [super initWithNibName: @"InfoPeersView" bundle: nil])) { - [self setTitle: NSLocalizedString(@"Peers", "Inspector view -> title")]; + self.title = NSLocalizedString(@"Peers", "Inspector view -> title"); } return self; @@ -56,51 +56,51 @@ - (void) awakeFromNib { - const CGFloat height = [[NSUserDefaults standardUserDefaults] floatForKey: @"InspectorContentHeightPeers"]; + const CGFloat height = [NSUserDefaults.standardUserDefaults floatForKey: @"InspectorContentHeightPeers"]; if (height != 0.0) { - NSRect viewRect = [[self view] frame]; + NSRect viewRect = self.view.frame; viewRect.size.height = height; - [[self view] setFrame: viewRect]; + self.view.frame = viewRect; } //set table header text - [[[fPeerTable tableColumnWithIdentifier: @"IP"] headerCell] setStringValue: NSLocalizedString(@"IP Address", - "inspector -> peer table -> header")]; - [[[fPeerTable tableColumnWithIdentifier: @"Client"] headerCell] setStringValue: NSLocalizedString(@"Client", - "inspector -> peer table -> header")]; - [[[fPeerTable tableColumnWithIdentifier: @"DL From"] headerCell] setStringValue: NSLocalizedString(@"DL", - "inspector -> peer table -> header")]; - [[[fPeerTable tableColumnWithIdentifier: @"UL To"] headerCell] setStringValue: 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] setStringValue: NSLocalizedString(@"Web Seeds", - "inspector -> web seed table -> header")]; - [[[fWebSeedTable tableColumnWithIdentifier: @"DL From"] headerCell] setStringValue: 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"] setHeaderToolTip: NSLocalizedString(@"Encrypted Connection", - "inspector -> peer table -> header tool tip")]; - [[fPeerTable tableColumnWithIdentifier: @"Progress"] setHeaderToolTip: NSLocalizedString(@"Available", - "inspector -> peer table -> header tool tip")]; - [[fPeerTable tableColumnWithIdentifier: @"DL From"] setHeaderToolTip: NSLocalizedString(@"Downloading From Peer", - "inspector -> peer table -> header tool tip")]; - [[fPeerTable tableColumnWithIdentifier: @"UL To"] setHeaderToolTip: 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"] setHeaderToolTip: NSLocalizedString(@"Downloading From Web Seed", - "inspector -> web seed table -> header tool tip")]; + [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 setTimingFunction: [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear]]; - [webSeedTableAnimation setDuration: 0.125]; - [webSeedTableAnimation setDelegate: self]; + webSeedTableAnimation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear]; + webSeedTableAnimation.duration = 0.125; + webSeedTableAnimation.delegate = self; [webSeedTableAnimation setValue: WEB_SEED_ANIMATION_ID forKey: ANIMATION_ID_KEY]; - [fWebSeedTableTopConstraint setAnimations: @{ @"constant": webSeedTableAnimation }]; + fWebSeedTableTopConstraint.animations = @{ @"constant": webSeedTableAnimation }; [self setWebSeedTableHidden: YES animate: NO]; } @@ -120,7 +120,7 @@ if (!fSet) [self setupInfo]; - if ([fTorrents count] == 0) + if (fTorrents.count == 0) return; if (!fPeers) @@ -138,36 +138,36 @@ BOOL anyActive = false; for (Torrent * torrent in fTorrents) { - if ([torrent webSeedCount] > 0) - [fWebSeeds addObjectsFromArray: [torrent webSeeds]]; + if (torrent.webSeedCount > 0) + [fWebSeeds addObjectsFromArray: torrent.webSeeds]; - if ([torrent isActive]) + if (torrent.active) { anyActive = YES; - [fPeers addObjectsFromArray: [torrent peers]]; + [fPeers addObjectsFromArray: torrent.peers]; - const NSUInteger connectedThis = [torrent totalPeersConnected]; + const NSUInteger connectedThis = torrent.totalPeersConnected; if (connectedThis > 0) { - connected += [torrent totalPeersConnected]; - tracker += [torrent totalPeersTracker]; - incoming += [torrent totalPeersIncoming]; - cache += [torrent totalPeersCache]; - lpd += [torrent totalPeersLocal]; - pex += [torrent totalPeersPex]; - dht += [torrent totalPeersDHT]; - ltep += [torrent totalPeersLTEP]; + connected += torrent.totalPeersConnected; + tracker += torrent.totalPeersTracker; + incoming += torrent.totalPeersIncoming; + cache += torrent.totalPeersCache; + lpd += torrent.totalPeersLocal; + pex += torrent.totalPeersPex; + dht += torrent.totalPeersDHT; + ltep += torrent.totalPeersLTEP; - toUs += [torrent peersSendingToUs]; - fromUs += [torrent peersGettingFromUs]; + toUs += torrent.peersSendingToUs; + fromUs += torrent.peersGettingFromUs; } } } - [fPeers sortUsingDescriptors: [self peerSortDescriptors]]; + [fPeers sortUsingDescriptors: self.peerSortDescriptors]; [fPeerTable reloadData]; - [fWebSeeds sortUsingDescriptors: [fWebSeedTable sortDescriptors]]; + [fWebSeeds sortUsingDescriptors: fWebSeedTable.sortDescriptors]; [fWebSeedTable reloadData]; [fWebSeedTable setWebSeeds: fWebSeeds]; @@ -185,7 +185,7 @@ if (fromUs > 0) [upDownComponents addObject: [NSString stringWithFormat: NSLocalizedString(@"UL to %d", "Inspector -> Peers tab -> peers"), fromUs]]; - if ([upDownComponents count] > 0) + if (upDownComponents.count > 0) connectedText = [connectedText stringByAppendingFormat: @": %@", [upDownComponents componentsJoinedByString: @", "]]; NSMutableArray * fromComponents = [NSMutableArray arrayWithCapacity: 7]; @@ -214,23 +214,23 @@ connectedText = [connectedText stringByAppendingFormat: @"\n%@", [fromComponents componentsJoinedByString: @", "]]; } - [fConnectedPeersField setStringValue: connectedText]; + fConnectedPeersField.stringValue = connectedText; } else { NSString * notActiveString; - if ([fTorrents count] == 1) + if (fTorrents.count == 1) notActiveString = NSLocalizedString(@"Transfer Not Active", "Inspector -> Peers tab -> peers"); else notActiveString = NSLocalizedString(@"Transfers Not Active", "Inspector -> Peers tab -> peers"); - [fConnectedPeersField setStringValue: notActiveString]; + fConnectedPeersField.stringValue = notActiveString; } } - (void) saveViewSize { - [[NSUserDefaults standardUserDefaults] setFloat: NSHeight([[self view] frame]) forKey: @"InspectorContentHeightPeers"]; + [NSUserDefaults.standardUserDefaults setFloat: NSHeight(self.view.frame) forKey: @"InspectorContentHeightPeers"]; } - (void) clearView @@ -242,29 +242,29 @@ - (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView { if (tableView == fWebSeedTable) - return fWebSeeds ? [fWebSeeds count] : 0; + return fWebSeeds ? fWebSeeds.count : 0; else - return fPeers ? [fPeers count] : 0; + return fPeers ? fPeers.count : 0; } - (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (NSInteger) row { if (tableView == fWebSeedTable) { - NSString * ident = [column identifier]; + NSString * ident = column.identifier; NSDictionary * webSeed = fWebSeeds[row]; if ([ident isEqualToString: @"DL From"]) { NSNumber * rate; - return (rate = webSeed[@"DL From Rate"]) ? [NSString stringForSpeedAbbrev: [rate doubleValue]] : @""; + return (rate = webSeed[@"DL From Rate"]) ? [NSString stringForSpeedAbbrev: rate.doubleValue] : @""; } else return webSeed[@"Address"]; } else { - NSString * ident = [column identifier]; + NSString * ident = column.identifier; NSDictionary * peer = fPeers[row]; if ([ident isEqualToString: @"Encryption"]) @@ -276,12 +276,12 @@ else if ([ident isEqualToString: @"UL To"]) { NSNumber * rate; - return (rate = peer[@"UL To Rate"]) ? [NSString stringForSpeedAbbrev: [rate doubleValue]] : @""; + 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]] : @""; + return (rate = peer[@"DL From Rate"]) ? [NSString stringForSpeedAbbrev: rate.doubleValue] : @""; } else return peer[@"IP"]; @@ -293,7 +293,7 @@ { if (tableView == fPeerTable) { - NSString * ident = [tableColumn identifier]; + NSString * ident = tableColumn.identifier; if ([ident isEqualToString: @"Progress"]) { @@ -309,7 +309,7 @@ { if (fWebSeeds) { - [fWebSeeds sortUsingDescriptors: [fWebSeedTable sortDescriptors]]; + [fWebSeeds sortUsingDescriptors: fWebSeedTable.sortDescriptors]; [tableView reloadData]; } } @@ -317,7 +317,7 @@ { if (fPeers) { - [fPeers sortUsingDescriptors: [self peerSortDescriptors]]; + [fPeers sortUsingDescriptors: self.peerSortDescriptors]; [tableView reloadData]; } } @@ -333,7 +333,7 @@ { if (tableView == fPeerTable) { - const BOOL multiple = [fTorrents count] > 1; + const BOOL multiple = fTorrents.count > 1; NSDictionary * peer = fPeers[row]; NSMutableArray * components = [NSMutableArray arrayWithCapacity: multiple ? 6 : 5]; @@ -419,7 +419,7 @@ [statusArray addObject: NSLocalizedString(@"You unchoked the peer, but the peer is not interested", "Inspector -> peer -> status")]; - if ([statusArray count] > 0) + if (statusArray.count > 0) { NSString * statusStrings = [statusArray componentsJoinedByString: @"\n\n"]; [components addObject: [@"\n" stringByAppendingString: statusStrings]]; @@ -429,7 +429,7 @@ } else { - if ([fTorrents count] > 1) + if (fTorrents.count > 1) return fWebSeeds[row][@"Name"]; } @@ -441,7 +441,7 @@ if (![[animation valueForKey: ANIMATION_ID_KEY] isEqualToString: WEB_SEED_ANIMATION_ID]) return; - [[fWebSeedTable enclosingScrollView] setHidden: NO]; + fWebSeedTable.enclosingScrollView.hidden = NO; } - (void) animationDidStop: (CAAnimation *) animation finished: (BOOL) finished @@ -449,7 +449,7 @@ if (![[animation valueForKey: ANIMATION_ID_KEY] isEqualToString: WEB_SEED_ANIMATION_ID]) return; - [[fWebSeedTable enclosingScrollView] setHidden: finished && fWebSeedTableTopConstraint.constant < 0]; + fWebSeedTable.enclosingScrollView.hidden = finished && fWebSeedTableTopConstraint.constant < 0; } @end @@ -460,17 +460,17 @@ { __block BOOL hasWebSeeds = NO; - if ([fTorrents count] == 0) + if (fTorrents.count == 0) { fPeers = nil; [fPeerTable reloadData]; - [fConnectedPeersField setStringValue: @""]; + fConnectedPeersField.stringValue = @""; } else { [fTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(Torrent * torrent, NSUInteger idx, BOOL *stop) { - if ([torrent webSeedCount] > 0) + if (torrent.webSeedCount > 0) { hasWebSeeds = YES; *stop = YES; @@ -492,27 +492,27 @@ - (void) setWebSeedTableHidden: (BOOL) hide animate: (BOOL) animate { - if (animate && (![[self view] window] || ![[[self view] window] isVisible])) + if (animate && (!self.view.window || !self.view.window.visible)) animate = NO; - const CGFloat webSeedTableTopMargin = hide ? -NSHeight([[fWebSeedTable enclosingScrollView] frame]) : fViewTopMargin; + const CGFloat webSeedTableTopMargin = hide ? -NSHeight(fWebSeedTable.enclosingScrollView.frame) : fViewTopMargin; - [(animate ? [fWebSeedTableTopConstraint animator] : fWebSeedTableTopConstraint) setConstant: webSeedTableTopMargin]; + (animate ? [fWebSeedTableTopConstraint animator] : fWebSeedTableTopConstraint).constant = webSeedTableTopMargin; } - (NSArray *) peerSortDescriptors { NSMutableArray * descriptors = [NSMutableArray arrayWithCapacity: 2]; - NSArray * oldDescriptors = [fPeerTable sortDescriptors]; + NSArray * oldDescriptors = fPeerTable.sortDescriptors; BOOL useSecond = YES, asc = YES; - if ([oldDescriptors count] > 0) + if (oldDescriptors.count > 0) { NSSortDescriptor * descriptor = oldDescriptors[0]; [descriptors addObject: descriptor]; - if ((useSecond = ![[descriptor key] isEqualToString: @"IP"])) - asc = [descriptor ascending]; + if ((useSecond = ![descriptor.key isEqualToString: @"IP"])) + asc = descriptor.ascending; } //sort by IP after primary sort diff --git a/macosx/InfoTabButtonBack.m b/macosx/InfoTabButtonBack.m index 5aa83e46e..a76b4150c 100644 --- a/macosx/InfoTabButtonBack.m +++ b/macosx/InfoTabButtonBack.m @@ -25,21 +25,20 @@ @implementation InfoTabButtonBack - - (void) drawRect: (NSRect) rect { NSInteger count = 0; NSRect gridRects[2]; NSColor * colorRects[2]; - NSRect lineBorderRect = NSMakeRect(NSMinX(rect), NSHeight([self bounds]) - 1.0, NSWidth(rect), 1.0); + 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, *)) { - colorRects[count] = [NSColor separatorColor]; + colorRects[count] = NSColor.separatorColor; } else { - colorRects[count] = [NSColor grayColor]; + colorRects[count] = NSColor.grayColor; } ++count; @@ -51,9 +50,9 @@ { gridRects[count] = lineBorderRect; if (@available(macOS 10.14, *)) { - colorRects[count] = [NSColor separatorColor]; + colorRects[count] = NSColor.separatorColor; } else { - colorRects[count] = [NSColor grayColor]; + colorRects[count] = NSColor.grayColor; } ++count; @@ -65,7 +64,7 @@ NSGradient *gradient; - if ([NSApp isDarkMode]) { + 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]; diff --git a/macosx/InfoTabButtonCell.m b/macosx/InfoTabButtonCell.m index c64d93d9e..7f9f9b68c 100644 --- a/macosx/InfoTabButtonCell.m +++ b/macosx/InfoTabButtonCell.m @@ -27,8 +27,8 @@ - (void) awakeFromNib { - if (![NSApp isOnMojaveOrBetter]) { - NSNotificationCenter * nc = [NSNotificationCenter defaultCenter]; + if (!NSApp.onMojaveOrBetter) { + NSNotificationCenter * nc = NSNotificationCenter.defaultCenter; [nc addObserver: self selector: @selector(updateControlTint:) name: NSControlTintDidChangeNotification object: NSApp]; } @@ -36,23 +36,23 @@ fSelected = NO; //expects the icon to currently be set as the image - fIcon = [self image]; + fIcon = self.image; } - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; } - (void) setControlView: (NSView *) controlView { - const BOOL hadControlView = [self controlView] != nil; + const BOOL hadControlView = self.controlView != nil; - [super setControlView: controlView]; + super.controlView = controlView; if (!hadControlView) { - [(NSMatrix *)[self controlView] setToolTip: [self title] forCell: self]; + [(NSMatrix *)self.controlView setToolTip: self.title forCell: self]; [self setSelectedTab: fSelected]; } } @@ -66,12 +66,12 @@ - (void) reloadAppearance { - if ([self controlView] == nil) + 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; @@ -84,17 +84,17 @@ { 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]]; + 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]]; + lightColor = [NSColor colorForControlTint: NSColor.currentControlTint]; + darkColor = [lightColor blendedColorWithFraction: 0.2 ofColor: NSColor.blackColor]; } gradient = [[NSGradient alloc] initWithStartingColor: lightColor endingColor: darkColor]; } else { - if ([NSApp isDarkMode]) { + 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]; @@ -106,9 +106,9 @@ } if (@available(macOS 10.14, *)) { - [[NSColor separatorColor] set]; + [NSColor.separatorColor set]; } else { - [[NSColor grayColor] set]; + [NSColor.grayColor set]; } NSRectFill(NSMakeRect(0.0, 0.0, NSWidth(tabRect), 1.0)); NSRectFill(NSMakeRect(0.0, NSHeight(tabRect) - 1.0, NSWidth(tabRect), 1.0)); @@ -120,7 +120,7 @@ if (fIcon) { - const NSSize iconSize = [fIcon size]; + const NSSize 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), @@ -131,12 +131,12 @@ [tabImage unlockFocus]; - [self setImage: tabImage]; + self.image = tabImage; } - (void) updateControlTint: (NSNotification *) notification { - NSAssert(![NSApp isOnMojaveOrBetter], @"should not be observing control tint color when accent color is available"); + NSAssert(!NSApp.onMojaveOrBetter, @"should not be observing control tint color when accent color is available"); if (fSelected) [self setSelectedTab: YES]; diff --git a/macosx/InfoTextField.m b/macosx/InfoTextField.m index d4ee82930..573a4064a 100644 --- a/macosx/InfoTextField.m +++ b/macosx/InfoTextField.m @@ -26,16 +26,16 @@ - (void) setStringValue: (NSString *) string { - [super setStringValue: string]; + super.stringValue = string; - [self setSelectable: ![[self stringValue] isEqualToString: @""]]; + self.selectable = ![self.stringValue isEqualToString: @""]; } - (void) setObjectValue: (id ) object { - [super setObjectValue: object]; + super.objectValue = object; - [self setSelectable: ![[self stringValue] isEqualToString: @""]]; + self.selectable = ![self.stringValue isEqualToString: @""]; } @end diff --git a/macosx/InfoTrackersViewController.m b/macosx/InfoTrackersViewController.m index ed333d8aa..d5daf7ed3 100644 --- a/macosx/InfoTrackersViewController.m +++ b/macosx/InfoTrackersViewController.m @@ -44,11 +44,11 @@ @implementation InfoTrackersViewController -- (id) init +- (instancetype) init { if ((self = [super initWithNibName: @"InfoTrackersView" bundle: nil])) { - [self setTitle: NSLocalizedString(@"Trackers", "Inspector view -> title")]; + self.title = NSLocalizedString(@"Trackers", "Inspector view -> title"); fTrackerCell = [[TrackerCell alloc] init]; } @@ -58,17 +58,17 @@ - (void) awakeFromNib { - [[fTrackerAddRemoveControl cell] setToolTip: NSLocalizedString(@"Add a tracker", "Inspector view -> tracker buttons") + [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") + [fTrackerAddRemoveControl.cell setToolTip: NSLocalizedString(@"Remove selected trackers", "Inspector view -> tracker buttons") forSegment: TRACKER_REMOVE_TAG]; - const CGFloat height = [[NSUserDefaults standardUserDefaults] floatForKey: @"InspectorContentHeightTracker"]; + const CGFloat height = [NSUserDefaults.standardUserDefaults floatForKey: @"InspectorContentHeightTracker"]; if (height != 0.0) { - NSRect viewRect = [[self view] frame]; + NSRect viewRect = self.view.frame; viewRect.size.height = height; - [[self view] setFrame: viewRect]; + self.view.frame = viewRect; } } @@ -86,52 +86,52 @@ if (!fSet) [self setupInfo]; - if ([fTorrents count] == 0) + if (fTorrents.count == 0) return; //get updated tracker stats - if ([fTrackerTable editedRow] == -1) + if (fTrackerTable.editedRow == -1) { NSArray * oldTrackers = fTrackers; - if ([fTorrents count] == 1) - fTrackers = [fTorrents[0] allTrackerStats]; + if (fTorrents.count == 1) + fTrackers = ((Torrent *)fTorrents[0]).allTrackerStats; else { fTrackers = [[NSMutableArray alloc] init]; for (Torrent * torrent in fTorrents) - [fTrackers addObjectsFromArray: [torrent allTrackerStats]]; + [fTrackers addObjectsFromArray: torrent.allTrackerStats]; } [fTrackerTable setTrackers: fTrackers]; if (oldTrackers && [fTrackers isEqualToArray: oldTrackers]) - [fTrackerTable setNeedsDisplay: YES]; + fTrackerTable.needsDisplay = YES; else [fTrackerTable reloadData]; } else { - NSAssert1([fTorrents count] == 1, @"Attempting to add tracker with %ld transfers selected", [fTorrents count]); + NSAssert1(fTorrents.count == 1, @"Attempting to add tracker with %ld transfers selected", fTorrents.count); - NSIndexSet * addedIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange([fTrackers count]-2, 2)]; + NSIndexSet * addedIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(fTrackers.count-2, 2)]; NSArray * tierAndTrackerBeingAdded = [fTrackers objectsAtIndexes: addedIndexes]; - fTrackers = [fTorrents[0] allTrackerStats]; + fTrackers = ((Torrent *)fTorrents[0]).allTrackerStats; [fTrackers addObjectsFromArray: tierAndTrackerBeingAdded]; [fTrackerTable setTrackers: fTrackers]; - NSIndexSet * updateIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTrackers count]-2)], - * columnIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [[fTrackerTable tableColumns] count])]; + NSIndexSet * updateIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTrackers.count-2)], + * columnIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fTrackerTable.tableColumns.count)]; [fTrackerTable reloadDataForRowIndexes: updateIndexes columnIndexes: columnIndexes]; } } - (void) saveViewSize { - [[NSUserDefaults standardUserDefaults] setFloat: NSHeight([[self view] frame]) forKey: @"InspectorContentHeightTracker"]; + [NSUserDefaults.standardUserDefaults setFloat: NSHeight(self.view.frame) forKey: @"InspectorContentHeightTracker"]; } - (void) clearView @@ -141,7 +141,7 @@ - (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView { - return fTrackers ? [fTrackers count] : 0; + return fTrackers ? fTrackers.count : 0; } - (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (NSInteger) row @@ -154,7 +154,7 @@ NSString * tierString = tier == -1 ? NSLocalizedString(@"New Tier", "Inspector -> tracker table") : [NSString stringWithFormat: NSLocalizedString(@"Tier %d", "Inspector -> tracker table"), tier]; - if ([fTorrents count] > 1) + if (fTorrents.count > 1) tierString = [tierString stringByAppendingFormat: @" - %@", item[@"Name"]]; return tierString; } @@ -174,7 +174,7 @@ if ([fTrackers[row] isKindOfClass: [NSDictionary class]]) return TRACKER_GROUP_SEPARATOR_HEIGHT; else - return [tableView rowHeight]; + return tableView.rowHeight; } - (BOOL) tableView: (NSTableView *) tableView shouldEditTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row @@ -185,12 +185,12 @@ - (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 { - 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 @@ -198,7 +198,7 @@ { id node = fTrackers[row]; if ([node isKindOfClass: [TrackerNode class]]) - return [(TrackerNode *)node fullAnnounceAddress]; + return ((TrackerNode *)node).fullAnnounceAddress; else return nil; } @@ -217,19 +217,19 @@ NSBeep(); //reset table with either new or old value - fTrackers = [torrent allTrackerStats]; + fTrackers = torrent.allTrackerStats; [fTrackerTable setTrackers: fTrackers]; [fTrackerTable reloadData]; [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 { //don't allow add/remove when currently adding - it leads to weird results - if ([fTrackerTable editedRow] != -1) + if (fTrackerTable.editedRow != -1) return; [self updateInfo]; @@ -246,7 +246,7 @@ - (void) setupInfo { - const NSUInteger numberSelected = [fTorrents count]; + const NSUInteger numberSelected = fTorrents.count; if (numberSelected != 1) { if (numberSelected == 0) @@ -278,36 +278,37 @@ #warning doesn't like blank addresses - (void) addTrackers { - [[[self view] window] makeKeyWindow]; + [self.view.window makeKeyWindow]; - NSAssert1([fTorrents count] == 1, @"Attempting to add tracker with %ld transfers selected", [fTorrents count]); + NSAssert1(fTorrents.count == 1, @"Attempting to add tracker with %ld transfers selected", fTorrents.count); [fTrackers addObject: @{@"Tier": @-1}]; [fTrackers addObject: @""]; [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 { - 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]; - for (NSUInteger i = 0; i < [fTrackers count]; ++i) + for (NSUInteger i = 0; i < fTrackers.count; ++i) { id object = fTrackers[i]; if ([object isKindOfClass: [TrackerNode class]]) { + TrackerNode * node = (TrackerNode *)object; if (groupSelected || [selectedIndexes containsIndex: i]) { - Torrent * torrent = [(TrackerNode *)object torrent]; + Torrent * torrent = node.torrent; NSMutableSet * removeSet; if (!(removeSet = removeIdentifiers[torrent])) { @@ -315,7 +316,7 @@ removeIdentifiers[torrent] = removeSet; } - [removeSet addObject: [(TrackerNode *)object fullAnnounceAddress]]; + [removeSet addObject: node.fullAnnounceAddress]; ++removeTrackerCount; [removeIndexes addIndex: i]; @@ -330,7 +331,7 @@ [removeIndexes addIndex: groupRowIndex]; groupSelected = [selectedIndexes containsIndex: i]; - if (!groupSelected && i > [selectedIndexes lastIndex]) + if (!groupSelected && i > selectedIndexes.lastIndex) { groupRowIndex = NSNotFound; break; @@ -344,39 +345,39 @@ if (groupRowIndex != NSNotFound) [removeIndexes addIndex: groupRowIndex]; - NSAssert2(removeTrackerCount <= [removeIndexes count], @"Marked %ld trackers to remove, but only removing %ld rows", removeTrackerCount, [removeIndexes count]); + 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"]) + if ([NSUserDefaults.standardUserDefaults boolForKey: @"WarningRemoveTrackers"]) { NSAlert * alert = [[NSAlert alloc] init]; if (removeTrackerCount > 1) { - [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Are you sure you want to remove %d trackers?", - "Remove trackers alert -> title"), removeTrackerCount]]; - [alert setInformativeText: 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 setMessageText: NSLocalizedString(@"Are you sure you want to remove this tracker?", "Remove trackers alert -> title")]; - [alert setInformativeText: NSLocalizedString(@"Once removed, Transmission will no longer attempt to contact it." - " This cannot be undone.", "Remove trackers alert -> message")]; + 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 addButtonWithTitle: NSLocalizedString(@"Remove", "Remove trackers alert -> button")]; [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Remove trackers alert -> button")]; - [alert setShowsSuppressionButton: YES]; + alert.showsSuppressionButton = YES; NSInteger result = [alert runModal]; - if ([[alert suppressionButton] state] == NSOnState) - [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningRemoveTrackers"]; + if (alert.suppressionButton.state == NSOnState) + [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningRemoveTrackers"]; if (result != NSAlertFirstButtonReturn) return; @@ -391,7 +392,7 @@ //reset table with either new or old value fTrackers = [[NSMutableArray alloc] init]; for (Torrent * torrent in fTorrents) - [fTrackers addObjectsFromArray: [torrent allTrackerStats]]; + [fTrackers addObjectsFromArray: torrent.allTrackerStats]; [fTrackerTable removeRowsAtIndexes: removeIndexes withAnimation: NSTableViewAnimationSlideLeft]; @@ -399,7 +400,7 @@ [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/InfoWindowController.h b/macosx/InfoWindowController.h index f14e1a591..2639e8ac9 100644 --- a/macosx/InfoWindowController.h +++ b/macosx/InfoWindowController.h @@ -61,8 +61,8 @@ - (void) setNextTab; - (void) setPreviousTab; -- (NSArray *) quickLookURLs; -- (BOOL) canQuickLook; +@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 07c42519b..b58c463d4 100644 --- a/macosx/InfoWindowController.m +++ b/macosx/InfoWindowController.m @@ -44,15 +44,14 @@ #define INVALID -99 -typedef enum -{ +typedef NS_ENUM(unsigned int, tabTag) { TAB_GENERAL_TAG = 0, TAB_ACTIVITY_TAG = 1, TAB_TRACKERS_TAG = 2, TAB_PEERS_TAG = 3, TAB_FILE_TAG = 4, TAB_OPTIONS_TAG = 5 -} tabTag; +}; @interface InfoWindowController (Private) @@ -63,7 +62,7 @@ typedef enum @implementation InfoWindowController -- (id) init +- (instancetype) init { self = [super initWithWindowNibName: @"InfoWindow"]; return self; @@ -71,25 +70,25 @@ typedef enum - (void) awakeFromNib { - [fNoneSelectedField setStringValue: NSLocalizedString(@"No Torrents Selected", "Inspector -> selected torrents")]; + fNoneSelectedField.stringValue = NSLocalizedString(@"No Torrents Selected", "Inspector -> selected torrents"); //window location and size - NSPanel * window = (NSPanel *)[self window]; + NSPanel * window = (NSPanel *)self.window; - [window setFloatingPanel: NO]; + window.floatingPanel = NO; - const CGFloat windowHeight = NSHeight([window frame]); - fMinWindowWidth = [window minSize].width; + const CGFloat windowHeight = NSHeight(window.frame); + fMinWindowWidth = window.minSize.width; [window setFrameAutosaveName: @"InspectorWindow"]; [window setFrameUsingName: @"InspectorWindow"]; - NSRect windowRect = [window frame]; + NSRect windowRect = window.frame; windowRect.origin.y -= windowHeight - NSHeight(windowRect); windowRect.size.height = windowHeight; [window setFrame: windowRect display: NO]; - [window setBecomesKeyOnlyIfNeeded: YES]; + window.becomesKeyOnlyIfNeeded = YES; //set tab tooltips [fTabMatrix setToolTip: NSLocalizedString(@"General Info", "Inspector -> tab") forCell: [fTabMatrix cellWithTag: TAB_GENERAL_TAG]]; @@ -101,7 +100,7 @@ typedef enum //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; @@ -117,17 +116,17 @@ typedef enum tag = TAB_OPTIONS_TAG; else //safety { - [[NSUserDefaults standardUserDefaults] setObject: TAB_INFO_IDENT forKey: @"InspectorSelected"]; + [NSUserDefaults.standardUserDefaults setObject: TAB_INFO_IDENT forKey: @"InspectorSelected"]; tag = TAB_GENERAL_TAG; } [fTabMatrix selectCellWithTag: tag]; [self setTab: nil]; //set blank inspector - [self setInfoForTorrents: [NSArray array]]; + [self setInfoForTorrents: @[]]; //allow for update notifications - NSNotificationCenter * nc = [NSNotificationCenter defaultCenter]; + 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]; @@ -135,7 +134,7 @@ typedef enum - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; if ([fViewController respondsToSelector: @selector(saveViewSize)]) [fViewController saveViewSize]; @@ -153,14 +152,14 @@ typedef enum - (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame { - NSRect windowRect = [window frame]; - windowRect.size.width = [window minSize].width; + NSRect windowRect = window.frame; + windowRect.size.width = window.minSize.width; return windowRect; } - (void) windowWillClose: (NSNotification *) notification { - if (fCurrentTabTag == TAB_FILE_TAG && ([QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible])) + if (fCurrentTabTag == TAB_FILE_TAG && ([QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible)) [[QLPreviewPanel sharedPreviewPanel] reloadData]; } @@ -184,8 +183,8 @@ typedef enum if ([fViewController respondsToSelector: @selector(clearView)]) [fViewController clearView]; - NSView * oldView = [fViewController view]; - oldHeight = NSHeight([oldView frame]); + NSView * oldView = fViewController.view; + oldHeight = NSHeight(oldView.frame); //remove old view [oldView removeFromSuperview]; @@ -260,34 +259,34 @@ typedef enum return; } - [[NSUserDefaults standardUserDefaults] setObject: identifier forKey: @"InspectorSelected"]; + [NSUserDefaults.standardUserDefaults setObject: identifier forKey: @"InspectorSelected"]; - NSWindow * window = [self window]; + NSWindow * window = self.window; - [window setTitle: [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]; + NSRect windowRect = window.frame, viewRect = view.frame; const CGFloat difference = NSHeight(viewRect) - oldHeight; windowRect.origin.y -= difference; windowRect.size.height += difference; - const CGFloat minWindowWidth = MAX(fMinWindowWidth, [view fittingSize].width); + const CGFloat 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 ([window screen]) + if (window.screen) { - const CGFloat screenHeight = NSHeight([[window screen] visibleFrame]); + const CGFloat screenHeight = NSHeight(window.screen.visibleFrame); if (NSHeight(windowRect) > screenHeight) { const CGFloat difference = screenHeight - NSHeight(windowRect); @@ -298,39 +297,39 @@ typedef enum } } - [window setMinSize: NSMakeSize(minWindowWidth, NSHeight(windowRect) - NSHeight(viewRect) + TAB_MIN_HEIGHT)]; - [window setMaxSize: NSMakeSize(FLT_MAX, FLT_MAX)]; + window.minSize = NSMakeSize(minWindowWidth, NSHeight(windowRect) - NSHeight(viewRect) + TAB_MIN_HEIGHT); + window.maxSize = NSMakeSize(FLT_MAX, FLT_MAX); } else { - [window setMinSize: NSMakeSize(minWindowWidth, NSHeight(windowRect))]; - [window setMaxSize: NSMakeSize(FLT_MAX, NSHeight(windowRect))]; + window.minSize = NSMakeSize(minWindowWidth, NSHeight(windowRect)); + window.maxSize = NSMakeSize(FLT_MAX, NSHeight(windowRect)); } viewRect.size.width = NSWidth(windowRect); - [view setFrame: viewRect]; + view.frame = viewRect; [window setFrame: windowRect display: YES animate: oldTabTag != INVALID]; - [[window contentView] addSubview: view]; + [window.contentView addSubview: view]; - [[window contentView] addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"H:|-0-[view]-0-|" + [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-|" + [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] isVisible])) + && ([QLPreviewPanel sharedPreviewPanelExists] && [QLPreviewPanel sharedPreviewPanel].visible)) [[QLPreviewPanel sharedPreviewPanel] reloadData]; } - (void) setNextTab { NSInteger tag = [fTabMatrix selectedTag]+1; - if (tag >= [fTabMatrix numberOfColumns]) + if (tag >= fTabMatrix.numberOfColumns) tag = 0; [fTabMatrix selectCellWithTag: tag]; @@ -341,7 +340,7 @@ typedef enum { NSInteger tag = [fTabMatrix selectedTag]-1; if (tag < 0) - tag = [fTabMatrix numberOfColumns]-1; + tag = fTabMatrix.numberOfColumns-1; [fTabMatrix selectCellWithTag: tag]; [self setTab: nil]; @@ -349,9 +348,9 @@ typedef enum - (void) swipeWithEvent: (NSEvent *) event { - if ([event deltaX] < 0.0) + if (event.deltaX < 0.0) [self setNextTab]; - else if ([event deltaX] > 0.0) + else if (event.deltaX > 0.0) [self setPreviousTab]; } @@ -367,15 +366,15 @@ typedef enum - (NSArray *) quickLookURLs { - return [fFileViewController quickLookURLs]; + return fFileViewController.quickLookURLs; } - (BOOL) canQuickLook { - if (fCurrentTabTag != TAB_FILE_TAG || ![[self window] isVisible]) + if (fCurrentTabTag != TAB_FILE_TAG || !self.window.visible) return NO; - return [fFileViewController canQuickLook]; + return fFileViewController.canQuickLook; } - (NSRect) quickLookSourceFrameForPreviewItem: (id ) item @@ -389,25 +388,25 @@ typedef enum - (void) resetInfo { - const NSUInteger numberSelected = [fTorrents count]; + const NSUInteger numberSelected = fTorrents.count; if (numberSelected != 1) { if (numberSelected > 0) { - [fImageView setImage: [NSImage imageNamed: NSImageNameMultipleDocuments]]; + fImageView.image = [NSImage imageNamed: NSImageNameMultipleDocuments]; - [fNameField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ Torrents Selected", + fNameField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"%@ Torrents Selected", "Inspector -> selected torrents"), - [NSString formattedUInteger: numberSelected]]]; - [fNameField setHidden: NO]; + [NSString formattedUInteger: numberSelected]]; + fNameField.hidden = NO; uint64_t size = 0; NSUInteger fileCount = 0, magnetCount = 0; for (Torrent * torrent in fTorrents) { - size += [torrent size]; - fileCount += [torrent fileCount]; - if ([torrent isMagnet]) + size += torrent.size; + fileCount += torrent.fileCount; + if (torrent.magnet) ++magnetCount; } @@ -437,52 +436,52 @@ typedef enum if (magnetCount < numberSelected) { - [fBasicInfoField setStringValue: [NSString stringWithFormat: @"%@, %@", fileString, + fBasicInfoField.stringValue = [NSString stringWithFormat: @"%@, %@", fileString, [NSString stringWithFormat: NSLocalizedString(@"%@ total", "Inspector -> selected torrents"), - [NSString stringForFileSize: size]]]]; + [NSString stringForFileSize: size]]]; NSByteCountFormatter * formatter = [[NSByteCountFormatter alloc] init]; - [formatter setAllowedUnits: NSByteCountFormatterUseBytes]; - [fBasicInfoField setToolTip: [formatter stringFromByteCount: size]]; + formatter.allowedUnits = NSByteCountFormatterUseBytes; + fBasicInfoField.toolTip = [formatter stringFromByteCount: size]; } else { - [fBasicInfoField setStringValue: fileString]; - [fBasicInfoField setToolTip: nil]; + fBasicInfoField.stringValue = fileString; + fBasicInfoField.toolTip = nil; } - [fBasicInfoField setHidden: NO]; + fBasicInfoField.hidden = NO; - [fNoneSelectedField setHidden: YES]; + fNoneSelectedField.hidden = YES; } else { - [fImageView setImage: [NSImage imageNamed: NSImageNameApplicationIcon]]; - [fNoneSelectedField setHidden: NO]; + fImageView.image = [NSImage imageNamed: NSImageNameApplicationIcon]; + fNoneSelectedField.hidden = NO; - [fNameField setHidden: YES]; - [fBasicInfoField setHidden: YES]; + fNameField.hidden = YES; + fBasicInfoField.hidden = YES; } - [fNameField setToolTip: nil]; + fNameField.toolTip = nil; } else { Torrent * torrent = fTorrents[0]; - [fImageView setImage: [torrent icon]]; + fImageView.image = torrent.icon; - NSString * name = [torrent name]; - [fNameField setStringValue: name]; - [fNameField setToolTip: name]; - [fNameField setHidden: NO]; + NSString * name = torrent.name; + fNameField.stringValue = name; + fNameField.toolTip = name; + fNameField.hidden = NO; - if (![torrent isMagnet]) + if (!torrent.magnet) { - NSString * basicString = [NSString stringForFileSize: [torrent size]]; - if ([torrent isFolder]) + NSString * basicString = [NSString stringForFileSize: torrent.size]; + if (torrent.folder) { NSString * fileString; - const NSUInteger fileCount = [torrent fileCount]; + const NSUInteger fileCount = torrent.fileCount; if (fileCount == 1) fileString = NSLocalizedString(@"1 file", "Inspector -> selected torrents"); else @@ -490,20 +489,20 @@ typedef enum [NSString formattedUInteger: fileCount]]; basicString = [NSString stringWithFormat: @"%@, %@", fileString, basicString]; } - [fBasicInfoField setStringValue: basicString]; + fBasicInfoField.stringValue = basicString; NSByteCountFormatter * formatter = [[NSByteCountFormatter alloc] init]; - [formatter setAllowedUnits: NSByteCountFormatterUseBytes]; - [fBasicInfoField setToolTip: [formatter stringFromByteCount: [torrent size]]]; + formatter.allowedUnits = NSByteCountFormatterUseBytes; + fBasicInfoField.toolTip = [formatter stringFromByteCount: torrent.size]; } else { - [fBasicInfoField setStringValue: NSLocalizedString(@"Magnetized transfer", "Inspector -> selected torrents")]; - [fBasicInfoField setToolTip: nil]; + fBasicInfoField.stringValue = NSLocalizedString(@"Magnetized transfer", "Inspector -> selected torrents"); + fBasicInfoField.toolTip = nil; } - [fBasicInfoField setHidden: NO]; + fBasicInfoField.hidden = NO; - [fNoneSelectedField setHidden: YES]; + fNoneSelectedField.hidden = YES; } [fGeneralViewController setInfoForTorrents: fTorrents]; @@ -518,7 +517,7 @@ typedef enum - (void) resetInfoForTorrent: (NSNotification *) notification { - Torrent * torrent = [notification userInfo][@"Torrent"]; + Torrent * torrent = notification.userInfo[@"Torrent"]; if (fTorrents && (!torrent || [fTorrents containsObject: torrent])) [self resetInfo]; } diff --git a/macosx/MessageWindowController.m b/macosx/MessageWindowController.m index d43070760..8cb8f5818 100644 --- a/macosx/MessageWindowController.m +++ b/macosx/MessageWindowController.m @@ -46,70 +46,70 @@ @implementation MessageWindowController -- (id) init +- (instancetype) init { return [super initWithWindowNibName: @"MessageWindow"]; } - (void) awakeFromNib { - NSWindow * window = [self window]; - [window setFrameAutosaveName: @"MessageWindowFrame"]; + NSWindow * window = self.window; + window.frameAutosaveName = @"MessageWindowFrame"; [window setFrameUsingName: @"MessageWindowFrame"]; - [window setRestorationClass: [self class]]; + window.restorationClass = [self class]; - [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(resizeColumn) + [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] setTitle: NSLocalizedString(@"Message Log", "Message window -> title")]; + self.window.title = NSLocalizedString(@"Message Log", "Message window -> title"); //set images and text for popup button items - [[fLevelButton itemAtIndex: LEVEL_ERROR] setTitle: NSLocalizedString(@"Error", "Message window -> level string")]; - [[fLevelButton itemAtIndex: LEVEL_INFO] setTitle: NSLocalizedString(@"Info", "Message window -> level string")]; - [[fLevelButton itemAtIndex: LEVEL_DEBUG] setTitle: 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]); + const CGFloat levelButtonOldWidth = NSWidth(fLevelButton.frame); [fLevelButton sizeToFit]; //set table column text - [[[fMessageTable tableColumnWithIdentifier: @"Date"] headerCell] setTitle: NSLocalizedString(@"Date", - "Message window -> table column")]; - [[[fMessageTable tableColumnWithIdentifier: @"Name"] headerCell] setTitle: NSLocalizedString(@"Process", - "Message window -> table column")]; - [[[fMessageTable tableColumnWithIdentifier: @"Message"] headerCell] setTitle: 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 setTitle: [NSLocalizedString(@"Save", "Message window -> save button") stringByAppendingEllipsis]]; + fSaveButton.title = [NSLocalizedString(@"Save", "Message window -> save button") stringByAppendingEllipsis]; [fSaveButton sizeToFit]; - NSRect saveButtonFrame = [fSaveButton frame]; + NSRect saveButtonFrame = fSaveButton.frame; saveButtonFrame.size.width += 10.0; - saveButtonFrame.origin.x += NSWidth([fLevelButton frame]) - levelButtonOldWidth; - [fSaveButton setFrame: saveButtonFrame]; + saveButtonFrame.origin.x += NSWidth(fLevelButton.frame) - levelButtonOldWidth; + fSaveButton.frame = saveButtonFrame; - const CGFloat oldClearButtonWidth = [fClearButton frame].size.width; + const CGFloat oldClearButtonWidth = fClearButton.frame.size.width; - [fClearButton setTitle: NSLocalizedString(@"Clear", "Message window -> save button")]; + fClearButton.title = NSLocalizedString(@"Clear", "Message window -> save button"); [fClearButton sizeToFit]; - NSRect clearButtonFrame = [fClearButton frame]; + NSRect clearButtonFrame = fClearButton.frame; clearButtonFrame.size.width = MAX(clearButtonFrame.size.width + 10.0, saveButtonFrame.size.width); clearButtonFrame.origin.x -= NSWidth(clearButtonFrame) - oldClearButtonWidth; - [fClearButton setFrame: clearButtonFrame]; + fClearButton.frame = clearButtonFrame; - [[fFilterField cell] setPlaceholderString: NSLocalizedString(@"Filter", "Message window -> filter field")]; - NSRect filterButtonFrame = [fFilterField frame]; + [fFilterField.cell setPlaceholderString: NSLocalizedString(@"Filter", "Message window -> filter field")]; + NSRect filterButtonFrame = fFilterField.frame; filterButtonFrame.origin.x -= NSWidth(clearButtonFrame) - oldClearButtonWidth; - [fFilterField setFrame: filterButtonFrame]; + fFilterField.frame = filterButtonFrame; - fAttributes = [[[[fMessageTable tableColumnWithIdentifier: @"Message"] dataCell] attributedStringValue] + 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]; @@ -121,7 +121,7 @@ [fLevelButton selectItemAtIndex: LEVEL_DEBUG]; break; default: //safety - [[NSUserDefaults standardUserDefaults] setInteger: TR_LOG_ERROR forKey: @"MessageLevel"]; + [NSUserDefaults.standardUserDefaults setInteger: TR_LOG_ERROR forKey: @"MessageLevel"]; [fLevelButton selectItemAtIndex: LEVEL_ERROR]; } @@ -133,7 +133,7 @@ - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; [fTimer invalidate]; } @@ -156,7 +156,7 @@ { 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); } @@ -177,21 +177,21 @@ static NSUInteger currentIndex = 0; - NSScroller * scroller = [[fMessageTable enclosingScrollView] verticalScroller]; - const BOOL shouldScroll = currentIndex == 0 || [scroller floatValue] == 1.0 || [scroller isHidden] - || [scroller knobProportion] == 1.0; + NSScroller * scroller = fMessageTable.enclosingScrollView.verticalScroller; + const BOOL shouldScroll = currentIndex == 0 || scroller.floatValue == 1.0 || scroller.hidden + || scroller.knobProportion == 1.0; - const NSInteger maxLevel = [[NSUserDefaults standardUserDefaults] integerForKey: @"MessageLevel"]; - NSString * filterString = [fFilterField stringValue]; + const NSInteger maxLevel = [NSUserDefaults.standardUserDefaults integerForKey: @"MessageLevel"]; + NSString * filterString = fFilterField.stringValue; BOOL changed = NO; for (tr_log_message * currentMessage = messages; currentMessage != NULL; currentMessage = currentMessage->next) { NSString * name = currentMessage->name != NULL ? @(currentMessage->name) - : [[NSProcessInfo processInfo] processName]; + : NSProcessInfo.processInfo.processName; - NSString * file = [[@(currentMessage->file) lastPathComponent] stringByAppendingFormat: @":%d", + NSString * file = [(@(currentMessage->file)).lastPathComponent stringByAppendingFormat: @":%d", currentMessage->line]; NSDictionary * message = @{ @@ -210,26 +210,26 @@ } } - if ([fMessages count] > TR_LOG_MAX_QUEUE_LENGTH) + if (fMessages.count > TR_LOG_MAX_QUEUE_LENGTH) { - const NSUInteger oldCount = [fDisplayedMessages count]; + const NSUInteger oldCount = fDisplayedMessages.count; - NSIndexSet * removeIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fMessages count]-TR_LOG_MAX_QUEUE_LENGTH)]; + NSIndexSet * removeIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, fMessages.count-TR_LOG_MAX_QUEUE_LENGTH)]; NSArray * itemsToRemove = [fMessages objectsAtIndexes: removeIndexes]; [fMessages removeObjectsAtIndexes: removeIndexes]; [fDisplayedMessages removeObjectsInArray: itemsToRemove]; - changed |= oldCount > [fDisplayedMessages count]; + 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]; @@ -239,12 +239,12 @@ - (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView { - return [fDisplayedMessages count]; + return fDisplayedMessages.count; } - (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (NSInteger) row { - NSString * ident = [column identifier]; + NSString * ident = column.identifier; NSDictionary * message = fDisplayedMessages[row]; if ([ident isEqualToString: @"Date"]) @@ -277,14 +277,14 @@ NSString * message = fDisplayedMessages[row][@"Message"]; NSTableColumn * column = [tableView tableColumnWithIdentifier: @"Message"]; - const CGFloat count = floorf([message sizeWithAttributes: fAttributes].width / [column width]); + const CGFloat count = floorf([message sizeWithAttributes: fAttributes].width / column.width); - return [tableView rowHeight] * (count + 1.0); + return tableView.rowHeight * (count + 1.0); } - (void) tableView: (NSTableView *) tableView sortDescriptorsDidChange: (NSArray *) oldDescriptors { - [fDisplayedMessages sortUsingDescriptors: [fMessageTable sortDescriptors]]; + [fDisplayedMessages sortUsingDescriptors: fMessageTable.sortDescriptors]; [fMessageTable reloadData]; } @@ -297,25 +297,25 @@ - (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]]; NSString * messageString = [messageStrings componentsJoinedByString: @"\n"]; - NSPasteboard * pb = [NSPasteboard generalPasteboard]; + NSPasteboard * pb = NSPasteboard.generalPasteboard; [pb clearContents]; [pb writeObjects: @[messageString]]; } - (BOOL) validateMenuItem: (NSMenuItem *) menuItem { - SEL action = [menuItem action]; + SEL action = menuItem.action; if (action == @selector(copy:)) - return [fMessageTable numberOfSelectedRows] > 0; + return fMessageTable.numberOfSelectedRows > 0; return YES; } @@ -323,7 +323,7 @@ - (void) changeLevel: (id) sender { NSInteger level; - switch ([fLevelButton indexOfSelectedItem]) + switch (fLevelButton.indexOfSelectedItem) { case LEVEL_ERROR: level = TR_LOG_ERROR; @@ -339,10 +339,10 @@ 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]; @@ -367,7 +367,7 @@ [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]; @@ -379,35 +379,35 @@ - (void) writeToFile: (id) sender { NSSavePanel * panel = [NSSavePanel savePanel]; - [panel setAllowedFileTypes: @[@"txt"]]; - [panel setCanSelectHiddenExtension: YES]; + panel.allowedFileTypes = @[@"txt"]; + panel.canSelectHiddenExtension = YES; - [panel setNameFieldStringValue: NSLocalizedString(@"untitled", "Save log panel -> default file name")]; + 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 = [[NSArray alloc] initWithObjects: descriptor, nil]; + NSArray * descriptors = @[descriptor]; NSArray * sortedMessages = [fDisplayedMessages sortedArrayUsingDescriptors: descriptors]; //create the text to output - NSMutableArray * messageStrings = [NSMutableArray arrayWithCapacity: [sortedMessages count]]; + 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]) + 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 setMessageText: NSLocalizedString(@"Log Could Not Be Saved", "Save log alert panel -> title")]; - [alert setInformativeText: [NSString stringWithFormat: + 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 setAlertStyle: NSWarningAlertStyle]; + "Save log alert panel -> message"), panel.URL.path.lastPathComponent]; + alert.alertStyle = NSWarningAlertStyle; [alert runModal]; } @@ -422,7 +422,7 @@ - (void) resizeColumn { [fMessageTable noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: - NSMakeRange(0, [fMessageTable numberOfRows])]]; + NSMakeRange(0, fMessageTable.numberOfRows)]]; } - (BOOL) shouldIncludeMessageForFilter: (NSString *) filterString message: (NSDictionary *) message @@ -437,14 +437,14 @@ - (void) updateListForFilter { - const NSInteger level = [[NSUserDefaults standardUserDefaults] integerForKey: @"MessageLevel"]; - NSString * filterString = [fFilterField stringValue]; + const NSInteger 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]; }]; - NSArray * tempMessages = [[fMessages objectsAtIndexes: indexes] sortedArrayUsingDescriptors: [fMessageTable sortDescriptors]]; + NSArray * tempMessages = [[fMessages objectsAtIndexes: indexes] sortedArrayUsingDescriptors: fMessageTable.sortDescriptors]; [fMessageTable beginUpdates]; @@ -455,7 +455,7 @@ for (NSDictionary * message in tempMessages) { - const NSUInteger previousIndex = [fDisplayedMessages indexOfObject: message inRange: NSMakeRange(currentIndex, [fDisplayedMessages count]-currentIndex)]; + const NSUInteger previousIndex = [fDisplayedMessages indexOfObject: message inRange: NSMakeRange(currentIndex, fDisplayedMessages.count-currentIndex)]; if (previousIndex == NSNotFound) { [itemsToAdd addObject: message]; @@ -475,9 +475,9 @@ } //remove trailing items - those are the unused - if (currentIndex < [fDisplayedMessages count]) + if (currentIndex < fDisplayedMessages.count) { - const NSRange removeRange = NSMakeRange(currentIndex, [fDisplayedMessages count]-currentIndex); + const NSRange removeRange = NSMakeRange(currentIndex, fDisplayedMessages.count-currentIndex); [fDisplayedMessages removeObjectsInRange: removeRange]; [fMessageTable removeRowsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: removeRange] withAnimation: NSTableViewAnimationSlideDown]; } diff --git a/macosx/NSApplicationAdditions.h b/macosx/NSApplicationAdditions.h index eb35935d5..249f23527 100644 --- a/macosx/NSApplicationAdditions.h +++ b/macosx/NSApplicationAdditions.h @@ -24,7 +24,7 @@ @interface NSApplication (NSApplicationAdditions) -- (BOOL) isOnMojaveOrBetter; -- (BOOL) isDarkMode; +@property (nonatomic, getter=isOnMojaveOrBetter, readonly) BOOL onMojaveOrBetter; +@property (nonatomic, getter=isDarkMode, readonly) BOOL darkMode; @end diff --git a/macosx/NSImageAdditions.m b/macosx/NSImageAdditions.m index 95de01ef8..a38af25ee 100644 --- a/macosx/NSImageAdditions.m +++ b/macosx/NSImageAdditions.m @@ -32,7 +32,7 @@ [color set]; - const NSSize size = [coloredImage size]; + const NSSize size = coloredImage.size; NSRectFillUsingOperation(NSMakeRect(0.0, 0.0, size.width, size.height), NSCompositeSourceAtop); [coloredImage unlockFocus]; diff --git a/macosx/NSStringAdditions.h b/macosx/NSStringAdditions.h index a69faae22..36094d5a4 100644 --- a/macosx/NSStringAdditions.h +++ b/macosx/NSStringAdditions.h @@ -24,7 +24,7 @@ @interface NSString (NSStringAdditions) -+ (NSString *) ellipsis; +@property (nonatomic, class, readonly) NSString * ellipsis; - (NSString *) stringByAppendingEllipsis; + (NSString *) formattedUInteger: (NSUInteger) value; diff --git a/macosx/NSStringAdditions.m b/macosx/NSStringAdditions.m index 480afe9d5..4d631353b 100644 --- a/macosx/NSStringAdditions.m +++ b/macosx/NSStringAdditions.m @@ -43,7 +43,7 @@ - (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 @@ -76,7 +76,7 @@ partialUnitsSame = magnitudePartial == magnitudeFull; } - [fileSizeFormatter setIncludesUnit: !partialUnitsSame]; + fileSizeFormatter.includesUnit = !partialUnitsSame; NSString * partialString = [fileSizeFormatter stringFromByteCount: partialSize]; @@ -127,16 +127,16 @@ - (NSComparisonResult) compareNumeric: (NSString *) string { const NSStringCompareOptions comparisonOptions = NSNumericSearch | NSForcedOrderingSearch; - return [self compare: string options: comparisonOptions range: NSMakeRange(0, [self length]) locale: [NSLocale currentLocale]]; + return [self compare: string options: comparisonOptions range: NSMakeRange(0, self.length) locale: NSLocale.currentLocale]; } - (NSArray *) betterComponentsSeparatedByCharactersInSet: (NSCharacterSet *) separators { NSMutableArray * components = [NSMutableArray array]; - NSCharacterSet * includededCharSet = [separators invertedSet]; + NSCharacterSet * includededCharSet = separators.invertedSet; NSUInteger index = 0; - const NSUInteger fullLength = [self length]; + const NSUInteger fullLength = self.length; do { const NSUInteger start = [self rangeOfCharacterFromSet: includededCharSet options: 0 range: NSMakeRange(index, fullLength - index)].location; @@ -195,9 +195,9 @@ //match Finder's behavior NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init]; - [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle]; - [numberFormatter setMinimumFractionDigits: 0]; - [numberFormatter setMaximumFractionDigits: decimals]; + numberFormatter.numberStyle = NSNumberFormatterDecimalStyle; + numberFormatter.minimumFractionDigits = 0; + numberFormatter.maximumFractionDigits = decimals; NSString * fileSizeString = [numberFormatter stringFromNumber: @(convertedSize)]; diff --git a/macosx/PeerProgressIndicatorCell.m b/macosx/PeerProgressIndicatorCell.m index bbfff633b..2e396248b 100644 --- a/macosx/PeerProgressIndicatorCell.m +++ b/macosx/PeerProgressIndicatorCell.m @@ -41,19 +41,19 @@ - (void) drawWithFrame: (NSRect) cellFrame inView: (NSView *) controlView { - if ([[NSUserDefaults standardUserDefaults] boolForKey: @"DisplayPeerProgressBarNumber"]) + if ([NSUserDefaults.standardUserDefaults boolForKey: @"DisplayPeerProgressBarNumber"]) { if (!fAttributes) { - NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; - [paragraphStyle setAlignment: NSRightTextAlignment]; + NSMutableParagraphStyle * paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + paragraphStyle.alignment = NSRightTextAlignment; 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 { @@ -68,7 +68,7 @@ { NSImage * checkImage = [NSImage imageNamed: @"CompleteCheck"]; - const NSSize imageSize = [checkImage size]; + 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); diff --git a/macosx/PeerTableView.m b/macosx/PeerTableView.m index 4dd203dce..79e974531 100644 --- a/macosx/PeerTableView.m +++ b/macosx/PeerTableView.m @@ -26,13 +26,13 @@ - (void) mouseDown: (NSEvent *) event { - NSPoint point = [self convertPoint: [event locationInWindow] fromView: nil]; + NSPoint point = [self convertPoint: event.locationInWindow fromView: nil]; if ([self rowAtPoint: point] != -1 && [self columnAtPoint: point] == [self columnWithIdentifier: @"Progress"]) { - [[NSUserDefaults standardUserDefaults] setBool: ![[NSUserDefaults standardUserDefaults] + [NSUserDefaults.standardUserDefaults setBool: ![NSUserDefaults.standardUserDefaults boolForKey: @"DisplayPeerProgressBarNumber"] forKey: @"DisplayPeerProgressBarNumber"]; - NSIndexSet * rowIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [self numberOfRows])], + NSIndexSet * rowIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, self.numberOfRows)], * columnIndexes = [NSIndexSet indexSetWithIndex: [self columnAtPoint: point]]; [self reloadDataForRowIndexes: rowIndexes columnIndexes: columnIndexes]; } diff --git a/macosx/PiecesView.m b/macosx/PiecesView.m index 0a86b6ed7..4602bbbb5 100644 --- a/macosx/PiecesView.m +++ b/macosx/PiecesView.m @@ -62,27 +62,27 @@ enum { [self clearView]; - fTorrent = (torrent && ![torrent isMagnet]) ? torrent : nil; + fTorrent = (torrent && !torrent.magnet) ? torrent : nil; if (fTorrent) { //determine relevant values - fNumPieces = MIN([fTorrent pieceCount], MAX_ACROSS * MAX_ACROSS); + fNumPieces = MIN(fTorrent.pieceCount, MAX_ACROSS * MAX_ACROSS); fAcross = ceil(sqrt(fNumPieces)); - const CGFloat width = [self bounds].size.width; + const CGFloat 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]; + [gradient drawInRect: self.bounds angle: 90.0]; [back unlockFocus]; - [self setImage: back]; + self.image = back; [self setNeedsDisplay]; } @@ -106,7 +106,7 @@ enum int8_t * pieces = NULL; float * piecesPercent = NULL; - const BOOL showAvailablity = [[NSUserDefaults standardUserDefaults] boolForKey: @"PiecesViewShowAvailability"]; + const BOOL showAvailablity = [NSUserDefaults.standardUserDefaults boolForKey: @"PiecesViewShowAvailability"]; if (showAvailablity) { pieces = (int8_t *)tr_malloc(fNumPieces * sizeof(int8_t)); @@ -118,7 +118,7 @@ enum [fTorrent getAmountFinished: piecesPercent size: fNumPieces]; } - NSImage * image = [self image]; + NSImage * image = self.image; NSRect fillRects[fNumPieces]; NSColor * fillColors[fNumPieces]; @@ -135,7 +135,7 @@ enum { if (!first && fPieces[index] != PIECE_FLASHING) { - pieceColor = [NSColor orangeColor]; + pieceColor = NSColor.orangeColor; fPieces[index] = PIECE_FLASHING; } else @@ -149,7 +149,7 @@ enum { if (first || fPieces[index] != PIECE_NONE) { - pieceColor = [NSColor whiteColor]; + pieceColor = NSColor.whiteColor; fPieces[index] = PIECE_NONE; } } @@ -166,7 +166,7 @@ enum //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]; + pieceColor = [NSColor.whiteColor blendedColorWithFraction: percent ofColor: fullColor]; fPieces[index] = PIECE_SOME; } @@ -175,7 +175,7 @@ enum const NSInteger across = index % fAcross, down = index / fAcross; fillRects[usedCount] = NSMakeRect(across * (fWidth + BETWEEN) + BETWEEN + fExtraBorder, - [image size].width - (down + 1) * (fWidth + BETWEEN) - fExtraBorder, + image.size.width - (down + 1) * (fWidth + BETWEEN) - fExtraBorder, fWidth, fWidth); fillColors[usedCount] = pieceColor; @@ -204,10 +204,10 @@ enum { if (fTorrent) { - const BOOL availability = ![[NSUserDefaults standardUserDefaults] boolForKey: @"PiecesViewShowAvailability"]; - [[NSUserDefaults standardUserDefaults] setBool: availability forKey: @"PiecesViewShowAvailability"]; + const BOOL availability = ![NSUserDefaults.standardUserDefaults boolForKey: @"PiecesViewShowAvailability"]; + [NSUserDefaults.standardUserDefaults setBool: availability forKey: @"PiecesViewShowAvailability"]; - [self sendAction:[self action] to:[self target]]; + [self sendAction:self.action to:self.target]; } [super mouseDown: event]; diff --git a/macosx/PortChecker.h b/macosx/PortChecker.h index 9f34da8c6..2a56fb725 100644 --- a/macosx/PortChecker.h +++ b/macosx/PortChecker.h @@ -22,13 +22,12 @@ #import -typedef enum -{ +typedef NS_ENUM(unsigned int, port_status_t) { PORT_STATUS_CHECKING, PORT_STATUS_OPEN, PORT_STATUS_CLOSED, PORT_STATUS_ERROR -} port_status_t; +}; @interface PortChecker : NSObject { @@ -41,9 +40,9 @@ typedef enum NSTimer * fTimer; } -- (id) initForPort: (NSInteger) portNumber delay: (BOOL) delay withDelegate: (id) delegate; +- (instancetype) initForPort: (NSInteger) portNumber delay: (BOOL) delay withDelegate: (id) delegate; - (void) cancelProbe; -- (port_status_t) status; +@property (nonatomic, readonly) port_status_t status; @end diff --git a/macosx/PortChecker.m b/macosx/PortChecker.m index ec474904b..c95c1c6c9 100644 --- a/macosx/PortChecker.m +++ b/macosx/PortChecker.m @@ -35,7 +35,7 @@ @implementation PortChecker -- (id) initForPort: (NSInteger) portNumber delay: (BOOL) delay withDelegate: (id) delegate +- (instancetype) initForPort: (NSInteger) portNumber delay: (BOOL) delay withDelegate: (id) delegate { if ((self = [super init])) { @@ -71,7 +71,7 @@ - (void) connection: (NSURLConnection *) connection didReceiveResponse: (NSURLResponse *) response { - [fPortProbeData setLength: 0]; + fPortProbeData.length = 0; } - (void) connection: (NSURLConnection *) connection didReceiveData: (NSData *) data @@ -81,7 +81,7 @@ - (void) connection: (NSURLConnection *) connection didFailWithError: (NSError *) error { - NSLog(@"Unable to get port status: connection failed (%@)", [error localizedDescription]); + NSLog(@"Unable to get port status: connection failed (%@)", error.localizedDescription); [self callBackWithStatus: PORT_STATUS_ERROR]; } diff --git a/macosx/PredicateEditorRowTemplateAny.m b/macosx/PredicateEditorRowTemplateAny.m index 57fca0f96..3eb6da78a 100644 --- a/macosx/PredicateEditorRowTemplateAny.m +++ b/macosx/PredicateEditorRowTemplateAny.m @@ -30,11 +30,11 @@ NSComparisonPredicate * predicate = (NSComparisonPredicate *)[super predicateWithSubpredicates: subpredicates]; //construct a near-identical predicate - return [NSComparisonPredicate predicateWithLeftExpression: [predicate leftExpression] - rightExpression: [predicate rightExpression] + return [NSComparisonPredicate predicateWithLeftExpression: predicate.leftExpression + rightExpression: predicate.rightExpression modifier: NSAnyPredicateModifier - type: [predicate predicateOperatorType] - options: [predicate options]]; + type: predicate.predicateOperatorType + options: predicate.options]; } @end diff --git a/macosx/PrefsController.h b/macosx/PrefsController.h index 3717e7c2c..ea7ee1f47 100644 --- a/macosx/PrefsController.h +++ b/macosx/PrefsController.h @@ -67,7 +67,7 @@ NSString * fRPCPassword; } -- (id) initWithHandle: (tr_session *) handle; +- (instancetype) initWithHandle: (tr_session *) handle; - (void) setAutoUpdateToBeta: (id) sender; @@ -78,7 +78,7 @@ - (void) updatePortStatus; - (void) portCheckerDidFinishProbing: (PortChecker *) portChecker; -- (NSArray *) sounds; +@property (nonatomic, readonly) NSArray *sounds; - (void) setSound: (id) sender; - (void) setUTP: (id) sender; diff --git a/macosx/PrefsController.m b/macosx/PrefsController.m index d509f9865..145e4976a 100644 --- a/macosx/PrefsController.m +++ b/macosx/PrefsController.m @@ -67,13 +67,13 @@ @implementation PrefsController -- (id) initWithHandle: (tr_session *) handle +- (instancetype) initWithHandle: (tr_session *) handle { if ((self = [super initWithWindowNibName: @"PrefsWindow"])) { fHandle = handle; - fDefaults = [NSUserDefaults standardUserDefaults]; + fDefaults = NSUserDefaults.standardUserDefaults; //check for old version download location (before 1.1) NSString * choice; @@ -93,9 +93,9 @@ [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: [NSString stringWithUTF8String: DEFAULT_BLOCKLIST_FILENAME]] + 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]; } @@ -107,13 +107,13 @@ 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]; + [((Controller *)NSApp.delegate).fileWatcherQueue addPath: autoPath.stringByExpandingTildeInPath notifyingAbout: VDKQueueNotifyAboutWrite]; //set special-handling of magnet link add window checkbox [self updateShowAddMagnetWindowField]; //set blocklist scheduler - [[BlocklistScheduler scheduler] updateSchedule]; + [BlocklistScheduler.scheduler updateSchedule]; //set encryption [self setEncryptionMode: nil]; @@ -142,7 +142,7 @@ - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; [fPortStatusTimer invalidate]; if (fPortChecker) @@ -155,15 +155,15 @@ { fHasLoaded = YES; - [[self window] setRestorationClass: [self class]]; + self.window.restorationClass = [self class]; NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"Preferences Toolbar"]; - [toolbar setDelegate: self]; - [toolbar setAllowsUserCustomization: NO]; - [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel]; - [toolbar setSizeMode: NSToolbarSizeModeRegular]; - [toolbar setSelectedItemIdentifier: TOOLBAR_GENERAL]; - [[self window] setToolbar: toolbar]; + toolbar.delegate = self; + toolbar.allowsUserCustomization = NO; + toolbar.displayMode = NSToolbarDisplayModeIconAndLabel; + toolbar.sizeMode = NSToolbarSizeModeRegular; + toolbar.selectedItemIdentifier = TOOLBAR_GENERAL; + self.window.toolbar = toolbar; [self setPrefView: nil]; @@ -171,63 +171,63 @@ [fFolderPopUp selectItemAtIndex: [fDefaults boolForKey: @"DownloadLocationConstant"] ? DOWNLOAD_FOLDER : DOWNLOAD_TORRENT]; //set stop ratio - [fRatioStopField setFloatValue: [fDefaults floatForKey: @"RatioLimit"]]; + fRatioStopField.floatValue = [fDefaults floatForKey: @"RatioLimit"]; //set idle seeding minutes - [fIdleStopField setIntegerValue: [fDefaults integerForKey: @"IdleLimitMinutes"]]; + fIdleStopField.integerValue = [fDefaults integerForKey: @"IdleLimitMinutes"]; //set limits [self updateLimitFields]; //set speed limit - [fSpeedLimitUploadField setIntValue: [fDefaults integerForKey: @"SpeedLimitUploadLimit"]]; - [fSpeedLimitDownloadField setIntValue: [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]]; + fSpeedLimitUploadField.intValue = [fDefaults integerForKey: @"SpeedLimitUploadLimit"]; + fSpeedLimitDownloadField.intValue = [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]; //set port - [fPortField setIntValue: [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]; //set peer connections - [fPeersGlobalField setIntValue: [fDefaults integerForKey: @"PeersTotal"]]; - [fPeersTorrentField setIntValue: [fDefaults integerForKey: @"PeersTorrent"]]; + fPeersGlobalField.intValue = [fDefaults integerForKey: @"PeersTotal"]; + fPeersTorrentField.intValue = [fDefaults integerForKey: @"PeersTorrent"]; //set queue values - [fQueueDownloadField setIntValue: [fDefaults integerForKey: @"QueueDownloadNumber"]]; - [fQueueSeedField setIntValue: [fDefaults integerForKey: @"QueueSeedNumber"]]; - [fStalledField setIntValue: [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"]; if (blocklistURL) - [fBlocklistURLField setStringValue: blocklistURL]; + fBlocklistURLField.stringValue = blocklistURL; [self updateBlocklistButton]; [self updateBlocklistFields]; - [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateLimitFields) + [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateLimitFields) name: @"UpdateSpeedLimitValuesOutsidePrefs" object: nil]; - [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateRatioStopField) + [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateRatioStopField) name: @"UpdateRatioStopValueOutsidePrefs" object: nil]; - [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateLimitStopField) + [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateLimitStopField) name: @"UpdateIdleStopValueOutsidePrefs" object: nil]; - [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateBlocklistFields) + [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateBlocklistFields) name: @"BlocklistUpdated" object: nil]; - [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateBlocklistURLField) + [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(updateBlocklistURLField) name: NSControlTextDidChangeNotification object: fBlocklistURLField]; //set rpc port - [fRPCPortField setIntValue: [fDefaults integerForKey: @"RPCPort"]]; + fRPCPortField.intValue = [fDefaults integerForKey: @"RPCPort"]; //set rpc password if (fRPCPassword) - [fRPCPasswordField setStringValue: fRPCPassword]; + fRPCPasswordField.stringValue = fRPCPassword; } - (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag @@ -236,91 +236,87 @@ if ([ident isEqualToString: TOOLBAR_GENERAL]) { - [item setLabel: NSLocalizedString(@"General", "Preferences -> toolbar item title")]; + item.label = NSLocalizedString(@"General", "Preferences -> toolbar item title"); if (@available(macOS 11.0, *)) { - [item setImage: [NSImage imageWithSystemSymbolName: @"gearshape" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"gearshape" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: NSImageNamePreferencesGeneral]]; + item.image = [NSImage imageNamed: NSImageNamePreferencesGeneral]; } - [item setTarget: self]; - [item setAction: @selector(setPrefView:)]; - [item setAutovalidates: NO]; + item.target = self; + item.action = @selector(setPrefView:); + item.autovalidates = NO; } else if ([ident isEqualToString: TOOLBAR_TRANSFERS]) { - [item setLabel: NSLocalizedString(@"Transfers", "Preferences -> toolbar item title")]; - [item setImage: [NSImage imageNamed: @"Transfers"]]; + item.label = NSLocalizedString(@"Transfers", "Preferences -> toolbar item title"); if (@available(macOS 11.0, *)) { - [item setImage: [NSImage imageWithSystemSymbolName: @"arrow.up.arrow.down" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"arrow.up.arrow.down" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: @"Transfers"]]; + item.image = [NSImage imageNamed: @"Transfers"]; } - [item setTarget: self]; - [item setAction: @selector(setPrefView:)]; - [item setAutovalidates: NO]; + item.target = self; + item.action = @selector(setPrefView:); + item.autovalidates = NO; } else if ([ident isEqualToString: TOOLBAR_GROUPS]) { - [item setLabel: NSLocalizedString(@"Groups", "Preferences -> toolbar item title")]; - [item setImage: [NSImage imageNamed: @"Groups"]]; + item.label = NSLocalizedString(@"Groups", "Preferences -> toolbar item title"); if (@available(macOS 11.0, *)) { - [item setImage: [NSImage imageWithSystemSymbolName: @"pin" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"pin" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: @"Groups"]]; + item.image = [NSImage imageNamed: @"Groups"]; } - [item setTarget: self]; - [item setAction: @selector(setPrefView:)]; - [item setAutovalidates: NO]; + item.target = self; + item.action = @selector(setPrefView:); + item.autovalidates = NO; } else if ([ident isEqualToString: TOOLBAR_BANDWIDTH]) { - [item setLabel: NSLocalizedString(@"Bandwidth", "Preferences -> toolbar item title")]; - [item setImage: [NSImage imageNamed: @"Bandwidth"]]; + item.label = NSLocalizedString(@"Bandwidth", "Preferences -> toolbar item title"); if (@available(macOS 11.0, *)) { - [item setImage: [NSImage imageWithSystemSymbolName: @"speedometer" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"speedometer" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: @"Bandwidth"]]; + item.image = [NSImage imageNamed: @"Bandwidth"]; } - [item setTarget: self]; - [item setAction: @selector(setPrefView:)]; - [item setAutovalidates: NO]; + item.target = self; + item.action = @selector(setPrefView:); + item.autovalidates = NO; } else if ([ident isEqualToString: TOOLBAR_PEERS]) { - [item setLabel: NSLocalizedString(@"Peers", "Preferences -> toolbar item title")]; - [item setImage: [NSImage imageNamed: NSImageNameUserGroup]]; + item.label = NSLocalizedString(@"Peers", "Preferences -> toolbar item title"); if (@available(macOS 11.0, *)) { - [item setImage: [NSImage imageWithSystemSymbolName: @"person.2" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"person.2" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: NSImageNameUserGroup]]; + item.image = [NSImage imageNamed: NSImageNameUserGroup]; } - [item setTarget: self]; - [item setAction: @selector(setPrefView:)]; - [item setAutovalidates: NO]; + item.target = self; + item.action = @selector(setPrefView:); + item.autovalidates = NO; } else if ([ident isEqualToString: TOOLBAR_NETWORK]) { - [item setLabel: NSLocalizedString(@"Network", "Preferences -> toolbar item title")]; + item.label = NSLocalizedString(@"Network", "Preferences -> toolbar item title"); if (@available(macOS 11.0, *)) { - [item setImage: [NSImage imageWithSystemSymbolName: @"network" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"network" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: NSImageNameNetwork]]; + item.image = [NSImage imageNamed: NSImageNameNetwork]; } - [item setTarget: self]; - [item setAction: @selector(setPrefView:)]; - [item setAutovalidates: NO]; + item.target = self; + item.action = @selector(setPrefView:); + item.autovalidates = NO; } else if ([ident isEqualToString: TOOLBAR_REMOTE]) { - [item setLabel: NSLocalizedString(@"Remote", "Preferences -> toolbar item title")]; + item.label = NSLocalizedString(@"Remote", "Preferences -> toolbar item title"); if (@available(macOS 11.0, *)) { - [item setImage: [NSImage imageWithSystemSymbolName: @"antenna.radiowaves.left.and.right" accessibilityDescription: nil]]; + item.image = [NSImage imageWithSystemSymbolName: @"antenna.radiowaves.left.and.right" accessibilityDescription: nil]; } else { - [item setImage: [NSImage imageNamed: @"Remote"]]; + item.image = [NSImage imageNamed: @"Remote"]; } - [item setTarget: self]; - [item setAction: @selector(setPrefView:)]; - [item setAutovalidates: NO]; + item.target = self; + item.action = @selector(setPrefView:); + item.autovalidates = NO; } else { @@ -348,7 +344,7 @@ + (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); } @@ -377,7 +373,7 @@ { const tr_port port = tr_sessionSetPeerPortRandom(fHandle); [fDefaults setInteger: port forKey: @"BindPort"]; - [fPortField setIntValue: port]; + fPortField.intValue = port; fPeerPort = -1; [self updatePortStatus]; @@ -385,7 +381,7 @@ - (void) setRandomPortOnStart: (id) sender { - tr_sessionSetPeerPortRandomOnStart(fHandle, [(NSButton *)sender state] == NSOnState); + tr_sessionSetPeerPortRandomOnStart(fHandle, ((NSButton *)sender).state == NSOnState); } - (void) setNat: (id) sender @@ -408,8 +404,8 @@ fNatStatus = fwd; fPeerPort = port; - [fPortStatusField setStringValue: @""]; - [fPortStatusImage setImage: nil]; + fPortStatusField.stringValue = @""; + fPortStatusImage.image = nil; [fPortStatusProgress startAnimation: self]; if (fPortChecker) @@ -424,22 +420,22 @@ - (void) portCheckerDidFinishProbing: (PortChecker *) portChecker { [fPortStatusProgress stopAnimation: self]; - switch ([fPortChecker status]) + switch (fPortChecker.status) { case PORT_STATUS_OPEN: - [fPortStatusField setStringValue: NSLocalizedString(@"Port is open", "Preferences -> Network -> port status")]; - [fPortStatusImage setImage: [NSImage imageNamed: NSImageNameStatusAvailable]]; + fPortStatusField.stringValue = NSLocalizedString(@"Port is open", "Preferences -> Network -> port status"); + fPortStatusImage.image = [NSImage imageNamed: NSImageNameStatusAvailable]; break; case PORT_STATUS_CLOSED: - [fPortStatusField setStringValue: NSLocalizedString(@"Port is closed", "Preferences -> Network -> port status")]; - [fPortStatusImage setImage: [NSImage imageNamed: NSImageNameStatusUnavailable]]; + fPortStatusField.stringValue = NSLocalizedString(@"Port is closed", "Preferences -> Network -> port status"); + fPortStatusImage.image = [NSImage imageNamed: NSImageNameStatusUnavailable]; break; case PORT_STATUS_ERROR: - [fPortStatusField setStringValue: NSLocalizedString(@"Port check site is down", "Preferences -> Network -> port status")]; - [fPortStatusImage setImage: [NSImage imageNamed: NSImageNameStatusPartiallyAvailable]]; + 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]); + NSAssert1(NO, @"Port checker returned invalid status: %d", fPortChecker.status); break; } fPortChecker = nil; @@ -456,12 +452,12 @@ 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]; + NSArray * directoryContents = [NSFileManager.defaultManager contentsOfDirectoryAtPath: directory error: NULL]; for (__strong NSString * sound in directoryContents) { - sound = [sound stringByDeletingPathExtension]; + sound = sound.stringByDeletingPathExtension; if ([NSSound soundNamed: sound]) [sounds addObject: sound]; } @@ -524,7 +520,7 @@ { tr_blocklistSetEnabled(fHandle, [fDefaults boolForKey: @"BlocklistNew"]); - [[BlocklistScheduler scheduler] updateSchedule]; + [BlocklistScheduler.scheduler updateSchedule]; [self updateBlocklistButton]; } @@ -536,7 +532,7 @@ - (void) setBlocklistAutoUpdate: (id) sender { - [[BlocklistScheduler scheduler] updateSchedule]; + [BlocklistScheduler.scheduler updateSchedule]; } - (void) updateBlocklistFields @@ -546,12 +542,12 @@ if (exists) { NSString * countString = [NSString formattedUInteger: tr_blocklistGetRuleCount(fHandle)]; - [fBlocklistMessageField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ IP address rules in list", - "Prefs -> blocklist -> message"), countString]]; + fBlocklistMessageField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"%@ IP address rules in list", + "Prefs -> blocklist -> message"), countString]; } else - [fBlocklistMessageField setStringValue: NSLocalizedString(@"A blocklist must first be downloaded", - "Prefs -> blocklist -> message")]; + fBlocklistMessageField.stringValue = NSLocalizedString(@"A blocklist must first be downloaded", + "Prefs -> blocklist -> message"); NSString * updatedDateString; if (exists) @@ -566,16 +562,16 @@ else updatedDateString = NSLocalizedString(@"Never", "Prefs -> blocklist -> message"); - [fBlocklistDateField setStringValue: [NSString stringWithFormat: @"%@: %@", - NSLocalizedString(@"Last updated", "Prefs -> blocklist -> message"), updatedDateString]]; + fBlocklistDateField.stringValue = [NSString stringWithFormat: @"%@: %@", + NSLocalizedString(@"Last updated", "Prefs -> blocklist -> message"), updatedDateString]; } - (void) updateBlocklistURLField { - NSString * blocklistString = [fBlocklistURLField stringValue]; + NSString * blocklistString = fBlocklistURLField.stringValue; [fDefaults setObject: blocklistString forKey: @"BlocklistURL"]; - tr_blocklistSetURL(fHandle, [blocklistString UTF8String]); + tr_blocklistSetURL(fHandle, blocklistString.UTF8String); [self updateBlocklistButton]; } @@ -585,7 +581,7 @@ NSString * blocklistString = [fDefaults objectForKey: @"BlocklistURL"]; const BOOL enable = (blocklistString && ![blocklistString isEqualToString: @""]) && [fDefaults boolForKey: @"BlocklistNew"]; - [fBlocklistButton setEnabled: enable]; + fBlocklistButton.enabled = enable; } - (void) setAutoStartDownloads: (id) sender @@ -601,7 +597,7 @@ 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 @@ -609,7 +605,7 @@ 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 @@ -618,10 +614,10 @@ 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 @@ -634,7 +630,7 @@ - (void) updateRatioStopField { if (fHasLoaded) - [fRatioStopField setFloatValue: [fDefaults floatForKey: @"RatioLimit"]]; + fRatioStopField.floatValue = [fDefaults floatForKey: @"RatioLimit"]; } - (void) updateRatioStopFieldOld @@ -650,10 +646,10 @@ 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 @@ -666,7 +662,7 @@ - (void) updateLimitStopField { if (fHasLoaded) - [fIdleStopField setIntegerValue: [fDefaults integerForKey: @"IdleLimitMinutes"]]; + fIdleStopField.integerValue = [fDefaults integerForKey: @"IdleLimitMinutes"]; } - (void) updateLimitFields @@ -674,8 +670,8 @@ if (!fHasLoaded) return; - [fUploadField setIntValue: [fDefaults integerForKey: @"UploadLimit"]]; - [fDownloadField setIntValue: [fDefaults integerForKey: @"DownloadLimit"]]; + fUploadField.intValue = [fDefaults integerForKey: @"UploadLimit"]; + fDownloadField.intValue = [fDefaults integerForKey: @"DownloadLimit"]; } - (void) setGlobalLimit: (id) sender @@ -704,28 +700,28 @@ - (void) setAutoSpeedLimitDay: (id) sender { - tr_sessionSetAltSpeedDay(fHandle, [[sender selectedItem] tag]); + tr_sessionSetAltSpeedDay(fHandle, [sender selectedItem].tag); } + (NSInteger) dateToTimeSum: (NSDate *) date { - NSCalendar * calendar = [NSCalendar currentCalendar]; + NSCalendar * calendar = NSCalendar.currentCalendar; NSDateComponents * components = [calendar components: NSCalendarUnitHour | NSCalendarUnitMinute fromDate: date]; - return [components hour] * 60 + [components minute]; + return components.hour * 60 + components.minute; } + (NSDate *) timeSumToDate: (NSInteger) sum { NSDateComponents * comps = [[NSDateComponents alloc] init]; - [comps setHour: sum / 60]; - [comps setMinute: sum % 60]; + 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 { - fInitialString = [control stringValue]; + fInitialString = control.stringValue; return YES; } @@ -735,7 +731,7 @@ NSBeep(); if (fInitialString) { - [control setStringValue: fInitialString]; + control.stringValue = fInitialString; fInitialString = nil; } return NO; @@ -743,12 +739,12 @@ - (void) setBadge: (id) sender { - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateUI" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: self]; } - (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 @@ -768,7 +764,7 @@ - (void) setDefaultForMagnets: (id) sender { - NSString * bundleID = [[NSBundle mainBundle] bundleIdentifier]; + NSString * bundleID = NSBundle.mainBundle.bundleIdentifier; const OSStatus result = LSSetDefaultHandlerForURLScheme((CFStringRef)@"magnet", (__bridge CFStringRef)bundleID); if (result != noErr) NSLog(@"Failed setting default magnet link handler"); @@ -781,7 +777,7 @@ 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 @@ -799,7 +795,7 @@ 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 @@ -809,12 +805,12 @@ 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 { - [fDefaults setBool: [fFolderPopUp indexOfSelectedItem] == DOWNLOAD_FOLDER forKey: @"DownloadLocationConstant"]; + [fDefaults setBool: fFolderPopUp.indexOfSelectedItem == DOWNLOAD_FOLDER forKey: @"DownloadLocationConstant"]; [self updateShowAddMagnetWindowField]; } @@ -822,24 +818,24 @@ { NSOpenPanel * panel = [NSOpenPanel openPanel]; - [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")]; - [panel setAllowsMultipleSelection: NO]; - [panel setCanChooseFiles: NO]; - [panel setCanChooseDirectories: YES]; - [panel setCanCreateDirectories: YES]; + panel.prompt = NSLocalizedString(@"Select", "Preferences -> Open panel prompt"); + panel.allowsMultipleSelection = NO; + panel.canChooseFiles = NO; + 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]; - NSString * folder = [[panel URLs][0] path]; + NSString * folder = panel.URLs[0].path; [fDefaults setObject: folder forKey: @"DownloadFolder"]; [fDefaults setBool: YES forKey: @"DownloadLocationConstant"]; [self updateShowAddMagnetWindowField]; assert(folder.length > 0); - tr_sessionSetDownloadDir(fHandle, [folder fileSystemRepresentation]); + tr_sessionSetDownloadDir(fHandle, folder.fileSystemRepresentation); } else { @@ -853,20 +849,20 @@ { NSOpenPanel * panel = [NSOpenPanel openPanel]; - [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")]; - [panel setAllowsMultipleSelection: NO]; - [panel setCanChooseFiles: NO]; - [panel setCanChooseDirectories: YES]; - [panel setCanCreateDirectories: YES]; + panel.prompt = NSLocalizedString(@"Select", "Preferences -> Open panel prompt"); + panel.allowsMultipleSelection = NO; + panel.canChooseFiles = NO; + 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]; + NSString * folder = panel.URLs[0].path; [fDefaults setObject: folder forKey: @"IncompleteDownloadFolder"]; assert(folder.length > 0); - tr_sessionSetIncompleteDir(fHandle, [folder fileSystemRepresentation]); + tr_sessionSetIncompleteDir(fHandle, folder.fileSystemRepresentation); } [fIncompleteFolderPopUp selectItemAtIndex: 0]; }]; @@ -876,21 +872,21 @@ { NSOpenPanel * panel = [NSOpenPanel openPanel]; - [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")]; - [panel setAllowsMultipleSelection: NO]; - [panel setCanChooseFiles: YES]; - [panel setCanChooseDirectories: NO]; - [panel setCanCreateDirectories: NO]; + panel.prompt = NSLocalizedString(@"Select", "Preferences -> Open panel prompt"); + panel.allowsMultipleSelection = NO; + panel.canChooseFiles = YES; + 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"]; - tr_sessionSetTorrentDoneScript(fHandle, [filePath fileSystemRepresentation]); + tr_sessionSetTorrentDoneScript(fHandle, filePath.fileSystemRepresentation); [fDefaults setBool: YES forKey: @"DoneScriptEnabled"]; tr_sessionSetTorrentDoneScriptEnabled(fHandle, YES); @@ -911,7 +907,7 @@ - (void) setShowAddMagnetWindow: (id) sender { - [fDefaults setBool: ([fShowMagnetAddWindowCheck state] == NSOnState) forKey: @"MagnetOpenAsk"]; + [fDefaults setBool: (fShowMagnetAddWindowCheck.state == NSOnState) forKey: @"MagnetOpenAsk"]; } - (void) updateShowAddMagnetWindowField @@ -919,19 +915,19 @@ if (![fDefaults boolForKey: @"DownloadLocationConstant"]) { //always show the add window for magnet links when the download location is the same as the torrent file - [fShowMagnetAddWindowCheck setState: NSOnState]; - [fShowMagnetAddWindowCheck setEnabled: NO]; + fShowMagnetAddWindowCheck.state = NSOnState; + fShowMagnetAddWindowCheck.enabled = NO; } else { - [fShowMagnetAddWindowCheck setState: [fDefaults boolForKey: @"MagnetOpenAsk"]]; - [fShowMagnetAddWindowCheck setEnabled: YES]; + fShowMagnetAddWindowCheck.state = [fDefaults boolForKey: @"MagnetOpenAsk"]; + fShowMagnetAddWindowCheck.enabled = YES; } } - (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"]; @@ -945,16 +941,16 @@ NSString * path; if ((path = [fDefaults stringForKey: @"AutoImportDirectory"])) { - VDKQueue * watcherQueue = [(Controller *)[NSApp delegate] fileWatcherQueue]; + VDKQueue * watcherQueue = ((Controller *)NSApp.delegate).fileWatcherQueue; if ([fDefaults boolForKey: @"AutoImport"]) { - path = [path stringByExpandingTildeInPath]; + path = path.stringByExpandingTildeInPath; [watcherQueue addPath: path notifyingAbout: VDKQueueNotifyAboutWrite]; } else [watcherQueue removeAllPaths]; - [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoImportSettingChange" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"AutoImportSettingChange" object: self]; } else [self importFolderSheetShow: nil]; @@ -964,23 +960,23 @@ { NSOpenPanel * panel = [NSOpenPanel openPanel]; - [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")]; - [panel setAllowsMultipleSelection: NO]; - [panel setCanChooseFiles: NO]; - [panel setCanChooseDirectories: YES]; - [panel setCanCreateDirectories: YES]; + panel.prompt = NSLocalizedString(@"Select", "Preferences -> Open panel prompt"); + panel.allowsMultipleSelection = NO; + panel.canChooseFiles = NO; + 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]; + NSString * path = (panel.URLs[0]).path; [fDefaults setObject: path forKey: @"AutoImportDirectory"]; - [watcherQueue addPath: [path stringByExpandingTildeInPath] notifyingAbout: VDKQueueNotifyAboutWrite]; + [watcherQueue addPath: path.stringByExpandingTildeInPath notifyingAbout: VDKQueueNotifyAboutWrite]; - [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoImportSettingChange" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"AutoImportSettingChange" object: self]; } else { @@ -995,7 +991,7 @@ - (void) setAutoSize: (id) sender { - [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoSizeSettingChange" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"AutoSizeSettingChange" object: self]; } - (void) setRPCEnabled: (id) sender @@ -1009,7 +1005,7 @@ - (void) linkWebUI: (id) sender { NSString * urlString = [NSString stringWithFormat: WEBUI_URL, [fDefaults integerForKey: @"RPCPort"]]; - [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: urlString]]; + [NSWorkspace.sharedWorkspace openURL: [NSURL URLWithString: urlString]]; } - (void) setRPCAuthorize: (id) sender @@ -1019,14 +1015,14 @@ - (void) setRPCUsername: (id) sender { - tr_sessionSetRPCUsername(fHandle, [[fDefaults stringForKey: @"RPCUsername"] UTF8String]); + tr_sessionSetRPCUsername(fHandle, [fDefaults stringForKey: @"RPCUsername"].UTF8String); } - (void) setRPCPassword: (id) sender { fRPCPassword = [[sender stringValue] copy]; - const char * password = [[sender stringValue] UTF8String]; + const char * password = [sender stringValue].UTF8String; [self setKeychainPassword: password forService: RPC_KEYCHAIN_SERVICE username: RPC_KEYCHAIN_NAME]; tr_sessionSetRPCPassword(fHandle, password); @@ -1049,7 +1045,7 @@ tr_sessionSetRPCPassword(fHandle, fullPassword); fRPCPassword = [[NSString alloc] initWithUTF8String: fullPassword]; - [fRPCPasswordField setStringValue: fRPCPassword]; + fRPCPasswordField.stringValue = fRPCPassword; } else fRPCPassword = nil; @@ -1072,29 +1068,29 @@ - (void) setRPCWebUIDiscovery: (id) sender { if ([fDefaults boolForKey:@"RPC"] && [fDefaults boolForKey: @"RPCWebDiscovery"]) - [[BonjourController defaultController] startWithPort: [fDefaults integerForKey: @"RPCPort"]]; + [BonjourController.defaultController startWithPort: [fDefaults integerForKey: @"RPCPort"]]; else { - if ([BonjourController defaultControllerExists]) - [[BonjourController defaultController] stop]; + if (BonjourController.defaultControllerExists) + [BonjourController.defaultController stop]; } } - (void) updateRPCWhitelist { NSString * string = [fRPCWhitelistArray componentsJoinedByString: @","]; - tr_sessionSetRPCWhitelist(fHandle, [string UTF8String]); + tr_sessionSetRPCWhitelist(fHandle, string.UTF8String); } - (void) addRemoveRPCIP: (id) sender { //don't allow add/remove when currently adding - it leads to weird results - if ([fRPCWhitelistTable editedRow] != -1) + if (fRPCWhitelistTable.editedRow != -1) return; if ([[sender cell] tagForSegment: [sender selectedSegment]] == RPC_IP_REMOVE_TAG) { - [fRPCWhitelistArray removeObjectsAtIndexes: [fRPCWhitelistTable selectedRowIndexes]]; + [fRPCWhitelistArray removeObjectsAtIndexes: fRPCWhitelistTable.selectedRowIndexes]; [fRPCWhitelistTable deselectAll: self]; [fRPCWhitelistTable reloadData]; @@ -1106,7 +1102,7 @@ [fRPCWhitelistArray addObject: @""]; [fRPCWhitelistTable reloadData]; - const int row = [fRPCWhitelistArray count] - 1; + const int row = fRPCWhitelistArray.count - 1; [fRPCWhitelistTable selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; [fRPCWhitelistTable editColumn: 0 row: row withEvent: nil select: YES]; } @@ -1114,7 +1110,7 @@ - (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView { - return [fRPCWhitelistArray count]; + return fRPCWhitelistArray.count; } - (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row @@ -1130,7 +1126,7 @@ //create better-formatted ip string BOOL valid = false; - if ([components count] == 4) + if (components.count == 4) { valid = true; for (NSString * component in components) @@ -1139,9 +1135,9 @@ [newComponents addObject: component]; else { - int num = [component intValue]; + int num = component.intValue; if (num >= 0 && num < 256) - [newComponents addObject: [@(num) stringValue]]; + [newComponents addObject: @(num).stringValue]; else { valid = false; @@ -1182,31 +1178,31 @@ - (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 { - [[NSHelpManager sharedHelpManager] openHelpAnchor: @"script" - inBook: [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleHelpBookName"]]; + [NSHelpManager.sharedHelpManager openHelpAnchor: @"script" + inBook: [NSBundle.mainBundle objectForInfoDictionaryKey: @"CFBundleHelpBookName"]]; } - (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 { - [[NSHelpManager sharedHelpManager] openHelpAnchor: @"network" - inBook: [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleHelpBookName"]]; + [NSHelpManager.sharedHelpManager openHelpAnchor: @"network" + inBook: [NSBundle.mainBundle objectForInfoDictionaryKey: @"CFBundleHelpBookName"]]; } - (void) helpForRemote: (id) sender { - [[NSHelpManager sharedHelpManager] openHelpAnchor: @"remote" - inBook: [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleHelpBookName"]]; + [NSHelpManager.sharedHelpManager openHelpAnchor: @"remote" + inBook: [NSBundle.mainBundle objectForInfoDictionaryKey: @"CFBundleHelpBookName"]]; } - (void) rpcUpdatePrefs @@ -1217,10 +1213,10 @@ [fDefaults setBool: encryptionMode == TR_ENCRYPTION_REQUIRED forKey: @"EncryptionRequire"]; //download directory - NSString * downloadLocation = [@(tr_sessionGetDownloadDir(fHandle)) stringByStandardizingPath]; + NSString * downloadLocation = @(tr_sessionGetDownloadDir(fHandle)).stringByStandardizingPath; [fDefaults setObject: downloadLocation forKey: @"DownloadFolder"]; - NSString * incompleteLocation = [@(tr_sessionGetIncompleteDir(fHandle)) stringByStandardizingPath]; + NSString * incompleteLocation = @(tr_sessionGetIncompleteDir(fHandle)).stringByStandardizingPath; [fDefaults setObject: incompleteLocation forKey: @"IncompleteDownloadFolder"]; const BOOL useIncomplete = tr_sessionIsIncompleteDirEnabled(fHandle); @@ -1365,8 +1361,8 @@ //utp handled by bindings - [fPeersGlobalField setIntValue: peersTotal]; - [fPeersTorrentField setIntValue: peersTorrent]; + fPeersGlobalField.intValue = peersTotal; + fPeersTorrentField.intValue = peersTorrent; //pex handled by bindings @@ -1374,46 +1370,46 @@ //lpd handled by bindings - [fPortField setIntValue: port]; + fPortField.intValue = port; //port forwarding (nat) handled by bindings //random port handled by bindings //limit check handled by bindings - [fDownloadField setIntValue: downLimit]; + fDownloadField.intValue = downLimit; //limit check handled by bindings - [fUploadField setIntValue: upLimit]; + fUploadField.intValue = upLimit; - [fSpeedLimitDownloadField setIntValue: downLimitAlt]; + fSpeedLimitDownloadField.intValue = downLimitAlt; - [fSpeedLimitUploadField setIntValue: upLimitAlt]; + fSpeedLimitUploadField.intValue = upLimitAlt; //speed limit schedule handled by bindings //speed limit schedule times and day handled by bindings - [fBlocklistURLField setStringValue: blocklistURL]; + fBlocklistURLField.stringValue = blocklistURL; [self updateBlocklistButton]; [self updateBlocklistFields]; //ratio limit enabled handled by bindings - [fRatioStopField setFloatValue: ratioLimit]; + fRatioStopField.floatValue = ratioLimit; //idle limit enabled handled by bindings - [fIdleStopField setIntegerValue: idleLimitMin]; + fIdleStopField.integerValue = idleLimitMin; //queues enabled handled by bindings - [fQueueDownloadField setIntValue: downloadQueueNum]; - [fQueueSeedField setIntValue: seedQueueNum]; + fQueueDownloadField.intValue = downloadQueueNum; + fQueueSeedField.intValue = seedQueueNum; //check stalled handled by bindings - [fStalledField setIntValue: stalledMinutes]; + 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 @@ -1426,10 +1422,10 @@ 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]) @@ -1450,33 +1446,33 @@ view = fGeneralView; } - [[[self window] toolbar] setSelectedItemIdentifier: identifier]; + self.window.toolbar.selectedItemIdentifier = identifier; - NSWindow * window = [self window]; - if ([window contentView] == view) + NSWindow * window = self.window; + if (window.contentView == view) return; - NSRect windowRect = [window frame]; - const CGFloat difference = NSHeight([view frame]) - NSHeight([[window contentView] frame]); + NSRect windowRect = window.frame; + const CGFloat difference = NSHeight(view.frame) - NSHeight(window.contentView.frame); windowRect.origin.y -= difference; windowRect.size.height += difference; - [view setHidden: YES]; - [window setContentView: view]; + view.hidden = YES; + window.contentView = view; [window setFrame: windowRect display: YES animate: YES]; - [view setHidden: NO]; + view.hidden = NO; //set title label if (sender) - [window setTitle: [sender label]]; + 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 setTitle: [item label]]; + window.title = item.label; break; } } @@ -1484,7 +1480,7 @@ 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 diff --git a/macosx/PrefsWindow.m b/macosx/PrefsWindow.m index 8d288b494..9e84ff4f0 100644 --- a/macosx/PrefsWindow.m +++ b/macosx/PrefsWindow.m @@ -34,7 +34,7 @@ - (void) keyDown: (NSEvent *) event { - if ([event keyCode] == 53) //esc key + if (event.keyCode == 53) //esc key [self close]; else [super keyDown: event]; diff --git a/macosx/ProgressGradients.h b/macosx/ProgressGradients.h index eb0d0883c..5b8c069e0 100644 --- a/macosx/ProgressGradients.h +++ b/macosx/ProgressGradients.h @@ -25,15 +25,15 @@ @interface ProgressGradients : NSObject -+ (NSGradient *) progressWhiteGradient; -+ (NSGradient *) progressGrayGradient; -+ (NSGradient *) progressLightGrayGradient; -+ (NSGradient *) progressBlueGradient; -+ (NSGradient *) progressDarkBlueGradient; -+ (NSGradient *) progressGreenGradient; -+ (NSGradient *) progressLightGreenGradient; -+ (NSGradient *) progressDarkGreenGradient; -+ (NSGradient *) progressRedGradient; -+ (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 7926bd2fe..597bd39d6 100644 --- a/macosx/ProgressGradients.m +++ b/macosx/ProgressGradients.m @@ -27,7 +27,7 @@ + (NSGradient *) progressGradientForRed: (CGFloat) redComponent green: (CGFloat) greenComponent blue: (CGFloat) blueComponent { - const CGFloat alpha = [[NSUserDefaults standardUserDefaults] boolForKey: @"SmallView"] ? 0.27 : 1.0; + const CGFloat alpha = [NSUserDefaults.standardUserDefaults boolForKey: @"SmallView"] ? 0.27 : 1.0; NSColor * baseColor = [NSColor colorWithCalibratedRed: redComponent green: greenComponent blue: blueComponent alpha: alpha]; diff --git a/macosx/ShareToolbarItem.m b/macosx/ShareToolbarItem.m index 450264770..4f1e052d4 100644 --- a/macosx/ShareToolbarItem.m +++ b/macosx/ShareToolbarItem.m @@ -14,17 +14,17 @@ - (NSMenuItem *) menuFormRepresentation { - NSMenuItem * menuItem = [[NSMenuItem alloc] initWithTitle: [self label] action: nil keyEquivalent: @""]; - [menuItem setEnabled: [[self target] validateToolbarItem: self]]; + NSMenuItem * menuItem = [[NSMenuItem alloc] initWithTitle: self.label action: nil keyEquivalent: @""]; + menuItem.enabled = [self.target validateToolbarItem: self]; - if ([menuItem isEnabled]) { + if (menuItem.enabled) { NSMenu *servicesMenu = [[NSMenu alloc] initWithTitle: @""]; - for (NSMenuItem * item in [[ShareTorrentFileHelper sharedHelper] menuItems]) + for (NSMenuItem * item in ShareTorrentFileHelper.sharedHelper.menuItems) { [servicesMenu addItem:item]; } - [menuItem setSubmenu:servicesMenu]; + menuItem.submenu = servicesMenu; } return menuItem; diff --git a/macosx/ShareTorrentFileHelper.h b/macosx/ShareTorrentFileHelper.h index 52d1a1559..5a2a6950c 100644 --- a/macosx/ShareTorrentFileHelper.h +++ b/macosx/ShareTorrentFileHelper.h @@ -10,9 +10,9 @@ @interface ShareTorrentFileHelper : NSObject -+ (ShareTorrentFileHelper *) sharedHelper; +@property (nonatomic, class, readonly) ShareTorrentFileHelper * sharedHelper; -- (NSArray *) shareTorrentURLs; -- (NSArray *) menuItems; +@property (nonatomic, readonly) NSArray *shareTorrentURLs; +@property (nonatomic, readonly) NSArray *menuItems; @end diff --git a/macosx/ShareTorrentFileHelper.m b/macosx/ShareTorrentFileHelper.m index fe4d1c47d..e8f194a6b 100644 --- a/macosx/ShareTorrentFileHelper.m +++ b/macosx/ShareTorrentFileHelper.m @@ -24,12 +24,12 @@ - (NSArray *) shareTorrentURLs { - NSArray * torrents = [(Controller *)[NSApp delegate] selectedTorrents]; - NSMutableArray * fileURLs = [NSMutableArray arrayWithCapacity: [torrents count]]; + 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) { + NSString * location = torrent.torrentLocation; + if (location.length > 0) { [fileURLs addObject: [NSURL fileURLWithPath: location]]; } } @@ -38,8 +38,8 @@ - (NSArray *) menuItems { - NSArray * services = [NSSharingService sharingServicesForItems: [self shareTorrentURLs]]; - NSMutableArray * items = [NSMutableArray arrayWithCapacity: [services count]]; + 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 @@ -47,7 +47,7 @@ keyEquivalent: @""]; item.image = service.image; item.representedObject = service; - service.delegate = (Controller *)[NSApp delegate]; + service.delegate = (Controller *)NSApp.delegate; item.target = self; [items addObject: item]; } @@ -58,7 +58,7 @@ - (void) performShareAction: (NSMenuItem *) item { NSSharingService * service = item.representedObject; - [service performWithItems: [self shareTorrentURLs]]; // on 10.9, use attachmentFileURLs? + [service performWithItems: self.shareTorrentURLs]; // on 10.9, use attachmentFileURLs? } @end diff --git a/macosx/StatsWindowController.h b/macosx/StatsWindowController.h index 3028871e0..58bdc7896 100644 --- a/macosx/StatsWindowController.h +++ b/macosx/StatsWindowController.h @@ -33,7 +33,7 @@ NSTimer * fTimer; } -+ (StatsWindowController *) statsWindow; +@property (nonatomic, class, readonly) StatsWindowController * statsWindow; - (void) resetStats: (id) sender; diff --git a/macosx/StatsWindowController.m b/macosx/StatsWindowController.m index fd304cd2b..88b7e7289 100644 --- a/macosx/StatsWindowController.m +++ b/macosx/StatsWindowController.m @@ -45,13 +45,13 @@ tr_session * fLib = NULL; { if ((fStatsWindowInstance = [[self alloc] init])) { - fLib = [(Controller *)[NSApp delegate] sessionHandle]; + fLib = ((Controller *)NSApp.delegate).sessionHandle; } } return fStatsWindowInstance; } -- (id) init +- (instancetype) init { return [super initWithWindowNibName: @"StatsWindow"]; } @@ -61,22 +61,22 @@ tr_session * fLib = NULL; [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]; + [NSRunLoop.currentRunLoop addTimer: fTimer forMode: NSModalPanelRunLoopMode]; + [NSRunLoop.currentRunLoop addTimer: fTimer forMode: NSEventTrackingRunLoopMode]; - [[self window] setRestorationClass: [self class]]; + self.window.restorationClass = [self class]; - [[self window] setTitle: NSLocalizedString(@"Statistics", "Stats window -> title")]; + self.window.title = NSLocalizedString(@"Statistics", "Stats window -> title"); //set label text - [fUploadedLabelField setStringValue: [NSLocalizedString(@"Uploaded", "Stats window -> label") stringByAppendingString: @":"]]; - [fDownloadedLabelField setStringValue: [NSLocalizedString(@"Downloaded", "Stats window -> label") stringByAppendingString: @":"]]; - [fRatioLabelField setStringValue: [NSLocalizedString(@"Ratio", "Stats window -> label") stringByAppendingString: @":"]]; - [fTimeLabelField setStringValue: [NSLocalizedString(@"Running Time", "Stats window -> label") stringByAppendingString: @":"]]; - [fNumOpenedLabelField setStringValue: [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; + const CGFloat oldWidth = fUploadedLabelField.frame.size.width; NSArray * labels = @[fUploadedLabelField, fDownloadedLabelField, fRatioLabelField, fTimeLabelField, fNumOpenedLabelField]; @@ -85,32 +85,32 @@ tr_session * fLib = NULL; { [label sizeToFit]; - const CGFloat width = [label frame].size.width; + const CGFloat width = label.frame.size.width; maxWidth = MAX(maxWidth, width); } for (NSTextField * label in labels) { - NSRect frame = [label frame]; + NSRect frame = label.frame; frame.size.width = maxWidth; - [label setFrame: frame]; + label.frame = frame; } //resize window for new label width - fields are set in nib to adjust correctly - NSRect windowRect = [[self window] frame]; + 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; + const CGFloat oldButtonWidth = fResetButton.frame.size.width; - [fResetButton setTitle: NSLocalizedString(@"Reset", "Stats window -> reset button")]; + fResetButton.title = NSLocalizedString(@"Reset", "Stats window -> reset button"); [fResetButton sizeToFit]; - NSRect buttonFrame = [fResetButton frame]; + NSRect buttonFrame = fResetButton.frame; buttonFrame.size.width += 10.0; buttonFrame.origin.x -= buttonFrame.size.width - oldButtonWidth; - [fResetButton setFrame: buttonFrame]; + fResetButton.frame = buttonFrame; } - (void) windowWillClose: (id) sender @@ -124,31 +124,31 @@ tr_session * fLib = NULL; { NSAssert1([identifier isEqualToString: @"StatsWindow"], @"Trying to restore unexpected identifier %@", identifier); - completionHandler([[StatsWindowController statsWindow] window], nil); + completionHandler(StatsWindowController.statsWindow.window, nil); } - (void) resetStats: (id) sender { - if (![[NSUserDefaults standardUserDefaults] boolForKey: @"WarningResetStats"]) + if (![NSUserDefaults.standardUserDefaults boolForKey: @"WarningResetStats"]) { [self performResetStats]; return; } NSAlert * alert = [[NSAlert alloc] init]; - [alert setMessageText: NSLocalizedString(@"Are you sure you want to reset usage statistics?", "Stats reset -> title")]; - [alert setInformativeText: NSLocalizedString(@"This will clear the global statistics displayed by Transmission." - " Individual transfer statistics will not be affected.", "Stats reset -> message")]; - [alert setAlertStyle: NSWarningAlertStyle]; + 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.alertStyle = NSWarningAlertStyle; [alert addButtonWithTitle: NSLocalizedString(@"Reset", "Stats reset -> button")]; [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Stats reset -> button")]; - [alert setShowsSuppressionButton: YES]; + alert.showsSuppressionButton = YES; - [alert beginSheetModalForWindow:[self window] completionHandler:^(NSModalResponse returnCode) { - [[alert window] orderOut: nil]; + [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { + [alert.window orderOut: nil]; - if ([[alert suppressionButton] state] == NSOnState) - [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningResetStats"]; + if (alert.suppressionButton.state == NSOnState) + [NSUserDefaults.standardUserDefaults setBool: NO forKey: @"WarningResetStats"]; if (returnCode == NSAlertFirstButtonReturn) [self performResetStats]; @@ -171,25 +171,25 @@ tr_session * fLib = NULL; tr_sessionGetStats(fLib, &statsSession); NSByteCountFormatter * byteFormatter = [[NSByteCountFormatter alloc] init]; - [byteFormatter setAllowedUnits: NSByteCountFormatterUseBytes]; + byteFormatter.allowedUnits = NSByteCountFormatterUseBytes; - [fUploadedField setStringValue: [NSString stringForFileSize: statsSession.uploadedBytes]]; - [fUploadedField setToolTip: [byteFormatter stringFromByteCount: statsSession.uploadedBytes]]; - [fUploadedAllField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"), [NSString stringForFileSize: statsAll.uploadedBytes]]]; - [fUploadedAllField setToolTip: [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 setStringValue: [NSString stringForFileSize: statsSession.downloadedBytes]]; - [fDownloadedField setToolTip: [byteFormatter stringFromByteCount: statsSession.downloadedBytes]]; - [fDownloadedAllField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"), [NSString stringForFileSize: statsAll.downloadedBytes]]]; - [fDownloadedAllField setToolTip: [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 setStringValue: [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"); - [fRatioAllField setStringValue: totalRatioString]; + : NSLocalizedString(@"Total N/A", "stats total"); + fRatioAllField.stringValue = totalRatioString; static NSDateComponentsFormatter *timeFormatter; static dispatch_once_t onceToken; @@ -200,13 +200,13 @@ tr_session * fLib = NULL; timeFormatter.allowedUnits = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekOfMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute; }); - [fTimeField setStringValue: [timeFormatter stringFromTimeInterval:statsSession.secondsActive]]; - [fTimeAllField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"), [timeFormatter stringFromTimeInterval:statsAll.secondsActive]]]; + fTimeField.stringValue = [timeFormatter stringFromTimeInterval:statsSession.secondsActive]; + fTimeAllField.stringValue = [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"), [timeFormatter stringFromTimeInterval:statsAll.secondsActive]]; if (statsAll.sessionCount == 1) - [fNumOpenedField setStringValue: NSLocalizedString(@"1 time", "stats window -> times opened")]; + fNumOpenedField.stringValue = NSLocalizedString(@"1 time", "stats window -> times opened"); else - [fNumOpenedField setStringValue: [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 diff --git a/macosx/StatusBarController.h b/macosx/StatusBarController.h index cc85e998e..00de741b8 100644 --- a/macosx/StatusBarController.h +++ b/macosx/StatusBarController.h @@ -35,7 +35,7 @@ CGFloat fPreviousDownloadRate, fPreviousUploadRate; } -- (id) initWithLib: (tr_session *) lib; +- (instancetype) initWithLib: (tr_session *) lib; - (void) updateWithDownload: (CGFloat) dlRate upload: (CGFloat) ulRate; - (void) setStatusLabel: (id) sender; diff --git a/macosx/StatusBarController.m b/macosx/StatusBarController.m index 22c965aa6..5a5f3b94b 100644 --- a/macosx/StatusBarController.m +++ b/macosx/StatusBarController.m @@ -30,13 +30,12 @@ #define STATUS_TRANSFER_TOTAL @"TransferTotal" #define STATUS_TRANSFER_SESSION @"TransferSession" -typedef enum -{ +typedef NS_ENUM(unsigned int, statusTag) { STATUS_RATIO_TOTAL_TAG = 0, STATUS_RATIO_SESSION_TAG = 1, STATUS_TRANSFER_TOTAL_TAG = 2, STATUS_TRANSFER_SESSION_TAG = 3 -} statusTag; +}; @interface StatusBarController (Private) @@ -46,7 +45,7 @@ typedef enum @implementation StatusBarController -- (id) initWithLib: (tr_session *) lib +- (instancetype) initWithLib: (tr_session *) lib { if ((self = [super initWithNibName: @"StatusBar" bundle: nil])) { @@ -62,33 +61,33 @@ typedef enum - (void) awakeFromNib { //localize menu items - [[[fStatusButton menu] itemWithTag: STATUS_RATIO_TOTAL_TAG] setTitle: NSLocalizedString(@"Total Ratio", - "Status Bar -> status menu")]; - [[[fStatusButton menu] itemWithTag: STATUS_RATIO_SESSION_TAG] setTitle: NSLocalizedString(@"Session Ratio", - "Status Bar -> status menu")]; - [[[fStatusButton menu] itemWithTag: STATUS_TRANSFER_TOTAL_TAG] setTitle: NSLocalizedString(@"Total Transfer", - "Status Bar -> status menu")]; - [[[fStatusButton menu] itemWithTag: STATUS_TRANSFER_SESSION_TAG] setTitle: 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] setBackgroundStyle: NSBackgroundStyleRaised]; - [[fTotalDLField cell] setBackgroundStyle: NSBackgroundStyleRaised]; - [[fTotalULField cell] setBackgroundStyle: NSBackgroundStyleRaised]; - [[fTotalDLImageView cell] setBackgroundStyle: NSBackgroundStyleRaised]; - [[fTotalULImageView cell] setBackgroundStyle: NSBackgroundStyleRaised]; + fStatusButton.cell.backgroundStyle = NSBackgroundStyleRaised; + fTotalDLField.cell.backgroundStyle = NSBackgroundStyleRaised; + fTotalULField.cell.backgroundStyle = NSBackgroundStyleRaised; + fTotalDLImageView.cell.backgroundStyle = NSBackgroundStyleRaised; + fTotalULImageView.cell.backgroundStyle = NSBackgroundStyleRaised; [self updateSpeedFieldsToolTips]; //update when speed limits are changed - [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateSpeedFieldsToolTips) + [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(resizeStatusButton) + name: NSWindowDidResizeNotification object: self.view.window]; } - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; } - (void) updateWithDownload: (CGFloat) dlRate upload: (CGFloat) ulRate @@ -96,18 +95,18 @@ typedef enum //set rates if (dlRate != fPreviousDownloadRate) { - [fTotalDLField setStringValue: [NSString stringForSpeed: dlRate]]; + fTotalDLField.stringValue = [NSString stringForSpeed: dlRate]; fPreviousDownloadRate = dlRate; } if (ulRate != fPreviousUploadRate) { - [fTotalULField setStringValue: [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]) { @@ -136,9 +135,9 @@ typedef enum } - if (![[fStatusButton title] isEqualToString: statusString]) + if (![fStatusButton.title isEqualToString: statusString]) { - [fStatusButton setTitle: statusString]; + fStatusButton.title = statusString; [self resizeStatusButton]; } } @@ -165,36 +164,36 @@ typedef enum return; } - [[NSUserDefaults standardUserDefaults] setObject: statusLabel forKey: @"StatusLabel"]; + [NSUserDefaults.standardUserDefaults setObject: statusLabel forKey: @"StatusLabel"]; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; } - (void) updateSpeedFieldsToolTips { NSString * uploadText, * downloadText; - if ([[NSUserDefaults standardUserDefaults] boolForKey: @"SpeedLimit"]) + 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"]]; + [NSUserDefaults.standardUserDefaults integerForKey: @"SpeedLimitUploadLimit"]]; downloadText = [NSString stringWithFormat: speedString, - [[NSUserDefaults standardUserDefaults] integerForKey: @"SpeedLimitDownloadLimit"]]; + [NSUserDefaults.standardUserDefaults integerForKey: @"SpeedLimitDownloadLimit"]]; } else { - if ([[NSUserDefaults standardUserDefaults] boolForKey: @"CheckUpload"]) + if ([NSUserDefaults.standardUserDefaults boolForKey: @"CheckUpload"]) uploadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"), - [[NSUserDefaults standardUserDefaults] integerForKey: @"UploadLimit"]]; + [NSUserDefaults.standardUserDefaults integerForKey: @"UploadLimit"]]; else uploadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip"); - if ([[NSUserDefaults standardUserDefaults] boolForKey: @"CheckDownload"]) + if ([NSUserDefaults.standardUserDefaults boolForKey: @"CheckDownload"]) downloadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"), - [[NSUserDefaults standardUserDefaults] integerForKey: @"DownloadLimit"]]; + [NSUserDefaults.standardUserDefaults integerForKey: @"DownloadLimit"]]; else downloadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip"); } @@ -204,19 +203,19 @@ typedef enum downloadText = [NSLocalizedString(@"Global download limit", "Status Bar -> speed tooltip") stringByAppendingFormat: @": %@", downloadText]; - [fTotalULField setToolTip: uploadText]; - [fTotalDLField setToolTip: downloadText]; + fTotalULField.toolTip = uploadText; + fTotalDLField.toolTip = downloadText; } - (BOOL) validateMenuItem: (NSMenuItem *) menuItem { - const SEL action = [menuItem action]; + const SEL action = menuItem.action; //enable sort options if (action == @selector(setStatusLabel:)) { NSString * statusLabel; - switch ([menuItem tag]) + switch (menuItem.tag) { case STATUS_RATIO_TOTAL_TAG: statusLabel = STATUS_RATIO_TOTAL; @@ -231,12 +230,12 @@ typedef enum statusLabel = STATUS_TRANSFER_SESSION; break; default: - NSAssert1(NO, @"Unknown status label tag received: %ld", [menuItem tag]); + NSAssert1(NO, @"Unknown status label tag received: %ld", menuItem.tag); statusLabel = STATUS_RATIO_TOTAL; } - [menuItem setState: [statusLabel isEqualToString: [[NSUserDefaults standardUserDefaults] stringForKey: @"StatusLabel"]] - ? NSOnState : NSOffState]; + menuItem.state = [statusLabel isEqualToString: [NSUserDefaults.standardUserDefaults stringForKey: @"StatusLabel"]] + ? NSOnState : NSOffState; return YES; } @@ -252,14 +251,14 @@ typedef enum [fStatusButton sizeToFit]; //width ends up being too long - NSRect statusFrame = [fStatusButton frame]; + NSRect statusFrame = fStatusButton.frame; statusFrame.size.width -= 25.0; - const CGFloat difference = NSMaxX(statusFrame) + 5.0 - NSMinX([fTotalDLImageView frame]); + const CGFloat difference = NSMaxX(statusFrame) + 5.0 - NSMinX(fTotalDLImageView.frame); if (difference > 0.0) statusFrame.size.width -= difference; - [fStatusButton setFrame: statusFrame]; + fStatusButton.frame = statusFrame; } @end diff --git a/macosx/StatusBarView.m b/macosx/StatusBarView.m index 56ca569b9..14b9b477a 100644 --- a/macosx/StatusBarView.m +++ b/macosx/StatusBarView.m @@ -43,13 +43,13 @@ - (void) drawRect: (NSRect) rect { - [[NSColor windowBackgroundColor] setFill]; + [NSColor.windowBackgroundColor setFill]; NSRectFill(rect); const NSRect lineBorderRect = NSMakeRect(NSMinX(rect), 0.0, NSWidth(rect), 1.0); if (NSIntersectsRect(lineBorderRect, rect)) { - [[NSColor gridColor] setFill]; + [NSColor.gridColor setFill]; NSRectFill(lineBorderRect); } } @@ -60,7 +60,7 @@ - (void) reload { - [self setNeedsDisplay: YES]; + self.needsDisplay = YES; } @end diff --git a/macosx/Torrent.h b/macosx/Torrent.h index 0b73e4221..9881933d8 100644 --- a/macosx/Torrent.h +++ b/macosx/Torrent.h @@ -27,32 +27,32 @@ @class FileListNode; -typedef enum { +typedef NS_ENUM(unsigned int, TorrentDeterminationType) { TorrentDeterminationAutomatic = 0, TorrentDeterminationUserSpecified -} TorrentDeterminationType; +}; #define kTorrentDidChangeGroupNotification @"TorrentDidChangeGroup" @interface Torrent : NSObject -- (id) initWithPath: (NSString *) path location: (NSString *) location deleteTorrentFile: (BOOL) torrentDelete - lib: (tr_session *) lib; -- (id) initWithTorrentStruct: (tr_torrent *) torrentStruct location: (NSString *) location lib: (tr_session *) lib; -- (id) initWithMagnetAddress: (NSString *) address location: (NSString *) location lib: (tr_session *) lib; -- (id) initWithHistory: (NSDictionary *) history lib: (tr_session *) lib forcePause: (BOOL) pause; -- (NSDictionary *) history; +- (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; - (void) closeRemoveTorrent: (BOOL) trashFiles; - (void) changeDownloadFolderBeforeUsing: (NSString *) folder determinationType: (TorrentDeterminationType) determinationType; -- (NSString *) currentDirectory; +@property (nonatomic, readonly) NSString *currentDirectory; - (void) getAvailability: (int8_t *) tab size: (NSInteger) size; - (void) getAmountFinished: (float *) tab size: (NSInteger) size; -- (NSIndexSet *) previousFinishedPieces; -- (void) setPreviousFinishedPieces: (NSIndexSet *) indexes; +@property (nonatomic) NSIndexSet *previousFinishedPieces; - (void) update; @@ -63,45 +63,37 @@ typedef enum { - (void) sleep; - (void) wakeUp; -- (NSInteger) queuePosition; -- (void) setQueuePosition: (NSUInteger) index; +@property (nonatomic) NSUInteger queuePosition; - (void) manualAnnounce; -- (BOOL) canManualAnnounce; +@property (nonatomic, readonly) BOOL canManualAnnounce; - (void) resetCache; -- (BOOL) isMagnet; -- (NSString *) magnetLink; +@property (nonatomic, getter=isMagnet, readonly) BOOL magnet; +@property (nonatomic, readonly) NSString *magnetLink; -- (CGFloat) ratio; -- (tr_ratiolimit) ratioSetting; -- (void) setRatioSetting: (tr_ratiolimit) setting; -- (CGFloat) ratioLimit; -- (void) setRatioLimit: (CGFloat) limit; -- (CGFloat) progressStopRatio; +@property (nonatomic, readonly) CGFloat ratio; +@property (nonatomic) tr_ratiolimit ratioSetting; +@property (nonatomic) CGFloat ratioLimit; +@property (nonatomic, readonly) CGFloat progressStopRatio; -- (tr_idlelimit) idleSetting; -- (void) setIdleSetting: (tr_idlelimit) setting; -- (NSUInteger) idleLimitMinutes; -- (void) setIdleLimitMinutes: (NSUInteger) limit; +@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; -- (BOOL) usesGlobalSpeedLimit; -- (void) setUseGlobalSpeedLimit: (BOOL) use; +@property (nonatomic) BOOL usesGlobalSpeedLimit; -- (void) setMaxPeerConnect: (uint16_t) count; -- (uint16_t) maxPeerConnect; +@property (nonatomic) uint16_t maxPeerConnect; @property (nonatomic) BOOL removeWhenFinishSeeding; -- (BOOL) waitingToStart; +@property (nonatomic, readonly) BOOL waitingToStart; -- (tr_priority_t) priority; -- (void) setPriority: (tr_priority_t) priority; +@property (nonatomic) tr_priority_t priority; + (BOOL) trashFile: (NSString *) path error: (NSError **) error; - (void) moveTorrentDataFileTo: (NSString *) folder; @@ -109,93 +101,93 @@ typedef enum { - (BOOL) alertForRemainingDiskSpace; -- (NSImage *) icon; +@property (nonatomic, readonly) NSImage *icon; -- (NSString *) name; -- (BOOL) isFolder; -- (uint64_t) size; -- (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; -- (NSMutableArray *) allTrackerStats; -- (NSArray *) allTrackersFlat; //used by GroupRules +@property (nonatomic, readonly) NSMutableArray *allTrackerStats; +@property (nonatomic, readonly) NSArray *allTrackersFlat; //used by GroupRules - (BOOL) addTrackerToNewTier: (NSString *) tracker; - (void) removeTrackers: (NSSet *) trackers; -- (NSString *) comment; -- (NSString *) creator; -- (NSDate *) dateCreated; +@property (nonatomic, readonly) NSString *comment; +@property (nonatomic, readonly) NSString *creator; +@property (nonatomic, readonly) NSDate *dateCreated; -- (NSInteger) pieceSize; -- (NSInteger) pieceCount; -- (NSString *) hashString; -- (BOOL) privateTorrent; +@property (nonatomic, readonly) NSInteger pieceSize; +@property (nonatomic, readonly) NSInteger pieceCount; +@property (nonatomic, readonly) NSString *hashString; +@property (nonatomic, readonly) BOOL privateTorrent; -- (NSString *) torrentLocation; -- (NSString *) dataLocation; +@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; -- (CGFloat) progress; -- (CGFloat) progressDone; -- (CGFloat) progressLeft; -- (CGFloat) checkingProgress; +@property (nonatomic, readonly) CGFloat progress; +@property (nonatomic, readonly) CGFloat progressDone; +@property (nonatomic, readonly) CGFloat progressLeft; +@property (nonatomic, readonly) CGFloat checkingProgress; -- (CGFloat) availableDesired; +@property (nonatomic, readonly) CGFloat availableDesired; -- (BOOL) isActive; -- (BOOL) isSeeding; -- (BOOL) isChecking; -- (BOOL) isCheckingWaiting; -- (BOOL) allDownloaded; -- (BOOL) isComplete; -- (BOOL) isFinishedSeeding; -- (BOOL) isError; -- (BOOL) isAnyErrorOrWarning; -- (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; -- (NSArray *) peers; +@property (nonatomic, readonly) NSArray *peers; -- (NSUInteger) webSeedCount; -- (NSArray *) webSeeds; +@property (nonatomic, readonly) NSUInteger webSeedCount; +@property (nonatomic, readonly) NSArray *webSeeds; -- (NSString *) progressString; -- (NSString *) statusString; -- (NSString *) shortStatusString; -- (NSString *) remainingTimeString; +@property (nonatomic, readonly) NSString *progressString; +@property (nonatomic, readonly) NSString *statusString; +@property (nonatomic, readonly) NSString *shortStatusString; +@property (nonatomic, readonly) NSString *remainingTimeString; -- (NSString *) stateString; -- (NSInteger) totalPeersConnected; -- (NSInteger) totalPeersTracker; -- (NSInteger) totalPeersIncoming; -- (NSInteger) totalPeersCache; -- (NSInteger) totalPeersPex; -- (NSInteger) totalPeersDHT; -- (NSInteger) totalPeersLocal; -- (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; -- (NSInteger) peersSendingToUs; -- (NSInteger) peersGettingFromUs; +@property (nonatomic, readonly) NSInteger peersSendingToUs; +@property (nonatomic, readonly) NSInteger peersGettingFromUs; -- (CGFloat) downloadRate; -- (CGFloat) uploadRate; -- (CGFloat) totalRate; -- (uint64_t) haveVerified; -- (uint64_t) haveTotal; -- (uint64_t) totalSizeSelected; -- (uint64_t) downloadedTotal; -- (uint64_t) uploadedTotal; -- (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; -- (NSInteger) groupValue; +@property (nonatomic, readonly) NSInteger groupValue; - (void) setGroupValue: (NSInteger) groupValue determinationType: (TorrentDeterminationType) determinationType;; -- (NSInteger) groupOrderValue; +@property (nonatomic, readonly) NSInteger groupOrderValue; - (void) checkGroupValueForRemoval: (NSNotification *) notification; -- (NSArray *) fileList; -- (NSArray *) flatFileList; -- (NSInteger) fileCount; +@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 @@ -208,22 +200,22 @@ typedef enum { - (BOOL) hasFilePriority: (tr_priority_t) priority forIndexes: (NSIndexSet *) indexSet; - (NSSet *) filePrioritiesForIndexes: (NSIndexSet *) indexSet; -- (NSDate *) dateAdded; -- (NSDate *) dateCompleted; -- (NSDate *) dateActivity; -- (NSDate *) dateActivityOrAdd; +@property (nonatomic, readonly) NSDate *dateAdded; +@property (nonatomic, readonly) NSDate *dateCompleted; +@property (nonatomic, readonly) NSDate *dateActivity; +@property (nonatomic, readonly) NSDate *dateActivityOrAdd; -- (NSInteger) secondsDownloading; -- (NSInteger) secondsSeeding; +@property (nonatomic, readonly) NSInteger secondsDownloading; +@property (nonatomic, readonly) NSInteger secondsSeeding; -- (NSInteger) stalledMinutes; -- (BOOL) isStalled; +@property (nonatomic, readonly) NSInteger stalledMinutes; +@property (nonatomic, getter=isStalled, readonly) BOOL stalled; - (void) updateTimeMachineExclude; -- (NSInteger) stateSortKey; -- (NSString *) trackerSortKey; +@property (nonatomic, readonly) NSInteger stateSortKey; +@property (nonatomic, readonly) NSString *trackerSortKey; -- (tr_torrent *) torrentStruct; +@property (nonatomic, readonly) tr_torrent *torrentStruct; @end diff --git a/macosx/Torrent.m b/macosx/Torrent.m index 658181933..871837ae8 100644 --- a/macosx/Torrent.m +++ b/macosx/Torrent.m @@ -36,7 +36,7 @@ @interface Torrent (Private) -- (id) initWithPath: (NSString *) path hash: (NSString *) hashString torrentStruct: (tr_torrent *) torrentStruct +- (instancetype) initWithPath: (NSString *) path hash: (NSString *) hashString torrentStruct: (tr_torrent *) torrentStruct magnetAddress: (NSString *) magnetAddress lib: (tr_session *) lib groupValue: (NSNumber *) groupValue removeWhenFinishSeeding: (NSNumber *) removeWhenFinishSeeding @@ -55,8 +55,8 @@ - (void) metadataRetrieved; - (void)renameFinished: (BOOL) success nodes: (NSArray *) nodes completionHandler: (void (^)(BOOL)) completionHandler oldPath: (NSString *) oldPath newName: (NSString *) newName; -- (BOOL) shouldShowEta; -- (NSString *) etaString; +@property (nonatomic, readonly) BOOL shouldShowEta; +@property (nonatomic, readonly) NSString *etaString; - (void) setTimeMachineExclude: (BOOL) exclude; @@ -121,7 +121,7 @@ bool trashDataFile(const char * filename, tr_error ** error) NSError * localError; if (![Torrent trashFile: @(filename) error: &localError]) { - tr_error_set_literal(error, [localError code], [[localError description] UTF8String]); + tr_error_set_literal(error, localError.code, localError.description.UTF8String); return false; } } @@ -157,7 +157,7 @@ bool trashDataFile(const char * filename, tr_error ** error) BOOL fTimeMachineExcludeInitialized; } -- (id) initWithPath: (NSString *) path location: (NSString *) location deleteTorrentFile: (BOOL) torrentDelete +- (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 @@ -168,13 +168,13 @@ bool trashDataFile(const char * filename, tr_error ** error) if (self) { - if (torrentDelete && ![[self torrentLocation] isEqualToString: path]) + if (torrentDelete && ![self.torrentLocation isEqualToString: path]) [Torrent trashFile: path error: nil]; } return self; } -- (id) 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 @@ -185,7 +185,7 @@ bool trashDataFile(const char * filename, tr_error ** error) return self; } -- (id) 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 @@ -195,7 +195,7 @@ bool trashDataFile(const char * filename, tr_error ** error) return self; } -- (id) 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"] @@ -212,7 +212,7 @@ bool trashDataFile(const char * filename, tr_error ** error) { //start transfer NSNumber * active; - if (!pause && (active = history[@"Active"]) && [active boolValue]) + if (!pause && (active = history[@"Active"]) && active.boolValue) { fStat = tr_torrentStat(fHandle); [self startTransferNoQueue]; @@ -221,26 +221,26 @@ bool trashDataFile(const char * filename, tr_error ** error) //upgrading from versions < 1.30: get old added, activity, and done dates NSDate * date; if ((date = history[@"Date"])) - tr_torrentSetAddedDate(fHandle, [date timeIntervalSince1970]); + tr_torrentSetAddedDate(fHandle, date.timeIntervalSince1970); if ((date = history[@"DateActivity"])) - tr_torrentSetActivityDate(fHandle, [date timeIntervalSince1970]); + tr_torrentSetActivityDate(fHandle, date.timeIntervalSince1970); if ((date = history[@"DateCompleted"])) - tr_torrentSetDoneDate(fHandle, [date timeIntervalSince1970]); + tr_torrentSetDoneDate(fHandle, date.timeIntervalSince1970); //upgrading from versions < 1.60: get old stop ratio settings NSNumber * ratioSetting; if ((ratioSetting = history[@"RatioSetting"])) { - switch ([ratioSetting intValue]) + switch (ratioSetting.intValue) { - case NSOnState: [self setRatioSetting: TR_RATIOLIMIT_SINGLE]; break; - case NSOffState: [self setRatioSetting: TR_RATIOLIMIT_UNLIMITED]; break; - case NSMixedState: [self setRatioSetting: 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; if ((ratioLimit = history[@"RatioLimit"])) - [self setRatioLimit: [ratioLimit floatValue]]; + self.ratioLimit = ratioLimit.floatValue; } return self; } @@ -248,25 +248,25 @@ bool trashDataFile(const char * filename, tr_error ** error) - (NSDictionary *) history { return @{ - @"InternalTorrentPath": [self torrentLocation], - @"TorrentHash": [self hashString], - @"Active": @([self isActive]), - @"WaitToStart": @([self waitingToStart]), + @"InternalTorrentPath": self.torrentLocation, + @"TorrentHash": self.hashString, + @"Active": @(self.active), + @"WaitToStart": @(self.waitingToStart), @"GroupValue": @(fGroupValue), @"RemoveWhenFinishSeeding": @(_removeWhenFinishSeeding)}; } - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; if (fFileStat) - tr_torrentFilesFree(fFileStat, [self fileCount]); + tr_torrentFilesFree(fFileStat, self.fileCount); } - (NSString *) description { - return [@"Torrent: " stringByAppendingString: [self name]]; + return [@"Torrent: " stringByAppendingString: self.name]; } - (id) copyWithZone: (NSZone *) zone @@ -287,7 +287,7 @@ bool trashDataFile(const char * filename, tr_error ** error) //if data existed in original download location, unexclude it before changing the location [self setTimeMachineExclude: NO]; - tr_torrentSetDownloadDir(fHandle, [folder UTF8String]); + tr_torrentSetDownloadDir(fHandle, folder.UTF8String); fDownloadFolderDetermination = determinationType; } @@ -310,7 +310,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (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) + if (fPreviousFinishedIndexesDate && fPreviousFinishedIndexesDate.timeIntervalSinceNow > -2.0) return fPreviousFinishedIndexes; else return nil; @@ -326,14 +326,14 @@ bool trashDataFile(const char * filename, tr_error ** error) - (void) update { //get previous stalled value before update - const BOOL wasStalled = fStat != NULL && [self isStalled]; + const BOOL wasStalled = fStat != NULL && self.stalled; fStat = tr_torrentStat(fHandle); //make sure the "active" filter is updated when stalled-ness changes - if (wasStalled != [self isStalled]) + 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] + [NSNotificationQueue.defaultQueue enqueueNotification: [NSNotification notificationWithName: @"UpdateQueue" object: self] postingStyle: NSPostASAP coalesceMask: NSNotificationCoalescingOnName forModes: nil]; @@ -351,7 +351,7 @@ 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]; } } @@ -373,7 +373,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (void) sleep { - if ((fResumeOnWake = [self isActive])) + if ((fResumeOnWake = self.active)) tr_torrentStop(fHandle); } @@ -386,7 +386,7 @@ bool trashDataFile(const char * filename, tr_error ** error) } } -- (NSInteger) queuePosition +- (NSUInteger) queuePosition { return fStat->queuePosition; } @@ -535,15 +535,15 @@ bool trashDataFile(const char * filename, tr_error ** 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]) + if (![NSFileManager.defaultManager removeItemAtPath: path error: &localError]) { - NSLog(@"old Could not trash %@: %@", path, [localError localizedDescription]); + NSLog(@"old Could not trash %@: %@", path, localError.localizedDescription); if (error != nil) *error = localError; return NO; @@ -559,24 +559,24 @@ bool trashDataFile(const char * filename, tr_error ** error) - (void) moveTorrentDataFileTo: (NSString *) folder { - NSString * oldFolder = [self currentDirectory]; + 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; + const NSUInteger oldCount = oldComponents.count; - if (oldCount < [newComponents count] && [newComponents[oldCount] isEqualToString: [self name]] + if (oldCount < newComponents.count && [newComponents[oldCount] isEqualToString: self.name] && [folder hasPrefix: oldFolder]) { NSAlert * alert = [[NSAlert alloc] init]; - [alert setMessageText: NSLocalizedString(@"A folder cannot be moved to inside itself.", - "Move inside itself alert -> title")]; - [alert setInformativeText: [NSString stringWithFormat: + 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]]]; + "Move inside itself alert -> message"), self.name]; [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move inside itself alert -> button")]; [alert runModal]; @@ -585,19 +585,19 @@ bool trashDataFile(const char * filename, tr_error ** error) } volatile int status; - tr_torrentSetLocation(fHandle, [folder UTF8String], YES, NULL, &status); + tr_torrentSetLocation(fHandle, folder.UTF8String, YES, NULL, &status); while (status == TR_LOC_MOVING) //block while moving (for now) [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]; - [alert setMessageText: NSLocalizedString(@"There was an error moving the data file.", "Move error alert -> title")]; - [alert setInformativeText: [NSString stringWithFormat: - NSLocalizedString(@"The move operation of \"%@\" cannot be done.", "Move error alert -> message"), [self name]]]; + 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 runModal]; @@ -608,41 +608,41 @@ bool trashDataFile(const char * filename, tr_error ** error) - (void) copyTorrentFileTo: (NSString *) path { - [[NSFileManager defaultManager] copyItemAtPath: [self torrentLocation] toPath: path error: NULL]; + [NSFileManager.defaultManager copyItemAtPath: self.torrentLocation toPath: path error: NULL]; } - (BOOL) alertForRemainingDiskSpace { - if ([self allDownloaded] || ![fDefaults boolForKey: @"WarningRemainingSpace"]) + if (self.allDownloaded || ![fDefaults boolForKey: @"WarningRemainingSpace"]) return YES; - NSString * downloadFolder = [self currentDirectory]; + NSString * downloadFolder = self.currentDirectory; NSDictionary * systemAttributes; - if ((systemAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath: downloadFolder error: NULL])) + if ((systemAttributes = [NSFileManager.defaultManager attributesOfFileSystemForPath: downloadFolder error: NULL])) { - const uint64_t remainingSpace = [systemAttributes[NSFileSystemFreeSize] unsignedLongLongValue]; + const uint64_t 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)) + 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 setMessageText: [NSString stringWithFormat: + alert.messageText = [NSString stringWithFormat: NSLocalizedString(@"Not enough remaining disk space to download \"%@\" completely.", - "Torrent disk space alert -> title"), [self name]]]; - [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"The transfer will be paused." + "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]]; + "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 setShowsSuppressionButton: YES]; - [[alert suppressionButton] setTitle: NSLocalizedString(@"Do not check disk space again", - "Torrent disk space alert -> button")]; + alert.showsSuppressionButton = YES; + alert.suppressionButton.title = NSLocalizedString(@"Do not check disk space again", + "Torrent disk space alert -> button"); const NSInteger result = [alert runModal]; - if ([[alert suppressionButton] state] == NSOnState) + if (alert.suppressionButton.state == NSOnState) [fDefaults setBool: NO forKey: @"WarningRemainingSpace"]; return result != NSAlertFirstButtonReturn; @@ -653,12 +653,12 @@ bool trashDataFile(const char * filename, tr_error ** error) - (NSImage *) icon { - if ([self isMagnet]) + if (self.magnet) return [NSImage imageNamed: @"Magnet"]; if (!fIcon) - fIcon = [self isFolder] ? [NSImage imageNamed: NSImageNameFolder] - : [[NSWorkspace sharedWorkspace] iconForFileType: [[self name] pathExtension]]; + fIcon = self.folder ? [NSImage imageNamed: NSImageNameFolder] + : [NSWorkspace.sharedWorkspace iconForFileType: self.name.pathExtension]; return fIcon; } @@ -694,7 +694,7 @@ bool trashDataFile(const char * filename, tr_error ** error) { 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; } @@ -718,7 +718,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (BOOL) addTrackerToNewTier: (NSString *) tracker { - tracker = [tracker stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; + tracker = [tracker stringByTrimmingCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; if ([tracker rangeOfString: @"://"].location == NSNotFound) tracker = [@"http://" stringByAppendingString: tracker]; @@ -729,7 +729,7 @@ bool trashDataFile(const char * filename, tr_error ** error) for (int i = 0; i < oldTrackerCount; ++i) trackerStructs[i] = fInfo->trackers[i]; - trackerStructs[oldTrackerCount].announce = (char *)[tracker UTF8String]; + trackerStructs[oldTrackerCount].announce = (char *)tracker.UTF8String; trackerStructs[oldTrackerCount].tier = trackerStructs[oldTrackerCount-1].tier + 1; trackerStructs[oldTrackerCount].id = oldTrackerCount; @@ -800,14 +800,14 @@ bool trashDataFile(const char * filename, tr_error ** error) - (NSString *) dataLocation { - if ([self isMagnet]) + if (self.magnet) return nil; - if ([self isFolder]) + 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; @@ -827,19 +827,19 @@ bool trashDataFile(const char * filename, tr_error ** error) - (NSString *) fileLocation: (FileListNode *) node { - if ([node isFolder]) + 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; @@ -857,19 +857,19 @@ bool trashDataFile(const char * filename, tr_error ** error) 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 { - NSParameterAssert([node torrent] == self); + NSParameterAssert(node.torrent == self); NSParameterAssert(newName != nil); NSParameterAssert(![newName isEqualToString: @""]); 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 @@ -884,10 +884,10 @@ bool trashDataFile(const char * filename, tr_error ** error) - (CGFloat) progressLeft { - if ([self size] == 0) //magnet links + if (self.size == 0) //magnet links return 0.0; - return (CGFloat)[self sizeLeft] / [self size]; + return (CGFloat)self.sizeLeft / self.size; } - (CGFloat) checkingProgress @@ -897,7 +897,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (CGFloat) availableDesired { - return (CGFloat)fStat->desiredAvailable / [self sizeLeft]; + return (CGFloat)fStat->desiredAvailable / self.sizeLeft; } - (BOOL) isActive @@ -922,12 +922,12 @@ bool trashDataFile(const char * filename, tr_error ** error) - (BOOL) allDownloaded { - return [self sizeLeft] == 0 && ![self isMagnet]; + return self.sizeLeft == 0 && !self.magnet; } - (BOOL) isComplete { - return [self progress] >= 1.0; + return self.progress >= 1.0; } - (BOOL) isFinishedSeeding @@ -947,7 +947,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (NSString *) errorMessage { - if (![self isAnyErrorOrWarning]) + if (!self.anyErrorOrWarning) return @""; NSString * error; @@ -973,7 +973,7 @@ bool trashDataFile(const char * filename, tr_error ** error) tr_peer_stat * peer = &peers[i]; NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 12]; - dict[@"Name"] = [self name]; + dict[@"Name"] = self.name; dict[@"From"] = @(peer->from); dict[@"IP"] = @(peer->addr); dict[@"Port"] = @(peer->port); @@ -1012,7 +1012,7 @@ bool trashDataFile(const char * filename, tr_error ** error) { NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 3]; - dict[@"Name"] = [self name]; + dict[@"Name"] = self.name; dict[@"Address"] = @(fInfo->webseeds[i]); if (dlSpeeds[i] != -1.0) @@ -1028,7 +1028,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (NSString *) progressString { - if ([self isMagnet]) + if (self.magnet) { NSString * progressString = fStat->metadataPercentComplete > 0.0 ? [NSString stringWithFormat: NSLocalizedString(@"%@ of torrent metadata retrieved", @@ -1041,18 +1041,18 @@ bool trashDataFile(const char * filename, tr_error ** error) NSString * string; - if (![self allDownloaded]) + if (!self.allDownloaded) { CGFloat progress; - if ([self isFolder] && [fDefaults boolForKey: @"DisplayStatusProgressSelected"]) + if (self.folder && [fDefaults boolForKey: @"DisplayStatusProgressSelected"]) { - string = [NSString stringForFilePartialSize: [self haveTotal] fullSize: [self totalSizeSelected]]; - progress = [self progressDone]; + string = [NSString stringForFilePartialSize: self.haveTotal fullSize: self.totalSizeSelected]; + progress = self.progressDone; } else { - string = [NSString stringForFilePartialSize: [self haveTotal] fullSize: [self size]]; - progress = [self progress]; + string = [NSString stringForFilePartialSize: self.haveTotal fullSize: self.size]; + progress = self.progress; } string = [string stringByAppendingFormat: @" (%@)", [NSString percentString: progress longDecimals: YES]]; @@ -1060,31 +1060,31 @@ bool trashDataFile(const char * filename, tr_error ** error) else { NSString * downloadString; - if (![self isComplete]) //only multifile possible + if (!self.complete) //only multifile possible { if ([fDefaults boolForKey: @"DisplayStatusProgressSelected"]) downloadString = [NSString stringWithFormat: NSLocalizedString(@"%@ selected", "Torrent -> progress string"), - [NSString stringForFileSize: [self haveTotal]]]; + [NSString stringForFileSize: self.haveTotal]]; else { - downloadString = [NSString stringForFilePartialSize: [self haveTotal] fullSize: [self size]]; + downloadString = [NSString stringForFilePartialSize: self.haveTotal fullSize: self.size]; downloadString = [downloadString stringByAppendingFormat: @" (%@)", - [NSString percentString: [self progress] longDecimals: YES]]; + [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]]]; + "Torrent -> progress string"), [NSString stringForFileSize: self.uploadedTotal], + [NSString stringForRatio: self.ratio]]; string = [downloadString stringByAppendingFormat: @", %@", uploadString]; } //add time when downloading or seed limit set - if ([self shouldShowEta]) - string = [string stringByAppendingFormat: @" - %@", [self etaString]]; + if (self.shouldShowEta) + string = [string stringByAppendingFormat: @" - %@", self.etaString]; return string; } @@ -1093,7 +1093,7 @@ bool trashDataFile(const char * filename, tr_error ** error) { NSString * string; - if ([self isAnyErrorOrWarning]) + if (self.anyErrorOrWarning) { switch (fStat->error) { @@ -1103,7 +1103,7 @@ bool trashDataFile(const char * filename, tr_error ** error) default: NSAssert(NO, @"unknown error state"); } - NSString * errorString = [self errorMessage]; + NSString * errorString = self.errorMessage; if (errorString && ![errorString isEqualToString: @""]) string = [string stringByAppendingFormat: @": %@", errorString]; } @@ -1112,7 +1112,7 @@ bool trashDataFile(const char * filename, tr_error ** error) switch (fStat->activity) { case TR_STATUS_STOPPED: - if ([self isFinishedSeeding]) + if (self.finishedSeeding) string = NSLocalizedString(@"Seeding complete", "Torrent -> status string"); else string = NSLocalizedString(@"Paused", "Torrent -> status string"); @@ -1133,16 +1133,16 @@ bool trashDataFile(const char * filename, tr_error ** error) case TR_STATUS_CHECK: string = [NSString stringWithFormat: @"%@ (%@)", NSLocalizedString(@"Checking existing data", "Torrent -> status string"), - [NSString percentString: [self checkingProgress] longDecimals: YES]]; + [NSString percentString: self.checkingProgress longDecimals: YES]]; break; case TR_STATUS_DOWNLOAD: - if ([self totalPeersConnected] != 1) + if (self.totalPeersConnected != 1) string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of %d peers", - "Torrent -> status string"), [self peersSendingToUs], [self totalPeersConnected]]; + "Torrent -> status string"), self.peersSendingToUs, self.totalPeersConnected]; else string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of 1 peer", - "Torrent -> status string"), [self peersSendingToUs]]; + "Torrent -> status string"), self.peersSendingToUs]; const NSInteger webSeedCount = fStat->webseedsSendingToUs; if (webSeedCount > 0) @@ -1160,28 +1160,28 @@ bool trashDataFile(const char * filename, tr_error ** error) break; case TR_STATUS_SEED: - if ([self totalPeersConnected] != 1) + if (self.totalPeersConnected != 1) string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"), - [self peersGettingFromUs], [self totalPeersConnected]]; + self.peersGettingFromUs, self.totalPeersConnected]; else string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of 1 peer", "Torrent -> status string"), - [self peersGettingFromUs]]; + self.peersGettingFromUs]; } - if ([self isStalled]) + if (self.stalled) string = [NSLocalizedString(@"Stalled", "Torrent -> status string") stringByAppendingFormat: @", %@", string]; } //append even if error - if ([self isActive] && ![self isChecking]) + 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]]]; + 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]]]; + NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: self.uploadRate]]; } return string; @@ -1194,7 +1194,7 @@ bool trashDataFile(const char * filename, tr_error ** error) switch (fStat->activity) { case TR_STATUS_STOPPED: - if ([self isFinishedSeeding]) + if (self.finishedSeeding) string = NSLocalizedString(@"Seeding complete", "Torrent -> status string"); else string = NSLocalizedString(@"Paused", "Torrent -> status string"); @@ -1215,19 +1215,19 @@ bool trashDataFile(const char * filename, tr_error ** error) case TR_STATUS_CHECK: string = [NSString stringWithFormat: @"%@ (%@)", NSLocalizedString(@"Checking existing data", "Torrent -> status string"), - [NSString percentString: [self checkingProgress] longDecimals: YES]]; + [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]]]; + 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]]]; + NSLocalizedString(@"Ratio", "Torrent -> status string"), [NSString stringForRatio: self.ratio], + NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: self.uploadRate]]; } return string; @@ -1235,10 +1235,10 @@ bool trashDataFile(const char * filename, tr_error ** error) - (NSString *) remainingTimeString { - if ([self shouldShowEta]) - return [self etaString]; + if (self.shouldShowEta) + return self.etaString; else - return [self shortStatusString]; + return self.shortStatusString; } - (NSString *) stateString @@ -1252,13 +1252,13 @@ bool trashDataFile(const char * filename, tr_error ** error) NSString * string = NSLocalizedString(@"Paused", "Torrent -> status string"); NSString * extra = nil; - if ([self waitingToStart]) + 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 isFinishedSeeding]) + else if (self.finishedSeeding) extra = NSLocalizedString(@"Seeding complete", "Torrent -> status string"); else; @@ -1271,7 +1271,7 @@ bool trashDataFile(const char * filename, tr_error ** error) case TR_STATUS_CHECK: return [NSString stringWithFormat: @"%@ (%@)", NSLocalizedString(@"Checking existing data", "Torrent -> status string"), - [NSString percentString: [self checkingProgress] longDecimals: YES]]; + [NSString percentString: self.checkingProgress longDecimals: YES]]; case TR_STATUS_DOWNLOAD: return NSLocalizedString(@"Downloading", "Torrent -> status string"); @@ -1343,7 +1343,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (CGFloat) totalRate { - return [self downloadRate] + [self uploadRate]; + return self.downloadRate + self.uploadRate; } - (uint64_t) haveVerified @@ -1353,7 +1353,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (uint64_t) haveTotal { - return [self haveVerified] + fStat->haveUnchecked; + return self.haveVerified + fStat->haveUnchecked; } - (uint64_t) totalSizeSelected @@ -1386,19 +1386,19 @@ bool trashDataFile(const char * filename, tr_error ** error) if (groupValue != fGroupValue) { fGroupValue = groupValue; - [[NSNotificationCenter defaultCenter] postNotificationName: kTorrentDidChangeGroupNotification object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: kTorrentDidChangeGroupNotification object: self]; } fGroupValueDetermination = determinationType; } - (NSInteger) groupOrderValue { - return [[GroupsController groups] rowValueForIndex: fGroupValue]; + return [GroupsController.groups rowValueForIndex: fGroupValue]; } - (void) checkGroupValueForRemoval: (NSNotification *) notification { - if (fGroupValue != -1 && [[notification userInfo][@"Index"] integerValue] == fGroupValue) + if (fGroupValue != -1 && [notification.userInfo[@"Index"] integerValue] == fGroupValue) fGroupValue = -1; } @@ -1420,46 +1420,46 @@ bool trashDataFile(const char * filename, tr_error ** error) - (void) updateFileStat { if (fFileStat) - tr_torrentFilesFree(fFileStat, [self fileCount]); + tr_torrentFilesFree(fFileStat, self.fileCount); fFileStat = tr_torrentFiles(fHandle, NULL); } - (CGFloat) fileProgress: (FileListNode *) node { - if ([self fileCount] == 1 || [self isComplete]) - return [self progress]; + 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; + 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]; + return (CGFloat)have / node.size; } - (BOOL) canChangeDownloadCheckForFile: (NSUInteger) index { - NSAssert2((NSInteger)index < [self fileCount], @"Index %ld is greater than file count %ld", index, [self fileCount]); + NSAssert2((NSInteger)index < self.fileCount, @"Index %ld is greater than file count %ld", index, self.fileCount); return [self canChangeDownloadCheckForFiles: [NSIndexSet indexSetWithIndex: index]]; } - (BOOL) canChangeDownloadCheckForFiles: (NSIndexSet *) indexSet { - if ([self fileCount] == 1 || [self isComplete]) + if (self.fileCount == 1 || self.complete) return NO; if (!fFileStat) @@ -1479,7 +1479,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (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]) onState = YES; @@ -1494,23 +1494,23 @@ bool trashDataFile(const char * filename, tr_error ** error) - (void) setFileCheckState: (NSInteger) state forIndexes: (NSIndexSet *) indexSet { - NSUInteger count = [indexSet count]; + 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++) + 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 { - const NSUInteger count = [indexSet count]; + 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++) + for (NSUInteger index = indexSet.firstIndex, i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++) files[i] = index; tr_torrentSetFilePriorities(fHandle, files, count, priority); @@ -1519,7 +1519,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (BOOL) hasFilePriority: (tr_priority_t) priority forIndexes: (NSIndexSet *) indexSet { - for (NSUInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: 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; @@ -1528,9 +1528,9 @@ bool trashDataFile(const char * filename, tr_error ** error) - (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; @@ -1584,8 +1584,8 @@ bool trashDataFile(const char * filename, tr_error ** error) - (NSDate *) dateActivityOrAdd { - NSDate * date = [self dateActivity]; - return date ? date : [self dateAdded]; + NSDate * date = self.dateActivity; + return date ? date : self.dateAdded; } - (NSInteger) secondsDownloading @@ -1613,19 +1613,19 @@ bool trashDataFile(const char * filename, tr_error ** error) - (void) updateTimeMachineExclude { - [self setTimeMachineExclude: ![self allDownloaded]]; + [self setTimeMachineExclude: !self.allDownloaded]; } - (NSInteger) stateSortKey { - if (![self isActive]) //paused + if (!self.active) //paused { - if ([self waitingToStart]) + if (self.waitingToStart) return 1; else return 0; } - else if ([self isSeeding]) //seeding + else if (self.seeding) //seeding return 10; else //downloading return 20; @@ -1656,7 +1656,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (NSURL *) previewItemURL { - NSString * location = [self dataLocation]; + NSString * location = self.dataLocation; return location ? [NSURL fileURLWithPath: location] : nil; } @@ -1664,7 +1664,7 @@ bool trashDataFile(const char * filename, tr_error ** error) @implementation Torrent (Private) -- (id) initWithPath: (NSString *) path hash: (NSString *) hashString torrentStruct: (tr_torrent *) torrentStruct +- (instancetype) initWithPath: (NSString *) path hash: (NSString *) hashString torrentStruct: (tr_torrent *) torrentStruct magnetAddress: (NSString *) magnetAddress lib: (tr_session *) lib groupValue: (NSNumber *) groupValue removeWhenFinishSeeding: (NSNumber *) removeWhenFinishSeeding @@ -1674,7 +1674,7 @@ bool trashDataFile(const char * filename, tr_error ** error) if (!(self = [super init])) return nil; - fDefaults = [NSUserDefaults standardUserDefaults]; + fDefaults = NSUserDefaults.standardUserDefaults; if (torrentStruct) fHandle = torrentStruct; @@ -1685,20 +1685,20 @@ bool trashDataFile(const char * filename, tr_error ** error) tr_ctorSetPaused(ctor, TR_FORCE, YES); if (downloadFolder) - tr_ctorSetDownloadDir(ctor, TR_FORCE, [downloadFolder UTF8String]); + tr_ctorSetDownloadDir(ctor, TR_FORCE, downloadFolder.UTF8String); if (incompleteFolder) - tr_ctorSetIncompleteDir(ctor, [incompleteFolder UTF8String]); + tr_ctorSetIncompleteDir(ctor, incompleteFolder.UTF8String); tr_parse_result result = TR_PARSE_ERR; if (path) - result = tr_ctorSetMetainfoFromFile(ctor, [path UTF8String]); + result = tr_ctorSetMetainfoFromFile(ctor, path.UTF8String); if (result != TR_PARSE_OK && magnetAddress) - result = tr_ctorSetMetainfoFromMagnetLink(ctor, [magnetAddress UTF8String]); + 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]); + result = tr_ctorSetMetainfoFromHash(ctor, hashString.UTF8String); if (result == TR_PARSE_OK) fHandle = tr_torrentNew(ctor, NULL, NULL); @@ -1719,12 +1719,12 @@ bool trashDataFile(const char * filename, tr_error ** error) tr_torrentSetIdleLimitHitCallback(fHandle, idleLimitHitCallback, (__bridge void *)(self)); tr_torrentSetMetadataCallback(fHandle, metadataCallback, (__bridge void *)(self)); - fHashString = [[NSString alloc] initWithUTF8String: fInfo->hashString]; + fHashString = @(fInfo->hashString); fResumeOnWake = NO; //don't do after this point - it messes with auto-group functionality - if (![self isMagnet]) + if (!self.magnet) [self createFileList]; fDownloadFolderDetermination = TorrentDeterminationAutomatic; @@ -1732,17 +1732,17 @@ bool trashDataFile(const char * filename, tr_error ** error) if (groupValue) { fGroupValueDetermination = TorrentDeterminationUserSpecified; - fGroupValue = [groupValue intValue]; + fGroupValue = groupValue.intValue; } 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:) + [NSNotificationCenter.defaultCenter addObserver: self selector: @selector(checkGroupValueForRemoval:) name: @"GroupValueRemoved" object: nil]; fTimeMachineExcludeInitialized = NO; @@ -1753,11 +1753,11 @@ bool trashDataFile(const char * filename, tr_error ** error) - (void) createFileList { - NSAssert(![self isMagnet], @"Cannot create a file list until the torrent is demagnetized"); + NSAssert(!self.magnet, @"Cannot create a file list until the torrent is demagnetized"); - if ([self isFolder]) + if (self.folder) { - const NSInteger count = [self fileCount]; + const NSInteger count = self.fileCount; NSMutableArray * flatFileList = [NSMutableArray arrayWithCapacity: count]; FileListNode * tempNode = nil; @@ -1767,7 +1767,7 @@ bool trashDataFile(const char * filename, tr_error ** error) tr_file * file = &fInfo->files[i]; NSString * fullPath = @(file->name); - NSArray * pathComponents = [fullPath pathComponents]; + NSArray * pathComponents = fullPath.pathComponents; if (!tempNode) tempNode = [[FileListNode alloc] initWithFolderName:pathComponents[0] path:@"" torrent:self]; @@ -1775,15 +1775,15 @@ bool trashDataFile(const char * filename, tr_error ** error) [self insertPathForComponents: pathComponents withComponentIndex: 1 forParent: tempNode fileSize: file->length index: i flatList: flatFileList]; } - [self sortFileList: [tempNode children]]; + [self sortFileList: tempNode.children]; [self sortFileList: flatFileList]; - fFileList = [[NSArray alloc] initWithArray: [tempNode children]]; + 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]; + FileListNode * node = [[FileListNode alloc] initWithFileName: self.name path: @"" size: self.size index: 0 torrent: self]; fFileList = @[node]; fFlatFileList = fFileList; } @@ -1792,18 +1792,18 @@ bool trashDataFile(const char * filename, tr_error ** error) - (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]); + NSParameterAssert(components.count > 0); + NSParameterAssert(componentIndex < components.count); NSString * name = components[componentIndex]; - const BOOL isFolder = componentIndex < ([components count]-1); + const BOOL isFolder = componentIndex < (components.count-1); //determine if folder node already exists __block FileListNode * node = nil; if (isFolder) { - [[parent children] enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(FileListNode * searchNode, NSUInteger idx, BOOL * stop) { - if ([[searchNode name] isEqualToString: name] && [searchNode isFolder]) + [parent.children enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(FileListNode * searchNode, NSUInteger idx, BOOL * stop) { + if ([searchNode.name isEqualToString: name] && searchNode.isFolder) { node = searchNode; *stop = YES; @@ -1814,7 +1814,7 @@ bool trashDataFile(const char * filename, tr_error ** error) //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]; else @@ -1840,14 +1840,14 @@ bool trashDataFile(const char * filename, tr_error ** error) [fileNodes sortUsingDescriptors: @[descriptor]]; [fileNodes enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(FileListNode * node, NSUInteger idx, BOOL * stop) { - if ([node isFolder]) - [self sortFileList: [node children]]; + if (node.isFolder) + [self sortFileList: node.children]; }]; } - (void) startQueue { - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateQueue" object: self]; } - (void) completenessChange: (tr_completeness) status wasRunning: (BOOL) wasRunning @@ -1860,19 +1860,19 @@ bool trashDataFile(const char * filename, tr_error ** error) case TR_PARTIAL_SEED: { NSDictionary * statusInfo = @{ @"Status" : @(status), @"WasRunning" : @(wasRunning) }; - [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self userInfo: statusInfo]; + [NSNotificationCenter.defaultCenter postNotificationName: @"TorrentFinishedDownloading" object: self userInfo: statusInfo]; //quarantine the finished data - NSString * dataLocation = [[self currentDirectory] stringByAppendingPathComponent: [self name]]; + 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]); + NSLog(@"Failed to quarantine %@: %@", dataLocation, error.description); break; } case TR_LEECH: - [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentRestartedDownloading" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"TorrentRestartedDownloading" object: self]; break; } @@ -1884,14 +1884,14 @@ bool trashDataFile(const char * filename, tr_error ** error) { fStat = tr_torrentStat(fHandle); - [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedSeeding" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"TorrentFinishedSeeding" object: self]; } - (void) idleLimitHit { fStat = tr_torrentStat(fHandle); - [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedSeeding" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"TorrentFinishedSeeding" object: self]; } - (void) metadataRetrieved @@ -1903,18 +1903,18 @@ bool trashDataFile(const char * filename, tr_error ** error) /* If the torrent is in no group, or the group was automatically determined based on criteria evaluated * before we had metadata for this torrent, redetermine the group */ - if ((fGroupValueDetermination == TorrentDeterminationAutomatic) || ([self groupValue] == -1)) - [self setGroupValue: [[GroupsController groups] groupIndexForTorrent: self] determinationType: TorrentDeterminationAutomatic]; + if ((fGroupValueDetermination == TorrentDeterminationAutomatic) || (self.groupValue == -1)) + [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]]; + 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 @@ -1923,18 +1923,18 @@ bool trashDataFile(const char * filename, tr_error ** error) NSParameterAssert(oldPath != nil); NSParameterAssert(newName != nil); - NSString * path = [oldPath stringByDeletingLastPathComponent]; + NSString * path = oldPath.stringByDeletingLastPathComponent; if (success) { - NSString * oldName = [oldPath lastPathComponent]; + 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) { + if (node.isFolder) { + [node.children enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(FileListNode * childNode, NSUInteger idx, BOOL * stop) { weakUpdateNodeAndChildrenForRename(childNode); }]; } @@ -1967,7 +1967,7 @@ bool trashDataFile(const char * filename, tr_error ** error) { if (fStat->activity == TR_STATUS_DOWNLOAD) return YES; - else if ([self isSeeding]) + else if (self.seeding) { //ratio: show if it's set at all if (tr_torrentGetSeedRatio(fHandle, NULL)) @@ -2020,7 +2020,7 @@ bool trashDataFile(const char * filename, tr_error ** error) - (void) setTimeMachineExclude: (BOOL) exclude { NSString * path; - if ((path = [self dataLocation])) + if ((path = self.dataLocation)) { CSBackupSetItemExcluded((__bridge CFURLRef)[NSURL fileURLWithPath: path], exclude, false); fTimeMachineExcludeInitialized = YES; diff --git a/macosx/TorrentCell.m b/macosx/TorrentCell.m index ffebb7116..b241e5cee 100644 --- a/macosx/TorrentCell.m +++ b/macosx/TorrentCell.m @@ -78,26 +78,26 @@ - (NSRect) revealButtonRectForBounds: (NSRect) bounds; - (NSRect) actionButtonRectForBounds: (NSRect) bounds; -- (NSAttributedString *) attributedTitle; +@property (nonatomic, readonly) NSAttributedString *attributedTitle; - (NSAttributedString *) attributedStatusString: (NSString *) string; -- (NSString *) buttonString; -- (NSString *) statusString; -- (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 -- (id) init +- (instancetype) init { if ((self = [super init])) { - fDefaults = [NSUserDefaults standardUserDefaults]; + fDefaults = NSUserDefaults.standardUserDefaults; - NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; - [paragraphStyle setLineBreakMode: NSLineBreakByTruncatingMiddle]; + NSMutableParagraphStyle * paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + paragraphStyle.lineBreakMode = NSLineBreakByTruncatingMiddle; fTitleAttributes = [[NSMutableDictionary alloc] initWithCapacity: 3]; fTitleAttributes[NSFontAttributeName] = [NSFont messageFontOfSize: 12.0]; @@ -118,7 +118,7 @@ - (id) copyWithZone: (NSZone *) zone { id value = [super copyWithZone: zone]; - [value setRepresentedObject: [self representedObject]]; + [value setRepresentedObject: self.representedObject]; return value; } @@ -132,10 +132,10 @@ - (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 isFlipped]) - || NSMouseInRect(point, [self revealButtonRectForBounds: cellFrame], [controlView isFlipped])) + if (NSMouseInRect(point, [self controlButtonRectForBounds: cellFrame], controlView.flipped) + || NSMouseInRect(point, [self revealButtonRectForBounds: cellFrame], controlView.flipped)) return NSCellHitContentArea | NSCellHitTrackableArea; return NSCellHitContentArea; @@ -150,25 +150,25 @@ { fTracking = YES; - [self setControlView: controlView]; + 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 isFlipped]); + const BOOL checkControl = NSMouseInRect(point, controlRect, controlView.flipped); const NSRect revealRect = [self revealButtonRectForBounds: cellFrame]; - const BOOL checkReveal = NSMouseInRect(point, revealRect, [controlView isFlipped]); + const BOOL checkReveal = NSMouseInRect(point, revealRect, controlView.flipped); [(TorrentTableView *)controlView removeTrackingAreas]; - while ([event type] != NSLeftMouseUp) + 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 isFlipped]); + const BOOL inControlButton = NSMouseInRect(point, controlRect, controlView.flipped); if (fMouseDownControlButton != inControlButton) { fMouseDownControlButton = inControlButton; @@ -177,7 +177,7 @@ } else if (checkReveal) { - const BOOL inRevealButton = NSMouseInRect(point, revealRect, [controlView isFlipped]); + const BOOL inRevealButton = NSMouseInRect(point, revealRect, controlView.flipped); if (fMouseDownRevealButton != inRevealButton) { fMouseDownRevealButton = inRevealButton; @@ -187,9 +187,9 @@ else; //send events to where necessary - if ([event type] == NSMouseEntered || [event type] == NSMouseExited) + if (event.type == NSMouseEntered || event.type == NSMouseExited) [NSApp sendEvent: event]; - event = [[controlView window] nextEventMatchingMask: + event = [controlView.window nextEventMatchingMask: (NSLeftMouseUpMask | NSLeftMouseDraggedMask | NSMouseEnteredMask | NSMouseExitedMask)]; } @@ -199,18 +199,18 @@ { fMouseDownControlButton = NO; - [(TorrentTableView *)controlView toggleControlForTorrent: [self representedObject]]; + [(TorrentTableView *)controlView toggleControlForTorrent: self.representedObject]; } else if (fMouseDownRevealButton) { fMouseDownRevealButton = NO; [controlView setNeedsDisplayInRect: cellFrame]; - NSString * location = [[self representedObject] dataLocation]; + NSString * location = ((Torrent *)self.representedObject).dataLocation; if (location) { NSURL * file = [NSURL fileURLWithPath: location]; - [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: @[file]]; + [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs: @[file]]; } } else; @@ -229,7 +229,7 @@ if ([fDefaults boolForKey: @"SmallView"]) { NSTrackingAreaOptions rowOptions = options; - if (NSMouseInRect(mouseLocation, cellFrame, [controlView isFlipped])) + if (NSMouseInRect(mouseLocation, cellFrame, controlView.flipped)) { rowOptions |= NSTrackingAssumeInside; [(TorrentTableView *)controlView setRowHover: [userInfo[@"Row"] integerValue]]; @@ -244,7 +244,7 @@ //control button NSRect controlButtonRect = [self controlButtonRectForBounds: cellFrame]; NSTrackingAreaOptions controlOptions = options; - if (NSMouseInRect(mouseLocation, controlButtonRect, [controlView isFlipped])) + if (NSMouseInRect(mouseLocation, controlButtonRect, controlView.flipped)) { controlOptions |= NSTrackingAssumeInside; [(TorrentTableView *)controlView setControlButtonHover: [userInfo[@"Row"] integerValue]]; @@ -259,7 +259,7 @@ //reveal button NSRect revealButtonRect = [self revealButtonRectForBounds: cellFrame]; NSTrackingAreaOptions revealOptions = options; - if (NSMouseInRect(mouseLocation, revealButtonRect, [controlView isFlipped])) + if (NSMouseInRect(mouseLocation, revealButtonRect, controlView.flipped)) { revealOptions |= NSTrackingAssumeInside; [(TorrentTableView *)controlView setRevealButtonHover: [userInfo[@"Row"] integerValue]]; @@ -274,7 +274,7 @@ //action button NSRect actionButtonRect = [self iconRectForBounds: cellFrame]; //use the whole icon NSTrackingAreaOptions actionOptions = options; - if (NSMouseInRect(mouseLocation, actionButtonRect, [controlView isFlipped])) + if (NSMouseInRect(mouseLocation, actionButtonRect, controlView.flipped)) { actionOptions |= NSTrackingAssumeInside; [(TorrentTableView *)controlView setActionButtonHover: [userInfo[@"Row"] integerValue]]; @@ -313,7 +313,7 @@ - (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"]; @@ -324,7 +324,7 @@ //group coloring const NSRect iconRect = [self iconRectForBounds: cellFrame]; - const NSInteger groupValue = [torrent groupValue]; + const NSInteger groupValue = torrent.groupValue; if (groupValue != -1) { NSRect groupRect = NSInsetRect(iconRect, -1.0, -2.0); @@ -335,29 +335,29 @@ } const CGFloat 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]; [darkGroupColor set]; - [bp setLineWidth: 2.0]; + 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]; + ofColor: NSColor.whiteColor] endingColor: darkGroupColor]; [gradient drawInBezierPath: bp angle: 90.0]; } - const BOOL error = [torrent isAnyErrorOrWarning]; + const BOOL 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]; + : torrent.icon; [icon drawInRect: iconRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil]; } @@ -371,12 +371,12 @@ //text color NSColor * titleColor, * statusColor; - if ([self backgroundStyle] == NSBackgroundStyleDark) - titleColor = statusColor = [NSColor whiteColor]; + if (self.backgroundStyle == NSBackgroundStyleDark) + titleColor = statusColor = NSColor.whiteColor; else { - titleColor = [NSColor labelColor]; - statusColor = [NSColor secondaryLabelColor]; + titleColor = NSColor.labelColor; + statusColor = NSColor.secondaryLabelColor; } fTitleAttributes[NSForegroundColorAttributeName] = titleColor; @@ -386,7 +386,7 @@ CGFloat minimalTitleRightBound; if (minimal) { - NSAttributedString * minimalString = [self attributedStatusString: [self minimalStatusString]]; + NSAttributedString * minimalString = [self attributedStatusString: self.minimalStatusString]; NSRect minimalStatusRect = [self rectForMinimalStatusWithString: minimalString inBounds: cellFrame]; if (!fHover) @@ -398,7 +398,7 @@ //progress if (!minimal) { - NSAttributedString * progressString = [self attributedStatusString: [torrent progressString]]; + NSAttributedString * progressString = [self attributedStatusString: torrent.progressString]; NSRect progressRect = [self rectForProgressWithStringInBounds: cellFrame]; [progressString drawInRect: progressRect]; @@ -416,13 +416,13 @@ controlImageSuffix = @"Off"; NSImage * controlImage; - if ([torrent isActive]) + if (torrent.active) controlImage = [NSImage imageNamed: [@"Pause" stringByAppendingString: controlImageSuffix]]; else { - if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) + if (NSApp.currentEvent.modifierFlags & NSAlternateKeyMask) controlImage = [NSImage imageNamed: [@"ResumeNoWait" stringByAppendingString: controlImageSuffix]]; - else if ([torrent waitingToStart]) + else if (torrent.waitingToStart) controlImage = [NSImage imageNamed: [@"Pause" stringByAppendingString: controlImageSuffix]]; else controlImage = [NSImage imageNamed: [@"Resume" stringByAppendingString: controlImageSuffix]]; @@ -463,26 +463,27 @@ } //title - NSAttributedString * titleString = [self attributedTitle]; + NSAttributedString * titleString = self.attributedTitle; NSRect titleRect = [self rectForTitleWithString: titleString withRightBound: minimalTitleRightBound inBounds: cellFrame]; [titleString drawInRect: titleRect]; //priority icon - if ([torrent priority] != TR_PRI_NORMAL) + 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); - NSColor * priorityColor = [self backgroundStyle] == NSBackgroundStyleDark ? [NSColor whiteColor] : [NSColor labelColor]; - NSImage * priorityImage = [[NSImage imageNamed: ([torrent priority] == TR_PRI_HIGH ? @"PriorityHighTemplate" : @"PriorityLowTemplate")] imageWithColor: priorityColor]; + 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]; } //status if (!minimal) { - NSAttributedString * statusString = [self attributedStatusString: [self statusString]]; + NSAttributedString * statusString = [self attributedStatusString: self.statusString]; [statusString drawInRect: [self rectForStatusWithStringInBounds: cellFrame]]; } } @@ -495,7 +496,7 @@ CGFloat minimalTitleRightBound; if (minimal) { - NSAttributedString * minimalString = [self attributedStatusString: [self minimalStatusString]]; + NSAttributedString * minimalString = [self attributedStatusString: self.minimalStatusString]; NSRect minimalStatusRect = [self rectForMinimalStatusWithString: minimalString inBounds: cellFrame]; minimalTitleRightBound = NSMinX(minimalStatusRect); @@ -507,13 +508,13 @@ minimalTitleRightBound = MIN(minimalTitleRightBound, NSMinX(controlRect)); } - NSAttributedString * titleString = [self attributedTitle]; + 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 isFlipped])) + && 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); @@ -527,8 +528,8 @@ cellFrame.origin.x += PADDING_EXPANSION_FRAME; cellFrame.origin.y += PADDING_EXPANSION_FRAME; - fTitleAttributes[NSForegroundColorAttributeName] = [NSColor labelColor]; - NSAttributedString * titleString = [self attributedTitle]; + fTitleAttributes[NSForegroundColorAttributeName] = NSColor.labelColor; + NSAttributedString * titleString = self.attributedTitle; [titleString drawInRect: cellFrame]; } @@ -540,7 +541,7 @@ { const BOOL minimal = [fDefaults boolForKey: @"SmallView"]; - const CGFloat piecesBarPercent = [(TorrentTableView *)[self controlView] piecesBarPercent]; + const CGFloat piecesBarPercent = ((TorrentTableView *)self.controlView).piecesBarPercent; if (piecesBarPercent > 0.0) { NSRect piecesBarRect, regularBarRect; @@ -552,7 +553,7 @@ } else { - [[self representedObject] setPreviousFinishedPieces: nil]; + ((Torrent *)self.representedObject).previousFinishedPieces = nil; [self drawRegularBar: barRect]; } @@ -564,88 +565,88 @@ - (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); + NSDivideRect(barRect, &haveRect, &missingRect, round(torrent.progress * NSWidth(barRect)), NSMinXEdge); if (!NSIsEmptyRect(haveRect)) { - if ([torrent isActive]) + if (torrent.active) { - if ([torrent isChecking]) - [[ProgressGradients progressYellowGradient] drawInRect: haveRect angle: 90]; - else if ([torrent isSeeding]) + if (torrent.checking) + [ProgressGradients.progressYellowGradient drawInRect: haveRect angle: 90]; + else if (torrent.seeding) { NSRect ratioHaveRect, ratioRemainingRect; - NSDivideRect(haveRect, &ratioHaveRect, &ratioRemainingRect, round([torrent progressStopRatio] * NSWidth(haveRect)), + 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.waitingToStart) { - if ([torrent allDownloaded]) - [[ProgressGradients progressDarkGreenGradient] drawInRect: haveRect angle: 90]; + if (torrent.allDownloaded) + [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]) + if (!torrent.allDownloaded) { - const CGFloat widthRemaining = round(NSWidth(barRect) * [torrent progressLeft]); + const CGFloat widthRemaining = round(NSWidth(barRect) * torrent.progressLeft); NSRect wantedRect; NSDivideRect(missingRect, &wantedRect, &missingRect, widthRemaining, NSMinXEdge); //not-available section - if ([torrent isActive] && ![torrent isChecking] && [torrent availableDesired] < 1.0 + if (torrent.active && !torrent.checking && torrent.availableDesired < 1.0 && [fDefaults boolForKey: @"DisplayProgressBarAvailable"]) { NSRect unavailableRect; - NSDivideRect(wantedRect, &wantedRect, &unavailableRect, round(NSWidth(wantedRect) * [torrent availableDesired]), + 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 isMagnet]) - [[ProgressGradients progressLightGrayGradient] drawInRect: missingRect angle: 90]; + if (!torrent.magnet) + [ProgressGradients.progressLightGrayGradient drawInRect: missingRect angle: 90]; else - [[ProgressGradients progressRedGradient] drawInRect: missingRect angle: 90]; + [ProgressGradients.progressRedGradient drawInRect: missingRect angle: 90]; } } - (void) drawPiecesBar: (NSRect) barRect { - Torrent * torrent = [self representedObject]; + Torrent * torrent = self.representedObject; //fill an all-white bar for magnet links - if ([torrent isMagnet]) + if (torrent.magnet) { [[NSColor colorWithCalibratedWhite: 1.0 alpha: [fDefaults boolForKey: @"SmallView"] ? 0.25 : 1.0] set]; NSRectFillUsingOperation(barRect, NSCompositeSourceOver); return; } - NSInteger pieceCount = MIN([torrent pieceCount], MAX_PIECES); + NSInteger pieceCount = MIN(torrent.pieceCount, MAX_PIECES); float * piecesPercent = malloc(pieceCount * sizeof(float)); [torrent getAmountFinished: piecesPercent size: pieceCount]; @@ -653,7 +654,7 @@ pixelsWide: pieceCount pixelsHigh: 1 bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES isPlanar: NO colorSpaceName: NSCalibratedRGBColorSpace bytesPerRow: 0 bitsPerPixel: 0]; - NSIndexSet * previousFinishedIndexes = [torrent previousFinishedPieces]; + NSIndexSet * previousFinishedIndexes = torrent.previousFinishedPieces; NSMutableIndexSet * finishedIndexes = [NSMutableIndexSet indexSet]; for (NSInteger i = 0; i < pieceCount; i++) @@ -662,13 +663,13 @@ if (piecesPercent[i] == 1.0f) { if (previousFinishedIndexes && ![previousFinishedIndexes containsIndex: i]) - pieceColor = [NSColor orangeColor]; + pieceColor = NSColor.orangeColor; else pieceColor = fBluePieceColor; [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]; @@ -676,7 +677,7 @@ free(piecesPercent); - [torrent setPreviousFinishedPieces: [finishedIndexes count] > 0 ? finishedIndexes : nil]; //don't bother saving if none are complete + 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 @@ -715,7 +716,7 @@ 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); @@ -815,7 +816,7 @@ - (NSAttributedString *) attributedTitle { - NSString * title = [(Torrent *)[self representedObject] name]; + NSString * title = ((Torrent *)self.representedObject).name; return [[NSAttributedString alloc] initWithString: title attributes: fTitleAttributes]; } @@ -830,14 +831,14 @@ return NSLocalizedString(@"Show the data file in Finder", "Torrent cell -> button info"); else if (fMouseDownControlButton || (!fTracking && fHoverControl)) { - Torrent * torrent = [self representedObject]; - if ([torrent isActive]) + Torrent * torrent = self.representedObject; + if (torrent.active) return NSLocalizedString(@"Pause the transfer", "Torrent Table -> tooltip"); else { - if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) + if (NSApp.currentEvent.modifierFlags & NSAlternateKeyMask) return NSLocalizedString(@"Resume the transfer right away", "Torrent cell -> button info"); - else if ([torrent waitingToStart]) + else if (torrent.waitingToStart) return NSLocalizedString(@"Stop waiting to start", "Torrent cell -> button info"); else return NSLocalizedString(@"Resume the transfer", "Torrent cell -> button info"); @@ -852,16 +853,16 @@ - (NSString *) statusString { NSString * buttonString; - if ((buttonString = [self buttonString])) + if ((buttonString = self.buttonString)) return buttonString; else - return [[self representedObject] statusString]; + return ((Torrent *)self.representedObject).statusString; } - (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 066dcc5a4..df1395645 100644 --- a/macosx/TorrentGroup.h +++ b/macosx/TorrentGroup.h @@ -28,14 +28,14 @@ NSMutableArray * fTorrents; } -- (id) initWithGroup: (NSInteger) group; +- (instancetype) initWithGroup: (NSInteger) group; -- (NSInteger) groupIndex; -- (NSInteger) groupOrderValue; -- (NSMutableArray *) torrents; +@property (nonatomic, readonly) NSInteger groupIndex; +@property (nonatomic, readonly) NSInteger groupOrderValue; +@property (nonatomic, readonly) NSMutableArray *torrents; -- (CGFloat) ratio; -- (CGFloat) uploadRate; -- (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 4c6601bba..f3827d19a 100644 --- a/macosx/TorrentGroup.m +++ b/macosx/TorrentGroup.m @@ -29,7 +29,7 @@ @implementation TorrentGroup -- (id) initWithGroup: (NSInteger) group +- (instancetype) initWithGroup: (NSInteger) group { if ((self = [super init])) { @@ -52,7 +52,7 @@ - (NSInteger) groupOrderValue { - return [[GroupsController groups] rowValueForIndex: fGroup]; + return [GroupsController.groups rowValueForIndex: fGroup]; } - (NSMutableArray *) torrents @@ -65,8 +65,8 @@ uint64_t uploaded = 0, downloaded = 0; for (Torrent * torrent in fTorrents) { - uploaded += [torrent uploadedTotal]; - downloaded += [torrent downloadedTotal]; + uploaded += torrent.uploadedTotal; + downloaded += torrent.downloadedTotal; } return tr_getRatio(uploaded, downloaded); @@ -76,7 +76,7 @@ { CGFloat rate = 0.0; for (Torrent * torrent in fTorrents) - rate += [torrent uploadRate]; + rate += torrent.uploadRate; return rate; } @@ -85,7 +85,7 @@ { CGFloat rate = 0.0; for (Torrent * torrent in fTorrents) - rate += [torrent downloadRate]; + rate += torrent.downloadRate; return rate; } diff --git a/macosx/TorrentTableView.h b/macosx/TorrentTableView.h index 0cae5b0e9..324e71b88 100644 --- a/macosx/TorrentTableView.h +++ b/macosx/TorrentTableView.h @@ -67,8 +67,8 @@ - (void) setActionButtonHover: (NSInteger) row; - (void) selectValues: (NSArray *) values; -- (NSArray *) selectedValues; -- (NSArray *) selectedTorrents; +@property (nonatomic, readonly) NSArray *selectedValues; +@property (nonatomic, readonly) NSArray *selectedTorrents; - (NSRect) iconRectForRow: (NSInteger) row; @@ -88,7 +88,7 @@ - (void) setPriority: (id) sender; - (void) togglePiecesBar; -- (CGFloat) piecesBarPercent; +@property (nonatomic, readonly) CGFloat piecesBarPercent; - (void) selectAndScrollToRow: (NSInteger) row; diff --git a/macosx/TorrentTableView.m b/macosx/TorrentTableView.m index 9d161dbf1..fc1e58501 100644 --- a/macosx/TorrentTableView.m +++ b/macosx/TorrentTableView.m @@ -53,11 +53,11 @@ @implementation TorrentTableView -- (id) initWithCoder: (NSCoder *) decoder +- (instancetype) initWithCoder: (NSCoder *) decoder { if ((self = [super initWithCoder: decoder])) { - fDefaults = [NSUserDefaults standardUserDefaults]; + fDefaults = NSUserDefaults.standardUserDefaults; fTorrentCell = [[TorrentCell alloc] init]; @@ -74,7 +74,7 @@ fActionPopoverShown = NO; - [self setDelegate: self]; + self.delegate = self; fPiecesBarPercent = [fDefaults boolForKey: @"PiecesBar"] ? 1.0 : 0.0; @@ -88,7 +88,7 @@ - (void) dealloc { - [[NSNotificationCenter defaultCenter] removeObserver: self]; + [NSNotificationCenter.defaultCenter removeObserver: self]; } - (void) awakeFromNib @@ -96,7 +96,7 @@ //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 @@ -132,7 +132,7 @@ - (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 @@ -151,13 +151,14 @@ { if (!tableColumn) { - [cell setRepresentedObject: item]; + TorrentCell * torrentCell = cell; + torrentCell.representedObject = item; const NSInteger row = [self rowForItem: item]; - [cell setHover: row == fMouseRow]; - [cell setControlHover: row == fMouseControlRow]; - [cell setRevealHover: row == fMouseRevealRow]; - [cell setActionHover: row == fMouseActionRow]; + torrentCell.hover = (row == fMouseRow); + torrentCell.controlHover = (row == fMouseControlRow); + torrentCell.revealHover = (row == fMouseRevealRow); + torrentCell.actionHover = (row == fMouseActionRow); } } } @@ -181,14 +182,14 @@ - (NSString *) outlineView: (NSOutlineView *) outlineView typeSelectStringForTableColumn: (NSTableColumn *) tableColumn item: (id) item { if ([item isKindOfClass: [Torrent class]]) - return [(Torrent *)item name]; + return ((Torrent *)item).name; else - return [[self dataSource] outlineView:outlineView objectValueForTableColumn:[self tableColumnWithIdentifier:@"Group"] byItem:item]; + 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]; + 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"]) @@ -196,7 +197,7 @@ : NSLocalizedString(@"Upload speed", "Torrent table -> group row -> tooltip"); else if (ident) { - NSUInteger count = [[item torrents] count]; + NSUInteger count = ((TorrentGroup *)item).torrents.count; if (count == 1) return NSLocalizedString(@"1 transfer", "Torrent table -> group row -> tooltip"); else @@ -212,11 +213,11 @@ [super updateTrackingAreas]; [self removeTrackingAreas]; - const NSRange rows = [self rowsInRect: [self visibleRect]]; + const NSRange 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]]) @@ -235,9 +236,9 @@ fMouseRevealRow = -1; fMouseActionRow = -1; - for (NSTrackingArea * area in [self trackingAreas]) + for (NSTrackingArea * area in self.trackingAreas) { - if ([area owner] == self && [area userInfo][@"Row"]) + if (area.owner == self && area.userInfo[@"Row"]) [self removeTrackingArea: area]; } } @@ -274,12 +275,12 @@ - (void) mouseEntered: (NSEvent *) event { - NSDictionary * dict = (NSDictionary *)[event userData]; + NSDictionary * dict = (NSDictionary *)event.userData; NSNumber * row; if ((row = dict[@"Row"])) { - NSInteger rowVal = [row integerValue]; + NSInteger rowVal = row.integerValue; NSString * type = dict[@"Type"]; if ([type isEqualToString: @"Action"]) fMouseActionRow = rowVal; @@ -300,7 +301,7 @@ - (void) mouseExited: (NSEvent *) event { - NSDictionary * dict = (NSDictionary *)[event userData]; + NSDictionary * dict = (NSDictionary *)event.userData; NSNumber * row; if ((row = dict[@"Row"])) @@ -319,7 +320,7 @@ return; } - [self setNeedsDisplayInRect: [self rectOfRow: [row integerValue]]]; + [self setNeedsDisplayInRect: [self rectOfRow: row.integerValue]]; } } @@ -333,30 +334,32 @@ - (void) outlineViewItemDidExpand: (NSNotification *) notification { - NSInteger value = [[notification userInfo][@"NSObject"] groupIndex]; + 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]; + [NSNotificationCenter.defaultCenter postNotificationName: @"OutlineExpandCollapse" object: self]; } } - (void) outlineViewItemDidCollapse: (NSNotification *) notification { - NSInteger value = [[notification userInfo][@"NSObject"] groupIndex]; + TorrentGroup * group = notification.userInfo[@"NSObject"]; + NSInteger value = group.groupIndex; if (value < 0) value = MAX_GROUP; [fCollapsedGroups addIndex: value]; - [[NSNotificationCenter defaultCenter] postNotificationName: @"OutlineExpandCollapse" object: self]; + [NSNotificationCenter.defaultCenter postNotificationName: @"OutlineExpandCollapse" object: self]; } - (void) mouseDown: (NSEvent *) event { - NSPoint point = [self convertPoint: [event locationInWindow] fromView: nil]; + NSPoint point = [self convertPoint: event.locationInWindow fromView: nil]; const NSInteger row = [self rowAtPoint: point]; //check to toggle group status before anything else @@ -372,7 +375,7 @@ //if pushing a button, don't change the selected rows if (pushed) - fSelectedValues = [self selectedValues]; + fSelectedValues = self.selectedValues; [super mouseDown: event]; @@ -384,7 +387,7 @@ #warning maybe make appear on mouse down [self displayTorrentActionPopoverForEvent: event]; } - else if (!pushed && [event clickCount] == 2) //double click + else if (!pushed && event.clickCount == 2) //double click { id item = nil; if (row != -1) @@ -417,11 +420,12 @@ } else { - const NSInteger group = [item groupIndex]; - for (NSInteger i = 0; i < [self numberOfRows]; i++) + TorrentGroup * group = (TorrentGroup *)item; + const NSInteger groupIndex = group.groupIndex; + for (NSInteger i = 0; i < self.numberOfRows; i++) { id tableItem = [self itemAtRow: i]; - if ([tableItem isKindOfClass: [TorrentGroup class]] && group == [tableItem groupIndex]) + if ([tableItem isKindOfClass: [TorrentGroup class]] && groupIndex == ((TorrentGroup *)tableItem).groupIndex) { [indexSet addIndex: i]; break; @@ -435,10 +439,10 @@ - (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]) + for (NSUInteger i = selectedIndexes.firstIndex; i != NSNotFound; i = [selectedIndexes indexGreaterThanIndex: i]) [values addObject: [self itemAtRow: i]]; return values; @@ -446,20 +450,20 @@ - (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]; else { - NSArray * groupTorrents = [item torrents]; + NSArray * groupTorrents = ((TorrentGroup *)item).torrents; [torrents addObjectsFromArray: groupTorrents]; if ([self isItemExpanded: item]) - i +=[groupTorrents count]; + i +=groupTorrents.count; } } @@ -468,7 +472,7 @@ - (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]) @@ -492,13 +496,13 @@ //option-command-f will focus the filter bar's search field - (void) keyDown: (NSEvent *) event { - const unichar firstChar = [[event charactersIgnoringModifiers] characterAtIndex: 0]; + const unichar firstChar = [event.charactersIgnoringModifiers characterAtIndex: 0]; - if (firstChar == 'f' && [event modifierFlags] & NSAlternateKeyMask && [event modifierFlags] & NSCommandKeyMask) + if (firstChar == 'f' && event.modifierFlags & NSAlternateKeyMask && event.modifierFlags & NSCommandKeyMask) [fController focusFilterField]; else if (firstChar == ' ') [fController toggleQuickLook: nil]; - else if ([event keyCode] == 53) //esc key + else if (event.keyCode == 53) //esc key [self deselectAll: nil]; else [super keyDown: event]; @@ -512,24 +516,24 @@ - (void) paste: (id) sender { NSURL * url; - if ((url = [NSURL URLFromPasteboard: [NSPasteboard generalPasteboard]])) - [fController openURL: [url absoluteString]]; + if ((url = [NSURL URLFromPasteboard: NSPasteboard.generalPasteboard])) + [fController openURL: url.absoluteString]; else { - 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) { - pbItem = [pbItem stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; + 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]]; + for (NSTextCheckingResult * result in [detector matchesInString: pbItem options: 0 range: NSMakeRange(0, pbItem.length)]) + [fController openURL: result.URL.absoluteString]; } } } @@ -538,22 +542,22 @@ - (BOOL) validateMenuItem: (NSMenuItem *) menuItem { - SEL action = [menuItem action]; + 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) { - pbItem = [pbItem stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; + pbItem = [pbItem stringByTrimmingCharactersInSet: NSCharacterSet.whitespaceAndNewlineCharacterSet]; if (([pbItem rangeOfString: @"magnet:" options: (NSAnchoredSearch | NSCaseInsensitiveSearch)].location != NSNotFound) - || [detector firstMatchInString: pbItem options: 0 range: NSMakeRange(0, [pbItem length])]) + || [detector firstMatchInString: pbItem options: 0 range: NSMakeRange(0, pbItem.length)]) return YES; } } @@ -566,13 +570,13 @@ - (void) toggleControlForTorrent: (Torrent *) torrent { - if ([torrent isActive]) + if (torrent.active) [fController stopTorrents: @[torrent]]; else { - if ([NSEvent modifierFlags] & NSAlternateKeyMask) + if (NSEvent.modifierFlags & NSAlternateKeyMask) [fController resumeTorrentsNoWait: @[torrent]]; - else if ([torrent waitingToStart]) + else if (torrent.waitingToStart) [fController stopTorrents: @[torrent]]; else [fController resumeTorrents: @[torrent]]; @@ -581,7 +585,7 @@ - (void) displayTorrentActionPopoverForEvent: (NSEvent *) event { - const NSInteger row = [self rowAtPoint: [self convertPoint: [event locationInWindow] fromView: nil]]; + const NSInteger row = [self rowAtPoint: [self convertPoint: event.locationInWindow fromView: nil]]; if (row < 0) return; @@ -593,10 +597,10 @@ Torrent * torrent = [self itemAtRow: row]; NSPopover * popover = [[NSPopover alloc] init]; - [popover setBehavior: NSPopoverBehaviorTransient]; + popover.behavior = NSPopoverBehaviorTransient; InfoOptionsViewController * infoViewController = [[InfoOptionsViewController alloc] init]; - [popover setContentViewController: infoViewController]; - [popover setDelegate: self]; + popover.contentViewController = infoViewController; + popover.delegate = self; [popover showRelativeToRect: rect ofView: self preferredEdge: NSMaxYEdge]; [infoViewController setInfoForTorrents: @[torrent]]; @@ -619,13 +623,13 @@ - (void) menuNeedsUpdate: (NSMenu *) menu { //this method seems to be called when it shouldn't be - if (!fMenuTorrent || ![menu supermenu]) + if (!fMenuTorrent || !menu.supermenu) return; if (menu == fUploadMenu || menu == fDownloadMenu) { NSMenuItem * item; - if ([menu numberOfItems] == 3) + 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 }; @@ -635,8 +639,8 @@ item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimit:) keyEquivalent: @""]; - [item setTarget: self]; - [item setRepresentedObject: @(speedLimitActionValue[i])]; + item.target = self; + item.representedObject = @(speedLimitActionValue[i]); [menu addItem: item]; } } @@ -645,17 +649,17 @@ const BOOL limit = [fMenuTorrent usesSpeedLimit: upload]; item = [menu itemWithTag: ACTION_MENU_LIMIT_TAG]; - [item setState: limit ? NSOnState : NSOffState]; - [item setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)", - "torrent action menu -> upload/download limit"), [fMenuTorrent speedLimit: upload]]]; + item.state = limit ? NSOnState : NSOffState; + 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 setState: !limit ? NSOnState : NSOffState]; + item.state = !limit ? NSOnState : NSOffState; } else if (menu == fRatioMenu) { NSMenuItem * item; - if ([menu numberOfItems] == 4) + if (menu.numberOfItems == 4) { const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1.0 }; @@ -663,37 +667,37 @@ { item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]] action: @selector(setQuickRatio:) keyEquivalent: @""]; - [item setTarget: self]; - [item setRepresentedObject: @(ratioLimitActionValue[i])]; + item.target = self; + item.representedObject = @(ratioLimitActionValue[i]); [menu addItem: item]; } } - const tr_ratiolimit mode = [fMenuTorrent ratioSetting]; + const tr_ratiolimit mode = fMenuTorrent.ratioSetting; item = [menu itemWithTag: ACTION_MENU_LIMIT_TAG]; - [item setState: mode == TR_RATIOLIMIT_SINGLE ? NSOnState : NSOffState]; - [item setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)", - "torrent action menu -> ratio stop"), [fMenuTorrent ratioLimit]]]; + 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 = [menu itemWithTag: ACTION_MENU_UNLIMITED_TAG]; - [item setState: mode == TR_RATIOLIMIT_UNLIMITED ? NSOnState : NSOffState]; + item.state = mode == TR_RATIOLIMIT_UNLIMITED ? NSOnState : NSOffState; item = [menu itemWithTag: ACTION_MENU_GLOBAL_TAG]; - [item setState: mode == TR_RATIOLIMIT_GLOBAL ? NSOnState : NSOffState]; + item.state = mode == TR_RATIOLIMIT_GLOBAL ? NSOnState : NSOffState; } else if (menu == fPriorityMenu) { - const tr_priority_t priority = [fMenuTorrent priority]; + const tr_priority_t priority = fMenuTorrent.priority; NSMenuItem * item = [menu itemWithTag: ACTION_MENU_PRIORITY_HIGH_TAG]; - [item setState: priority == TR_PRI_HIGH ? NSOnState : NSOffState]; + item.state = priority == TR_PRI_HIGH ? NSOnState : NSOffState; item = [menu itemWithTag: ACTION_MENU_PRIORITY_NORMAL_TAG]; - [item setState: priority == TR_PRI_NORMAL ? NSOnState : NSOffState]; + item.state = priority == TR_PRI_NORMAL ? NSOnState : NSOffState; item = [menu itemWithTag: ACTION_MENU_PRIORITY_LOW_TAG]; - [item setState: priority == TR_PRI_LOW ? NSOnState : NSOffState]; + item.state = priority == TR_PRI_LOW ? NSOnState : NSOffState; } } @@ -703,7 +707,7 @@ const BOOL 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 @@ -712,14 +716,14 @@ [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 { - [fMenuTorrent setUseGlobalSpeedLimit: [(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 @@ -740,17 +744,17 @@ return; } - [fMenuTorrent setRatioSetting: mode]; + fMenuTorrent.ratioSetting = mode; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptions" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateOptions" object: nil]; } - (void) setQuickRatio: (id) sender { - [fMenuTorrent setRatioSetting: TR_RATIOLIMIT_SINGLE]; - [fMenuTorrent setRatioLimit: [[sender representedObject] floatValue]]; + 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 @@ -772,9 +776,9 @@ priority = TR_PRI_NORMAL; } - [fMenuTorrent setPriority: priority]; + fMenuTorrent.priority = priority; - [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateUI" object: nil]; + [NSNotificationCenter.defaultCenter postNotificationName: @"UpdateUI" object: nil]; } - (void) togglePiecesBar @@ -785,9 +789,9 @@ //this stops a previous animation fPiecesBarAnimation = [[NSAnimation alloc] initWithDuration: TOGGLE_PROGRESS_SECONDS animationCurve: NSAnimationEaseIn]; - [fPiecesBarAnimation setAnimationBlockingMode: NSAnimationNonblocking]; - [fPiecesBarAnimation setProgressMarks: progressMarks]; - [fPiecesBarAnimation setDelegate: self]; + fPiecesBarAnimation.animationBlockingMode = NSAnimationNonblocking; + fPiecesBarAnimation.progressMarks = progressMarks; + fPiecesBarAnimation.delegate = self; [fPiecesBarAnimation startAnimation]; } @@ -809,7 +813,7 @@ else fPiecesBarPercent = 1.0 - progress; - [self setNeedsDisplay: YES]; + self.needsDisplay = YES; } } @@ -821,19 +825,19 @@ - (void) selectAndScrollToRow: (NSInteger) row { NSParameterAssert(row >= 0); - NSParameterAssert(row < [self numberOfRows]); + NSParameterAssert(row < self.numberOfRows); [self selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO]; const NSRect rowRect = [self rectOfRow: row]; - const NSRect viewRect = [[self superview] frame]; + const NSRect 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 @@ -846,7 +850,7 @@ if (row < 0 || [[self itemAtRow: row] isKindOfClass: [Torrent class]]) return NO; - NSString * ident = [[self tableColumns][[self columnAtPoint: point]] identifier]; + NSString * ident = (self.tableColumns[[self columnAtPoint: point]]).identifier; return [ident isEqualToString: @"UL"] || [ident isEqualToString: @"UL Image"] || [ident isEqualToString: @"DL"] || [ident isEqualToString: @"DL Image"]; } @@ -855,8 +859,8 @@ { const BOOL ratio = [fDefaults boolForKey: @"DisplayGroupRowRatio"]; - [[self tableColumnWithIdentifier: @"DL"] setHidden: ratio]; - [[self tableColumnWithIdentifier: @"DL Image"] setHidden: ratio]; + [self tableColumnWithIdentifier: @"DL"].hidden = ratio; + [self tableColumnWithIdentifier: @"DL Image"].hidden = ratio; } @end diff --git a/macosx/TrackerCell.m b/macosx/TrackerCell.m index 3c3721360..a693e6b63 100644 --- a/macosx/TrackerCell.m +++ b/macosx/TrackerCell.m @@ -38,7 +38,7 @@ @interface TrackerCell (Private) -- (NSImage *) favIcon; +@property (nonatomic, readonly) NSImage *favIcon; - (void) loadTrackerIcon: (NSString *) baseAddress; - (NSRect) imageRectForBounds: (NSRect) bounds; @@ -48,7 +48,7 @@ - (NSRect) rectForStatusWithString: (NSAttributedString *) string withAboveRect: (NSRect) aboveRect withRightRect: (NSRect) rightRect inBounds: (NSRect) bounds; -- (NSAttributedString *) attributedName; +@property (nonatomic, readonly) NSAttributedString *attributedName; - (NSAttributedString *) attributedStatusWithString: (NSString *) statusString; - (NSAttributedString *) attributedCount: (NSInteger) count; @@ -66,12 +66,12 @@ NSMutableSet * fTrackerIconLoading; fTrackerIconLoading = [[NSMutableSet alloc] init]; } -- (id) init +- (instancetype) init { if ((self = [super init])) { - NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; - [paragraphStyle setLineBreakMode: NSLineBreakByTruncatingTail]; + NSMutableParagraphStyle * paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy]; + paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; fNameAttributes = [[NSMutableDictionary alloc] initWithObjectsAndKeys: [NSFont messageFontOfSize: 12.0], NSFontAttributeName, @@ -99,38 +99,38 @@ NSMutableSet * fTrackerIconLoading; - (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; - if ([self backgroundStyle] == NSBackgroundStyleDark) - nameColor = statusColor = [NSColor whiteColor]; + if (self.backgroundStyle == NSBackgroundStyleDark) + nameColor = statusColor = NSColor.whiteColor; else { - nameColor = [NSColor labelColor]; - statusColor = [NSColor secondaryLabelColor]; + nameColor = NSColor.labelColor; + statusColor = NSColor.secondaryLabelColor; } fNameAttributes[NSForegroundColorAttributeName] = nameColor; fStatusAttributes[NSForegroundColorAttributeName] = statusColor; - TrackerNode * node = (TrackerNode *)[self objectValue]; + TrackerNode * node = (TrackerNode *)self.objectValue; //name - NSAttributedString * nameString = [self attributedName]; + NSAttributedString * nameString = self.attributedName; const NSRect nameRect = [self rectForNameWithString: nameString inBounds: cellFrame]; [nameString drawInRect: nameRect]; //count strings - NSAttributedString * seederString = [self attributedCount: [node totalSeeders]]; + NSAttributedString * seederString = [self attributedCount: node.totalSeeders]; const NSRect seederRect = [self rectForCountWithString: seederString withAboveRect: nameRect inBounds: cellFrame]; [seederString drawInRect: seederRect]; - NSAttributedString * leecherString = [self attributedCount: [node totalLeechers]]; + NSAttributedString * leecherString = [self attributedCount: node.totalLeechers]; const NSRect leecherRect = [self rectForCountWithString: leecherString withAboveRect: seederRect inBounds: cellFrame]; [leecherString drawInRect: leecherRect]; - NSAttributedString * downloadedString = [self attributedCount: [node totalDownloaded]]; + NSAttributedString * downloadedString = [self attributedCount: node.totalDownloaded]; const NSRect downloadedRect = [self rectForCountWithString: downloadedString withAboveRect: leecherRect inBounds: cellFrame]; [downloadedString drawInRect: downloadedRect]; @@ -154,17 +154,17 @@ NSMutableSet * fTrackerIconLoading; [downloadedLabelString drawInRect: downloadedLabelRect]; //status strings - NSAttributedString * lastAnnounceString = [self attributedStatusWithString: [node lastAnnounceStatusString]]; + NSAttributedString * lastAnnounceString = [self attributedStatusWithString: node.lastAnnounceStatusString]; const NSRect lastAnnounceRect = [self rectForStatusWithString: lastAnnounceString withAboveRect: nameRect withRightRect: seederLabelRect inBounds: cellFrame]; [lastAnnounceString drawInRect: lastAnnounceRect]; - NSAttributedString * nextAnnounceString = [self attributedStatusWithString: [node nextAnnounceStatusString]]; + NSAttributedString * nextAnnounceString = [self attributedStatusWithString: node.nextAnnounceStatusString]; const NSRect nextAnnounceRect = [self rectForStatusWithString: nextAnnounceString withAboveRect: lastAnnounceRect withRightRect: leecherLabelRect inBounds: cellFrame]; [nextAnnounceString drawInRect: nextAnnounceRect]; - NSAttributedString * lastScrapeString = [self attributedStatusWithString: [node lastScrapeStatusString]]; + NSAttributedString * lastScrapeString = [self attributedStatusWithString: node.lastScrapeStatusString]; const NSRect lastScrapeRect = [self rectForStatusWithString: lastScrapeString withAboveRect: nextAnnounceRect withRightRect: downloadedLabelRect inBounds: cellFrame]; [lastScrapeString drawInRect: lastScrapeRect]; @@ -177,20 +177,20 @@ NSMutableSet * fTrackerIconLoading; - (NSImage *) favIcon { id icon = nil; - NSURL * address = [NSURL URLWithString: [(TrackerNode *)[self objectValue] fullAnnounceAddress]]; + NSURL * address = [NSURL URLWithString: ((TrackerNode *)self.objectValue).fullAnnounceAddress]; NSString * host; - if ((host = [address host])) + if ((host = address.host)) { //don't try to parse ip address - const BOOL separable = !tr_addressIsIP([host UTF8String]); + const BOOL separable = !tr_addressIsIP(host.UTF8String); NSArray * hostComponents = separable ? [host componentsSeparatedByString: @"."] : nil; //let's try getting the tracker address without using any subdomains NSString * baseAddress; - if (separable && [hostComponents count] > 1) + if (separable && hostComponents.count > 1) baseAddress = [NSString stringWithFormat: @"http://%@.%@", - hostComponents[[hostComponents count]-2], [hostComponents lastObject]]; + hostComponents[hostComponents.count-2], hostComponents.lastObject]; else baseAddress = [NSString stringWithFormat: @"http://%@", host]; @@ -292,7 +292,7 @@ NSMutableSet * fTrackerIconLoading; - (NSAttributedString *) attributedName { - NSString * name = [(TrackerNode *)[self objectValue] host]; + NSString * name = ((TrackerNode *)self.objectValue).host; return [[NSAttributedString alloc] initWithString: name attributes: fNameAttributes]; } diff --git a/macosx/TrackerNode.h b/macosx/TrackerNode.h index 6b14ae451..1d740a93f 100644 --- a/macosx/TrackerNode.h +++ b/macosx/TrackerNode.h @@ -30,23 +30,23 @@ @property (nonatomic, weak, readonly) Torrent * torrent; -- (id) initWithTrackerStat: (tr_tracker_stat *) stat torrent: (Torrent *) torrent; +- (instancetype) initWithTrackerStat: (tr_tracker_stat *) stat torrent: (Torrent *) torrent; - (BOOL) isEqual: (id) object; -- (NSString *) host; -- (NSString *) fullAnnounceAddress; +@property (nonatomic, readonly) NSString *host; +@property (nonatomic, readonly) NSString *fullAnnounceAddress; -- (NSInteger) tier; +@property (nonatomic, readonly) NSInteger tier; -- (NSUInteger) identifier; +@property (nonatomic, readonly) NSUInteger identifier; -- (NSInteger) totalSeeders; -- (NSInteger) totalLeechers; -- (NSInteger) totalDownloaded; +@property (nonatomic, readonly) NSInteger totalSeeders; +@property (nonatomic, readonly) NSInteger totalLeechers; +@property (nonatomic, readonly) NSInteger totalDownloaded; -- (NSString *) lastAnnounceStatusString; -- (NSString *) nextAnnounceStatusString; -- (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 eae4b0d35..c00cba512 100644 --- a/macosx/TrackerNode.m +++ b/macosx/TrackerNode.m @@ -29,7 +29,7 @@ tr_tracker_stat fStat; } -- (id) initWithTrackerStat: (tr_tracker_stat *) stat torrent: (Torrent *) torrent +- (instancetype) initWithTrackerStat: (tr_tracker_stat *) stat torrent: (Torrent *) torrent { if ((self = [super init])) { @@ -42,7 +42,7 @@ - (NSString *) description { - return [@"Tracker: " stringByAppendingString: [self fullAnnounceAddress]]; + return [@"Tracker: " stringByAppendingString: self.fullAnnounceAddress]; } - (id) copyWithZone: (NSZone *) zone @@ -58,11 +58,12 @@ if (![object isKindOfClass: [self class]]) return NO; - - if ([self torrent] != [object torrent]) + + typeof(self) other = (typeof(self))object; + if (self.torrent != other.torrent) return NO; - return [self tier] == [object tier] && [[self fullAnnounceAddress] isEqualToString: [object fullAnnounceAddress]]; + return self.tier == other.tier && [self.fullAnnounceAddress isEqualToString: other.fullAnnounceAddress]; } - (NSString *) host @@ -106,9 +107,9 @@ if (fStat.hasAnnounced) { NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; - [dateFormatter setDateStyle: NSDateFormatterFullStyle]; - [dateFormatter setTimeStyle: NSDateFormatterShortStyle]; - [dateFormatter setDoesRelativeDateFormatting: YES]; + dateFormatter.dateStyle = NSDateFormatterFullStyle; + dateFormatter.timeStyle = NSDateFormatterShortStyle; + dateFormatter.doesRelativeDateFormatting = YES; dateString = [dateFormatter stringFromDate: [NSDate dateWithTimeIntervalSince1970: fStat.lastAnnounceTime]]; } @@ -155,7 +156,7 @@ case TR_TRACKER_WAITING: { - const NSTimeInterval nextAnnounceTimeLeft = fStat.nextAnnounceTime - [[NSDate date] timeIntervalSince1970]; + const NSTimeInterval nextAnnounceTimeLeft = fStat.nextAnnounceTime - [NSDate date].timeIntervalSince1970; static NSDateComponentsFormatter *formatter; static dispatch_once_t onceToken; @@ -189,9 +190,9 @@ if (fStat.hasScraped) { NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; - [dateFormatter setDateStyle: NSDateFormatterFullStyle]; - [dateFormatter setTimeStyle: NSDateFormatterShortStyle]; - [dateFormatter setDoesRelativeDateFormatting: YES]; + dateFormatter.dateStyle = NSDateFormatterFullStyle; + dateFormatter.timeStyle = NSDateFormatterShortStyle; + dateFormatter.doesRelativeDateFormatting = YES; dateString = [dateFormatter stringFromDate: [NSDate dateWithTimeIntervalSince1970: fStat.lastScrapeTime]]; } diff --git a/macosx/TrackerTableView.m b/macosx/TrackerTableView.m index 181dc01f1..3715ad765 100644 --- a/macosx/TrackerTableView.m +++ b/macosx/TrackerTableView.m @@ -28,7 +28,7 @@ - (void) mouseDown: (NSEvent *) event { - [[self window] makeKeyWindow]; + [self.window makeKeyWindow]; [super mouseDown: event]; } @@ -44,24 +44,24 @@ - (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]]) { - 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"]; - NSPasteboard * pb = [NSPasteboard generalPasteboard]; + NSPasteboard * pb = NSPasteboard.generalPasteboard; [pb clearContents]; [pb writeObjects: @[text]]; } @@ -72,7 +72,7 @@ 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) @@ -89,13 +89,13 @@ - (BOOL) validateMenuItem: (NSMenuItem *) menuItem { - const SEL action = [menuItem action]; + const SEL action = menuItem.action; if (action == @selector(copy:)) - return [self numberOfSelectedRows] > 0; + 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 f77f29ad7..c372bd35c 100644 --- a/macosx/URLSheetWindowController.h +++ b/macosx/URLSheetWindowController.h @@ -33,11 +33,11 @@ Controller * fController; } -- (id) initWithController: (Controller *) controller; +- (instancetype) initWithController: (Controller *) controller; - (void) openURLEndSheet: (id) sender; - (void) openURLCancelEndSheet: (id) sender; -- (NSString *) urlString; +@property (nonatomic, readonly) NSString *urlString; @end diff --git a/macosx/URLSheetWindowController.m b/macosx/URLSheetWindowController.m index cff95ee63..55f44ced4 100644 --- a/macosx/URLSheetWindowController.m +++ b/macosx/URLSheetWindowController.m @@ -33,7 +33,7 @@ NSString * urlString = nil; -- (id) initWithController: (Controller *) controller +- (instancetype) initWithController: (Controller *) controller { if ((self = [self initWithWindowNibName: @"URLSheetWindow"])) { @@ -44,26 +44,26 @@ NSString * urlString = nil; - (void) awakeFromNib { - [fLabelField setStringValue: NSLocalizedString(@"Internet address of torrent file:", "URL sheet label")]; + fLabelField.stringValue = NSLocalizedString(@"Internet address of torrent file:", "URL sheet label"); if (urlString) { - [fTextField setStringValue: urlString]; + fTextField.stringValue = urlString; [fTextField selectText: self]; [self updateOpenButtonForURL: urlString]; } - [fOpenButton setTitle: NSLocalizedString(@"Open", "URL sheet button")]; - [fCancelButton setTitle: NSLocalizedString(@"Cancel", "URL sheet button")]; + fOpenButton.title = NSLocalizedString(@"Open", "URL sheet button"); + fCancelButton.title = NSLocalizedString(@"Cancel", "URL sheet button"); [fOpenButton sizeToFit]; [fCancelButton sizeToFit]; //size the two buttons the same - NSRect openFrame = [fOpenButton frame]; + NSRect openFrame = fOpenButton.frame; openFrame.size.width += 10.0; - NSRect cancelFrame = [fCancelButton frame]; + NSRect cancelFrame = fCancelButton.frame; cancelFrame.size.width += 10.0; if (NSWidth(openFrame) > NSWidth(cancelFrame)) @@ -71,33 +71,33 @@ NSString * urlString = nil; 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 setFrame: openFrame]; + 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; cancelFrame.origin.x = NSMinX(openFrame) - NSWidth(cancelFrame); - [fCancelButton setFrame: cancelFrame]; + fCancelButton.frame = cancelFrame; } - (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 { - [[self window] orderOut: sender]; - [NSApp endSheet: [self window] returnCode: 0]; + [self.window orderOut: sender]; + [NSApp endSheet: self.window returnCode: 0]; } - (NSString *) urlString { - return [fTextField stringValue]; + return fTextField.stringValue; } - (void) controlTextDidChange: (NSNotification *) notification { - [self updateOpenButtonForURL: [fTextField stringValue]]; + [self updateOpenButtonForURL: fTextField.stringValue]; } @end @@ -112,11 +112,11 @@ NSString * urlString = nil; else { NSRange prefixRange = [string rangeOfString: @"://"]; - if (prefixRange.location != NSNotFound && [string length] == NSMaxRange(prefixRange)) + if (prefixRange.location != NSNotFound && string.length == NSMaxRange(prefixRange)) enable = NO; } - [fOpenButton setEnabled: enable]; + fOpenButton.enabled = enable; } @end diff --git a/macosx/VDKQueue/VDKQueue.h b/macosx/VDKQueue/VDKQueue.h index c68792cdd..97b00cf4a 100755 --- a/macosx/VDKQueue/VDKQueue.h +++ b/macosx/VDKQueue/VDKQueue.h @@ -1,23 +1,23 @@ -// VDKQueue.h -// Created by Bryan D K Jones on 28 March 2012 -// Copyright 2013 Bryan D K Jones +// VDKQueue.h +// Created by Bryan D K Jones on 28 March 2012 +// Copyright 2013 Bryan D K Jones // // Based heavily on UKKQueue, which was created and copyrighted by Uli Kusterer on 21 Dec 2003. // -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source -// distribution. +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source +// distribution. // // BASED ON UKKQUEUE: @@ -72,15 +72,15 @@ // Logical OR these values into the u_int that you pass in the -addPath:notifyingAbout: method // to specify the types of notifications you're interested in. Pass the default value to receive all of them. // -#define VDKQueueNotifyAboutRename NOTE_RENAME // Item was renamed. -#define VDKQueueNotifyAboutWrite NOTE_WRITE // Item contents changed (also folder contents changed). -#define VDKQueueNotifyAboutDelete NOTE_DELETE // item was removed. -#define VDKQueueNotifyAboutAttributeChange NOTE_ATTRIB // Item attributes changed. -#define VDKQueueNotifyAboutSizeIncrease NOTE_EXTEND // Item size increased. -#define VDKQueueNotifyAboutLinkCountChanged NOTE_LINK // Item's link count changed. -#define VDKQueueNotifyAboutAccessRevocation NOTE_REVOKE // Access to item was revoked. +#define VDKQueueNotifyAboutRename NOTE_RENAME // Item was renamed. +#define VDKQueueNotifyAboutWrite NOTE_WRITE // Item contents changed (also folder contents changed). +#define VDKQueueNotifyAboutDelete NOTE_DELETE // item was removed. +#define VDKQueueNotifyAboutAttributeChange NOTE_ATTRIB // Item attributes changed. +#define VDKQueueNotifyAboutSizeIncrease NOTE_EXTEND // Item size increased. +#define VDKQueueNotifyAboutLinkCountChanged NOTE_LINK // Item's link count changed. +#define VDKQueueNotifyAboutAccessRevocation NOTE_REVOKE // Access to item was revoked. -#define VDKQueueNotifyDefault (VDKQueueNotifyAboutRename | VDKQueueNotifyAboutWrite \ +#define VDKQueueNotifyDefault (VDKQueueNotifyAboutRename | VDKQueueNotifyAboutWrite \ | VDKQueueNotifyAboutDelete | VDKQueueNotifyAboutAttributeChange \ | VDKQueueNotifyAboutSizeIncrease | VDKQueueNotifyAboutLinkCountChanged \ | VDKQueueNotifyAboutAccessRevocation) @@ -122,8 +122,8 @@ extern NSString * VDKQueueAccessRevocationNotification; BOOL _alwaysPostNotifications; // By default, notifications are posted only if there is no delegate set. Set this value to YES to have notes posted even when there is a delegate. @private - int _coreQueueFD; // The actual kqueue ID (Unix file descriptor). - NSMutableDictionary *_watchedPathEntries; // List of VDKQueuePathEntries. Keys are NSStrings of the path that each VDKQueuePathEntry is for. + int _coreQueueFD; // The actual kqueue ID (Unix file descriptor). + NSMutableDictionary *_watchedPathEntries; // List of VDKQueuePathEntries. Keys are NSStrings of the path that each VDKQueuePathEntry is for. BOOL _keepWatcherThreadRunning; // Set to NO to cancel the thread that watches _coreQueueFD for kQueue events } @@ -141,7 +141,7 @@ extern NSString * VDKQueueAccessRevocationNotification; - (void) removeAllPaths; -- (NSUInteger) numberOfWatchedPaths; // Returns the number of paths that this VDKQueue instance is actively watching. +@property (nonatomic, readonly) NSUInteger numberOfWatchedPaths; // Returns the number of paths that this VDKQueue instance is actively watching. diff --git a/macosx/VDKQueue/VDKQueue.m b/macosx/VDKQueue/VDKQueue.m index c0c1f5a1d..e84a2e429 100755 --- a/macosx/VDKQueue/VDKQueue.m +++ b/macosx/VDKQueue/VDKQueue.m @@ -1,23 +1,23 @@ -// VDKQueue.m -// Created by Bryan D K Jones on 28 March 2012 -// Copyright 2013 Bryan D K Jones +// VDKQueue.m +// Created by Bryan D K Jones on 28 March 2012 +// Copyright 2013 Bryan D K Jones // // Based heavily on UKKQueue, which was created and copyrighted by Uli Kusterer on 21 Dec 2003. // -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source -// distribution. +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source +// distribution. #import @@ -47,12 +47,12 @@ NSString * VDKQueueAccessRevocationNotification = @"VDKQueueAccessWasRevokedNoti // This is a simple model class used to hold info about each path we watch. @interface VDKQueuePathEntry : NSObject { - NSString* _path; - int _watchedFD; - u_int _subscriptionFlags; + NSString* _path; + int _watchedFD; + u_int _subscriptionFlags; } -- (id) initWithPath:(NSString*)inPath andSubscriptionFlags:(u_int)flags; +- (instancetype) initWithPath:(NSString*)inPath andSubscriptionFlags:(u_int)flags NS_DESIGNATED_INITIALIZER; @property (atomic, copy) NSString *path; @property (atomic, assign) int watchedFD; @@ -64,28 +64,28 @@ NSString * VDKQueueAccessRevocationNotification = @"VDKQueueAccessWasRevokedNoti @synthesize path = _path, watchedFD = _watchedFD, subscriptionFlags = _subscriptionFlags; -- (id) initWithPath:(NSString*)inPath andSubscriptionFlags:(u_int)flags; +- (instancetype) initWithPath:(NSString*)inPath andSubscriptionFlags:(u_int)flags; { self = [super init]; - if (self) - { - _path = [inPath copy]; - _watchedFD = open([_path fileSystemRepresentation], O_EVTONLY, 0); - if (_watchedFD < 0) - { - return nil; - } - _subscriptionFlags = flags; - } - return self; + if (self) + { + _path = [inPath copy]; + _watchedFD = open(_path.fileSystemRepresentation, O_EVTONLY, 0); + if (_watchedFD < 0) + { + return nil; + } + _subscriptionFlags = flags; + } + return self; } --(void) dealloc +-(void) dealloc { - if (_watchedFD >= 0) close(_watchedFD); - _watchedFD = -1; - + if (_watchedFD >= 0) close(_watchedFD); + _watchedFD = -1; + } @end @@ -119,21 +119,21 @@ NSString * VDKQueueAccessRevocationNotification = @"VDKQueueAccessWasRevokedNoti #pragma mark - #pragma mark INIT/DEALLOC -- (id) init +- (instancetype) init { - self = [super init]; - if (self) - { - _coreQueueFD = kqueue(); - if (_coreQueueFD == -1) - { - return nil; - } - + self = [super init]; + if (self) + { + _coreQueueFD = kqueue(); + if (_coreQueueFD == -1) + { + return nil; + } + _alwaysPostNotifications = NO; - _watchedPathEntries = [[NSMutableDictionary alloc] init]; - } - return self; + _watchedPathEntries = [[NSMutableDictionary alloc] init]; + } + return self; } @@ -155,47 +155,47 @@ NSString * VDKQueueAccessRevocationNotification = @"VDKQueueAccessWasRevokedNoti #pragma mark - #pragma mark PRIVATE METHODS -- (VDKQueuePathEntry *) addPathToQueue:(NSString *)path notifyingAbout:(u_int)flags +- (VDKQueuePathEntry *) addPathToQueue:(NSString *)path notifyingAbout:(u_int)flags { - @synchronized(self) - { + @synchronized(self) + { // Are we already watching this path? - VDKQueuePathEntry *pathEntry = _watchedPathEntries[path]; - + VDKQueuePathEntry *pathEntry = _watchedPathEntries[path]; + if (pathEntry) - { + { // All flags already set? - if(([pathEntry subscriptionFlags] & flags) == flags) + if((pathEntry.subscriptionFlags & flags) == flags) { - return pathEntry; + return pathEntry; } - - flags |= [pathEntry subscriptionFlags]; - } - - struct timespec nullts = { 0, 0 }; - struct kevent ev; - - if (!pathEntry) + + flags |= pathEntry.subscriptionFlags; + } + + struct timespec nullts = { 0, 0 }; + struct kevent ev; + + if (!pathEntry) { pathEntry = [[VDKQueuePathEntry alloc] initWithPath:path andSubscriptionFlags:flags]; } - if (pathEntry) - { - EV_SET(&ev, [pathEntry watchedFD], EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, flags, 0, (__bridge void *) pathEntry); - - [pathEntry setSubscriptionFlags:flags]; + if (pathEntry) + { + EV_SET(&ev, [pathEntry watchedFD], EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, flags, 0, (__bridge void *) pathEntry); + + pathEntry.subscriptionFlags = flags; _watchedPathEntries[path] = pathEntry; kevent(_coreQueueFD, &ev, 1, NULL, 0, &nullts); - // Start the thread that fetches and processes our events if it's not already running. - if(!_keepWatcherThreadRunning) - { - _keepWatcherThreadRunning = YES; - [NSThread detachNewThreadSelector:@selector(watcherThread:) toTarget:self withObject:nil]; - } + // Start the thread that fetches and processes our events if it's not already running. + if(!_keepWatcherThreadRunning) + { + _keepWatcherThreadRunning = YES; + [NSThread detachNewThreadSelector:@selector(watcherThread:) toTarget:self withObject:nil]; + } } return pathEntry; @@ -207,17 +207,17 @@ NSString * VDKQueueAccessRevocationNotification = @"VDKQueueAccessWasRevokedNoti - (void) watcherThread:(id)sender { - int n; - struct kevent ev; + int n; + struct kevent ev; struct timespec timeout = { 1, 0 }; // 1 second timeout. Should be longer, but we need this thread to exit when a kqueue is dealloced, so 1 second timeout is quite a while to wait. - int theFD = _coreQueueFD; // So we don't have to risk accessing iVars when the thread is terminated. + int theFD = _coreQueueFD; // So we don't have to risk accessing iVars when the thread is terminated. NSMutableArray *notesToPost = [[NSMutableArray alloc] initWithCapacity:5]; #if DEBUG_LOG_THREAD_LIFETIME - NSLog(@"watcherThread started."); + NSLog(@"watcherThread started."); #endif - + while(_keepWatcherThreadRunning) { @try @@ -295,8 +295,8 @@ NSString * VDKQueueAccessRevocationNotification = @"VDKQueueAccessWasRevokedNoti if (!_delegate || _alwaysPostNotifications) { - NSDictionary * userInfoDict = [[NSDictionary alloc] initWithObjects: @[fpath] forKeys: @[@"path"]]; - [[[NSWorkspace sharedWorkspace] notificationCenter] postNotificationName:note object:self userInfo:userInfoDict]; + NSDictionary * userInfoDict = @{@"path": fpath}; + [[NSWorkspace sharedWorkspace].notificationCenter postNotificationName:note object:self userInfo:userInfoDict]; } } @@ -313,14 +313,14 @@ NSString * VDKQueueAccessRevocationNotification = @"VDKQueueAccessWasRevokedNoti } } - // Close our kqueue's file descriptor - if(close(theFD) == -1) { + // Close our kqueue's file descriptor + if(close(theFD) == -1) { NSLog(@"VDKQueue watcherThread: Couldn't close main kqueue (%d)", errno); } #if DEBUG_LOG_THREAD_LIFETIME - NSLog(@"watcherThread finished."); + NSLog(@"watcherThread finished."); #endif } @@ -382,14 +382,14 @@ NSString * VDKQueueAccessRevocationNotification = @"VDKQueueAccessWasRevokedNoti if (!aPath) return; @synchronized(self) - { - VDKQueuePathEntry *entry = _watchedPathEntries[aPath]; + { + VDKQueuePathEntry *entry = _watchedPathEntries[aPath]; // Remove it only if we're watching it. if (entry) { [_watchedPathEntries removeObjectForKey:aPath]; } - } + } } @@ -409,7 +409,7 @@ NSString * VDKQueueAccessRevocationNotification = @"VDKQueueAccessWasRevokedNoti @synchronized(self) { - count = [_watchedPathEntries count]; + count = _watchedPathEntries.count; } return count; diff --git a/macosx/WebSeedTableView.m b/macosx/WebSeedTableView.m index ba1eb2ae5..0bd58094e 100644 --- a/macosx/WebSeedTableView.m +++ b/macosx/WebSeedTableView.m @@ -26,7 +26,7 @@ - (void) mouseDown: (NSEvent *) event { - [[self window] makeKeyWindow]; + [self.window makeKeyWindow]; [super mouseDown: event]; } @@ -37,25 +37,25 @@ - (void) copy: (id) sender { - NSIndexSet * indexes = [self selectedRowIndexes]; - NSMutableArray * addresses = [NSMutableArray arrayWithCapacity: [indexes count]]; + 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"]; - NSPasteboard * pb = [NSPasteboard generalPasteboard]; + NSPasteboard * pb = NSPasteboard.generalPasteboard; [pb clearContents]; [pb writeObjects: @[text]]; } - (BOOL) validateMenuItem: (NSMenuItem *) menuItem { - const SEL action = [menuItem action]; + const SEL action = menuItem.action; if (action == @selector(copy:)) - return [self numberOfSelectedRows] > 0; + return self.numberOfSelectedRows > 0; return YES; }