AppDelegate.mm 14 KB
Newer Older
1
/*
Alexandre Lision's avatar
Alexandre Lision committed
2
 *  Copyright (C) 2015-2016 Savoir-faire Linux Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *  Author: Alexandre Lision <alexandre.lision@savoirfairelinux.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
 */
19 20
#import <SystemConfiguration/SystemConfiguration.h>

Alexandre Lision's avatar
Alexandre Lision committed
21 22
#import "AppDelegate.h"

23
#import <callmodel.h>
Edric Milaret's avatar
Edric Milaret committed
24
#import <qapplication.h>
25 26
#import <accountmodel.h>
#import <protocolmodel.h>
27 28
#import <media/recordingmodel.h>
#import <media/textrecording.h>
29
#import <QItemSelectionModel>
30
#import <QDebug>
31
#import <account.h>
32
#import <AvailableAccountModel.h>
33
#import <api/lrc.h>
34

35

36 37 38 39
#if ENABLE_SPARKLE
#import <Sparkle/Sparkle.h>
#endif

40
#import "Constants.h"
41
#import "RingWizardWC.h"
Alexandre Lision's avatar
Alexandre Lision committed
42
#import "DialpadWC.h"
43

44 45 46
#if ENABLE_SPARKLE
@interface AppDelegate() <SUUpdaterDelegate>
#else
47
@interface AppDelegate()
48
#endif
49 50 51

@property RingWindowController* ringWindowController;
@property RingWizardWC* wizard;
Alexandre Lision's avatar
Alexandre Lision committed
52
@property DialpadWC* dialpad;
53 54
@property (nonatomic, strong) dispatch_queue_t scNetworkQueue;
@property (nonatomic, assign) SCNetworkReachabilityRef currentReachability;
55 56 57

@end

58
@implementation AppDelegate {
Alexandre Lision's avatar
Alexandre Lision committed
59

60
NSTimer* preventSleepTimer;
61 62
std::unique_ptr<lrc::api::Lrc> lrc;
}
63

Alexandre Lision's avatar
Alexandre Lision committed
64
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
65 66 67 68 69 70 71 72 73 74 75

    // hide "Check for update" menu item when sparkle is disabled
    NSMenu *mainMenu = [[NSApplication sharedApplication] mainMenu];
    NSMenu *ringMenu = [[mainMenu itemAtIndex:0] submenu];
    NSMenuItem *updateItem = [ringMenu itemAtIndex:1];
#if ENABLE_SPARKLE
    updateItem.hidden = false;
#else
    updateItem.hidden = true;
#endif

Alexandre Lision's avatar
Alexandre Lision committed
76 77
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints"];

78 79
    [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];

Edric Milaret's avatar
Edric Milaret committed
80 81
    NSAppleEventManager* appleEventManager = [NSAppleEventManager sharedAppleEventManager];
    [appleEventManager setEventHandler:self andSelector:@selector(handleQuitEvent:withReplyEvent:) forEventClass:kCoreEventClass andEventID:kAEQuitApplication];
82
    lrc = std::make_unique<lrc::api::Lrc>();
Edric Milaret's avatar
Edric Milaret committed
83

84 85 86 87 88
    if([self checkForRingAccount]) {
        [self showMainWindow];
    } else {
        [self showWizard];
    }
89
    [self connect];
90 91 92 93 94

    dispatch_queue_t queue = NULL;
    queue = dispatch_queue_create("scNetworkReachability", DISPATCH_QUEUE_SERIAL);
    [self setScNetworkQueue:queue];
    [self beginObservingReachabilityStatus];
95 96 97 98 99 100 101 102 103 104 105 106
    [self startSleepPreventionTimer];
}

- (void) startSleepPreventionTimer
{
    if (preventSleepTimer != nil) {
        [preventSleepTimer invalidate];
    }
    preventSleepTimer = [NSTimer timerWithTimeInterval:30.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        UpdateSystemActivity(OverallAct);
    }];
    [[NSRunLoop mainRunLoop] addTimer:preventSleepTimer forMode:NSRunLoopCommonModes];
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
}

- (void) beginObservingReachabilityStatus
{
    SCNetworkReachabilityRef reachabilityRef = NULL;

    void (^callbackBlock)(SCNetworkReachabilityFlags) = ^(SCNetworkReachabilityFlags flags) {
        BOOL reachable = (flags & kSCNetworkReachabilityFlagsReachable) != 0;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            AccountModel::instance().slotConnectivityChanged();
        }];
    };

    SCNetworkReachabilityContext context = {
        .version = 0,
        .info = (void *)CFBridgingRetain(callbackBlock),
        .release = CFRelease
    };

    reachabilityRef = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "test");
    if (SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context)){
        if (!SCNetworkReachabilitySetDispatchQueue(reachabilityRef, [self scNetworkQueue]) ){
            // Remove our callback if we can't use the queue
            SCNetworkReachabilitySetCallback(reachabilityRef, NULL, NULL);
        }
        [self setCurrentReachability:reachabilityRef];
    }
}

- (void) endObsvervingReachabilityStatusForHost:(NSString *)__unused host
{
    // Un-set the dispatch queue
    if (SCNetworkReachabilitySetDispatchQueue([self currentReachability], NULL) ){
        SCNetworkReachabilitySetCallback([self currentReachability], NULL, NULL);
    }
}

static void ReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkConnectionFlags flags, void* info)
{
    void (^callbackBlock)(SCNetworkReachabilityFlags) = (__bridge id)info;
    callbackBlock(flags);
148 149 150 151
}

- (void) connect
{
152 153 154 155 156 157 158 159 160 161

    //ProfileModel::instance().addCollection<LocalProfileCollection>(LoadOptions::FORCE_ENABLED);
    QObject::connect(&AccountModel::instance(),
                     &AccountModel::registrationChanged,
                     [=](Account* a, bool registration) {
                         qDebug() << "registrationChanged:" << a->id() << ":" << registration;
                         //track buddy for account
                         AccountModel::instance().subscribeToBuddies(a->id());
                     });

Alexandre Lision's avatar
Alexandre Lision committed
162
    QObject::connect(&CallModel::instance(),
163 164
                     &CallModel::incomingCall,
                     [=](Call* call) {
165 166 167 168 169 170 171 172
                         // on incoming call set selected account match call destination account
                         if (call->account()) {
                             QModelIndex index = call->account()->index();
                             index = AvailableAccountModel::instance().mapFromSource(index);

                             AvailableAccountModel::instance().selectionModel()->setCurrentIndex(index,
                                                                                                 QItemSelectionModel::ClearAndSelect);
                         }
173 174
                         BOOL shouldComeToForeground = [[NSUserDefaults standardUserDefaults] boolForKey:Preferences::WindowBehaviour];
                         BOOL shouldNotify = [[NSUserDefaults standardUserDefaults] boolForKey:Preferences::Notifications];
175
                         if (shouldComeToForeground) {
176
                             [NSApp activateIgnoringOtherApps:YES];
177 178 179 180
                             if ([self.ringWindowController.window isMiniaturized]) {
                                 [self.ringWindowController.window deminiaturize:self];
                             }
                         }
181 182 183 184 185

                         if(shouldNotify) {
                             [self showIncomingNotification:call];
                         }
                     });
186

187 188 189
    QObject::connect(&media::RecordingModel::instance(),
                     &media::RecordingModel::newTextMessage,
                     [=](media::TextRecording* t, ContactMethod* cm) {
190 191 192 193 194

                         BOOL shouldNotify = [[NSUserDefaults standardUserDefaults] boolForKey:Preferences::Notifications];
                         auto qIdx = t->instantTextMessagingModel()->index(t->instantTextMessagingModel()->rowCount()-1, 0);

                         // Don't show a notification if we are sending the text OR window already has focus OR user disabled notifications
195
                         if(qvariant_cast<media::Media::Direction>(qIdx.data((int)media::TextRecording::Role::Direction)) == media::Media::Direction::OUT
196
                            || self.ringWindowController.window.isMainWindow || !shouldNotify)
197 198 199 200
                             return;

                         NSUserNotification* notification = [[NSUserNotification alloc] init];

201
                         NSString* localizedTitle = [NSString stringWithFormat:NSLocalizedString(@"Message from %@", @"Message from {Name}"), qIdx.data((int)media::TextRecording::Role::AuthorDisplayname).toString().toNSString()];
202 203 204 205 206 207 208

                         [notification setTitle:localizedTitle];
                         [notification setSoundName:NSUserNotificationDefaultSoundName];
                         [notification setSubtitle:qIdx.data().toString().toNSString()];

                         [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
                     });
209 210 211
}

- (void) showIncomingNotification:(Call*) call{
Alexandre Lision's avatar
Alexandre Lision committed
212
    NSUserNotification* notification = [[NSUserNotification alloc] init];
Alexandre Lision's avatar
Alexandre Lision committed
213 214
    NSString* localizedTitle = [NSString stringWithFormat:
                                NSLocalizedString(@"Incoming call from %@", @"Incoming call from {Name}"), call->peerName().toNSString()];
215 216
    [notification setTitle:localizedTitle];
    [notification setSoundName:NSUserNotificationDefaultSoundName];
217

Alexandre Lision's avatar
Alexandre Lision committed
218 219 220 221 222 223 224 225 226 227
    // try to activate action button
    @try {
        [notification setValue:@YES forKey:@"_showsButtons"];
    }
    @catch (NSException *exception) {
        // private API _showsButtons has changed...
        NSLog(@"Action button not activable on notification");
    }
    [notification setActionButtonTitle:NSLocalizedString(@"Refuse", @"Button Action")];

228
    [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
Alexandre Lision's avatar
Alexandre Lision committed
229 230
}

Alexandre Lision's avatar
Alexandre Lision committed
231 232 233 234 235 236 237 238 239 240 241 242
- (void) userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
{
    if(notification.activationType == NSUserNotificationActivationTypeActionButtonClicked) {
        CallModel::instance().selectedCall() << Call::Action::REFUSE;
    } else {
        [NSApp activateIgnoringOtherApps:YES];
        if ([self.ringWindowController.window isMiniaturized]) {
            [self.ringWindowController.window deminiaturize:self];
        }
    }
}

243 244 245
- (void) showWizard
{
    if(self.wizard == nil) {
246
        self.wizard = [[RingWizardWC alloc] initWithNibName:@"RingWizard" bundle: nil accountmodel: &lrc->getAccountModel()];
247
    }
248
    [self.wizard.window makeKeyAndOrderFront:self];
249 250 251 252
}

- (void) showMainWindow
{
253
    if(self.ringWindowController == nil) {
254
        self.ringWindowController = [[RingWindowController alloc] initWithWindowNibName:@"RingWindow" bundle: nil accountModel:&lrc->getAccountModel() dataTransferModel:&lrc->getDataTransferModel() behaviourController:&lrc->getBehaviorController()];
255
    }
256
    [[NSApplication sharedApplication] removeWindowsItem:self.wizard.window];
257 258 259
    [self.ringWindowController.window makeKeyAndOrderFront:self];
}

Alexandre Lision's avatar
Alexandre Lision committed
260 261 262 263 264 265 266 267 268
- (void) showDialpad
{
    if (self.dialpad == nil) {
        self.dialpad = [[DialpadWC alloc] initWithWindowNibName:@"Dialpad"];
    }
    [self.dialpad.window makeKeyAndOrderFront:self];
}


269 270
- (BOOL) checkForRingAccount
{
271
    BOOL foundRingAcc = NO;
Alexandre Lision's avatar
Alexandre Lision committed
272 273 274
    for (int i = 0 ; i < AccountModel::instance().rowCount() ; ++i) {
        QModelIndex idx = AccountModel::instance().index(i);
        Account* acc = AccountModel::instance().getAccountByModelIndex(idx);
275
        if(acc->protocol() == Account::Protocol::RING && !acc->isNew()) {
276 277 278
            if (acc->displayName().isEmpty())
                acc->setDisplayName(acc->alias());
            foundRingAcc = YES;
279 280
        }
    }
281
    return foundRingAcc;
282 283
}

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
-(void)applicationWillFinishLaunching:(NSNotification *)aNotification
{
    NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager];
    [appleEventManager setEventHandler:self
                           andSelector:@selector(handleGetURLEvent:withReplyEvent:)
                         forEventClass:kInternetEventClass andEventID:kAEGetURL];
}

/**
 * Recognized patterns:
 *   - ring:<hash>
 *   - ring://<hash>
 */
- (void)handleGetURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
    NSString* query = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
    NSURL* url = [[NSURL alloc] initWithString:query];
    NSString* ringID = [url host];
    if (!ringID) {
        //not a valid NSURL, try to parse query directly
        ringID = [query substringFromIndex:@"ring:".length];
    }

    // check for a valid ring hash
    NSCharacterSet *hexSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefABCDEF"];
    BOOL valid = [[ringID stringByTrimmingCharactersInSet:hexSet] isEqualToString:@""];

    if(valid && ringID.length == 40) {
Alexandre Lision's avatar
Alexandre Lision committed
312
        Call* c = CallModel::instance().dialingCall();
313 314 315 316 317 318 319 320 321 322 323 324
        c->setDialNumber(QString::fromNSString([NSString stringWithFormat:@"ring:%@",ringID]));
        c << Call::Action::ACCEPT;
    } else {
        NSAlert *alert = [[NSAlert alloc] init];
        [alert addButtonWithTitle:@"OK"];
        [alert setMessageText:@"Error"];
        [alert setInformativeText:@"ringID cannot be read from this URL."];
        [alert setAlertStyle:NSWarningAlertStyle];
        [alert runModal];
    }
}

325 326 327 328 329 330 331 332 333 334
- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
{
    if([self checkForRingAccount]) {
        [self showMainWindow];
    } else {
        [self showWizard];
    }
    return YES;
}

Edric Milaret's avatar
Edric Milaret committed
335 336
- (void)handleQuitEvent:(NSAppleEventDescriptor*)event withReplyEvent:(NSAppleEventDescriptor*)replyEvent
{
337
    [[NSApplication sharedApplication] terminate:self];
Edric Milaret's avatar
Edric Milaret committed
338 339 340 341
}

-(void)applicationWillTerminate:(NSNotification *)notification
{
342 343 344 345 346
    [self cleanExit];
}

- (void) cleanExit
{
347 348 349
    if (preventSleepTimer != nil) {
        [preventSleepTimer invalidate];
    }
350 351
    [self.wizard close];
    [self.ringWindowController close];
Alexandre Lision's avatar
Alexandre Lision committed
352
    delete CallModel::instance().QObject::parent();
Edric Milaret's avatar
Edric Milaret committed
353 354 355
    [[NSApplication sharedApplication] terminate:self];
}

356 357
#if ENABLE_SPARKLE

358
#pragma mark - Sparkle delegate
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

- (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
{
    [NSApp activateIgnoringOtherApps:YES];
}

- (BOOL)updaterMayCheckForUpdates:(SUUpdater *)bundle
{
    return YES;
}

- (BOOL)updaterShouldRelaunchApplication:(SUUpdater *)updater
{
    return YES;
}

- (void)updater:(SUUpdater *)updater didAbortWithError:(NSError *)error
{
    NSLog(@"Error:%@", error.localizedDescription);
}

#endif
Alexandre Lision's avatar
Alexandre Lision committed
381
@end