aka RedditBar, Mac OS X menu bar reddit client
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

AppDelegate.m 14KB

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