PersonLinkerVC.mm 10 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 23 24 25 26 27 28 29 30
 *  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 "PersonLinkerVC.h"

//Qt
#import <QtMacExtras/qmacfunctions.h>
#import <QPixmap>

//LRC
#import <person.h>
#import <personmodel.h>
#import <contactmethod.h>
#import <numbercategorymodel.h>
31
#import <globalinstances.h>
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

#import "QNSTreeController.h"
#import "delegates/ImageManipulationDelegate.h"

class OnlyPersonProxyModel : public QSortFilterProxyModel
{
public:
    OnlyPersonProxyModel(QAbstractItemModel* parent) : QSortFilterProxyModel(parent)
    {
        setSourceModel(parent);
    }
    virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
    {
        bool match = filterRegExp().indexIn(sourceModel()->index(source_row,0,source_parent).data(Qt::DisplayRole).toString()) != -1;
        //qDebug() << "FILTERING" << sourceModel()->index(source_row,0,source_parent) << "match:" << match;
        return match && !sourceModel()->index(source_row,0,source_parent).parent().isValid();
    }
};

51
@interface PersonLinkerVC () <NSTextFieldDelegate, NSComboBoxDelegate, NSComboBoxDataSource> {
52

53 54 55 56 57 58 59
    __unsafe_unretained IBOutlet NSTextField *contactMethodLabel;
    __unsafe_unretained IBOutlet NSOutlineView *personsView;
    __unsafe_unretained IBOutlet NSTextField *firstNameField;
    __unsafe_unretained IBOutlet NSTextField *lastNameField;
    __unsafe_unretained IBOutlet NSButton *createNewContactButton;
    __unsafe_unretained IBOutlet NSComboBox *categoryComboBox;
    __unsafe_unretained IBOutlet NSView *linkToExistingSubview;
60

61 62 63 64
    QSortFilterProxyModel* contactProxyModel;
    QNSTreeController* treeController;
    IBOutlet NSView *createContactSubview;
}
65 66 67 68

@end

@implementation PersonLinkerVC
69 70 71 72 73 74 75

// Tags for views
NSInteger const FIRSTNAME_TAG = 1;
NSInteger const LASTNAME_TAG = 2;
NSInteger const IMAGE_TAG = 100;
NSInteger const DISPLAYNAME_TAG = 200;
NSInteger const DETAILS_TAG = 300;
76 77 78 79 80 81 82 83 84 85

-(void) awakeFromNib
{
    NSLog(@"INIT PersonLinkerVC");

    [firstNameField setTag:FIRSTNAME_TAG];
    [lastNameField setTag:LASTNAME_TAG];

    [categoryComboBox selectItemAtIndex:0];

86
    contactProxyModel = new OnlyPersonProxyModel(&PersonModel::instance());
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    contactProxyModel->setSortRole(static_cast<int>(Qt::DisplayRole));
    contactProxyModel->sort(0,Qt::AscendingOrder);
    contactProxyModel->setFilterRole(Qt::DisplayRole);
    treeController = [[QNSTreeController alloc] initWithQModel:contactProxyModel];

    [treeController setAvoidsEmptySelection:NO];
    [treeController setChildrenKeyPath:@"children"];

    [personsView bind:@"content" toObject:treeController withKeyPath:@"arrangedObjects" options:nil];
    [personsView bind:@"sortDescriptors" toObject:treeController withKeyPath:@"sortDescriptors" options:nil];
    [personsView bind:@"selectionIndexPaths" toObject:treeController withKeyPath:@"selectionIndexPaths" options:nil];
    [personsView setTarget:self];
    [personsView setDoubleAction:@selector(addToContact:)];

    [contactMethodLabel setStringValue:self.methodToLink->uri().toNSString()];
}

- (IBAction)addToContact:(id)sender
{
    /* get the selected number category */
107
    const auto& idx = NumberCategoryModel::instance().index([categoryComboBox indexOfSelectedItem]);
108
    if (idx.isValid()) {
109
        auto category = NumberCategoryModel::instance().getCategory(idx.data().toString());
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
        self.methodToLink->setCategory(category);
    }

    if([[treeController selectedNodes] count] > 0) {
        QModelIndex qIdx = [treeController toQIdx:[treeController selectedNodes][0]];
        ContactMethod* m = nil;
        if(((NSTreeNode*)[treeController selectedNodes][0]).indexPath.length == 1) {
            // Person
            QVariant var = qIdx.data((int)Person::Role::Object);
            if (var.isValid()) {
                Person *p = var.value<Person*>();
                Person::ContactMethods cms = p->phoneNumbers();
                cms.append(self.methodToLink);
                p->setContactMethods(cms);
                self.methodToLink->setPerson(p);
                p->save();
                [self.contactLinkedDelegate contactLinked];
            }
        }
    }
}

- (void) dealloc
{
    // No ARC for c++ pointers
    delete contactProxyModel;
}

- (IBAction)presentNewContactForm:(id)sender {
    [createContactSubview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
    //[createContactSubview setBounds:linkToExistingSubview.bounds];
    [createContactSubview setFrame:linkToExistingSubview.frame];
    [linkToExistingSubview setHidden:YES];
    [self.view addSubview:createContactSubview];

    [[[NSApplication sharedApplication] mainWindow] makeFirstResponder:firstNameField];
    [firstNameField setNextKeyView:lastNameField];
    [lastNameField setNextKeyView:createNewContactButton];
    [createNewContactButton setNextKeyView:firstNameField];
}

- (IBAction)createContact:(id)sender
{
    /* get the selected number category */
154
    const auto& idx = NumberCategoryModel::instance().index([categoryComboBox indexOfSelectedItem]);
155
    if (idx.isValid()) {
156
        auto category = NumberCategoryModel::instance().getCategory(idx.data().toString());
157 158 159 160 161 162 163 164 165 166 167 168 169
        self.methodToLink->setCategory(category);
    }

    /* create a new person */
    Person *p = new Person();
    p->setFirstName(QString::fromNSString(firstNameField.stringValue));
    p->setFamilyName(QString::fromNSString(lastNameField.stringValue));
    p->setFormattedName(QString::fromNSString([[NSString alloc] initWithFormat:@"%@ %@", firstNameField.stringValue, lastNameField.stringValue]));
    /* associate the new person with the contact method */
    Person::ContactMethods numbers;
    numbers << self.methodToLink;
    p->setContactMethods(numbers);
    self.methodToLink->setPerson(p);
170
    PersonModel::instance().addNewPerson(p);
171 172 173 174 175 176 177 178 179 180 181
    [self.contactLinkedDelegate contactLinked];
}

#pragma mark - NSOutlineViewDelegate methods

// -------------------------------------------------------------------------------
//	shouldSelectItem:item
// -------------------------------------------------------------------------------
- (BOOL)outlineView:(NSOutlineView *)outlineView shouldSelectItem:(id)item;
{
    QModelIndex qIdx = [treeController toQIdx:((NSTreeNode*)item)];
182
    return qIdx.isValid();
183 184 185 186 187 188 189 190 191 192 193 194
}

// -------------------------------------------------------------------------------
//	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;
}

195 196 197
/* View Based OutlineView: See the delegate method -tableView:viewForTableColumn:row: in NSTableView.
 */
- (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item
198 199 200
{
    QModelIndex qIdx = [treeController toQIdx:((NSTreeNode*)item)];

201 202 203
    NSTableCellView *result = [outlineView makeViewWithIdentifier:@"MainCell" owner:outlineView];
    NSImageView* photoView = [result viewWithTag:IMAGE_TAG];
    NSTextField* displayName = [result viewWithTag:DISPLAYNAME_TAG];
204

205 206 207 208 209

    if (!qIdx.isValid()) {
        [photoView setImage:nil];
        [displayName setStringValue:qIdx.data(Qt::DisplayRole).toString().toNSString()];
        return result;
210
    }
211 212 213 214 215 216 217 218 219 220 221 222

    if (auto p = qvariant_cast<Person*>(qIdx.data((int)Person::Role::Object))) {
        QVariant photo = GlobalInstances::pixmapManipulator().contactPhoto(p, QSize(35,35));
        [photoView setImage:QtMac::toNSImage(qvariant_cast<QPixmap>(photo))];
    } else {
        QVariant photo = GlobalInstances::pixmapManipulator().contactPhoto(nil, QSize(35,35));
        [photoView setImage:QtMac::toNSImage(qvariant_cast<QPixmap>(photo))];
    }

    [displayName setStringValue:qIdx.data(Qt::DisplayRole).toString().toNSString()];

    return result;
223 224 225 226 227 228 229 230
}

// -------------------------------------------------------------------------------
//	outlineViewSelectionDidChange:notification
// -------------------------------------------------------------------------------

- (CGFloat)outlineView:(NSOutlineView *)outlineView heightOfRowByItem:(id)item
{
231
    return 60.0;
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
}

#pragma mark - NSTextFieldDelegate

- (void)controlTextDidChange:(NSNotification *) notification
{
    if ([notification.object tag] == FIRSTNAME_TAG || [notification.object tag] == LASTNAME_TAG) {
        NSTextView *textView = notification.userInfo[@"NSFieldEditor"];
        BOOL enableCreate = textView.textStorage.string.length > 0;
        [createNewContactButton setEnabled:enableCreate];
    } else {
        NSTextView *textView = notification.userInfo[@"NSFieldEditor"];
        contactProxyModel->setFilterRegExp(QRegExp(QString::fromNSString(textView.textStorage.string), Qt::CaseInsensitive, QRegExp::FixedString));
        [personsView scrollToBeginningOfDocument:nil];
    }
}

#pragma mark - NSComboBoxDelegate

- (void)comboBoxSelectionDidChange:(NSNotification*) notification
{
    [(NSComboBox *)[notification object] indexOfSelectedItem];
}

#pragma mark - NSComboBoxDatasource

- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)aComboBox
{
260
    return NumberCategoryModel::instance().rowCount();
261 262 263 264
}

- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)index
{
265
    return NumberCategoryModel::instance().index(index).data().toString().toNSString();
266 267 268
}

@end