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.

888 lines
31 KiB

9 years ago
// Created by Abhishek Banthia on 11/4/15.
// Copyright (c) 2015 Abhishek Banthia All rights reserved.
//
// Copyright (c) 2015, Abhishek Banthia
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#import "PanelController.h"
#import "BackgroundView.h"
#import "StatusItemView.h"
#import "MenubarController.h"
#import <Crashlytics/Crashlytics.h>
#import "CLRatingCellView.h"
9 years ago
#import "CommonStrings.h"
9 years ago
#import "CLTimezoneCellView.h"
9 years ago
#import "DateTools.h"
9 years ago
#import "CLTimezoneData.h"
9 years ago
#define OPEN_DURATION .15
#define CLOSE_DURATION .1
#define SEARCH_INSET 17
#define POPUP_HEIGHT 300
#define PANEL_WIDTH 280
#define MENU_ANIMATION_DURATION .1
#define BUFFER 2
#define MAX_TALL 15
#pragma mark -
#import "CLOneWindowController.h"
9 years ago
#import "CommonStrings.h"
9 years ago
#import "Reachability.h"
9 years ago
9 years ago
NSString *const CLPanelNibIdentifier = @"Panel";
NSString *const CLRatingCellViewIdentifier = @"ratingCellView";
NSString *const CLTimezoneCellViewIdentifier = @"timeZoneCell";
9 years ago
@implementation PanelController
#pragma mark -
- (id)initWithDelegate:(id<PanelControllerDelegate>)delegate
{
9 years ago
self = [super initWithWindowNibName:CLPanelNibIdentifier];
9 years ago
if (self != nil)
{
_delegate = delegate;
self.window.backgroundColor = [NSColor whiteColor];
}
return self;
}
#pragma mark -
- (void)awakeFromNib
{
[super awakeFromNib];
if (!self.dateFormatter)
{
self.dateFormatter = [[NSDateFormatter alloc] init];
}
9 years ago
[self updateDefaultPreferences];
9 years ago
9 years ago
if ([[[NSUserDefaults standardUserDefaults] objectForKey:CLThemeKey] isEqualToString:@"Black"]) {
self.shutdownButton.image = [NSImage imageNamed:@"PowerIcon-White"];
self.preferencesButton.image = [NSImage imageNamed:@"Settings-White"];
}
else
{
self.shutdownButton.image = [NSImage imageNamed:@"PowerIcon"];
self.preferencesButton.image = [NSImage imageNamed:NSImageNameActionTemplate];
}
[self updateDefaultPreferences];
9 years ago
self.mainTableview.selectionHighlightStyle = NSTableViewSelectionHighlightStyleNone;
9 years ago
9 years ago
NSPanel *panel = (id)[self window];
[panel setAcceptsMouseMovedEvents:YES];
[panel setLevel:NSPopUpMenuWindowLevel];
[panel setOpaque:NO];
[panel setBackgroundColor:[NSColor clearColor]];
//Register for drag and drop
9 years ago
[self.mainTableview registerForDraggedTypes: [NSArray arrayWithObject:CLDragSessionKey]];
9 years ago
}
#pragma mark -
#pragma mark Updating Timezones
#pragma mark -
9 years ago
- (void) updateDefaultPreferences
{
9 years ago
NSArray *defaultZones = [[NSUserDefaults standardUserDefaults] objectForKey:CLDefaultPreferenceKey];
9 years ago
self.defaultPreferences = self.defaultPreferences == nil ? [[NSMutableArray alloc] initWithArray:defaultZones] : [NSMutableArray arrayWithArray:defaultZones];
9 years ago
9 years ago
self.scrollViewHeight.constant = self.showReviewCell ? (self.defaultPreferences.count+1)*55+40 : self.defaultPreferences.count*55 + 30;
if (self.defaultPreferences.count == 0) {
self.futureSlider.hidden = YES;
self.sliderLabel.hidden = YES;
}
else
{
self.futureSlider.hidden = NO;
self.sliderLabel.hidden = NO;
}
9 years ago
}
#pragma mark - Public accessors
- (BOOL)hasActivePanel
{
return _hasActivePanel;
}
- (void)setHasActivePanel:(BOOL)flag
{
if (_hasActivePanel != flag)
{
_hasActivePanel = flag;
_hasActivePanel ? [self openPanel] : [self closePanel];
9 years ago
}
}
#pragma mark - NSWindowDelegate
- (void)windowWillClose:(NSNotification *)notification
{
self.hasActivePanel = NO;
}
- (void)windowDidResignKey:(NSNotification *)notification;
{
if ([[self window] isVisible])
{
self.hasActivePanel = NO;
}
}
- (void)windowDidResize:(NSNotification *)notification
{
NSWindow *panel = [self window];
NSRect statusRect = [self statusRectForWindow:panel];
NSRect panelRect = [panel frame];
CGFloat statusX = roundf(NSMidX(statusRect));
CGFloat panelX = statusX - NSMinX(panelRect);
self.backgroundView.arrowX = panelX;
}
#pragma mark - Keyboard
- (void)cancelOperation:(id)sender
{
self.hasActivePanel = NO;
}
#pragma mark - Public methods
- (NSRect)statusRectForWindow:(NSWindow *)window
{
NSRect screenRect = [[[NSScreen screens] objectAtIndex:0] frame];
NSRect statusRect = NSZeroRect;
StatusItemView *statusItemView = nil;
if ([self.delegate respondsToSelector:@selector(statusItemViewForPanelController:)])
{
statusItemView = [self.delegate statusItemViewForPanelController:self];
}
if (statusItemView)
{
statusRect = statusItemView.globalRect;
statusRect.origin.y = NSMinY(statusRect) - NSHeight(statusRect);
}
else
{
statusRect.size = NSMakeSize(STATUS_ITEM_VIEW_WIDTH, [[NSStatusBar systemStatusBar] thickness]);
statusRect.origin.x = roundf((NSWidth(screenRect) - NSWidth(statusRect)) / 2);
statusRect.origin.y = NSHeight(screenRect) - NSHeight(statusRect) * 2;
}
return statusRect;
}
- (void)openPanel
{
self.futureSliderValue = 0;
9 years ago
NSWindow *panel = [self window];
NSRect screenRect = [[[NSScreen screens] objectAtIndex:0] frame];
NSRect statusRect = [self statusRectForWindow:panel];
NSRect panelRect = [panel frame];
panelRect.size.width = PANEL_WIDTH;
9 years ago
panelRect.size.height = self.showReviewCell ? (self.defaultPreferences.count+1)*55+40: self.defaultPreferences.count*55 + 30;
9 years ago
panelRect.origin.x = roundf(NSMidX(statusRect) - NSWidth(panelRect) / 2);
panelRect.origin.y = NSMaxY(statusRect) - NSHeight(panelRect);
if (NSMaxX(panelRect) > (NSMaxX(screenRect) - ARROW_HEIGHT))
panelRect.origin.x -= NSMaxX(panelRect) - (NSMaxX(screenRect) - ARROW_HEIGHT);
[NSApp activateIgnoringOtherApps:NO];
[panel setAlphaValue:0];
[panel setFrame:statusRect display:YES];
[panel makeKeyAndOrderFront:nil];
NSTimeInterval openDuration = OPEN_DURATION;
NSEvent *currentEvent = [NSApp currentEvent];
if ([currentEvent type] == NSLeftMouseDown)
{
NSUInteger clearFlags = ([currentEvent modifierFlags] & NSDeviceIndependentModifierFlagsMask);
BOOL shiftPressed = (clearFlags == NSShiftKeyMask);
BOOL shiftOptionPressed = (clearFlags == (NSShiftKeyMask | NSAlternateKeyMask));
if (shiftPressed || shiftOptionPressed)
{
openDuration *= 5;
}
}
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:openDuration];
[[panel animator] setFrame:panelRect display:YES];
[[panel animator] setAlphaValue:1];
[NSAnimationContext endGrouping];
9 years ago
[self.mainTableview reloadData];
9 years ago
}
- (void)closePanel
{
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:CLOSE_DURATION];
[[[self window] animator] setAlphaValue:0];
[NSAnimationContext endGrouping];
dispatch_after(dispatch_walltime(NULL, NSEC_PER_SEC * CLOSE_DURATION * 2), dispatch_get_main_queue(), ^{
[self.window orderOut:nil];
});
}
#pragma mark -
#pragma mark NSTableview Datasource
#pragma mark -
9 years ago
-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
if (self.showReviewCell) {
return self.defaultPreferences.count+1;
}
9 years ago
return self.defaultPreferences.count;
}
9 years ago
9 years ago
-(NSView*)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
if (self.showReviewCell && row == self.defaultPreferences.count) {
CLRatingCellView *cellView = [self.mainTableview
makeViewWithIdentifier:CLRatingCellViewIdentifier
owner:self];
return cellView;
}
9 years ago
CLTimezoneCellView *cell = [tableView makeViewWithIdentifier:CLTimezoneCellViewIdentifier owner:self];
9 years ago
CLTimezoneData *dataObject = self.defaultPreferences[row];
NSTextView *customLabel = (NSTextView*)[cell.relativeDate.window fieldEditor:YES
forObject:cell.relativeDate];
9 years ago
NSString *theme = [[NSUserDefaults standardUserDefaults] objectForKey:CLThemeKey];
9 years ago
if (theme.length > 0 && ![theme isEqualToString:@"Default"])
{
9 years ago
// [cell updateTextColorWithColor:[NSColor whiteColor] andCell:cell];
9 years ago
[self.mainTableview setBackgroundColor:[NSColor blackColor]];
self.window.alphaValue = 0.90;
[cell.customName setDrawsBackground:YES];
[cell.customName setBackgroundColor:[NSColor blackColor]];
customLabel.insertionPointColor = [NSColor whiteColor];
9 years ago
}
else
{
9 years ago
// [cell updateTextColorWithColor:[NSColor blackColor] andCell:cell];
[cell.customName setDrawsBackground:NO];
9 years ago
[self.mainTableview setBackgroundColor:[NSColor whiteColor]];
self.window.alphaValue = 1;
customLabel.insertionPointColor = [NSColor blackColor];
9 years ago
}
9 years ago
cell.relativeDate.stringValue = [self getDateForTimeZone:self.defaultPreferences[row]];
9 years ago
9 years ago
cell.time.stringValue = [self getTimeForTimeZone:dataObject.timezoneID];
9 years ago
9 years ago
cell.rowNumber = row;
9 years ago
9 years ago
cell.customName.stringValue = [self formatStringShouldContainCity:YES
9 years ago
withTimezoneName:dataObject];
9 years ago
NSNumber *displaySuntimings = [[NSUserDefaults standardUserDefaults] objectForKey:CLDisplaySunTimingKey];
9 years ago
if ([displaySuntimings isEqualToNumber:[NSNumber numberWithInteger:0]] && dataObject.sunriseTime && dataObject.sunsetTime) {
cell.sunTime.stringValue = [self getFormattedSunriseOrSunsetTime:dataObject andSunImage:cell];
9 years ago
}
else
{
cell.sunImage.image = nil;
cell.sunTime.stringValue = CLEmptyString;
}
NSNumber *displayFutureSlider = [[NSUserDefaults standardUserDefaults] objectForKey:CLDisplayFutureSliderKey];
if ([displayFutureSlider isEqualToNumber:[NSNumber numberWithInteger:0]])
{
self.futureSlider.hidden = NO;
self.sliderLabel.hidden = NO;
}
else
{
self.sliderLabel.hidden = YES;
self.futureSlider.hidden = YES;
}
9 years ago
[cell setUpAutoLayoutWithCell:cell];
9 years ago
return cell;
}
9 years ago
#pragma mark -
#pragma mark Datasource formatting
#pragma mark -
9 years ago
- (NSString *)formatStringShouldContainCity:(BOOL)value withTimezoneName:(CLTimezoneData *)dataObject
9 years ago
{
9 years ago
if (dataObject.customLabel) {
NSString *customLabel = dataObject.customLabel;
if (customLabel.length > 0)
{
9 years ago
return customLabel;
}
}
9 years ago
if ([dataObject.formattedAddress length] > 0)
{
9 years ago
return dataObject.formattedAddress;
}
9 years ago
else if (dataObject.timezoneID.length > 0)
{
9 years ago
NSString *timezoneID = dataObject.timezoneID;
NSRange range = [timezoneID rangeOfString:@"/"];
9 years ago
if (range.location != NSNotFound)
{
timezoneID = [timezoneID substringWithRange:NSMakeRange(range.location+1, timezoneID.length-1 - range.location)];
9 years ago
}
return timezoneID;
9 years ago
}
else
{
return @"Error";
}
9 years ago
}
9 years ago
- (NSString *)getFormattedSunriseOrSunsetTime:(CLTimezoneData *)dataObject
9 years ago
andSunImage:(CLTimezoneCellView *)cell
9 years ago
{
9 years ago
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm";
9 years ago
NSDate *sunTime = [formatter dateFromString:dataObject.sunriseTime];
9 years ago
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
9 years ago
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:dataObject.timezoneID];
9 years ago
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
dateFormatter.timeStyle = kCFDateFormatterShortStyle;
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
NSString *newDate = [dateFormatter stringFromDate:[NSDate date]];
NSDateFormatter *dateConversion = [[NSDateFormatter alloc] init];
9 years ago
dateConversion.timeZone = [NSTimeZone timeZoneWithName:dataObject.timezoneID];
9 years ago
dateConversion.dateStyle = kCFDateFormatterShortStyle;
dateConversion.timeStyle = kCFDateFormatterShortStyle;
dateConversion.dateFormat = @"yyyy-MM-dd HH:mm";
NSString *theme = [[NSUserDefaults standardUserDefaults] objectForKey:CLThemeKey];
if ([sunTime laterDate:[dateConversion dateFromString:newDate]] == sunTime)
{
cell.sunImage.image = theme.length > 0 && [theme isEqualToString:@"Default"] ?
[NSImage imageNamed:@"Sunrise"] : [NSImage imageNamed:@"White Sunrise"];
9 years ago
return [dataObject.sunriseTime substringFromIndex:11];
9 years ago
}
else
{
cell.sunImage.image = theme.length > 0 && [theme isEqualToString:@"Default"] ?
[NSImage imageNamed:@"Sunset"] : [NSImage imageNamed:@"White Sunset"];
9 years ago
return [dataObject.sunsetTime substringFromIndex:11];
9 years ago
}
9 years ago
}
- (NSString *)getTimeForTimeZone:(NSString *)timezoneID
9 years ago
{
NSCalendar *currentCalendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *newDate = [currentCalendar dateByAddingUnit:NSCalendarUnitHour
value:self.futureSliderValue
toDate:[NSDate date]
options:kNilOptions];
9 years ago
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = kCFDateFormatterNoStyle;
NSNumber *is24HourFormatSelected = [[NSUserDefaults standardUserDefaults] objectForKey:CL24hourFormatSelectedKey];
9 years ago
is24HourFormatSelected.boolValue ? [dateFormatter setDateFormat:@"HH:mm"] : [dateFormatter setDateFormat:@"hh:mm a"];
9 years ago
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:timezoneID];
9 years ago
//In the format 22:10
return [dateFormatter stringFromDate:newDate];
9 years ago
}
- (NSString *)getLocalCurrentDate
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
dateFormatter.timeStyle = kCFDateFormatterNoStyle;
dateFormatter.timeZone = [NSTimeZone systemTimeZone];
return [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterNoStyle];
9 years ago
}
9 years ago
- (NSString *)compareSystemDate:(NSString *)systemDate toTimezoneDate:(NSString *)date andDataObject:(CLTimezoneData *)dataObject
9 years ago
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
9 years ago
formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"MM/dd/yyyy"
options:0
locale:[NSLocale currentLocale]];
9 years ago
NSDate *localDate = [formatter dateFromString:systemDate];
NSDate *timezoneDate = [formatter dateFromString:date];
if (localDate == nil || timezoneDate == nil) {
[CrashlyticsKit setUserEmail:systemDate];
[CrashlyticsKit setUserIdentifier:date];
return @"Today";
}
9 years ago
// Specify which units we would like to use
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSInteger weekday = [calendar component:NSCalendarUnitWeekday fromDate:localDate];
9 years ago
9 years ago
if ([dataObject.nextUpdate isKindOfClass:[NSString class]])
{
NSUInteger units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *comps = [[NSCalendar currentCalendar] components:units fromDate:timezoneDate];
comps.day = comps.day + 1;
NSDate *tomorrowMidnight = [[NSCalendar currentCalendar] dateFromComponents:comps];
9 years ago
CLTimezoneData *newDataObject = [dataObject mutableCopy];
newDataObject.nextUpdate = tomorrowMidnight;
9 years ago
[self.defaultPreferences replaceObjectAtIndex:[self.defaultPreferences indexOfObject:dataObject] withObject:newDataObject];
[[NSUserDefaults standardUserDefaults] setObject:self.defaultPreferences forKey:CLDefaultPreferenceKey];
}
9 years ago
else if ([dataObject.nextUpdate isKindOfClass:[NSDate class]] &&
[dataObject.nextUpdate isEarlierThanOrEqualTo:timezoneDate])
{
9 years ago
[self getTimeZoneForLatitude:dataObject.latitude
andLongitude:dataObject.longitude
andDataObject:dataObject];
}
9 years ago
NSInteger daysApart = [timezoneDate daysFrom:localDate];
if (daysApart == 0) {
return @"Today";
9 years ago
}
9 years ago
else if (daysApart == -1)
9 years ago
{
return @"Yesterday";
9 years ago
}
9 years ago
else if (daysApart == 1)
9 years ago
{
return @"Tomorrow";
9 years ago
}
else
{
return [self getWeekdayFromInteger:weekday+2];
}
9 years ago
}
9 years ago
- (NSString *)getDateForTimeZone:(CLTimezoneData *)dataObject
9 years ago
{
NSCalendar *currentCalendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *newDate = [currentCalendar dateByAddingUnit:NSCalendarUnitHour
value:self.futureSliderValue
toDate:[NSDate date]
options:kNilOptions];
9 years ago
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
dateFormatter.timeStyle = kCFDateFormatterNoStyle;
9 years ago
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:dataObject.timezoneID];
9 years ago
9 years ago
NSNumber *relativeDayPreference = [[NSUserDefaults standardUserDefaults] objectForKey:CLRelativeDateKey];
if (relativeDayPreference.integerValue == 0) {
return [self compareSystemDate:[self getLocalCurrentDate]
9 years ago
toTimezoneDate:[dateFormatter stringFromDate:newDate] andDataObject:dataObject] ;;
}
else
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"MM/dd/yyyy" options:0 locale:[NSLocale currentLocale]];
NSDate *convertedDate = [formatter dateFromString:[dateFormatter stringFromDate:newDate]];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSInteger weekday = [calendar component:NSCalendarUnitWeekday fromDate:convertedDate];
return [self getWeekdayFromInteger:weekday];
}
9 years ago
}
#pragma mark -
#pragma mark NSTableview Drag and Drop
#pragma mark -
9 years ago
- (BOOL)tableView:(NSTableView *)tableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard
{
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
9 years ago
[pboard declareTypes:[NSArray arrayWithObject:CLDragSessionKey] owner:self];
[pboard setData:data forType:CLDragSessionKey];
9 years ago
return YES;
}
9 years ago
-(void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
if ([object isKindOfClass:[NSString class]])
{
9 years ago
CLTimezoneData *dataObject = self.defaultPreferences[row];
9 years ago
if ([dataObject.formattedAddress isEqualToString:object])
{
return;
}
9 years ago
CLTimezoneData *mutableTimeZoneData = [dataObject mutableCopy];
mutableTimeZoneData.customLabel = object;
[self.defaultPreferences replaceObjectAtIndex:row withObject:mutableTimeZoneData];
9 years ago
[[NSUserDefaults standardUserDefaults] setObject:self.defaultPreferences forKey:CLDefaultPreferenceKey];
[self.mainTableview reloadData];
}
}
9 years ago
-(BOOL)tableView:(NSTableView *)tableView acceptDrop:(id<NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)dropOperation
{
NSPasteboard *pBoard = [info draggingPasteboard];
9 years ago
NSData *data = [pBoard dataForType:CLDragSessionKey];
9 years ago
NSIndexSet *rowIndexes = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[self.defaultPreferences exchangeObjectAtIndex:rowIndexes.firstIndex
withObjectAtIndex:row];
9 years ago
[[NSUserDefaults standardUserDefaults] setObject:self.defaultPreferences
forKey:CLDefaultPreferenceKey];
9 years ago
for (NSWindow *window in [NSApplication sharedApplication].windows) {
9 years ago
if ([window.windowController isMemberOfClass:[CLOneWindowController class]]) {
CLOneWindowController *ref = (CLOneWindowController *) window.windowController;
[ref.preferencesView refereshTimezoneTableView];
}
}
9 years ago
[self.mainTableview reloadData];
9 years ago
return YES;
}
-(NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id<NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)dropOperation
{
return NSDragOperationEvery;
}
#pragma mark -
#pragma mark Preferences Target-Action
#pragma mark -
9 years ago
- (IBAction)openPreferences:(id)sender
{
self.oneWindow = [CLOneWindowController sharedWindow];
[self.oneWindow showWindow:nil];
9 years ago
[NSApp activateIgnoringOtherApps:YES];
}
#pragma mark -
#pragma mark Hiding Buttons on Mouse Exit
#pragma mark -
9 years ago
- (void)showOptions:(BOOL)value
{
if (!self.futureSlider.isHidden) {
self.sliderLabel.hidden = !value;
}
9 years ago
9 years ago
if (self.defaultPreferences.count == 0)
{
value = YES;
if (!self.futureSlider.isHidden)
{
self.sliderLabel.hidden = YES;
}
9 years ago
}
9 years ago
self.shutdownButton.hidden = !value;
self.preferencesButton.hidden = !value;
9 years ago
}
- (IBAction)sliderMoved:(id)sender
{
NSCalendar *currentCalendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *newDate = [currentCalendar dateByAddingUnit:NSCalendarUnitHour
value:self.futureSliderValue
toDate:[NSDate date]
options:kNilOptions];
self.dateFormatter.dateStyle = kCFDateFormatterNoStyle;
self.dateFormatter.timeStyle = kCFDateFormatterShortStyle;
NSString *relativeDate = [currentCalendar isDateInToday:newDate] ? @"Today" : @"Tomorrow";
NSString *helper = [self.dateFormatter stringFromDate:newDate];
9 years ago
NSHelpManager *helpManager = [NSHelpManager sharedHelpManager];
NSPoint pointInScreen = [NSEvent mouseLocation];
pointInScreen.y -= 5;
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@", relativeDate, helper]];
[NSHelpManager setContextHelpModeActive:YES];
[helpManager setContextHelp:attributedString forObject:self.futureSlider];
[helpManager showContextHelpForObject:self.futureSlider locationHint:pointInScreen];
[self.mainTableview reloadData];
}
- (void)removeContextHelpForSlider
{
NSEvent *newEvent = [NSEvent mouseEventWithType:NSLeftMouseDown
location:self.window.mouseLocationOutsideOfEventStream
modifierFlags:0
timestamp:0
windowNumber:self.window.windowNumber
context:self.window.graphicsContext
eventNumber:0
clickCount:1
pressure:0];
[NSApp postEvent:newEvent atStart:NO];
newEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
location:self.window.mouseLocationOutsideOfEventStream
modifierFlags:0
timestamp:0
windowNumber:self.window.windowNumber
context:self.window.graphicsContext
eventNumber:0
clickCount:1
pressure:0];
[NSApp postEvent:newEvent atStart:NO];
}
- (NSString *)getWeekdayFromInteger:(NSInteger)weekdayInteger
{
if (weekdayInteger > 7) {
weekdayInteger = weekdayInteger - 7;
}
switch (weekdayInteger) {
case 1:
return @"Sunday";
break;
case 2:
return @"Monday";
break;
case 3:
return @"Tuesday";
break;
case 4:
return @"Wednesday";
break;
case 5:
return @"Thursday";
break;
case 6:
return @"Friday";
break;
case 7:
return @"Saturday";
break;
default:
return @"Error";
break;
}
9 years ago
}
9 years ago
- (void)getTimeZoneForLatitude:(NSString *)latitude andLongitude:(NSString *)longitude andDataObject:(CLTimezoneData *)dataObject
9 years ago
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
if (networkStatus == NotReachable)
{
//Could not fetch data
return;
}
NSString *urlString = [NSString stringWithFormat:@"http://api.geonames.org/timezoneJSON?lat=%@&lng=%@&username=abhishaker17", latitude, longitude];
NSURL *url = [NSURL URLWithString:urlString];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"GET";
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSError *error = nil;
if (!error) {
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (httpResp.statusCode == 200)
{
9 years ago
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:nil];
if (json.count == 0) {
//No results found
return;
}
9 years ago
if ([json[@"status"][@"message"]
isEqualToString:@"the hourly limit of 2000 credits for abhishaker17 has been exceeded. Please throttle your requests or use the commercial service."])
{
return;
}
9 years ago
9 years ago
CLTimezoneData *newDataObject = [[CLTimezoneData alloc] init];
newDataObject.timezoneID = dataObject.timezoneID;
newDataObject.formattedAddress = dataObject.formattedAddress;
newDataObject.latitude = dataObject.latitude;
newDataObject.longitude = dataObject.longitude;
newDataObject.sunriseTime = dataObject.sunriseTime;
newDataObject.sunsetTime = dataObject.sunsetTime;
newDataObject.customLabel = dataObject.customLabel;
newDataObject.place_id = dataObject.place_id;
newDataObject.nextUpdate = dataObject.nextUpdate;
9 years ago
if (json[@"sunrise"] && json[@"sunset"]) {
9 years ago
newDataObject.sunriseTime = json[@"sunrise"];
newDataObject.sunsetTime = json[@"sunset"];
}
NSUInteger units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
9 years ago
NSDateComponents *comps = [[NSCalendar currentCalendar] components:units fromDate:dataObject.nextUpdate];
comps.day = comps.day + 1;
NSDate *tomorrowMidnight = [[NSCalendar currentCalendar] dateFromComponents:comps];
9 years ago
newDataObject.nextUpdate = tomorrowMidnight;
9 years ago
NSArray *defaultPreference = [[NSUserDefaults standardUserDefaults] objectForKey:CLDefaultPreferenceKey];
if (defaultPreference == nil)
{
defaultPreference = [[NSMutableArray alloc] init];
}
NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:defaultPreference];
9 years ago
for (NSMutableDictionary *timeDictionary in self.defaultPreferences) {
9 years ago
if ([dataObject.place_id isEqualToString:timeDictionary[CLPlaceIdentifier]]) {
[newArray replaceObjectAtIndex:[self.defaultPreferences indexOfObject:dataObject] withObject:newDataObject];
9 years ago
}
}
9 years ago
[[NSUserDefaults standardUserDefaults] setObject:newArray forKey:CLDefaultPreferenceKey];
[self.mainTableview reloadData];
9 years ago
});
}
}
else
{
//error
}
}];
[dataTask resume];
}
}
9 years ago
- (void)updatePanelColor
{
NSString *theme = [[NSUserDefaults standardUserDefaults] objectForKey:CLThemeKey];
if (theme.length > 0 && ![theme isEqualToString:@"Default"])
{
[self.mainTableview setBackgroundColor:[NSColor blackColor]];
self.window.alphaValue = 0.90;
}
else
{
[self.mainTableview setBackgroundColor:[NSColor whiteColor]];
self.window.alphaValue = 1;
}
}
9 years ago
@end