aka RedditBar, Mac OS X menu bar reddit client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppDelegate.m 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 10
  35. #define SUBMENU_INDEX_LINK 0
  36. #define SUBMENU_INDEX_COMMENTS 1
  37. #define SUBMENU_INDEX_BOTH 2
  38. @synthesize statusMenu, statusItem, statusImage, statusHighlightImage, orangeredImage, orangeredHighlightImage, prefWindow, currentState, application, api, firstMenuItem, menuItems, redditItems, lastFullName, refreshTimer, PMItem, PMSeparator;
  39. - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
  40. statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
  41. NSBundle *bundle = [NSBundle mainBundle];
  42. statusImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"icon" ofType:@"png"]];
  43. statusHighlightImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"icon-alt" ofType:@"png"]];
  44. orangeredImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"orangered" ofType:@"png"]];
  45. orangeredHighlightImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"orangered-alt" ofType:@"png"]];
  46. [statusItem setImage:statusImage];
  47. [statusItem setAlternateImage:statusHighlightImage];
  48. [statusItem setMenu:statusMenu];
  49. [statusItem setToolTip:NSLocalizedString(@"RedditBar", @"Main Menuitem Tooltip")];
  50. [statusItem setHighlightMode:YES];
  51. currentState = [[StateModel alloc] init];
  52. [currentState registerDefaultPreferences];
  53. [currentState loadPreferences];
  54. lastFullName = nil;
  55. [self reloadListWithOptions];
  56. [self recreateRefreshTimer];
  57. }
  58. -(void)recreateRefreshTimer {
  59. if (refreshTimer != nil)
  60. [refreshTimer invalidate];
  61. refreshTimer = [NSTimer scheduledTimerWithTimeInterval:(currentState.refreshInterval * MULTIPLIER_PM_INTERVALL_TO_SEC) target:self selector:@selector(refreshTick:) userInfo:nil repeats:YES];
  62. [refreshTimer fire];
  63. }
  64. -(void)refreshTick:(NSTimer *)timer {
  65. [NSThread detachNewThreadSelector:@selector(readPMs:) toTarget:api withObject:self];
  66. }
  67. -(void)readPMsCallback:(NSNumber *)items {
  68. if ((items == nil) || ([items integerValue] == 0)) {
  69. [statusItem setImage:statusImage];
  70. [statusItem setAlternateImage:statusHighlightImage];
  71. [PMItem setHidden:TRUE];
  72. [PMSeparator setHidden:TRUE];
  73. } else {
  74. [statusItem setImage:orangeredImage];
  75. [statusItem setAlternateImage:orangeredHighlightImage];
  76. [PMItem setTitle:[NSString stringWithFormat:NSLocalizedString(@"You've got %ld unread PMs!", @"PM message"), (long)items.integerValue]];
  77. [PMItem setHidden:FALSE];
  78. [PMSeparator setHidden:FALSE];
  79. }
  80. }
  81. -(void)reloadListNotAuthenticatedCallback {
  82. [firstMenuItem setTitle:NSLocalizedString(@"Login Error!", @"Statusitem when API is not authenticated")];
  83. [self clearMenuItems];
  84. [firstMenuItem setHidden:NO];
  85. }
  86. -(void)reloadListHasFrontpageCallback:(NSArray *)items {
  87. [self reloadListHasXCallback:items ErrorMessage:NSLocalizedString(@"Error reading Frontpage!", @"Status api Read error")];
  88. }
  89. -(void)reloadListHasSubredditsCallback:(NSArray *)items {
  90. [self reloadListHasXCallback:items ErrorMessage:NSLocalizedString(@"Error reading Subreddits!", @"Status api read error")];
  91. }
  92. -(void)reloadListHasXCallback:(NSArray *)items ErrorMessage:(NSString*)error {
  93. if (items == nil) {
  94. [firstMenuItem setTitle:error];
  95. [self clearMenuItems];
  96. [firstMenuItem setHidden:NO];
  97. return;
  98. }
  99. lastFullName = [items objectAtIndex:[items count] - 1]; // last link fullname is at end of array
  100. items = [items subarrayWithRange:NSMakeRange(0, [items count] - 1)]; // Remove last item
  101. redditItems = items;
  102. [self clearMenuItems];
  103. [firstMenuItem setHidden:YES];
  104. [self putItemArrayInMenu:redditItems];
  105. }
  106. -(void)reloadListIsAuthenticatedCallback {
  107. if (currentState.useSubscriptions) {
  108. [NSThread detachNewThreadSelector:@selector(readFrontpage:) toTarget:api withObject:self];
  109. } else {
  110. [api setSubreddits:currentState.subreddits];
  111. [NSThread detachNewThreadSelector:@selector(readSubreddits:) toTarget:api withObject:self];
  112. }
  113. }
  114. -(void)singleItemReloadedCallback:(NSArray *)items {
  115. if (items != nil) {
  116. lastFullName = [items objectAtIndex:[items count] - 1]; // last link fullname is at end of array
  117. items = [items subarrayWithRange:NSMakeRange(0, [items count] - 1)]; // Remove last item
  118. NSMutableArray *newMenuItems = [NSMutableArray arrayWithArray:menuItems];
  119. NSMenuItem *item = [self prepareItemForMenu:[items objectAtIndex:0]];
  120. [newMenuItems addObject:item];
  121. [statusMenu insertItem:item atIndex:([statusMenu numberOfItems] - numberOfStaticMenuItems + itemsBeforeLinkList)];
  122. menuItems = newMenuItems;
  123. redditItems = [redditItems arrayByAddingObjectsFromArray:items];
  124. }
  125. }
  126. -(void)reloadListWithOptions {
  127. if ([currentState.modhash isEqualToString:@""]) {
  128. [firstMenuItem setTitle:NSLocalizedString(@"Not logged in!", @"Statusitem when no modhash is stored")];
  129. [self clearMenuItems];
  130. [firstMenuItem setHidden:NO];
  131. [self showPreferences:nil];
  132. return;
  133. }
  134. api = [[Reddit alloc] initWithUsername:currentState.username Modhash:currentState.modhash Length:currentState.length TitleLength:currentState.titleLength];
  135. [NSThread detachNewThreadSelector:@selector(isAuthenticatedNewModhash:) toTarget:api withObject:self];
  136. }
  137. - (IBAction)reloadCompleteList:(id)sender {
  138. [firstMenuItem setTitle:NSLocalizedString(@"Loading...", @"Statusitem when user clicks reload")];
  139. [self clearMenuItems];
  140. [firstMenuItem setHidden:NO];
  141. lastFullName = nil; // reload from start
  142. [self reloadListWithOptions];
  143. }
  144. - (IBAction)reloadNextList:(id)sender {
  145. [firstMenuItem setTitle:NSLocalizedString(@"Loading...", nil)];
  146. [self clearMenuItems];
  147. [firstMenuItem setHidden:NO];
  148. [self reloadListWithOptions];
  149. }
  150. -(void)openAndRemoveAndReloadWithIndex:(NSInteger)index Comments:(Boolean)comments Both:(Boolean)both {
  151. RedditItem *rItem = [redditItems objectAtIndex:index];
  152. NSString *url;
  153. if (comments) {
  154. url = [rItem comments];
  155. [rItem setVisitedComments:TRUE];
  156. } else {
  157. url = [rItem link];
  158. [rItem setVisitedLink:TRUE];
  159. }
  160. [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:url]];
  161. if (both) {
  162. if (!comments) {
  163. url = [rItem comments];
  164. [rItem setVisitedComments:TRUE];
  165. } else {
  166. url = [rItem link];
  167. [rItem setVisitedLink:TRUE];
  168. }
  169. [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:url]];
  170. }
  171. if (currentState.removeVisited) {
  172. Boolean removed = FALSE;
  173. if ((rItem.isSelf && (rItem.visitedLink || rItem.visitedComments)) || ((!rItem.isSelf) && rItem.visitedLink && rItem.visitedComments)) {
  174. [statusMenu removeItem:[menuItems objectAtIndex:index]];
  175. removed = TRUE;
  176. }
  177. if (removed && ([statusMenu numberOfItems] <= numberOfStaticMenuItems)) {
  178. [self reloadNextList:nil];
  179. } else {
  180. if (removed && currentState.reloadAfterVisit) {
  181. [NSThread detachNewThreadSelector:@selector(readSingleItem:) toTarget:api withObject:self];
  182. }
  183. }
  184. }
  185. }
  186. -(IBAction)linkToOpen:(id)sender {
  187. NSString *title = [(NSMenuItem *)sender title];
  188. if ([title isEqualToString:NSLocalizedString(@"Link...", nil)] || [title isEqualToString:NSLocalizedString(@"Comments...", nil)] || [title isEqualToString:NSLocalizedString(@"Both", nil)]) {
  189. for (NSUInteger i = 0; i < [menuItems count]; i++) {
  190. NSMenuItem *item = [menuItems objectAtIndex:i];
  191. NSMenu *submenu = item.submenu;
  192. Boolean isComments = [title isEqualToString:NSLocalizedString(@"Comments...", nil)];
  193. Boolean isBoth = [title isEqualToString:NSLocalizedString(@"Both", nil)];
  194. if (isBoth) {
  195. isComments = !isComments; // Open comments first, then link
  196. }
  197. NSInteger index;
  198. if ([title isEqualToString:NSLocalizedString(@"Link...", nil)])
  199. index = SUBMENU_INDEX_LINK;
  200. else if ([title isEqualToString:NSLocalizedString(@"Comments...", nil)])
  201. index = SUBMENU_INDEX_COMMENTS;
  202. else
  203. index = SUBMENU_INDEX_BOTH;
  204. if ((submenu != nil) && (sender == [submenu itemAtIndex:index])) {
  205. [self openAndRemoveAndReloadWithIndex:i Comments:isComments Both:isBoth];
  206. break;
  207. }
  208. }
  209. } else {
  210. for (NSUInteger i = 0; i < [menuItems count]; i++) {
  211. NSMenuItem *item = [menuItems objectAtIndex:i];
  212. if (sender == item) {
  213. [self openAndRemoveAndReloadWithIndex:i Comments:FALSE Both:FALSE];
  214. break;
  215. }
  216. }
  217. }
  218. }
  219. -(IBAction)openUnread:(id)sender {
  220. [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.reddit.com/message/unread"]];
  221. [NSTimer scheduledTimerWithTimeInterval:RECHECK_PM_AFTER_OPEN target:self selector:@selector(refreshTick:) userInfo:nil repeats:NO];
  222. }
  223. -(void)clearMenuItems {
  224. if (menuItems != nil) {
  225. for (NSUInteger i = 0; i < [menuItems count]; i++) {
  226. NSMenuItem *item = [menuItems objectAtIndex:i];
  227. if ([statusMenu indexOfItem:item] != -1)
  228. [statusMenu removeItem:item];
  229. }
  230. menuItems = nil;
  231. }
  232. }
  233. -(void)putItemArrayInMenu:(NSArray *)array {
  234. NSMutableArray *items = [NSMutableArray arrayWithCapacity:array.count];
  235. for (NSUInteger i = 0; i < [array count]; i++) {
  236. NSMenuItem *item = [self prepareItemForMenu:[array objectAtIndex:i]];
  237. [items addObject:item];
  238. [statusMenu insertItem:item atIndex:(i + itemsBeforeLinkList)];
  239. }
  240. menuItems = items;
  241. }
  242. -(NSMenuItem *)prepareItemForMenu:(RedditItem *)reddit {
  243. NSMenuItem *item = [[NSMenuItem alloc] init];
  244. [item setTitle:reddit.name];
  245. if (![reddit.name isEqualToString:reddit.fullName])
  246. [item setToolTip:reddit.fullName];
  247. if (reddit.isSelf) {
  248. [item setAction:@selector(linkToOpen:)];
  249. [item setKeyEquivalent:@""];
  250. } else {
  251. NSMenu *submenu = [[NSMenu alloc] init];
  252. [submenu addItemWithTitle:NSLocalizedString(@"Link...", @"Link item") action:@selector(linkToOpen:) keyEquivalent:@""];
  253. [submenu addItemWithTitle:NSLocalizedString(@"Comments...", @"comment item") action:@selector(linkToOpen:) keyEquivalent:@""];
  254. [submenu addItemWithTitle:NSLocalizedString(@"Both", @"Link & Comment item") action:@selector(linkToOpen:) keyEquivalent:@""];
  255. [item setSubmenu:submenu];
  256. }
  257. return item;
  258. }
  259. -(IBAction)showPreferences:(id)sender {
  260. [NSApp activateIgnoringOtherApps:YES];
  261. prefWindow = [[PrefController alloc] initWithWindowNibName:@"Prefs"];
  262. [prefWindow setParent:self];
  263. [prefWindow setState:currentState];
  264. [prefWindow showWindow:self];
  265. [[prefWindow window] makeKeyAndOrderFront:self];
  266. }
  267. -(IBAction)showAbout:(id)sender {
  268. [NSApp activateIgnoringOtherApps:YES];
  269. [application orderFrontStandardAboutPanel:self];
  270. }
  271. -(void)prefsDidSave {
  272. [currentState savePreferences];
  273. [firstMenuItem setTitle:NSLocalizedString(@"Loading...", nil)];
  274. [self clearMenuItems];
  275. [firstMenuItem setHidden:NO];
  276. lastFullName = nil; // reload from start
  277. [self reloadListWithOptions];
  278. [self recreateRefreshTimer];
  279. }
  280. @end