aka RedditBar, Mac OS X menu bar reddit client
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

AppDelegate.m 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. * AppDelegate.m
  3. *
  4. * Copyright (c) 2013, Thomas Buck <xythobuz@xythobuz.de>
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * - Redistributions of source code must retain the above copyright notice,
  11. * this list of conditions and the following disclaimer.
  12. *
  13. * - Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  19. * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  20. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  21. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  22. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  23. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  24. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  25. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  26. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #import "AppDelegate.h"
  30. @implementation AppDelegate
  31. NSInteger itemsBeforeLinkList = 2;
  32. NSInteger numberOfStaticMenuItems = 10;
  33. #define MULTIPLIER_PM_INTERVALL_TO_SEC 60
  34. #define RECHECK_PM_AFTER_OPEN 7
  35. #define SUBMENU_INDEX_LINK 0
  36. #define SUBMENU_INDEX_COMMENTS 1
  37. #define SUBMENU_INDEX_BOTH 2
  38. @synthesize statusMenu, statusItem, statusImage, orangeredImage, prefWindow, currentState, application, api, firstMenuItem, menuItems, redditItems, lastFullName, refreshTimer, PMItem, PMSeparator;
  39. - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
  40. statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
  41. statusImage = [NSImage imageNamed:@"icon"];
  42. [statusImage setTemplate:YES];
  43. orangeredImage = [NSImage imageNamed:@"orangered"];
  44. [orangeredImage setTemplate:YES];
  45. [statusItem setImage:statusImage];
  46. [statusItem setMenu:statusMenu];
  47. [statusItem setToolTip:NSLocalizedString(@"RedditBar", @"Main Menuitem Tooltip")];
  48. [statusItem setHighlightMode:YES];
  49. currentState = [[StateModel alloc] init];
  50. [currentState registerDefaultPreferences];
  51. [currentState loadPreferences];
  52. lastFullName = nil;
  53. [self reloadListWithOptions];
  54. [self recreateRefreshTimer];
  55. [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
  56. }
  57. -(BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification {
  58. return YES;
  59. }
  60. -(void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification {
  61. [self openUnread:nil];
  62. }
  63. -(void)recreateRefreshTimer {
  64. if (refreshTimer != nil)
  65. [refreshTimer invalidate];
  66. refreshTimer = [NSTimer scheduledTimerWithTimeInterval:(currentState.refreshInterval * MULTIPLIER_PM_INTERVALL_TO_SEC) target:self selector:@selector(refreshTick:) userInfo:nil repeats:YES];
  67. [refreshTimer fire];
  68. }
  69. -(void)refreshTick:(NSTimer *)timer {
  70. [NSThread detachNewThreadSelector:@selector(readPMs:) toTarget:api withObject:self];
  71. }
  72. -(void)readPMsCallback:(NSArray *)items {
  73. if ((items == nil) || ([items count] < 1) || (((NSNumber *)[items objectAtIndex:0]).integerValue == 0)) {
  74. [statusItem setImage:statusImage];
  75. [PMItem setHidden:TRUE];
  76. [PMSeparator setHidden:TRUE];
  77. } else {
  78. [statusItem setImage:orangeredImage];
  79. [PMItem setTitle:[NSString stringWithFormat:NSLocalizedString(@"You've got %ld unread PMs.", @"PM message"), (long)((NSNumber *)[items objectAtIndex:0]).integerValue]];
  80. [PMItem setHidden:FALSE];
  81. [PMSeparator setHidden:FALSE];
  82. if ([items count] >= 2) {
  83. if (![currentState.lastNotifiedPM isEqualToString:[items objectAtIndex:1]]) {
  84. currentState.lastNotifiedPM = [items objectAtIndex:1];
  85. [currentState savePreferences];
  86. NSUserNotification *notification = [[NSUserNotification alloc] init];
  87. notification.title = NSLocalizedString(@"New Reddit PM!", @"Notification Title");
  88. notification.informativeText = [NSString stringWithFormat:NSLocalizedString(@"You've got %ld unread PMs.", nil), (long)((NSNumber *)[items objectAtIndex:0]).integerValue];
  89. [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
  90. }
  91. }
  92. }
  93. }
  94. -(void)reloadListNotAuthenticatedCallback {
  95. [firstMenuItem setTitle:NSLocalizedString(@"Login Error!", @"Statusitem when API is not authenticated")];
  96. [self clearMenuItems];
  97. [firstMenuItem setHidden:NO];
  98. }
  99. -(void)reloadListHasFrontpageCallback:(NSArray *)items {
  100. [self reloadListHasXCallback:items ErrorMessage:NSLocalizedString(@"Error reading Frontpage!", @"Status api Read error")];
  101. }
  102. -(void)reloadListHasSubredditsCallback:(NSArray *)items {
  103. [self reloadListHasXCallback:items ErrorMessage:NSLocalizedString(@"Error reading Subreddits!", @"Status api read error")];
  104. }
  105. -(void)reloadListHasXCallback:(NSArray *)items ErrorMessage:(NSString*)error {
  106. if (items == nil) {
  107. [firstMenuItem setTitle:error];
  108. [self clearMenuItems];
  109. [firstMenuItem setHidden:NO];
  110. return;
  111. }
  112. lastFullName = [items objectAtIndex:[items count] - 1]; // last link fullname is at end of array
  113. items = [items subarrayWithRange:NSMakeRange(0, [items count] - 1)]; // Remove last item
  114. redditItems = items;
  115. [self clearMenuItems];
  116. [firstMenuItem setHidden:YES];
  117. [self putItemArrayInMenu:redditItems];
  118. }
  119. -(void)reloadListIsAuthenticatedCallback {
  120. if (currentState.useSubscriptions) {
  121. [NSThread detachNewThreadSelector:@selector(readFrontpage:) toTarget:api withObject:self];
  122. } else {
  123. [api setSubreddits:currentState.subreddits];
  124. [NSThread detachNewThreadSelector:@selector(readSubreddits:) toTarget:api withObject:self];
  125. }
  126. }
  127. -(void)singleItemReloadedCallback:(NSArray *)items {
  128. if (items != nil) {
  129. lastFullName = [items objectAtIndex:[items count] - 1]; // last link fullname is at end of array
  130. items = [items subarrayWithRange:NSMakeRange(0, [items count] - 1)]; // Remove last item
  131. NSMutableArray *newMenuItems = [NSMutableArray arrayWithArray:menuItems];
  132. NSMenuItem *item = [self prepareItemForMenu:[items objectAtIndex:0]];
  133. [newMenuItems addObject:item];
  134. [statusMenu insertItem:item atIndex:([statusMenu numberOfItems] - numberOfStaticMenuItems + itemsBeforeLinkList)];
  135. menuItems = newMenuItems;
  136. redditItems = [redditItems arrayByAddingObjectsFromArray:items];
  137. }
  138. }
  139. -(void)reloadListWithOptions {
  140. if ([currentState.modhash isEqualToString:@""]) {
  141. [firstMenuItem setTitle:NSLocalizedString(@"Not logged in!", @"Statusitem when no modhash is stored")];
  142. [self clearMenuItems];
  143. [firstMenuItem setHidden:NO];
  144. [self showPreferences:nil];
  145. return;
  146. }
  147. api = [[Reddit alloc] initWithUsername:currentState.username Modhash:currentState.modhash Length:currentState.length TitleLength:currentState.titleLength];
  148. [NSThread detachNewThreadSelector:@selector(isAuthenticatedNewModhash:) toTarget:api withObject:self];
  149. }
  150. - (IBAction)reloadCompleteList:(id)sender {
  151. [firstMenuItem setTitle:NSLocalizedString(@"Loading...", @"Statusitem when user clicks reload")];
  152. [self clearMenuItems];
  153. [firstMenuItem setHidden:NO];
  154. lastFullName = nil; // reload from start
  155. [self reloadListWithOptions];
  156. }
  157. - (IBAction)reloadNextList:(id)sender {
  158. [firstMenuItem setTitle:NSLocalizedString(@"Loading...", nil)];
  159. [self clearMenuItems];
  160. [firstMenuItem setHidden:NO];
  161. [self reloadListWithOptions];
  162. }
  163. -(void)openAndRemoveAndReloadWithIndex:(NSInteger)index Comments:(Boolean)comments Both:(Boolean)both {
  164. RedditItem *rItem = [redditItems objectAtIndex:index];
  165. NSString *url;
  166. if (comments) {
  167. url = [rItem comments];
  168. [rItem setVisitedComments:TRUE];
  169. } else {
  170. url = [rItem link];
  171. [rItem setVisitedLink:TRUE];
  172. }
  173. [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:url]];
  174. if (both) {
  175. if (!comments) {
  176. url = [rItem comments];
  177. [rItem setVisitedComments:TRUE];
  178. } else {
  179. url = [rItem link];
  180. [rItem setVisitedLink:TRUE];
  181. }
  182. [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:url]];
  183. }
  184. if (currentState.removeVisited) {
  185. Boolean removed = FALSE;
  186. if ((rItem.isSelf && (rItem.visitedLink || rItem.visitedComments)) || ((!rItem.isSelf) && rItem.visitedLink && rItem.visitedComments)) {
  187. [statusMenu removeItem:[menuItems objectAtIndex:index]];
  188. removed = TRUE;
  189. }
  190. if (removed && ([statusMenu numberOfItems] <= numberOfStaticMenuItems)) {
  191. [self reloadNextList:nil];
  192. } else {
  193. if (removed && currentState.reloadAfterVisit) {
  194. [NSThread detachNewThreadSelector:@selector(readSingleItem:) toTarget:api withObject:self];
  195. }
  196. }
  197. }
  198. }
  199. -(IBAction)linkToOpen:(id)sender {
  200. NSString *title = [(NSMenuItem *)sender title];
  201. if ([title isEqualToString:NSLocalizedString(@"Link...", nil)] || [title isEqualToString:NSLocalizedString(@"Comments...", nil)] || [title isEqualToString:NSLocalizedString(@"Both", nil)]) {
  202. for (NSUInteger i = 0; i < [menuItems count]; i++) {
  203. NSMenuItem *item = [menuItems objectAtIndex:i];
  204. NSMenu *submenu = item.submenu;
  205. Boolean isComments = [title isEqualToString:NSLocalizedString(@"Comments...", nil)];
  206. Boolean isBoth = [title isEqualToString:NSLocalizedString(@"Both", nil)];
  207. if (isBoth) {
  208. isComments = !isComments; // Open comments first, then link
  209. }
  210. NSInteger index;
  211. if ([title isEqualToString:NSLocalizedString(@"Link...", nil)])
  212. index = SUBMENU_INDEX_LINK;
  213. else if ([title isEqualToString:NSLocalizedString(@"Comments...", nil)])
  214. index = SUBMENU_INDEX_COMMENTS;
  215. else
  216. index = SUBMENU_INDEX_BOTH;
  217. if ((submenu != nil) && (sender == [submenu itemAtIndex:index])) {
  218. [self openAndRemoveAndReloadWithIndex:i Comments:isComments Both:isBoth];
  219. break;
  220. }
  221. }
  222. } else {
  223. for (NSUInteger i = 0; i < [menuItems count]; i++) {
  224. NSMenuItem *item = [menuItems objectAtIndex:i];
  225. if (sender == item) {
  226. [self openAndRemoveAndReloadWithIndex:i Comments:FALSE Both:FALSE];
  227. break;
  228. }
  229. }
  230. }
  231. }
  232. -(IBAction)openUnread:(id)sender {
  233. [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.reddit.com/message/unread"]];
  234. [NSTimer scheduledTimerWithTimeInterval:RECHECK_PM_AFTER_OPEN target:self selector:@selector(refreshTick:) userInfo:nil repeats:NO];
  235. }
  236. -(void)clearMenuItems {
  237. if (menuItems != nil) {
  238. for (NSUInteger i = 0; i < [menuItems count]; i++) {
  239. NSMenuItem *item = [menuItems objectAtIndex:i];
  240. if ([statusMenu indexOfItem:item] != -1)
  241. [statusMenu removeItem:item];
  242. }
  243. menuItems = nil;
  244. }
  245. }
  246. -(void)putItemArrayInMenu:(NSArray *)array {
  247. NSMutableArray *items = [NSMutableArray arrayWithCapacity:array.count];
  248. for (NSUInteger i = 0; i < [array count]; i++) {
  249. NSMenuItem *item = [self prepareItemForMenu:[array objectAtIndex:i]];
  250. [items addObject:item];
  251. [statusMenu insertItem:item atIndex:(i + itemsBeforeLinkList)];
  252. }
  253. menuItems = items;
  254. }
  255. -(NSMenuItem *)prepareItemForMenu:(RedditItem *)reddit {
  256. NSMenuItem *item = [[NSMenuItem alloc] init];
  257. [item setTitle:reddit.name];
  258. if (![reddit.name isEqualToString:reddit.fullName])
  259. [item setToolTip:reddit.fullName];
  260. if (reddit.isSelf) {
  261. [item setAction:@selector(linkToOpen:)];
  262. [item setKeyEquivalent:@""];
  263. } else {
  264. NSMenu *submenu = [[NSMenu alloc] init];
  265. [submenu addItemWithTitle:NSLocalizedString(@"Link...", @"Link item") action:@selector(linkToOpen:) keyEquivalent:@""];
  266. [submenu addItemWithTitle:NSLocalizedString(@"Comments...", @"comment item") action:@selector(linkToOpen:) keyEquivalent:@""];
  267. [submenu addItemWithTitle:NSLocalizedString(@"Both", @"Link & Comment item") action:@selector(linkToOpen:) keyEquivalent:@""];
  268. [item setSubmenu:submenu];
  269. }
  270. return item;
  271. }
  272. -(IBAction)showPreferences:(id)sender {
  273. [NSApp activateIgnoringOtherApps:YES];
  274. prefWindow = [[PrefController alloc] initWithWindowNibName:@"Prefs"];
  275. [prefWindow setParent:self];
  276. [prefWindow setState:currentState];
  277. [prefWindow showWindow:self];
  278. [[prefWindow window] makeKeyAndOrderFront:self];
  279. }
  280. -(IBAction)showAbout:(id)sender {
  281. [NSApp activateIgnoringOtherApps:YES];
  282. [application orderFrontStandardAboutPanel:self];
  283. }
  284. -(void)prefsDidSaveReload:(Boolean)shouldReload {
  285. [currentState savePreferences];
  286. [self recreateRefreshTimer];
  287. if (shouldReload) {
  288. [firstMenuItem setTitle:NSLocalizedString(@"Loading...", nil)];
  289. [self clearMenuItems];
  290. [firstMenuItem setHidden:NO];
  291. lastFullName = nil; // reload from start
  292. [self reloadListWithOptions];
  293. }
  294. }
  295. @end