chat: add conversation screen

- ability to chat off call
- system notification on incoming msg
- notification in smartlist

Tuleap: #202
Change-Id: Ide10f80f677f23022ad4296a82ae122e69a892cc
diff --git a/src/AppDelegate.mm b/src/AppDelegate.mm
index 96f5294..77d58e5 100644
--- a/src/AppDelegate.mm
+++ b/src/AppDelegate.mm
@@ -22,6 +22,8 @@
 #import <qapplication.h>
 #import <accountmodel.h>
 #import <protocolmodel.h>
+#import <media/recordingmodel.h>
+#import <media/textrecording.h>
 #import <QItemSelectionModel>
 #import <account.h>
 
@@ -79,13 +81,42 @@
                              [self showIncomingNotification:call];
                          }
                      });
+
+
+
+    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];
+
+                         NSString* localizedTitle = NSLocalizedString(([NSString stringWithFormat:@"Message from %@",
+                                                                        qIdx.data((int)Media::TextRecording::Role::AuthorDisplayname).toString().toNSString()]),
+                                                                      @"Text message notification title");
+
+                         [notification setTitle:localizedTitle];
+                         [notification setSoundName:NSUserNotificationDefaultSoundName];
+                         [notification setSubtitle:qIdx.data().toString().toNSString()];
+
+                         [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
+                     });
 }
 
 - (void) showIncomingNotification:(Call*) call{
     NSUserNotification *notification = [[NSUserNotification alloc] init];
-    notification.title = @"Incoming call", call->peerName();
-    //notification.informativeText = @"A notification";
-    notification.soundName = NSUserNotificationDefaultSoundName;
+    NSString* localizedTitle = NSLocalizedString(([NSString stringWithFormat:@"Incoming call from %@",
+                                                   call->peerName().toNSString()]),
+                                                 @"Call notification title");
+    [notification setTitle:localizedTitle];
+    [notification setSoundName:NSUserNotificationDefaultSoundName];
 
     [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
 }
@@ -99,7 +130,6 @@
 
 - (void) showWizard
 {
-    NSLog(@"Showing wizard");
     if(self.wizard == nil) {
         self.wizard = [[RingWizardWC alloc] initWithWindowNibName:@"RingWizard"];
     }
diff --git a/src/ConversationVC.h b/src/ConversationVC.h
new file mode 100644
index 0000000..9cecc25
--- /dev/null
+++ b/src/ConversationVC.h
@@ -0,0 +1,35 @@
+/*
+ *  Copyright (C) 2016 Savoir-faire Linux Inc.
+ *  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 <Cocoa/Cocoa.h>
+
+@interface ConversationVC : NSViewController
+
+-(void) initFrame;
+-(void) animateIn;
+-(IBAction) animateOut:(id)sender;
+
+/**
+ * Message contained in messageField TextField.
+ * This is a KVO method to bind the text with the send Button
+ * if message.length is > 0, button is enabled, otherwise disabled
+ */
+@property (retain) NSString* message;
+
+@end
diff --git a/src/ConversationVC.mm b/src/ConversationVC.mm
new file mode 100644
index 0000000..142da89
--- /dev/null
+++ b/src/ConversationVC.mm
@@ -0,0 +1,361 @@
+/*
+ *  Copyright (C) 2016 Savoir-faire Linux Inc.
+ *  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 "ConversationVC.h"
+
+#import <QItemSelectionModel>
+#import <qstring.h>
+#import <QPixmap>
+#import <QtMacExtras/qmacfunctions.h>
+
+#import <media/media.h>
+#import <recentmodel.h>
+#import <person.h>
+#import <contactmethod.h>
+#import <media/text.h>
+#import <media/textrecording.h>
+#import <callmodel.h>
+#import <globalinstances.h>
+
+#import "views/IconButton.h"
+#import "views/IMTableCellView.h"
+#import "views/NSColor+RingTheme.h"
+#import "QNSTreeController.h"
+#import "delegates/ImageManipulationDelegate.h"
+
+#import <QuartzCore/QuartzCore.h>
+
+@interface ConversationVC () <NSOutlineViewDelegate> {
+
+    __unsafe_unretained IBOutlet IconButton* backButton;
+    __unsafe_unretained IBOutlet NSTextField* messageField;
+    QVector<ContactMethod*> contactMethods;
+    NSMutableString* textSelection;
+
+    QNSTreeController* treeController;
+
+    __unsafe_unretained IBOutlet NSView* sendPanel;
+    __unsafe_unretained IBOutlet NSTextField* conversationTitle;
+    __unsafe_unretained IBOutlet NSTextField* emptyConversationPlaceHolder;
+    __unsafe_unretained IBOutlet IconButton* sendButton;
+    __unsafe_unretained IBOutlet NSOutlineView* conversationView;
+    __unsafe_unretained IBOutlet NSPopUpButton* contactMethodsPopupButton;
+}
+
+@end
+
+@implementation ConversationVC
+
+- (void)viewDidLoad {
+    [super viewDidLoad];
+    // 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];
+
+    [sendPanel setWantsLayer:YES];
+    [sendPanel setLayer:[CALayer layer]];
+
+    [self setupChat];
+
+}
+
+- (void) initFrame
+{
+    [self.view setFrame:self.view.superview.bounds];
+    [self.view setHidden:YES];
+    self.view.layer.position = self.view.frame.origin;
+}
+
+- (void) setupChat
+{
+    QObject::connect(RecentModel::instance().selectionModel(),
+                     &QItemSelectionModel::currentChanged,
+                     [=](const QModelIndex &current, const QModelIndex &previous) {
+
+                         contactMethods = RecentModel::instance().getContactMethods(current);
+                         if (contactMethods.isEmpty()) {
+                             return ;
+                         }
+
+                         [contactMethodsPopupButton removeAllItems];
+                         for (auto cm : contactMethods) {
+                             [contactMethodsPopupButton addItemWithTitle:cm->uri().toNSString()];
+                         }
+
+                         [contactMethodsPopupButton setEnabled:(contactMethods.length() > 1)];
+
+                         [emptyConversationPlaceHolder setHidden:NO];
+                         // Select first cm
+                         [contactMethodsPopupButton selectItemAtIndex:0];
+                         [self itemChanged:contactMethodsPopupButton];
+
+                         NSString* localizedTitle = current.data((int)Ring::Role::Name).toString().toNSString();
+                        [conversationTitle setStringValue:localizedTitle];
+
+                     });
+}
+
+- (IBAction)sendMessage:(id)sender
+{
+    /* make sure there is text to send */
+    NSString* text = self.message;
+    if (text && text.length > 0) {
+        QMap<QString, QString> messages;
+        messages["text/plain"] = QString::fromNSString(text);
+        contactMethods.at([contactMethodsPopupButton indexOfSelectedItem])->sendOfflineTextMessage(messages);
+        self.message = @"";
+    }
+}
+
+- (IBAction)placeCall:(id)sender
+{
+    if(auto cm = contactMethods.at([contactMethodsPopupButton indexOfSelectedItem])) {
+        auto c = CallModel::instance().dialingCall();
+        c->setPeerContactMethod(cm);
+        c << Call::Action::ACCEPT;
+        CallModel::instance().selectCall(c);
+    }
+}
+
+# pragma mark 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];
+    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
+    [self.view.layer addAnimation:animation forKey:animation.keyPath];
+
+    [CATransaction commit];
+}
+
+-(IBAction) animateOut:(id)sender
+{
+    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];
+    [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 - NSOutlineViewDelegate methods
+
+- (BOOL)outlineView:(NSOutlineView *)outlineView shouldSelectItem:(id)item;
+{
+    return YES;
+}
+
+- (BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item
+{
+    return YES;
+}
+
+- (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item
+{
+    QModelIndex qIdx = [treeController toQIdx:((NSTreeNode*)item)];
+    auto dir = qvariant_cast<Media::Media::Direction>(qIdx.data((int)Media::TextRecording::Role::Direction));
+    IMTableCellView* result;
+
+    if (dir == Media::Media::Direction::IN) {
+        result = [outlineView makeViewWithIdentifier:@"LeftMessageView" owner:self];
+    } else {
+        result = [outlineView makeViewWithIdentifier:@"RightMessageView" owner:self];
+    }
+
+    [result setup];
+
+    NSMutableAttributedString* msgAttString =
+    [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n",qIdx.data((int)Qt::DisplayRole).toString().toNSString()]
+                                           attributes:[self messageAttributesFor:qIdx]];
+
+    NSAttributedString* timestampAttrString =
+    [[NSAttributedString alloc] initWithString:qIdx.data((int)Media::TextRecording::Role::FormattedDate).toString().toNSString()
+                                    attributes:[self timestampAttributesFor:qIdx]];
+
+
+    CGFloat finalWidth = MAX(msgAttString.size.width, timestampAttrString.size.width);
+    finalWidth = MIN(finalWidth + 30, result.frame.size.width - result.photoView.frame.size.width - 30);
+
+    [msgAttString appendAttributedString:timestampAttrString];
+    [[result.msgView textStorage] appendAttributedString:msgAttString];
+    [result.msgView checkTextInDocument:nil];
+    [result.msgView setWantsLayer:YES];
+    result.msgView.layer.cornerRadius = 5.0f;
+
+    [result updateWidthConstraint:finalWidth];
+
+    Person* p = qvariant_cast<Person*>(qIdx.data((int)Person::Role::Object));
+    QVariant photo = GlobalInstances::pixmapManipulator().contactPhoto(p, QSize(50,50));
+    [result.photoView setImage:QtMac::toNSImage(qvariant_cast<QPixmap>(photo))];
+
+    return result;
+}
+
+- (void)outlineView:(NSOutlineView *)outlineView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
+{
+    if (auto txtRecording = contactMethods.at([contactMethodsPopupButton indexOfSelectedItem])->textRecording()) {
+        [emptyConversationPlaceHolder setHidden:txtRecording->instantMessagingModel()->rowCount() > 0];
+        txtRecording->setAllRead();
+    }
+}
+
+- (CGFloat)outlineView:(NSOutlineView *)outlineView heightOfRowByItem:(id)item
+{
+    QModelIndex qIdx = [treeController toQIdx:((NSTreeNode*)item)];
+
+    double someWidth = outlineView.frame.size.width;
+
+    NSMutableAttributedString* msgAttString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n",qIdx.data((int)Qt::DisplayRole).toString().toNSString()]
+                                                                                     attributes:[self messageAttributesFor:qIdx]];
+    NSAttributedString *timestampAttrString = [[NSAttributedString alloc] initWithString:
+                                               qIdx.data((int)Media::TextRecording::Role::FormattedDate).toString().toNSString()
+                                                                              attributes:[self timestampAttributesFor:qIdx]];
+
+    [msgAttString appendAttributedString:timestampAttrString];
+
+    NSRect frame = NSMakeRect(0, 0, someWidth, MAXFLOAT);
+    NSTextView *tv = [[NSTextView alloc] initWithFrame:frame];
+    [tv setEnabledTextCheckingTypes:NSTextCheckingTypeLink];
+    [tv setAutomaticLinkDetectionEnabled:YES];
+    [[tv textStorage] setAttributedString:msgAttString];
+    [tv sizeToFit];
+
+    double height = tv.frame.size.height + 20;
+
+    return MAX(height, 60.0f);
+}
+
+#pragma mark - Text formatting
+
+- (NSMutableDictionary*) timestampAttributesFor:(QModelIndex) qIdx
+{
+    auto dir = qvariant_cast<Media::Media::Direction>(qIdx.data((int)Media::TextRecording::Role::Direction));
+    NSMutableDictionary* attrs = [NSMutableDictionary dictionary];
+
+    if (dir == Media::Media::Direction::IN) {
+        attrs[NSForegroundColorAttributeName] = [NSColor grayColor];
+    } else {
+        attrs[NSForegroundColorAttributeName] = [NSColor whiteColor];
+    }
+
+    NSFont* systemFont = [NSFont systemFontOfSize:12.0f];
+    attrs[NSFontAttributeName] = systemFont;
+    attrs[NSParagraphStyleAttributeName] = [self paragraphStyle];
+
+    return attrs;
+}
+
+- (NSMutableDictionary*) messageAttributesFor:(QModelIndex) qIdx
+{
+    auto dir = qvariant_cast<Media::Media::Direction>(qIdx.data((int)Media::TextRecording::Role::Direction));
+    NSMutableDictionary* attrs = [NSMutableDictionary dictionary];
+
+    if (dir == Media::Media::Direction::IN) {
+        attrs[NSForegroundColorAttributeName] = [NSColor blackColor];
+    } else {
+        attrs[NSForegroundColorAttributeName] = [NSColor whiteColor];
+    }
+
+    NSFont* systemFont = [NSFont systemFontOfSize:14.0f];
+    attrs[NSFontAttributeName] = systemFont;
+    attrs[NSParagraphStyleAttributeName] = [self paragraphStyle];
+
+    return attrs;
+}
+
+- (NSParagraphStyle*) paragraphStyle
+{
+    /*
+     The only way to instantiate an NSMutableParagraphStyle is to mutably copy an
+     NSParagraphStyle. And since we don't have an existing NSParagraphStyle available
+     to copy, we use the default one.
+
+     The default values supplied by the default NSParagraphStyle are:
+     Alignment   NSNaturalTextAlignment
+     Tab stops   12 left-aligned tabs, spaced by 28.0 points
+     Line break mode   NSLineBreakByWordWrapping
+     All others   0.0
+     */
+    NSMutableParagraphStyle* aMutableParagraphStyle =
+    [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
+
+    // Now adjust our NSMutableParagraphStyle formatting to be whatever we want.
+    // The numeric values below are in points (72 points per inch)
+    [aMutableParagraphStyle setAlignment:NSLeftTextAlignment];
+    [aMutableParagraphStyle setLineSpacing:1.5];
+    [aMutableParagraphStyle setParagraphSpacing:5.0];
+    [aMutableParagraphStyle setHeadIndent:5.0];
+    [aMutableParagraphStyle setTailIndent:-5.0];
+    [aMutableParagraphStyle setFirstLineHeadIndent:5.0];
+    [aMutableParagraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
+    return aMutableParagraphStyle;
+}
+
+#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;
+}
+
+#pragma mark - NSPopUpButton item selection
+
+- (IBAction)itemChanged:(id)sender {
+    NSInteger index = [(NSPopUpButton *)sender indexOfSelectedItem];
+
+    if (auto txtRecording = contactMethods.at(index)->textRecording()) {
+        treeController = [[QNSTreeController alloc] initWithQModel:txtRecording->instantMessagingModel()];
+        [treeController setAvoidsEmptySelection:NO];
+        [treeController setChildrenKeyPath:@"children"];
+        [conversationView bind:@"content" toObject:treeController withKeyPath:@"arrangedObjects" options:nil];
+        [conversationView bind:@"sortDescriptors" toObject:treeController withKeyPath:@"sortDescriptors" options:nil];
+        [conversationView bind:@"selectionIndexPaths" toObject:treeController withKeyPath:@"selectionIndexPaths" options:nil];
+    }
+
+    [conversationView scrollToEndOfDocument:nil];
+}
+
+
+@end
diff --git a/src/CurrentCallVC.h b/src/CurrentCallVC.h
index 5a3dc3d..58105bb 100644
--- a/src/CurrentCallVC.h
+++ b/src/CurrentCallVC.h
@@ -28,6 +28,8 @@
 
 }
 
-- (void) initFrame;
+-(void) initFrame;
+-(void) animateIn;
+-(void) animateOut;
 
 @end
diff --git a/src/CurrentCallVC.mm b/src/CurrentCallVC.mm
index e234abe..1c3efdd 100644
--- a/src/CurrentCallVC.mm
+++ b/src/CurrentCallVC.mm
@@ -124,7 +124,7 @@
     NSButton* a = actionHash[(int) action];
     if (a) {
         [a setHidden:!(idx.flags() & Qt::ItemIsEnabled)];
-        [a setState:(idx.data(Qt::CheckStateRole) == Qt::Checked) ? NSOnState : NSOffState];
+        [a setHighlighted:(idx.data(Qt::CheckStateRole) == Qt::Checked) ? YES : NO];
     }
 }
 
@@ -245,7 +245,6 @@
                      [=](const QModelIndex &current, const QModelIndex &previous) {
                          auto call = RecentModel::instance().getActiveCall(current);
                          if(!current.isValid() || !call) {
-                             [self animateOut];
                              return;
                          }
 
@@ -258,7 +257,6 @@
                          [self collapseRightView];
                          [self updateCall];
                          [self updateAllActions];
-                         [self animateOut];
                      });
 
     QObject::connect(CallModel::instance().userActionModel(),
diff --git a/src/RingWindowController.mm b/src/RingWindowController.mm
index 8addce9..c589d57 100644
--- a/src/RingWindowController.mm
+++ b/src/RingWindowController.mm
@@ -17,16 +17,24 @@
  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
  */
 #import "RingWindowController.h"
+#import <QuartzCore/QuartzCore.h>
+
+
+//Qt
+#import <QItemSelectionModel>
+#import <QItemSelection>
 
 //LRC
 #import <accountmodel.h>
 #import <callmodel.h>
 #import <account.h>
 #import <call.h>
+#import <recentmodel.h>
 
 #import "AppDelegate.h"
 #import "Constants.h"
 #import "CurrentCallVC.h"
+#import "ConversationVC.h"
 
 #import "PreferencesWC.h"
 #import "views/NSColor+RingTheme.h"
@@ -37,7 +45,8 @@
     __unsafe_unretained IBOutlet NSTextField *ringIDLabel;
 
     PreferencesWC *preferencesWC;
-    CurrentCallVC* currentVC;
+    CurrentCallVC* currentCallVC;
+    ConversationVC* offlineVC;
 }
 
 static NSString* const kPreferencesIdentifier = @"PreferencesIdentifier";
@@ -46,23 +55,52 @@
     [super windowDidLoad];
     [self.window setMovableByWindowBackground:YES];
 
-    currentVC = [[CurrentCallVC alloc] initWithNibName:@"CurrentCall" bundle:nil];
+    currentCallVC = [[CurrentCallVC alloc] initWithNibName:@"CurrentCall" bundle:nil];
+    offlineVC = [[ConversationVC alloc] initWithNibName:@"Conversation" bundle:nil];
+
     [callView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
-    [[currentVC view] setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
+    [[currentCallVC view] setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
+    [[offlineVC view] setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
 
-    [callView addSubview:[currentVC view] positioned:NSWindowAbove relativeTo:nil];
+    [callView addSubview:[currentCallVC view] positioned:NSWindowAbove relativeTo:nil];
+    [callView addSubview:[offlineVC view] positioned:NSWindowAbove relativeTo:nil];
 
-    [currentVC initFrame];
+    [currentCallVC initFrame];
+    [offlineVC initFrame];
 
     // Fresh run, we need to make sure RingID appears
     [self updateRingID];
 
+    [self connect];
+}
+
+- (void) connect
+{
     // Update Ring ID label based on account model changes
     QObject::connect(&AccountModel::instance(),
                      &AccountModel::dataChanged,
                      [=] {
                          [self updateRingID];
                      });
+
+    QObject::connect(RecentModel::instance().selectionModel(),
+                     &QItemSelectionModel::currentChanged,
+                     [=](const QModelIndex &current, const QModelIndex &previous) {
+                         auto call = RecentModel::instance().getActiveCall(current);
+                         if(!current.isValid()) {
+                             [offlineVC animateOut:self];
+                             [currentCallVC animateOut];
+                             return;
+                         }
+
+                         if (!call) {
+                             [currentCallVC animateOut];
+                             [offlineVC animateIn];
+                         } else {
+                             [currentCallVC animateIn];
+                             [offlineVC animateOut:self];
+                         }
+                     });
 }
 
 /**
diff --git a/src/SmartViewVC.mm b/src/SmartViewVC.mm
index b2be8bb..d026458 100644
--- a/src/SmartViewVC.mm
+++ b/src/SmartViewVC.mm
@@ -33,6 +33,7 @@
 #import <person.h>
 #import <contactmethod.h>
 #import <globalinstances.h>
+#import <phonedirectorymodel.h>
 
 #import "QNSTreeController.h"
 #import "delegates/ImageManipulationDelegate.h"
@@ -42,7 +43,7 @@
 #import "views/ContextualTableCellView.h"
 
 @interface SmartViewVC () <NSOutlineViewDelegate, NSPopoverDelegate, ContextMenuDelegate, ContactLinkedDelegate, KeyboardShortcutDelegate> {
-    BOOL isShowingContacts;
+
     QNSTreeController *treeController;
     NSPopover* addToContactPopover;
 
@@ -69,9 +70,8 @@
 {
     NSLog(@"INIT SmartView VC");
 
-    isShowingContacts = false;
+    RecentModel::instance().peopleProxy()->setFilterRole((int)Ring::Role::Name);
     treeController = [[QNSTreeController alloc] initWithQModel:RecentModel::instance().peopleProxy()];
-
     [treeController setAvoidsEmptySelection:NO];
     [treeController setChildrenKeyPath:@"children"];
 
@@ -105,9 +105,8 @@
                          if (proxyIdx.isValid()) {
                              [treeController setSelectionQModelIndex:proxyIdx];
 
-                             [showContactsButton setState:NO];
-                             isShowingContacts = NO;
-                             [showHistoryButton setState:NO];
+                             [showContactsButton setHighlighted:NO];
+                             [showHistoryButton setHighlighted:NO];
                              [tabbar selectTabViewItemAtIndex:0];
                              [smartView scrollRowToVisible:proxyIdx.row()];
                          }
@@ -124,6 +123,10 @@
 
 -(void) selectRow:(id)sender
 {
+    if ([treeController selectedNodes].count == 0) {
+        RecentModel::instance().selectionModel()->clearCurrentIndex();
+        return;
+    }
     auto qIdx = [treeController toQIdx:[treeController selectedNodes][0]];
     auto proxyIdx = RecentModel::instance().peopleProxy()->mapToSource(qIdx);
     RecentModel::instance().selectionModel()->setCurrentIndex(proxyIdx, QItemSelectionModel::ClearAndSelect);
@@ -164,53 +167,42 @@
     }
 }
 
-- (IBAction)showHistory:(NSButton*)sender {
-    if (isShowingContacts) {
-        [showContactsButton setState:NO];
-        isShowingContacts = NO;
-        [tabbar selectTabViewItemAtIndex:1];
-    } else if ([sender state] == NSOffState) {
+- (IBAction)showHistory:(NSButton*)sender
+{
+    [showContactsButton setHighlighted:NO];
+    [showHistoryButton setHighlighted:![sender isHighlighted]];
+
+    if (![sender isHighlighted]) {
         [tabbar selectTabViewItemAtIndex:0];
     } else {
         [tabbar selectTabViewItemAtIndex:1];
     }
 }
 
-- (IBAction)showContacts:(NSButton*)sender {
-    if (isShowingContacts) {
-        [showContactsButton setState:NO];
+- (IBAction)showContacts:(NSButton*)sender
+{
+    [showContactsButton setHighlighted:![sender isHighlighted]];
+    [showHistoryButton setHighlighted:NO];
+
+    if (![sender isHighlighted]) {
         [tabbar selectTabViewItemAtIndex:0];
     } else {
-        [showHistoryButton setState:![sender state]];
         [tabbar selectTabViewItemAtIndex:2];
     }
-
-    isShowingContacts = [sender state];
 }
 
 #pragma mark - NSOutlineViewDelegate methods
 
-// -------------------------------------------------------------------------------
-//	shouldSelectItem:item
-// -------------------------------------------------------------------------------
 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldSelectItem:(id)item;
 {
     return YES;
 }
 
-// -------------------------------------------------------------------------------
-//	shouldEditTableColumn:tableColumn:item
-//
-//	Decide to allow the edit of the given outline view "item".
-// -------------------------------------------------------------------------------
 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item
 {
     return NO;
 }
 
-// -------------------------------------------------------------------------------
-//	outlineViewSelectionDidChange:notification
-// -------------------------------------------------------------------------------
 - (void)outlineViewSelectionDidChange:(NSNotification *)notification
 {
     if ([treeController selectedNodes].count <= 0) {
@@ -219,8 +211,6 @@
     }
 }
 
-/* View Based OutlineView: See the delegate method -tableView:viewForTableColumn:row: in NSTableView.
- */
 - (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item
 {
     QModelIndex qIdx = [treeController toQIdx:((NSTreeNode*)item)];
@@ -229,7 +219,8 @@
         result = [outlineView makeViewWithIdentifier:@"MainCell" owner:outlineView];
         NSTextField* details = [result viewWithTag:DETAILS_TAG];
 
-        [((ContextualTableCellView*) result) setContextualsControls:[NSMutableArray arrayWithObject:[result viewWithTag:CALL_BUTTON_TAG]]];
+        NSMutableArray* controls = [NSMutableArray arrayWithObject:[result viewWithTag:CALL_BUTTON_TAG]];
+        [((ContextualTableCellView*) result) setContextualsControls:controls];
 
         if (auto call = RecentModel::instance().getActiveCall(RecentModel::instance().peopleProxy()->mapToSource(qIdx))) {
             [details setStringValue:call->roleData((int)Ring::Role::FormattedState).toString().toNSString()];
@@ -239,6 +230,12 @@
             [((ContextualTableCellView*) result) setActiveState:NO];
         }
 
+        NSTextField* unreadCount = [result viewWithTag:TXT_BUTTON_TAG];
+        int unread = qIdx.data((int)Ring::Role::UnreadTextMessageCount).toInt();
+        [unreadCount setHidden:(unread == 0)];
+        [unreadCount.layer setCornerRadius:5.0f];
+        [unreadCount setStringValue:qIdx.data((int)Ring::Role::UnreadTextMessageCount).toString().toNSString()];
+
     } else {
         result = [outlineView makeViewWithIdentifier:@"CallCell" owner:outlineView];
         NSTextField* details = [result viewWithTag:DETAILS_TAG];
@@ -247,7 +244,7 @@
     }
 
     NSTextField* displayName = [result viewWithTag:DISPLAYNAME_TAG];
-    [displayName setStringValue:qIdx.data(Qt::DisplayRole).toString().toNSString()];
+    [displayName setStringValue:qIdx.data((int)Ring::Role::Name).toString().toNSString()];
     NSImageView* photoView = [result viewWithTag:IMAGE_TAG];
     Person* p = qvariant_cast<Person*>(qIdx.data((int)Person::Role::Object));
     QVariant photo = GlobalInstances::pixmapManipulator().contactPhoto(p, QSize(50,50));
@@ -255,6 +252,16 @@
     return result;
 }
 
+- (void)outlineView:(NSOutlineView *)outlineView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
+{
+    [outlineView scrollRowToVisible:0];
+}
+
+- (NSTableRowView *)outlineView:(NSOutlineView *)outlineView rowViewForItem:(id)item
+{
+    return [outlineView makeViewWithIdentifier:@"HoverRowView" owner:nil];
+}
+
 - (IBAction)callClickedAtRow:(id)sender {
     NSInteger row = [smartView rowForView:sender];
     [smartView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
@@ -267,52 +274,18 @@
     CallModel::instance().getCall(CallModel::instance().selectionModel()->currentIndex()) << Call::Action::REFUSE;
 }
 
-/* View Based OutlineView: See the delegate method -tableView:rowViewForRow: in NSTableView.
-*/
-- (NSTableRowView *)outlineView:(NSOutlineView *)outlineView rowViewForItem:(id)item
-{
-    return [outlineView makeViewWithIdentifier:@"HoverRowView" owner:nil];
-}
-
-
-/* View Based OutlineView: This delegate method can be used to know when a new 'rowView' has been added to the table. At this point, you can choose to add in extra views, or modify any properties on 'rowView'.
- */
-- (void)outlineView:(NSOutlineView *)outlineView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
-{
-
-}
-
-/* View Based OutlineView: This delegate method can be used to know when 'rowView' has been removed from the table. The removed 'rowView' may be reused by the table so any additionally inserted views should be removed at this point. A 'row' parameter is included. 'row' will be '-1' for rows that are being deleted from the table and no longer have a valid row, otherwise it will be the valid row that is being removed due to it being moved off screen.
- */
-- (void)outlineView:(NSOutlineView *)outlineView didRemoveRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
-{
-
-}
-
 - (CGFloat)outlineView:(NSOutlineView *)outlineView heightOfRowByItem:(id)item
 {
     QModelIndex qIdx = [treeController toQIdx:((NSTreeNode*)item)];
     return (((NSTreeNode*)item).indexPath.length == 1) ? 60.0 : 45.0;
 }
 
-- (void) placeCallFromSearchField
+- (void) startConversationFromSearchField
 {
-    Call* c = CallModel::instance().dialingCall();
-    // check for a valid ring hash
-    NSCharacterSet *hexSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefABCDEF"];
-    BOOL valid = [[[searchField stringValue] stringByTrimmingCharactersInSet:hexSet] isEqualToString:@""];
-
-    if(valid && searchField.stringValue.length == 40) {
-        c->setDialNumber(QString::fromNSString([NSString stringWithFormat:@"ring:%@",[searchField stringValue]]));
-    } else {
-        c->setDialNumber(QString::fromNSString([searchField stringValue]));
-    }
-
-    c << Call::Action::ACCEPT;
-
-    [searchField setStringValue:@""];
-    RecentModel::instance().peopleProxy()->
-    setFilterRegExp(QRegExp(QString::fromNSString([searchField stringValue]), Qt::CaseInsensitive, QRegExp::FixedString));
+    auto cm = PhoneDirectoryModel::instance().getNumber(QString::fromNSString([searchField stringValue]));
+    time_t currentTime;
+    ::time(&currentTime);
+    cm->setLastUsed(currentTime);
 }
 
 - (void) addToContact
@@ -365,7 +338,7 @@
 {
     if (commandSelector == @selector(insertNewline:)) {
         if([[searchField stringValue] isNotEqualTo:@""]) {
-            [self placeCallFromSearchField];
+            [self startConversationFromSearchField];
             return YES;
         }
     }
@@ -385,8 +358,7 @@
 
 - (void)controlTextDidChange:(NSNotification *) notification
 {
-    RecentModel::instance().peopleProxy()->
-    setFilterRegExp(QRegExp(QString::fromNSString([searchField stringValue]), Qt::CaseInsensitive, QRegExp::FixedString));
+    RecentModel::instance().peopleProxy()->setFilterWildcard(QString::fromNSString([searchField stringValue]));
 }
 
 #pragma mark - ContactLinkedDelegate
diff --git a/src/views/IMTableCellView.h b/src/views/IMTableCellView.h
new file mode 100644
index 0000000..68fd839
--- /dev/null
+++ b/src/views/IMTableCellView.h
@@ -0,0 +1,30 @@
+/*
+ *  Copyright (C) 2016 Savoir-faire Linux Inc.
+ *  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 <Cocoa/Cocoa.h>
+
+@interface IMTableCellView : NSTableCellView
+
+@property (nonatomic, strong) IBOutlet NSImageView* photoView;
+@property (nonatomic, strong) IBOutlet NSTextView* msgView;
+
+- (void) setup;
+- (void) updateWidthConstraint:(CGFloat) newWidth;
+
+@end
diff --git a/src/views/IMTableCellView.mm b/src/views/IMTableCellView.mm
new file mode 100644
index 0000000..a9d9497
--- /dev/null
+++ b/src/views/IMTableCellView.mm
@@ -0,0 +1,55 @@
+/*
+ *  Copyright (C) 2016 Savoir-faire Linux Inc.
+ *  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 "IMTableCellView.h"
+
+#import "NSColor+RingTheme.h"
+
+@implementation IMTableCellView
+@synthesize msgView;
+@synthesize photoView;
+
+
+- (void) setup
+{
+    if ([self.identifier isEqualToString:@"RightMessageView"]) {
+        [self.msgView setBackgroundColor:[NSColor ringBlue]];
+    }
+    [self.msgView setString:@""];
+    [self.msgView setAutoresizingMask:NSViewWidthSizable];
+    [self.msgView setEnabledTextCheckingTypes:NSTextCheckingTypeLink];
+    [self.msgView setAutomaticLinkDetectionEnabled:YES];
+}
+
+- (void) updateWidthConstraint:(CGFloat) newWidth
+{
+    [self.msgView removeConstraints:[self.msgView constraints]];
+    NSLayoutConstraint* constraint = [NSLayoutConstraint
+                                      constraintWithItem:self.msgView
+                                      attribute:NSLayoutAttributeWidth
+                                      relatedBy:NSLayoutRelationEqual
+                                      toItem: nil
+                                      attribute:NSLayoutAttributeWidth
+                                      multiplier:1.0f
+                                      constant:newWidth];
+
+    [self.msgView addConstraint:constraint];
+}
+
+@end
diff --git a/src/views/IconButton.mm b/src/views/IconButton.mm
index 59db443..24ce76e 100644
--- a/src/views/IconButton.mm
+++ b/src/views/IconButton.mm
@@ -40,53 +40,63 @@
 {
     [super drawRect:dirtyRect];
 
-    NSColor* backgroundColor6;
-    NSColor* backgroundStrokeColor5;
+    NSColor* backgroundColor;
+    NSColor* backgroundStrokeColor;
+    NSColor* tintColor = [NSColor whiteColor];
 
-    if (self.mouseDown || self.state == NSOnState) {
+    if (self.mouseDown || self.isHighlighted) {
         if (self.highlightColor) {
-            backgroundColor6 = self.highlightColor;
-            backgroundStrokeColor5 = [self.highlightColor darkenColorByValue:0.1];
+            backgroundColor = self.highlightColor;
+            backgroundStrokeColor = [self.highlightColor darkenColorByValue:0.1];
         } else {
-            backgroundColor6 = [self.bgColor darkenColorByValue:0.3];
-            backgroundStrokeColor5 = [self.bgColor darkenColorByValue:0.4];
+            backgroundColor = [self.bgColor darkenColorByValue:0.3];
+            backgroundStrokeColor = [self.bgColor darkenColorByValue:0.4];
         }
-
+    } else if (!self.isEnabled) {
+        backgroundColor = [self.bgColor colorWithAlphaComponent:0.7];
+        backgroundStrokeColor = [self.bgColor colorWithAlphaComponent:0.7];
+        tintColor = [[NSColor grayColor] colorWithAlphaComponent:0.3];
     } else {
-        backgroundColor6 = self.bgColor;
-        backgroundStrokeColor5 = [self.bgColor darkenColorByValue:0.1];
+        backgroundColor = self.bgColor;
+        backgroundStrokeColor = [self.bgColor darkenColorByValue:0.1];
     }
 
     //// Subframes
-    NSRect group = NSMakeRect(NSMinX(dirtyRect) + floor(NSWidth(dirtyRect) * 0.03333) + 0.5, NSMinY(dirtyRect) + floor(NSHeight(dirtyRect) * 0.03333) + 0.5, floor(NSWidth(dirtyRect) * 0.96667) - floor(NSWidth(dirtyRect) * 0.03333), floor(NSHeight(dirtyRect) * 0.96667) - floor(NSHeight(dirtyRect) * 0.03333));
+    NSRect group = NSMakeRect(NSMinX(dirtyRect) + floor(NSWidth(dirtyRect) * 0.03333) + 0.5,
+                              NSMinY(dirtyRect) + floor(NSHeight(dirtyRect) * 0.03333) + 0.5,
+                              floor(NSWidth(dirtyRect) * 0.96667) - floor(NSWidth(dirtyRect) * 0.03333),
+                              floor(NSHeight(dirtyRect) * 0.96667) - floor(NSHeight(dirtyRect) * 0.03333));
 
     //// Group
     {
         //// Oval Drawing
-        NSBezierPath* ovalPath = [NSBezierPath bezierPathWithRoundedRect:NSMakeRect(NSMinX(group) + floor(NSWidth(group) * 0.00000 + 0.5), NSMinY(group) + floor(NSHeight(group) * 0.00000 + 0.5), floor(NSWidth(group) * 1.00000 + 0.5) - floor(NSWidth(group) * 0.00000 + 0.5), floor(NSHeight(group) * 1.00000 + 0.5) - floor(NSHeight(group) * 0.00000 + 0.5)) xRadius:[self.cornerRadius floatValue] yRadius:[self.cornerRadius floatValue]];
+        NSBezierPath* ovalPath = [NSBezierPath bezierPathWithRoundedRect:
+                                  NSMakeRect(NSMinX(group) + floor(NSWidth(group) * 0.00000 + 0.5),
+                                             NSMinY(group) + floor(NSHeight(group) * 0.00000 + 0.5),
+                                             floor(NSWidth(group) * 1.00000 + 0.5) - floor(NSWidth(group) * 0.00000 + 0.5),
+                                             floor(NSHeight(group) * 1.00000 + 0.5) - floor(NSHeight(group) * 0.00000 + 0.5))
+                                                                 xRadius:[self.cornerRadius floatValue] yRadius:[self.cornerRadius floatValue]];
 
-        [backgroundColor6 setFill];
+        [backgroundColor setFill];
         [ovalPath fill];
-        [backgroundStrokeColor5 setStroke];
+        [backgroundStrokeColor setStroke];
         [ovalPath setLineWidth: 0.5];
         [ovalPath stroke];
 
         [NSGraphicsContext saveGraphicsState];
 
-        NSBezierPath *path = [NSBezierPath bezierPathWithRect:dirtyRect];
+        NSBezierPath* path = [NSBezierPath bezierPathWithRect:dirtyRect];
         [path addClip];
 
         [self setImagePosition:NSImageOnly];
-        auto rect2 = NSInsetRect(dirtyRect, self.imageInsets, self.imageInsets);
+        auto rect = NSInsetRect(dirtyRect, self.imageInsets, self.imageInsets);
 
-
-        [[NSColor image:self.image tintedWithColor:[NSColor whiteColor]]
-                drawInRect:rect2
+        [[NSColor image:self.image tintedWithColor:tintColor] drawInRect:rect
                  fromRect:NSZeroRect
                 operation:NSCompositeSourceOver
                  fraction:1.0
-                respectFlipped:YES
-                         hints:nil];
+           respectFlipped:YES
+                    hints:nil];
 
         [NSGraphicsContext restoreGraphicsState];
     }
diff --git a/src/views/NSColor+RingTheme.h b/src/views/NSColor+RingTheme.h
index 35f58ab..08d145b 100644
--- a/src/views/NSColor+RingTheme.h
+++ b/src/views/NSColor+RingTheme.h
@@ -27,6 +27,7 @@
 + (NSColor*) ringDarkBlue;
 
 + (NSColor*) ringGreyHighlight;
++ (NSColor*) ringGreyLight;
 + (NSColor*) ringDarkGrey;
 
 - (NSColor *)lightenColorByValue:(float)value;
diff --git a/src/views/NSColor+RingTheme.mm b/src/views/NSColor+RingTheme.mm
index bf1f256..1090e95 100644
--- a/src/views/NSColor+RingTheme.mm
+++ b/src/views/NSColor+RingTheme.mm
@@ -41,6 +41,11 @@
     return [NSColor colorWithCalibratedRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1.0];
 }
 
++ (NSColor*) ringGreyLight
+{
+    return [NSColor colorWithCalibratedRed:176/255.0 green:176/255.0 blue:176/255.0 alpha:1.0];
+}
+
 + (NSColor*) ringDarkGrey
 {
     return [NSColor colorWithCalibratedRed:41/255.0 green:41/255.0 blue:41/255.0 alpha:1.0];