aka RedditBar, Mac OS X menu bar reddit client
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

AppDelegate.m 12KB

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