AppDelegate.mm 9.29 KB
Newer Older
1
/*
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 "AppDelegate.h"

21
#import <callmodel.h>
22
#import <qapplication.h>
23 24
#import <accountmodel.h>
#import <protocolmodel.h>
25 26
#import <media/recordingmodel.h>
#import <media/textrecording.h>
27 28 29
#import <QItemSelectionModel>
#import <account.h>

30 31 32 33
#if ENABLE_SPARKLE
#import <Sparkle/Sparkle.h>
#endif

34
#import "Constants.h"
35 36
#import "RingWizardWC.h"

37 38 39
#if ENABLE_SPARKLE
@interface AppDelegate() <SUUpdaterDelegate>
#else
40
@interface AppDelegate()
41
#endif
42 43 44 45 46 47

@property RingWindowController* ringWindowController;
@property RingWizardWC* wizard;

@end

48 49 50
@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
51 52
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints"];

53 54
    [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];

55 56 57
    NSAppleEventManager* appleEventManager = [NSAppleEventManager sharedAppleEventManager];
    [appleEventManager setEventHandler:self andSelector:@selector(handleQuitEvent:withReplyEvent:) forEventClass:kCoreEventClass andEventID:kAEQuitApplication];

58 59 60 61 62
    if([self checkForRingAccount]) {
        [self showMainWindow];
    } else {
        [self showWizard];
    }
63 64 65 66 67
    [self connect];
}

- (void) connect
{
68
    QObject::connect(&CallModel::instance(),
69 70
                     &CallModel::incomingCall,
                     [=](Call* call) {
71 72
                         BOOL shouldComeToForeground = [[NSUserDefaults standardUserDefaults] boolForKey:Preferences::WindowBehaviour];
                         BOOL shouldNotify = [[NSUserDefaults standardUserDefaults] boolForKey:Preferences::Notifications];
73
                         if (shouldComeToForeground) {
74
                             [NSApp activateIgnoringOtherApps:YES];
75 76 77 78
                             if ([self.ringWindowController.window isMiniaturized]) {
                                 [self.ringWindowController.window deminiaturize:self];
                             }
                         }
79 80 81 82 83

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


Alexandre Lision's avatar
Alexandre Lision committed
86 87 88 89 90 91
    QObject::connect(&Media::RecordingModel::instance(),
                     &Media::RecordingModel::unreadMessagesCountChanged,
                     [=](int unreadCount) {
                         NSDockTile *tile = [[NSApplication sharedApplication] dockTile];
                         NSString* label = unreadCount ? [NSString stringWithFormat:@"%d", unreadCount]: @"";
                         [tile setBadgeLabel:label];
92
                         [NSApp requestUserAttention:NSCriticalRequest];
Alexandre Lision's avatar
Alexandre Lision committed
93
                     });
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

    QObject::connect(&Media::RecordingModel::instance(),
                     &Media::RecordingModel::newTextMessage,
                     [=](Media::TextRecording* t, ContactMethod* cm) {

                         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
                         if(qvariant_cast<Media::Media::Direction>(qIdx.data((int)Media::TextRecording::Role::Direction)) == Media::Media::Direction::OUT
                            || self.ringWindowController.window.keyWindow || !shouldNotify)
                             return;

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

109
                         NSString* localizedTitle = [NSString stringWithFormat:NSLocalizedString(@"Message from %@", @"Message from {Name}"), qIdx.data((int)Media::TextRecording::Role::AuthorDisplayname).toString().toNSString()];
110 111 112 113 114 115 116

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

                         [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
                     });
117 118 119 120
}

- (void) showIncomingNotification:(Call*) call{
    NSUserNotification *notification = [[NSUserNotification alloc] init];
121 122
    NSString* localizedTitle = [NSString stringWithFormat:
                                NSLocalizedString(@"Incoming call from %@", @"Incoming call from {Name}"), call->peerName().toNSString()];
123 124
    [notification setTitle:localizedTitle];
    [notification setSoundName:NSUserNotificationDefaultSoundName];
125 126

    [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
127 128
}

129 130 131 132 133 134 135 136 137 138 139 140
/**
 * click in MainMenu "Setup Ring"
 */
- (IBAction)showWizard:(id)sender {
    [self showWizard];
}

- (void) showWizard
{
    if(self.wizard == nil) {
        self.wizard = [[RingWizardWC alloc] initWithWindowNibName:@"RingWizard"];
    }
141
    [self.wizard.window makeKeyAndOrderFront:self];
142 143 144 145
}

- (void) showMainWindow
{
146
    if(self.ringWindowController == nil) {
147
        self.ringWindowController = [[RingWindowController alloc] initWithWindowNibName:@"RingWindow"];
148
    }
149 150 151 152 153
    [self.ringWindowController.window makeKeyAndOrderFront:self];
}

- (BOOL) checkForRingAccount
{
154
    BOOL foundRingAcc = NO;
155 156 157
    for (int i = 0 ; i < AccountModel::instance().rowCount() ; ++i) {
        QModelIndex idx = AccountModel::instance().index(i);
        Account* acc = AccountModel::instance().getAccountByModelIndex(idx);
158
        if(acc->protocol() == Account::Protocol::RING && !acc->isNew()) {
159 160 161
            if (acc->displayName().isEmpty())
                acc->setDisplayName(acc->alias());
            foundRingAcc = YES;
162 163
        }
    }
164
    return foundRingAcc;
165 166
}

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
-(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) {
195
        Call* c = CallModel::instance().dialingCall();
196 197 198 199 200 201 202 203 204 205 206 207
        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];
    }
}

208 209 210 211 212 213 214 215 216 217
- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
{
    if([self checkForRingAccount]) {
        [self showMainWindow];
    } else {
        [self showWizard];
    }
    return YES;
}

218 219
- (void)handleQuitEvent:(NSAppleEventDescriptor*)event withReplyEvent:(NSAppleEventDescriptor*)replyEvent
{
220
    [self cleanExit];
221 222 223 224
}

-(void)applicationWillTerminate:(NSNotification *)notification
{
225 226 227 228 229 230 231
    [self cleanExit];
}

- (void) cleanExit
{
    [self.wizard close];
    [self.ringWindowController close];
232
    delete CallModel::instance().QObject::parent();
233 234 235
    [[NSApplication sharedApplication] terminate:self];
}

236 237
#if ENABLE_SPARKLE

238
#pragma mark - Sparkle delegate
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

- (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
261
@end