CurrentCallVC.mm 30.7 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 19 20 21 22
 *  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.
 */
#import "CurrentCallVC.h"

#import <QuartzCore/QuartzCore.h>

23 24 25 26 27 28 29 30 31
///Qt
#import <QMimeData>
#import <QtMacExtras/qmacfunctions.h>
#import <QtCore/qabstractitemmodel.h>
#import <QItemSelectionModel>
#import <QItemSelection>
#import <QPixmap>

///LRC
32 33
#import <call.h>
#import <callmodel.h>
34
#import <recentmodel.h>
35 36 37 38
#import <useractionmodel.h>
#import <contactmethod.h>
#import <video/previewmanager.h>
#import <video/renderer.h>
Alexandre Lision's avatar
Alexandre Lision committed
39
#import <media/text.h>
40
#import <person.h>
41
#import <globalinstances.h>
42

43
#import "views/ITProgressIndicator.h"
44
#import "views/CallView.h"
45
#import "delegates/ImageManipulationDelegate.h"
46
#import "PersonLinkerVC.h"
Alexandre Lision's avatar
Alexandre Lision committed
47
#import "ChatVC.h"
48
#import "BrokerVC.h"
49

50 51 52 53 54 55 56 57 58 59 60 61
@interface RendererConnectionsHolder : NSObject

@property QMetaObject::Connection frameUpdated;
@property QMetaObject::Connection started;
@property QMetaObject::Connection stopped;

@end

@implementation RendererConnectionsHolder

@end

62
@interface CurrentCallVC () <NSPopoverDelegate, ContactLinkedDelegate>
63

64 65 66
// Main container
@property (unsafe_unretained) IBOutlet NSSplitView* splitView;

67 68
// Header info
@property (unsafe_unretained) IBOutlet NSView* headerContainer;
69 70
@property (unsafe_unretained) IBOutlet NSTextField* personLabel;
@property (unsafe_unretained) IBOutlet NSTextField* stateLabel;
71
@property (unsafe_unretained) IBOutlet NSTextField* timeSpentLabel;
72
@property (unsafe_unretained) IBOutlet NSImageView* personPhoto;
73 74 75

// Call Controls
@property (unsafe_unretained) IBOutlet NSView* controlsPanel;
76
@property QHash<int, NSButton*> actionHash;
77 78 79 80 81 82 83 84
@property (unsafe_unretained) IBOutlet NSButton* holdOnOffButton;
@property (unsafe_unretained) IBOutlet NSButton* hangUpButton;
@property (unsafe_unretained) IBOutlet NSButton* recordOnOffButton;
@property (unsafe_unretained) IBOutlet NSButton* pickUpButton;
@property (unsafe_unretained) IBOutlet NSButton* muteAudioButton;
@property (unsafe_unretained) IBOutlet NSButton* muteVideoButton;
@property (unsafe_unretained) IBOutlet NSButton* addContactButton;
@property (unsafe_unretained) IBOutlet NSButton* transferButton;
85 86
@property (unsafe_unretained) IBOutlet NSButton* addParticipantButton;
@property (unsafe_unretained) IBOutlet NSButton* chatButton;
87 88


89 90 91 92
// Join call panel
@property (unsafe_unretained) IBOutlet NSView* joinPanel;
@property (unsafe_unretained) IBOutlet NSButton* mergeCallsButton;

93
@property (strong) NSPopover* addToContactPopover;
94
@property (strong) NSPopover* brokerPopoverVC;
95
@property (strong) IBOutlet ChatVC* chatVC;
96

97 98 99 100 101 102 103 104
// Ringing call panel
@property (unsafe_unretained) IBOutlet NSView* ringingPanel;
@property (unsafe_unretained) IBOutlet NSImageView* incomingPersonPhoto;
@property (unsafe_unretained) IBOutlet NSTextField* incomingDisplayName;

// Outgoing call panel
@property (unsafe_unretained) IBOutlet NSView* outgoingPanel;
@property (unsafe_unretained) IBOutlet ITProgressIndicator *loadingIndicator;
105 106

// Video
Alexandre Lision's avatar
Alexandre Lision committed
107 108
@property (unsafe_unretained) IBOutlet CallView *videoView;
@property (unsafe_unretained) IBOutlet NSView *previewView;
109 110 111

@property RendererConnectionsHolder* previewHolder;
@property RendererConnectionsHolder* videoHolder;
112
@property QMetaObject::Connection videoStarted;
113
@property QMetaObject::Connection selectedCallChanged;
114 115
@property QMetaObject::Connection messageConnection;
@property QMetaObject::Connection mediaAddedConnection;
116 117 118 119

@end

@implementation CurrentCallVC
120
@synthesize personLabel, personPhoto, actionHash, stateLabel, holdOnOffButton, hangUpButton,
121
            recordOnOffButton, pickUpButton, chatButton, transferButton, addParticipantButton, timeSpentLabel,
122 123
            muteVideoButton, muteAudioButton, controlsPanel, headerContainer, videoView, incomingDisplayName, incomingPersonPhoto,
            previewView, splitView, loadingIndicator, ringingPanel, joinPanel, outgoingPanel;
124 125 126 127

@synthesize previewHolder;
@synthesize videoHolder;

128
- (void) updateAllActions
129
{
130
    for (int i = 0 ; i < CallModel::instance().userActionModel()->rowCount() ; i++) {
131 132 133 134 135 136
        [self updateActionAtIndex:i];
    }
}

- (void) updateActionAtIndex:(int) row
{
137
    const QModelIndex& idx = CallModel::instance().userActionModel()->index(row,0);
138 139
    UserActionModel::Action action = qvariant_cast<UserActionModel::Action>(idx.data(UserActionModel::Role::ACTION));
    NSButton* a = actionHash[(int) action];
140 141
    if (a) {
        [a setHidden:!(idx.flags() & Qt::ItemIsEnabled)];
142
        [a setHighlighted:(idx.data(Qt::CheckStateRole) == Qt::Checked) ? YES : NO];
143 144 145
    }
}

146
-(void) updateCall:(BOOL) firstRun
147
{
148
    QModelIndex callIdx = CallModel::instance().selectionModel()->currentIndex();
149 150 151
    if (!callIdx.isValid()) {
        return;
    }
152
    auto current = CallModel::instance().selectedCall();
153

Alexandre Lision's avatar
Alexandre Lision committed
154 155
    [personLabel setStringValue:callIdx.data(Qt::DisplayRole).toString().toNSString()];
    [timeSpentLabel setStringValue:callIdx.data((int)Call::Role::Length).toString().toNSString()];
Alexandre Lision's avatar
Alexandre Lision committed
156
    [stateLabel setStringValue:callIdx.data((int)Call::Role::HumanStateName).toString().toNSString()];
157

158 159 160 161 162
    if (firstRun) {
        QVariant photo = GlobalInstances::pixmapManipulator().callPhoto(current, QSize(50,50));
        [personPhoto setImage:QtMac::toNSImage(qvariant_cast<QPixmap>(photo))];
    }

163 164 165 166
    auto contactmethod = qvariant_cast<Call*>(callIdx.data(static_cast<int>(Call::Role::Object)))->peerContactMethod();
    BOOL shouldShow = (!contactmethod->contact() || contactmethod->contact()->isPlaceHolder());
    [self.addContactButton setHidden:!shouldShow];

167
    // Default values for this views
168
    [loadingIndicator setHidden:YES];
169
    [videoView setShouldAcceptInteractions:NO];
170 171 172 173
    [ringingPanel setHidden:YES];
    [outgoingPanel setHidden:YES];
    [controlsPanel setHidden:NO];
    [headerContainer setHidden:NO];
174

175
    auto state = callIdx.data((int)Call::Role::State).value<Call::State>();
176
    switch (state) {
177 178
        case Call::State::NEW:
            break;
179
        case Call::State::DIALING:
180
        case Call::State::INITIALIZATION:
181 182
        case Call::State::CONNECTED:
            [loadingIndicator setHidden:NO];
183
        case Call::State::RINGING:
184 185 186 187 188
            [controlsPanel setHidden:YES];
            [outgoingPanel setHidden:NO];
            break;
        case Call::State::INCOMING:
            [self setupIncoming:current];
189
            break;
190
        case Call::State::CONFERENCE:
191
            [self setupConference:current];
192
            break;
193
        case Call::State::CURRENT:
194
            [self setupCurrent:current];
195 196 197 198 199 200
            break;
        case Call::State::HOLD:
            break;
        case Call::State::BUSY:
            break;
        case Call::State::OVER:
201
        case Call::State::FAILURE:
202 203
            [controlsPanel setHidden:YES];
            [outgoingPanel setHidden:NO];
204 205
            if(self.splitView.isInFullScreenMode)
                [self.splitView exitFullScreenModeWithOptions:nil];
206 207 208 209 210
            break;
    }

}

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
-(void) setupIncoming:(Call*) c
{
    [ringingPanel setHidden:NO];
    [controlsPanel setHidden:YES];
    [headerContainer setHidden:YES];
    QVariant photo = GlobalInstances::pixmapManipulator().callPhoto(c, QSize(100,100));
    [incomingPersonPhoto setImage:QtMac::toNSImage(qvariant_cast<QPixmap>(photo))];
    [incomingDisplayName setStringValue:c->formattedName().toNSString()];
}

-(void) setupCurrent:(Call*) c
{
    [joinPanel setHidden:!c->hasParentCall()];
    [controlsPanel setHidden:c->hasParentCall()];
    [videoView setShouldAcceptInteractions:YES];
    [self.chatButton setHidden:NO];
    [self.addParticipantButton setHidden:NO];
    [self.transferButton setHidden:NO];
}

-(void) setupConference:(Call*) c
{
    [videoView setShouldAcceptInteractions:YES];
    [self.chatButton setHidden:NO];
    [joinPanel setHidden:YES];
    [self.addParticipantButton setHidden:NO];
    [self.transferButton setHidden:YES];
}


241 242 243
- (void)awakeFromNib
{
    NSLog(@"INIT CurrentCall VC");
244
    [self.view setWantsLayer:YES];
245

246 247 248 249
    actionHash[ (int)UserActionModel::Action::ACCEPT] = pickUpButton;
    actionHash[ (int)UserActionModel::Action::HOLD  ] = holdOnOffButton;
    actionHash[ (int)UserActionModel::Action::RECORD] = recordOnOffButton;
    actionHash[ (int)UserActionModel::Action::HANGUP] = hangUpButton;
250 251
    actionHash[ (int)UserActionModel::Action::MUTE_AUDIO] = muteAudioButton;
    actionHash[ (int)UserActionModel::Action::MUTE_VIDEO] = muteVideoButton;
252 253 254 255 256 257 258

    [videoView setWantsLayer:YES];
    [videoView.layer setBackgroundColor:[NSColor blackColor].CGColor];
    [videoView.layer setFrame:videoView.frame];
    [videoView.layer setContentsGravity:kCAGravityResizeAspect];

    [previewView setWantsLayer:YES];
259 260 261
    [previewView.layer setBackgroundColor:[NSColor blackColor].CGColor];
    [previewView.layer setContentsGravity:kCAGravityResizeAspectFill];
    [previewView.layer setFrame:previewView.frame];
262 263 264 265 266

    [controlsPanel setWantsLayer:YES];
    [controlsPanel.layer setBackgroundColor:[NSColor clearColor].CGColor];
    [controlsPanel.layer setFrame:controlsPanel.frame];

267 268 269
    previewHolder = [[RendererConnectionsHolder alloc] init];
    videoHolder = [[RendererConnectionsHolder alloc] init];

270 271 272 273 274 275
    [loadingIndicator setColor:[NSColor whiteColor]];
    [loadingIndicator setNumberOfLines:100];
    [loadingIndicator setWidthOfLine:2];
    [loadingIndicator setLengthOfLine:2];
    [loadingIndicator setInnerMargin:30];

276
    [self.videoView setCallDelegate:self];
Alexandre Lision's avatar
Alexandre Lision committed
277

278 279 280 281 282
    [self connect];
}

- (void) connect
{
283
    QObject::connect(RecentModel::instance().selectionModel(),
284 285
                     &QItemSelectionModel::currentChanged,
                     [=](const QModelIndex &current, const QModelIndex &previous) {
286 287
                         auto call = RecentModel::instance().getActiveCall(current);
                         if(!current.isValid() || !call) {
288 289
                             return;
                         }
290

291
                         [self changeCallSelection:call];
292

293 294 295 296
                         if (call->state() == Call::State::HOLD) {
                             call << Call::Action::HOLD;
                         }

Alexandre Lision's avatar
Alexandre Lision committed
297
                         [self collapseRightView];
298
                         [self updateCall:YES];
299
                         [self updateAllActions];
300 301
                     });

302
    QObject::connect(CallModel::instance().userActionModel(),
303 304 305 306
                     &QAbstractItemModel::dataChanged,
                     [=](const QModelIndex &topLeft, const QModelIndex &bottomRight) {
                         const int first(topLeft.row()),last(bottomRight.row());
                         for(int i = first; i <= last;i++) {
307
                             [self updateActionAtIndex:i];
308 309 310
                         }
                     });

311
    QObject::connect(&CallModel::instance(),
312 313
                     &CallModel::callStateChanged,
                     [self](Call* c, Call::State state) {
Alexandre Lision's avatar
Alexandre Lision committed
314 315 316 317 318
                         auto current = CallModel::instance().selectionModel()->currentIndex();
                         if (!current.isValid())
                             [self animateOut];
                         else if (CallModel::instance().getIndex(c) == current) {
                             if (c->state() == Call::State::OVER) {
319
                                 RecentModel::instance().selectionModel()->clearCurrentIndex();
Alexandre Lision's avatar
Alexandre Lision committed
320
                             } else {
321
                                 [self updateCall:NO];
Alexandre Lision's avatar
Alexandre Lision committed
322 323
                             }
                         }
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
                     });

    QObject::connect(&CallModel::instance(),
                     &CallModel::incomingCall,
                     [self](Call* c) {
                         [self changeCallSelection:c];
                     });
}

- (void) changeCallSelection:(Call* )c
{
    QObject::disconnect(self.selectedCallChanged);
    CallModel::instance().selectCall(c);
    self.selectedCallChanged = QObject::connect(CallModel::instance().selectedCall(),
                                                &Call::changed,
                                                [=]() {
340
                                                    [self updateCall:NO];
341
                                                });
342 343
}

344 345 346 347 348 349 350 351 352 353 354 355
- (void) monitorIncomingTextMessages:(Media::Text*) media
{
    /* connect to incoming chat messages to open the chat view */
    QObject::disconnect(self.messageConnection);
    self.messageConnection = QObject::connect(media,
                                              &Media::Text::messageReceived,
                                              [self] (const QMap<QString,QString>& m) {
                                                  if([[self splitView] isSubviewCollapsed:[[[self splitView] subviews] objectAtIndex: 1]])
                                                      [self uncollapseRightView];
                                              });
}

356 357
-(void) connectVideoSignals
{
358 359
    QModelIndex idx = CallModel::instance().selectionModel()->currentIndex();
    Call* call = CallModel::instance().getCall(idx);
360
    QObject::disconnect(self.videoStarted);
Alexandre Lision's avatar
Alexandre Lision committed
361
    self.videoStarted = QObject::connect(call,
362 363
                     &Call::videoStarted,
                     [=](Video::Renderer* renderer) {
364 365
                         NSLog(@"Video started!");
                         [self connectVideoRenderer:renderer];
366 367 368 369 370 371 372 373 374 375 376 377 378
                     });

    if(call->videoRenderer())
    {
        [self connectVideoRenderer:call->videoRenderer()];
    }

    [self connectPreviewRenderer];

}

-(void) connectPreviewRenderer
{
379 380 381
    QObject::disconnect(previewHolder.frameUpdated);
    QObject::disconnect(previewHolder.stopped);
    QObject::disconnect(previewHolder.started);
382
    previewHolder.started = QObject::connect(&Video::PreviewManager::instance(),
383 384 385 386 387 388
                     &Video::PreviewManager::previewStarted,
                     [=](Video::Renderer* renderer) {
                         QObject::disconnect(previewHolder.frameUpdated);
                         previewHolder.frameUpdated = QObject::connect(renderer,
                                                                       &Video::Renderer::frameUpdated,
                                                                       [=]() {
389
                                                                           [self renderer:Video::PreviewManager::instance().previewRenderer()
390 391 392 393
                                                                       renderFrameForView:previewView];
                                                                       });
                     });

394
    previewHolder.stopped = QObject::connect(&Video::PreviewManager::instance(),
395 396 397 398 399 400
                     &Video::PreviewManager::previewStopped,
                     [=](Video::Renderer* renderer) {
                         QObject::disconnect(previewHolder.frameUpdated);
                        [previewView.layer setContents:nil];
                     });

401
    previewHolder.frameUpdated = QObject::connect(Video::PreviewManager::instance().previewRenderer(),
402 403
                                                 &Video::Renderer::frameUpdated,
                                                 [=]() {
404
                                                     [self renderer:Video::PreviewManager::instance().previewRenderer()
405 406 407 408 409 410
                                                            renderFrameForView:previewView];
                                                 });
}

-(void) connectVideoRenderer: (Video::Renderer*)renderer
{
411 412 413
    QObject::disconnect(videoHolder.frameUpdated);
    QObject::disconnect(videoHolder.started);
    QObject::disconnect(videoHolder.stopped);
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    videoHolder.frameUpdated = QObject::connect(renderer,
                     &Video::Renderer::frameUpdated,
                     [=]() {
                         [self renderer:renderer renderFrameForView:videoView];
                     });

    videoHolder.started = QObject::connect(renderer,
                     &Video::Renderer::started,
                     [=]() {
                         QObject::disconnect(videoHolder.frameUpdated);
                         videoHolder.frameUpdated = QObject::connect(renderer,
                                                                     &Video::Renderer::frameUpdated,
                                                                     [=]() {
                                                                         [self renderer:renderer renderFrameForView:videoView];
                                                                     });
                     });

    videoHolder.stopped = QObject::connect(renderer,
                     &Video::Renderer::stopped,
                     [=]() {
                         QObject::disconnect(videoHolder.frameUpdated);
                        [videoView.layer setContents:nil];
                     });
}

-(void) renderer: (Video::Renderer*)renderer renderFrameForView:(NSView*) view
{
    QSize res = renderer->size();

443 444 445 446 447
    auto frame_ptr = renderer->currentFrame();
    auto frame_data = frame_ptr.ptr;
    if (!frame_data)
        return;

448 449

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
450
    CGContextRef newContext = CGBitmapContextCreate(frame_data,
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
                                                    res.width(),
                                                    res.height(),
                                                    8,
                                                    4*res.width(),
                                                    colorSpace,
                                                    kCGImageAlphaPremultipliedLast);


    CGImageRef newImage = CGBitmapContextCreateImage(newContext);

    /*We release some components*/
    CGContextRelease(newContext);
    CGColorSpaceRelease(colorSpace);

    [CATransaction begin];
    view.layer.contents = (__bridge id)newImage;
    [CATransaction commit];

    CFRelease(newImage);
}

- (void) initFrame
{
    [self.view setFrame:self.view.superview.bounds];
    [self.view setHidden:YES];
    self.view.layer.position = self.view.frame.origin;
477
    [self collapseRightView];
478 479 480 481 482 483 484 485 486 487 488 489 490 491
}

# pragma private IN/OUT animations

-(void) animateIn
{
    CGRect frame = CGRectOffset(self.view.superview.bounds, -self.view.superview.bounds.size.width, 0);
    [self.view setHidden:NO];

    [CATransaction begin];
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setFromValue:[NSValue valueWithPoint:frame.origin]];
    [animation setToValue:[NSValue valueWithPoint:self.view.superview.bounds.origin]];
    [animation setDuration:0.2f];
492
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
493
    [CATransaction setCompletionBlock:^{
494 495 496 497

        // when call comes in we want to show the controls/header
        [self mouseIsMoving:YES];

498
        [self connectVideoSignals];
499
        /* check if text media is already present */
500
        if(!CallModel::instance().selectedCall())
501
            return;
502

503
        [loadingIndicator setAnimates:YES];
504
        [self updateCall:YES];
505

506 507
        if (CallModel::instance().selectedCall()->hasMedia(Media::Media::Type::TEXT, Media::Media::Direction::IN)) {
            Media::Text *text = CallModel::instance().selectedCall()->firstMedia<Media::Text>(Media::Media::Direction::IN);
508
            [self monitorIncomingTextMessages:text];
509 510
        } else if (CallModel::instance().selectedCall()->hasMedia(Media::Media::Type::TEXT, Media::Media::Direction::OUT)) {
            Media::Text *text = CallModel::instance().selectedCall()->firstMedia<Media::Text>(Media::Media::Direction::OUT);
511 512 513
            [self monitorIncomingTextMessages:text];
        } else {
            /* monitor media for messaging text messaging */
514
            self.mediaAddedConnection = QObject::connect(CallModel::instance().selectedCall(),
515 516 517 518 519 520 521
                                                         &Call::mediaAdded,
                                                         [self] (Media::Media* media) {
                                                             if (media->type() == Media::Media::Type::TEXT) {                                                                     [self monitorIncomingTextMessages:(Media::Text*)media];
                                                                 QObject::disconnect(self.mediaAddedConnection);
                                                             }
                                                         });
        }
522 523 524 525 526 527 528 529
    }];
    [self.view.layer addAnimation:animation forKey:animation.keyPath];

    [CATransaction commit];
}

-(void) cleanUp
{
530 531 532 533 534 535
    QObject::disconnect(videoHolder.frameUpdated);
    QObject::disconnect(videoHolder.started);
    QObject::disconnect(videoHolder.stopped);
    QObject::disconnect(previewHolder.frameUpdated);
    QObject::disconnect(previewHolder.stopped);
    QObject::disconnect(previewHolder.started);
536 537
    [videoView.layer setContents:nil];
    [previewView.layer setContents:nil];
538

539
    [_brokerPopoverVC performClose:self];
540
    [self.addToContactPopover performClose:self];
Alexandre Lision's avatar
Alexandre Lision committed
541

542 543 544 545
    [self.chatButton setHidden:YES];
    [self.addParticipantButton setHidden:YES];
    [self.transferButton setHidden:YES];

546
    [self.chatButton setState:NSOffState];
547
    [self.mergeCallsButton setState:NSOffState];
548
    [self collapseRightView];
Alexandre Lision's avatar
Alexandre Lision committed
549 550 551 552 553

    [personLabel setStringValue:@""];
    [timeSpentLabel setStringValue:@""];
    [stateLabel setStringValue:@""];
    [self.addContactButton setHidden:YES];
554 555 556 557 558 559 560 561 562 563 564 565 566 567
}

-(void) animateOut
{
    if(self.view.frame.origin.x < 0) {
        return;
    }

    CGRect frame = CGRectOffset(self.view.frame, -self.view.frame.size.width, 0);
    [CATransaction begin];
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setFromValue:[NSValue valueWithPoint:self.view.frame.origin]];
    [animation setToValue:[NSValue valueWithPoint:frame.origin]];
    [animation setDuration:0.2f];
568
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
569 570 571

    [CATransaction setCompletionBlock:^{
        [self.view setHidden:YES];
572
        // first make sure everything is disconnected
573
        [self cleanUp];
574
        if (RecentModel::instance().getActiveCall(RecentModel::instance().selectionModel()->currentIndex())) {
575 576 577 578
            [self animateIn];
        }
    }];
    [self.view.layer addAnimation:animation forKey:animation.keyPath];
579 580

    [self.view.layer setPosition:frame.origin];
581 582 583 584 585 586 587 588 589 590 591
    [CATransaction commit];
}

/**
 *  Debug purpose
 */
-(void) dumpFrame:(CGRect) frame WithName:(NSString*) name
{
    NSLog(@"frame %@ : %f %f %f %f \n\n",name ,frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
}

Alexandre Lision's avatar
Alexandre Lision committed
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
-(void)collapseRightView
{
    NSView *right = [[splitView subviews] objectAtIndex:1];
    NSView *left  = [[splitView subviews] objectAtIndex:0];
    NSRect leftFrame = [left frame];
    [right setHidden:YES];
    [splitView display];
}

-(void)uncollapseRightView
{
    NSView *left  = [[splitView subviews] objectAtIndex:0];
    NSView *right = [[splitView subviews] objectAtIndex:1];
    [right setHidden:NO];

    CGFloat dividerThickness = [splitView dividerThickness];

    // get the different frames
    NSRect leftFrame = [left frame];
    NSRect rightFrame = [right frame];

    leftFrame.size.width = (leftFrame.size.width - rightFrame.size.width - dividerThickness);
    rightFrame.origin.x = leftFrame.size.width + dividerThickness;
    [left setFrameSize:leftFrame.size];
    [right setFrame:rightFrame];
    [splitView display];
Alexandre Lision's avatar
Alexandre Lision committed
618 619

    [self.chatVC takeFocus];
Alexandre Lision's avatar
Alexandre Lision committed
620 621 622 623
}


#pragma mark - Button methods
624

625
- (IBAction)addToContact:(NSButton*) sender {
626
    auto contactmethod = CallModel::instance().getCall(CallModel::instance().selectionModel()->currentIndex())->peerContactMethod();
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643

    if (self.addToContactPopover != nullptr) {
        [self.addToContactPopover performClose:self];
        self.addToContactPopover = NULL;
    } else if (!contactmethod->contact() || contactmethod->contact()->isPlaceHolder()) {
        auto* editorVC = [[PersonLinkerVC alloc] initWithNibName:@"PersonLinker" bundle:nil];
        [editorVC setMethodToLink:contactmethod];
        [editorVC setContactLinkedDelegate:self];
        self.addToContactPopover = [[NSPopover alloc] init];
        [self.addToContactPopover setContentSize:editorVC.view.frame.size];
        [self.addToContactPopover setContentViewController:editorVC];
        [self.addToContactPopover setAnimates:YES];
        [self.addToContactPopover setBehavior:NSPopoverBehaviorTransient];
        [self.addToContactPopover setDelegate:self];

        [self.addToContactPopover showRelativeToRect:sender.bounds ofView:sender preferredEdge:NSMaxXEdge];
    }
644 645

    [videoView setCallDelegate:nil];
646 647
}

648
- (IBAction)hangUp:(id)sender {
649
    CallModel::instance().getCall(CallModel::instance().selectionModel()->currentIndex()) << Call::Action::REFUSE;
650 651 652
}

- (IBAction)accept:(id)sender {
653
    CallModel::instance().getCall(CallModel::instance().selectionModel()->currentIndex()) << Call::Action::ACCEPT;
654 655 656
}

- (IBAction)toggleRecording:(id)sender {
657
    CallModel::instance().getCall(CallModel::instance().selectionModel()->currentIndex()) << Call::Action::RECORD_AUDIO;
658 659 660
}

- (IBAction)toggleHold:(id)sender {
661
    CallModel::instance().getCall(CallModel::instance().selectionModel()->currentIndex()) << Call::Action::HOLD;
662 663
}

Alexandre Lision's avatar
Alexandre Lision committed
664 665 666 667 668
-(IBAction)toggleChat:(id)sender;
{
    BOOL rightViewCollapsed = [[self splitView] isSubviewCollapsed:[[[self splitView] subviews] objectAtIndex: 1]];
    if (rightViewCollapsed) {
        [self uncollapseRightView];
669
        CallModel::instance().getCall(CallModel::instance().selectionModel()->currentIndex())->addOutgoingMedia<Media::Text>();
Alexandre Lision's avatar
Alexandre Lision committed
670 671 672 673 674 675
    } else {
        [self collapseRightView];
    }
    [chatButton setState:rightViewCollapsed];
}

676 677
- (IBAction)muteAudio:(id)sender
{
678
    UserActionModel* uam = CallModel::instance().userActionModel();
679 680 681 682 683
    uam << UserActionModel::Action::MUTE_AUDIO;
}

- (IBAction)muteVideo:(id)sender
{
684
    UserActionModel* uam = CallModel::instance().userActionModel();
685 686
    uam << UserActionModel::Action::MUTE_VIDEO;
}
687 688

- (IBAction)toggleTransferView:(id)sender {
689 690 691
    if (_brokerPopoverVC != nullptr) {
        [_brokerPopoverVC performClose:self];
        _brokerPopoverVC = NULL;
692 693
        [self.transferButton setState:NSOffState];
    } else {
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
        auto* brokerVC = [[BrokerVC alloc] initWithMode:BrokerMode::TRANSFER];
        _brokerPopoverVC = [[NSPopover alloc] init];
        [_brokerPopoverVC setContentSize:brokerVC.view.frame.size];
        [_brokerPopoverVC setContentViewController:brokerVC];
        [_brokerPopoverVC setAnimates:YES];
        [_brokerPopoverVC setBehavior:NSPopoverBehaviorTransient];
        [_brokerPopoverVC setDelegate:self];
        [_brokerPopoverVC showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMinYEdge];
        [videoView setCallDelegate:nil];
    }
}

- (IBAction)toggleAddParticipantView:(id)sender {
    if (_brokerPopoverVC != nullptr) {
        [_brokerPopoverVC performClose:self];
        _brokerPopoverVC = NULL;
        [self.addParticipantButton setState:NSOffState];
    } else {
        auto* brokerVC = [[BrokerVC alloc] initWithMode:BrokerMode::CONFERENCE];
        _brokerPopoverVC = [[NSPopover alloc] init];
        [_brokerPopoverVC setContentSize:brokerVC.view.frame.size];
        [_brokerPopoverVC setContentViewController:brokerVC];
        [_brokerPopoverVC setAnimates:YES];
        [_brokerPopoverVC setBehavior:NSPopoverBehaviorTransient];
        [_brokerPopoverVC setDelegate:self];
        [_brokerPopoverVC showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMinYEdge];
720 721
        [videoView setCallDelegate:nil];
    }
722
}
723

724 725 726 727 728 729 730 731 732
/**
 *  Merge current call with its parent call
 */
- (IBAction)mergeCalls:(id)sender
{
    auto current = CallModel::instance().selectedCall();
    current->joinToParent();
}

733 734
#pragma mark - NSPopOverDelegate

735 736
- (void)popoverWillClose:(NSNotification *)notification
{
737 738 739
    if (_brokerPopoverVC != nullptr) {
        [_brokerPopoverVC performClose:self];
        _brokerPopoverVC = NULL;
740 741 742 743 744 745 746
    }

    if (self.addToContactPopover != nullptr) {
        [self.addToContactPopover performClose:self];
        self.addToContactPopover = NULL;
    }

747
    [self.addContactButton setState:NSOffState];
748
    [self.transferButton setState:NSOffState];
749
    [self.addParticipantButton setState:NSOffState];
750 751
}

752 753
- (void)popoverDidClose:(NSNotification *)notification
{
754
    [videoView setCallDelegate:self];
755 756 757 758 759 760 761 762 763 764 765 766
}

#pragma mark - ContactLinkedDelegate

- (void)contactLinked
{
    if (self.addToContactPopover != nullptr) {
        [self.addToContactPopover performClose:self];
        self.addToContactPopover = NULL;
    }
}

Alexandre Lision's avatar
Alexandre Lision committed
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
#pragma mark - NSSplitViewDelegate

/* Return YES if the subview should be collapsed because the user has double-clicked on an adjacent divider. If a split view has a delegate, and the delegate responds to this message, it will be sent once for the subview before a divider when the user double-clicks on that divider, and again for the subview after the divider, but only if the delegate returned YES when sent -splitView:canCollapseSubview: for the subview in question. When the delegate indicates that both subviews should be collapsed NSSplitView's behavior is undefined.
 */
- (BOOL)splitView:(NSSplitView *)splitView shouldCollapseSubview:(NSView *)subview forDoubleClickOnDividerAtIndex:(NSInteger)dividerIndex;
{
    NSView* rightView = [[splitView subviews] objectAtIndex:1];
    return ([subview isEqual:rightView]);
}


- (BOOL)splitView:(NSSplitView *)splitView canCollapseSubview:(NSView *)subview;
{
    NSView* rightView = [[splitView subviews] objectAtIndex:1];
    return ([subview isEqual:rightView]);
}


785
# pragma mark - CallnDelegate
Alexandre Lision's avatar
Alexandre Lision committed
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800

- (void) callShouldToggleFullScreen
{
    if(self.splitView.isInFullScreenMode)
        [self.splitView exitFullScreenModeWithOptions:nil];
    else {
        NSApplicationPresentationOptions options = NSApplicationPresentationDefault +NSApplicationPresentationAutoHideDock +
        NSApplicationPresentationAutoHideMenuBar + NSApplicationPresentationAutoHideToolbar;
        NSDictionary *opts = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInt:options],
                              NSFullScreenModeApplicationPresentationOptions, nil];

        [self.splitView enterFullScreenMode:[NSScreen mainScreen]  withOptions:opts];
    }
}

801 802 803 804 805 806
-(void) mouseIsMoving:(BOOL) move
{
    [[controlsPanel animator] setAlphaValue:move]; // fade out
    [[headerContainer animator] setAlphaValue:move];
}

807
@end