ConversationVC.mm 10.4 KB
Newer Older
1
/*
2
 *  Copyright (C) 2016-2018 Savoir-faire Linux Inc.
3
 *  Author: Alexandre Lision <alexandre.lision@savoirfairelinux.com>
4
 *  Author: Anthony Léonard <anthony.leonard@savoirfairelinux.com>
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 *  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 "ConversationVC.h"

#import <QItemSelectionModel>
#import <qstring.h>
#import <QPixmap>
#import <QtMacExtras/qmacfunctions.h>

28
// LRC
29 30 31 32 33 34
#import <globalinstances.h>

#import "views/IconButton.h"
#import "views/IMTableCellView.h"
#import "views/NSColor+RingTheme.h"
#import "QNSTreeController.h"
35
#import "INDSequentialTextSelectionManager.h"
36
#import "delegates/ImageManipulationDelegate.h"
37 38 39
#import "PhoneDirectoryModel.h"
#import "account.h"
#import "AvailableAccountModel.h"
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
40
#import "MessagesVC.h"
41
#import "utils.h"
42
#import "RingWindowController.h"
43 44 45

#import <QuartzCore/QuartzCore.h>

46
@interface ConversationVC () {
47 48 49 50 51 52

    __unsafe_unretained IBOutlet NSTextField* messageField;
    NSMutableString* textSelection;

    __unsafe_unretained IBOutlet NSView* sendPanel;
    __unsafe_unretained IBOutlet NSTextField* conversationTitle;
53
    __unsafe_unretained IBOutlet NSTextField *conversationID;
54
    __unsafe_unretained IBOutlet IconButton* sendButton;
55
    __unsafe_unretained IBOutlet IconButton *sendFileButton;
56 57
    __unsafe_unretained IBOutlet NSLayoutConstraint* sentContactRequestWidth;
    __unsafe_unretained IBOutlet NSButton* sentContactRequestButton;
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
58
    IBOutlet MessagesVC* messagesViewVC;
59

60
    IBOutlet NSLayoutConstraint *titleCenteredConstraint;
61
    IBOutlet NSLayoutConstraint* titleTopConstraint;
62 63 64 65 66

    std::string convUid_;
    const lrc::api::conversation::Info* cachedConv_;
    lrc::api::ConversationModel* convModel_;

67 68
    RingWindowController* delegate;

69
    // All those connections are needed to invalidate cached conversation as pointer
70
    // may not be referencing the same conversation anymore
71 72
    QMetaObject::Connection modelSortedConnection_, filterChangedConnection_, newConversationConnection_, conversationRemovedConnection_;

73 74
}

75

76 77 78 79
@end

@implementation ConversationVC

80 81 82 83 84 85 86 87 88
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil delegate:(RingWindowController*) mainWindow
{
    if (self = [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
    {
        delegate = mainWindow;
    }
    return self;
}

89 90 91 92 93 94 95 96 97 98
-(const lrc::api::conversation::Info*) getCurrentConversation
{
    if (convModel_ == nil || convUid_.empty())
        return nil;

    if (cachedConv_ != nil)
        return cachedConv_;

    auto& convQueue = convModel_->allFilteredConversations();

99
    auto it = getConversationFromUid(convUid_, *convModel_);
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

    if (it != convQueue.end())
        cachedConv_ = &(*it);

    return cachedConv_;
}

-(void) setConversationUid:(const std::string)convUid model:(lrc::api::ConversationModel *)model {
    if (convUid_ == convUid && convModel_ == model)
        return;

    cachedConv_ = nil;
    convUid_ = convUid;
    convModel_ = model;

    [messagesViewVC setConversationUid:convUid_ model:convModel_];

    if (convUid_.empty() || convModel_ == nil)
        return;

    // Signals tracking changes in conversation list, we need them as cached conversation can be invalid
    // after a reordering.
122 123 124 125 126
    QObject::disconnect(modelSortedConnection_);
    QObject::disconnect(filterChangedConnection_);
    QObject::disconnect(newConversationConnection_);
    QObject::disconnect(conversationRemovedConnection_);
    modelSortedConnection_ = QObject::connect(convModel_, &lrc::api::ConversationModel::modelSorted,
127 128 129
                                          [self](){
                                              cachedConv_ = nil;
                                          });
130
    filterChangedConnection_ = QObject::connect(convModel_, &lrc::api::ConversationModel::filterChanged,
131 132 133
                                            [self](){
                                                cachedConv_ = nil;
                                            });
134 135 136 137 138 139 140 141
    filterChangedConnection_ = QObject::connect(convModel_, &lrc::api::ConversationModel::newConversation,
                                                [self](){
                                                    cachedConv_ = nil;
                                                });
    filterChangedConnection_ = QObject::connect(convModel_, &lrc::api::ConversationModel::conversationRemoved,
                                                [self](){
                                                    cachedConv_ = nil;
                                                });
142 143 144 145 146 147 148 149

    auto* conv = [self getCurrentConversation];

    if (conv == nil)
        return;

    // Setup UI elements according to new conversation
    NSString* bestName = bestNameForConversation(*conv, *convModel_);
150
    NSString* bestId = bestIDForConversation(*conv, *convModel_);
151
    [conversationTitle setStringValue: bestName];
152
    [conversationID setStringValue: bestId];
153
    [sendFileButton setEnabled:(convModel_->owner.contactModel->getContact(conv->participants[0]).profileInfo.type != lrc::api::profile::Type::SIP)];
154

155
    BOOL hideBestId = [bestNameForConversation(*conv, *convModel_) isEqualTo:bestIDForConversation(*conv, *convModel_)];
156

157 158 159
    [conversationID setHidden:hideBestId];
    [titleCenteredConstraint setActive:hideBestId];
    [titleTopConstraint setActive:!hideBestId];
160 161
}

162 163
- (void)loadView {
    [super loadView];
164 165 166 167 168 169
    // Do view setup here.
    [self.view setWantsLayer:YES];
    [self.view setLayer:[CALayer layer]];
    [self.view.layer setBackgroundColor:[NSColor ringGreyHighlight].CGColor];
    [self.view.layer setCornerRadius:5.0f];

170
    [messageField setFocusRingType:NSFocusRingTypeNone];
171 172
}

173 174 175 176 177 178 179 180 181 182
-(Account* ) chosenAccount
{
    QModelIndex index = AvailableAccountModel::instance().selectionModel()->currentIndex();
    if(!index.isValid()) {
        return nullptr;
    }
    Account* account = index.data(static_cast<int>(Account::Role::Object)).value<Account*>();
    return account;
}

183 184 185 186 187 188 189 190 191 192 193 194
- (void) initFrame
{
    [self.view setFrame:self.view.superview.bounds];
    [self.view setHidden:YES];
    self.view.layer.position = self.view.frame.origin;
}

- (IBAction)sendMessage:(id)sender
{
    /* make sure there is text to send */
    NSString* text = self.message;
    if (text && text.length > 0) {
Anthony Léonard's avatar
Anthony Léonard committed
195 196
        auto* conv = [self getCurrentConversation];
        bool isPending = convModel_->owner.contactModel->getContact(conv->participants[0]).profileInfo.type == lrc::api::profile::Type::PENDING;
Anthony Léonard's avatar
Anthony Léonard committed
197
        convModel_->sendMessage(convUid_, std::string([text UTF8String]));
198
        self.message = @"";
Anthony Léonard's avatar
Anthony Léonard committed
199 200
        if (isPending)
            [delegate currentConversationTrusted];
201
        [messagesViewVC newMessageSent];
202
    }
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
}

- (IBAction)sendFile:(id)sender
{
    NSOpenPanel* filePicker = [NSOpenPanel openPanel];
    [filePicker setCanChooseFiles:YES];
    [filePicker setCanChooseDirectories:NO];
    [filePicker setAllowsMultipleSelection:NO];

    if ([filePicker runModal] == NSFileHandlingPanelOKButton) {
        if ([[filePicker URLs] count] == 1) {
            NSURL* url = [[filePicker URLs] objectAtIndex:0];
            const char* fullPath = [url fileSystemRepresentation];
            NSString* fileName = [url lastPathComponent];
            if (convModel_) {
218 219 220
                auto* conv = [self getCurrentConversation];
                bool isPending = convModel_->owner.contactModel->getContact(conv->participants[0]).profileInfo.type == lrc::api::profile::Type::PENDING;

221
                convModel_->sendFile(convUid_, std::string(fullPath), std::string([fileName UTF8String]));
222 223 224

                if (isPending)
                    [delegate currentConversationTrusted];
225 226 227
            }
        }
    }
228 229 230 231
}

- (IBAction)placeCall:(id)sender
{
232 233
    auto* conv = [self getCurrentConversation];
    convModel_->placeCall(conv->uid);
234 235
}

236
- (IBAction)backPressed:(id)sender {
237
    [delegate rightPanelClosed];
238
    [self hideWithAnimation:false];
239 240
}

241 242
# pragma mark private IN/OUT animations

243
-(void) showWithAnimation:(BOOL)animate
244
{
245 246 247 248 249
    if (!animate) {
        [self.view setHidden:NO];
        return;
    }

250 251 252 253 254 255 256 257 258 259 260 261 262 263
    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];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    [self.view.layer addAnimation:animation forKey:animation.keyPath];

    [CATransaction commit];
}

264
-(void) hideWithAnimation:(BOOL)animate
265 266 267 268 269
{
    if(self.view.frame.origin.x < 0) {
        return;
    }

270 271 272 273 274
    if (!animate) {
        [self.view setHidden:YES];
        return;
    }

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    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];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];

    [CATransaction setCompletionBlock:^{
        [self.view setHidden:YES];
    }];
    [self.view.layer addAnimation:animation forKey:animation.keyPath];

    [self.view.layer setPosition:frame.origin];
    [CATransaction commit];
}

#pragma mark - NSTextFieldDelegate

- (BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor doCommandBySelector:(SEL)commandSelector
{
    if (commandSelector == @selector(insertNewline:) && self.message.length > 0) {
        [self sendMessage:nil];
        return YES;
    }
    return NO;
}


@end