File: nsearchview.cpp

package info (click to toggle)
nixnote2 2.0~beta11-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 9,448 kB
  • ctags: 7,058
  • sloc: cpp: 68,338; java: 1,096; sh: 834; makefile: 27
file content (540 lines) | stat: -rw-r--r-- 17,676 bytes parent folder | download
1
2
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
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
443
444
445
446
447
448
449
450
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
/*********************************************************************************
NixNote - An open-source client for the Evernote service.
Copyright (C) 2013 Randy Baumgarte

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 2
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.
***********************************************************************************/

#include "nsearchview.h"
#include "global.h"
#include "nsearchviewitem.h"
#include "dialog/savedsearchproperties.h"
#include "sql/searchtable.h"
#include "gui/treewidgeteditor.h"
#include "gui/widgetpanel.h"
#include "sql/nsqlquery.h"

#include <QHeaderView>
#include <QMouseEvent>
#include <QDrag>
#include <QtSql>
#include <QAction>
#include <QMessageBox>
#include <QPainter>

#define NAME_POSITION 0

extern Global global;

// Constructor
NSearchView::NSearchView(QWidget *parent) :
    QTreeWidget(parent)
{
    this->setFont(global.getGuiFont(font()));
    setAcceptDrops(false);
    setDragEnabled(true);

    filterPosition = -1;

    // setup options
    this->setEditTriggers(QAbstractItemView::NoEditTriggers);
    this->setSelectionBehavior(QAbstractItemView::SelectRows);
    this->setSelectionMode(QAbstractItemView::SingleSelection);
    this->setRootIsDecorated(true);
    this->setSortingEnabled(false);
    this->header()->setVisible(false);

    // Build the root item
    QIcon icon = global.getIconResource(":searchIcon");
    root = new NSearchViewItem(this);
    root->setIcon(NAME_POSITION,icon);
    root->setRootColor(true);
    root->setData(NAME_POSITION, Qt::UserRole, "root");
    root->setData(NAME_POSITION, Qt::DisplayRole, tr("Saved Searches"));
    this->addTopLevelItem(root);
    this->loadData();
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    connect(this, SIGNAL(itemExpanded(QTreeWidgetItem*)), this, SLOT(calculateHeight()));
    connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), this, SLOT(calculateHeight()));
    connect(this, SIGNAL(itemSelectionChanged()), this, SLOT(buildSelection()));

    addAction = context.addAction(tr("Create Saved Search"));
    addAction->setShortcut(QKeySequence(Qt::Key_Insert));
    addAction->setShortcutContext(Qt::WidgetShortcut);

    addShortcut = new QShortcut(this);
    addShortcut->setKey(QKeySequence(Qt::Key_Insert));
    addShortcut->setContext(Qt::WidgetShortcut);

    context.addSeparator();
    deleteAction = context.addAction(tr("Delete"));
    deleteAction->setShortcut(QKeySequence(Qt::Key_Delete));

    deleteShortcut = new QShortcut(this);
    deleteShortcut->setKey(QKeySequence(Qt::Key_Delete));
    deleteShortcut->setContext(Qt::WidgetShortcut);

    renameAction = context.addAction(tr("Rename"));
    renameAction->setShortcutContext(Qt::WidgetShortcut);

    context.addSeparator();
    propertiesAction = context.addAction(tr("Properties"));

    connect(addAction, SIGNAL(triggered()), this, SLOT(addRequested()));
    connect(deleteAction, SIGNAL(triggered()), this, SLOT(deleteRequested()));
    connect(renameAction, SIGNAL(triggered()), this, SLOT(renameRequested()));
    connect(propertiesAction, SIGNAL(triggered()), this, SLOT(propertiesRequested()));

    connect(addShortcut, SIGNAL(activated()), this, SLOT(addRequested()));
    connect(deleteShortcut, SIGNAL(activated()), this, SLOT(deleteRequested()));
    this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);
    this->setFrameShape(QFrame::NoFrame);

    expandedImage = new QImage(":expandedIcon");
    collapsedImage = new QImage(":collapsedIcon");

}


// Destructor
NSearchView::~NSearchView() {
    delete root;
}



// This allows for the tree item to be toggled.  If the prior item is selected again
// it is deselected.  If it is the root item, we don't permit the selection.
void NSearchView::mousePressEvent(QMouseEvent *event)
{
    QModelIndex item = indexAt(event->pos());
    bool selected = selectionModel()->isSelected(indexAt(event->pos()));
    QTreeView::mousePressEvent(event);
    if (selected && (event->buttons() & Qt::LeftButton))
        selectionModel()->select(item, QItemSelectionModel::Deselect);

    for (int i=0; i<this->selectedItems() .size(); i++) {
        if (this->selectedIndexes().at(i).data(Qt::UserRole) == "root") {
            if (!root->isExpanded())
                root->setExpanded(true);
            selectionModel()->select(this->selectedIndexes().at(i), QItemSelectionModel::Deselect);
        }
    }
}


// Load up the data from the database
void NSearchView::loadData() {
    NSqlQuery query(global.db);
    query.exec("Select lid, name from SearchModel order by name");
    while (query.next()) {
        qint32 lid = query.value(0).toInt();
        SearchTable table(global.db);
        if (!table.isDeleted(lid)) {
            NSearchViewItem *newWidget = new NSearchViewItem();
            newWidget->setData(NAME_POSITION, Qt::DisplayRole, query.value(1).toString());
            newWidget->setData(NAME_POSITION, Qt::UserRole, lid);
            this->dataStore.insert(query.value(0).toInt(), newWidget);
            root->addChild(newWidget);
        }
    }
    query.finish();
}


//*************************************************************
// This function is called when a search has been updated from
// somewhere else.
//*************************************************************
void NSearchView::searchUpdated(qint32 lid, QString name) {
    // Check if it already exists
    if (this->dataStore.contains(lid)) {
        NSearchViewItem *newWidget = this->dataStore.value(lid);
        newWidget->setData(NAME_POSITION, Qt::DisplayRole, name);
        newWidget->setData(NAME_POSITION, Qt::UserRole, lid);
    } else {
        NSearchViewItem *newWidget = new NSearchViewItem();
        newWidget->setData(NAME_POSITION, Qt::DisplayRole, name);
        newWidget->setData(NAME_POSITION, Qt::UserRole, lid);
        this->dataStore.insert(lid, newWidget);
        root->addChild(newWidget);
        if (this->dataStore.count() == 1) {
            this->expandAll();
        }
    }
    this->sortItems(NAME_POSITION, Qt::AscendingOrder);
    resetSize();
    this->sortByColumn(NAME_POSITION);
}


//*************************************************************
// This function is called when a search has been removed
// during a sync.
//*************************************************************
void NSearchView::searchExpunged(qint32 lid) {
    // Check if it already exists
    if (this->dataStore.contains(lid)) {
        NSearchViewItem *item = this->dataStore.value(lid);
        item->parent()->removeChild(item);
        this->dataStore.remove(lid);
    }
    this->resetSize();
}




//*************************************************************
// Calculate the tree height.
//*************************************************************
void NSearchView::calculateHeight()
{
    int h = 0;

    int topLevelCount = topLevelItemCount();

    for(int i = 0;i < topLevelCount;i++)
    {
        QTreeWidgetItem * item = topLevelItem(i);
        h += calculateHeightRec(item);
        h += item->sizeHint(0).height() + 5;
    }

    if(h != 0)
    {
        setMinimumHeight(h);
        setMaximumHeight(h);
    }
    setMaximumWidth(sizeHint().width());
}



int NSearchView::calculateHeightRec(QTreeWidgetItem * item)
{
    if(!item)
        return 0;

    QModelIndex index = indexFromItem(item);

    if(!item->isExpanded())
    {
        return rowHeight(index);
    }

    int h = item->sizeHint(0).height() + 2 + rowHeight(index);
    int childCount = item->childCount();
    for(int i = 0; i < childCount;i++)
    {
        h += calculateHeightRec(item->child(i));
    }

    return h;
}


void NSearchView::resetSize() {
    calculateHeight();
}





//*************************************************************
// This function is called when a user selects something
// within this tree.  It also emits a signal that will
// be picked up by the main nixnote program.
//*************************************************************
void NSearchView::buildSelection() {
    QLOG_TRACE() << "Inside NNotebookView::buildSelection()";

    QList<QTreeWidgetItem*> selectedItems = this->selectedItems();

    // First, find out if we're already viewing history.  If we are we
    // chop off the end of the history & start a new one
    if (global.filterPosition+1 < global.filterCriteria.size()) {
        while (global.filterPosition+1 < global.filterCriteria.size())
            global.filterCriteria.removeLast();
    }

    filterPosition++;
    FilterCriteria *newFilter = new FilterCriteria();
    global.filterCriteria.push_back(newFilter);
    global.filterPosition++;

    if (selectedItems.size() > 0) {
        newFilter->setSavedSearch(*(NSearchViewItem*)(selectedItems[0]));
        qint32 lid = selectedItems[0]->data(NAME_POSITION, Qt::UserRole).toInt();
        SearchTable stable(global.db);
        SavedSearch search;
        if (stable.get(search, lid))
            newFilter->setSearchString(search.query);
    }

    newFilter->resetAttribute = true;
    newFilter->resetFavorite = true;
    newFilter->resetDeletedOnly = true;
    newFilter->resetNotebook =true;
    newFilter->resetTags = true;
    newFilter->resetSavedSearch = true;
    newFilter->resetSearchString = true;

    emit updateSelectionRequested();

    QLOG_TRACE() << "Leaving NNotebookView::buildSelection()";
}


//*************************************************************
// This function is called from the main NixNote class.
// it will reset the items which are selected based upon
// what the user did somewhere else (outside this widget).
//*************************************************************
void NSearchView::updateSelection() {
    blockSignals(true);

    FilterCriteria *criteria = global.filterCriteria[global.filterPosition];
    if (global.filterPosition != filterPosition) {
        QList<QTreeWidgetItem*> selectedItems = this->selectedItems();
        for (int i=0; i<selectedItems.size() && criteria->resetSavedSearch; i++) {
            selectedItems[i]->setSelected(false);
        }
    }
    filterPosition = global.filterPosition;

    blockSignals(false);
}



//*************************************************************
// This function is called when a user right-clicks on an
// item to bring up the popup menu.
//*************************************************************
void NSearchView::contextMenuEvent(QContextMenuEvent *event) {
    QList<QTreeWidgetItem*> items = selectedItems();
    if (items.size() == 0) {
        propertiesAction->setEnabled(false);
        deleteAction->setEnabled(false);
        renameAction->setEnabled(false);
    } else {
        propertiesAction->setEnabled(true);
        deleteAction->setEnabled(true);
        renameAction->setEnabled(true);
    }
    context.exec(event->globalPos());
}


//*************************************************************
// This function is called when a user clicks "add" from
// the popup menu.
//*************************************************************
void NSearchView::addRequested() {
    SavedSearchProperties dialog;
    QList<QTreeWidgetItem*> items = selectedItems();

    dialog.setLid(0);

    dialog.exec();
    if (!dialog.okPressed)
        return;

    SearchTable table(global.db);
    NSearchViewItem *newWidget = new NSearchViewItem();
    QString name = dialog.name.text().trimmed();
    qint32 lid = table.findByName(name);
    newWidget->setData(NAME_POSITION, Qt::DisplayRole, name);
    newWidget->setData(NAME_POSITION, Qt::UserRole, lid);
    this->dataStore.insert(lid, newWidget);
    root->addChild(newWidget);
    this->sortItems(NAME_POSITION, Qt::AscendingOrder);
    resetSize();
    this->sortByColumn(NAME_POSITION);

    dataStore.insert(lid, newWidget);
}


//*************************************************************
// This function is called when a user clicks "properties"
// from the popup menu.
//*************************************************************
void NSearchView::propertiesRequested() {
    SavedSearchProperties dialog;
    QList<QTreeWidgetItem*> items = selectedItems();

    qint32 lid = items[0]->data(NAME_POSITION, Qt::UserRole).toInt();
    dialog.setLid(lid);

    dialog.exec();
    if (!dialog.okPressed)
        return;
    items[0]->setData(NAME_POSITION, Qt::DisplayRole, dialog.name.text().trimmed());
}



//*************************************************************
// This function is called when a user clicks "delete" from
// the popup menu.
//*************************************************************
void NSearchView::deleteRequested() {
    QList<QTreeWidgetItem*> items = selectedItems();

    qint32 lid = items[0]->data(NAME_POSITION, Qt::UserRole).toInt();
    if (global.confirmDeletes()) {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Question);
        msgBox.setText(tr("Are you sure you want to delete this saved search?"));
        msgBox.setWindowTitle(tr("Verify Delete"));
        msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        msgBox.setDefaultButton(QMessageBox::No);
        int ret = msgBox.exec();
        if (ret == QMessageBox::No)
            return;
    }
    SearchTable s(global.db);
    s.deleteSearch(lid);
    items[0]->setHidden(true);
    dataStore.remove(lid);
    emit searchDeleted(lid);
}



//*************************************************************
// This function is called when a user clicks "rename" from
// the popup menu.
//*************************************************************
void NSearchView::renameRequested() {
    editor = new TreeWidgetEditor(this);
    connect(editor, SIGNAL(editComplete()), this, SLOT(editComplete()));

    QList<QTreeWidgetItem*> items = selectedItems();
    editor->setText(items[0]->text(NAME_POSITION));
    editor->lid = items[0]->data(NAME_POSITION, Qt::UserRole).toInt();
    editor->setTreeWidgetItem(items[0], NAME_POSITION);
    QFontMetrics m(font());
    editor->setMinimumHeight(m.height()+4);
    editor->setMaximumHeight(m.height()+4);
    setItemWidget(items[0], NAME_POSITION, editor);
    editor->setFocus();
}



//*************************************************************
// This function is called when a user has finished editing a
// search.
//*************************************************************
void NSearchView::editComplete() {
    QString text = editor->text().trimmed();
    qint32 lid = editor->lid;
    SearchTable table(global.db);
    SavedSearch s;
    table.get(s, lid);

    // Check that this search doesn't already exist
    // if it exists, we go back to the original name
    qint32 check = table.findByName(text);
    if (check != 0) {
        NSearchViewItem *item = dataStore[lid];
        QString name = "";
        if (s.name.isSet())
            name = s.name;
        item->setData(NAME_POSITION, Qt::DisplayRole,name);
    } else {
        s.name = text;
        table.update(lid, s, true);
    }
    this->sortItems(NAME_POSITION, Qt::AscendingOrder);
    resetSize();
    this->sortByColumn(NAME_POSITION);
}



QSize NSearchView::sizeHint() {
    return QTreeView::sizeHint();
}



//*************************************************************
// Draw the branches of the tree.
//*************************************************************
void NSearchView::drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const {
    if (!index.child(0,0).isValid())
        return;

    painter->save();
    if (isExpanded(index)) {
        int offset = rect.width()-expandedImage->width()-1;
        painter->drawImage(offset, rect.y(),*expandedImage);
    } else {
        int offset = rect.width()-collapsedImage->width()-1;
        painter->drawImage(offset, rect.y(),*collapsedImage);
    }
    painter->restore();
    return;
}



//*************************************************************
// Process mouse movements.
//*************************************************************
void NSearchView::mouseMoveEvent(QMouseEvent *event)
{
    QTreeView::mouseMoveEvent(event);

    if (currentItem() == NULL)
        return;

    if (!(event->buttons() & Qt::LeftButton))
        return;

    QDrag *drag = new QDrag(this);
    QMimeData *mimeData = new QMimeData;

    NSearchViewItem *current = (NSearchViewItem*)currentItem();
    QByteArray mime = current->data(NAME_POSITION, Qt::UserRole).toByteArray();

    QString userdata = current->data(NAME_POSITION, Qt::UserRole).toString();
    if (userdata.startsWith("root", Qt::CaseInsensitive))
        return;

    mimeData->setData("application/x-nixnote-search", mime);
    drag->setMimeData(mimeData);

    drag->exec(Qt::MoveAction);
    QTreeView::mouseMoveEvent(event);
}



//*************************************************************
// Reload icens in the tree.  This is useful if the theme
// changes.
//*************************************************************
void NSearchView::reloadIcons() {
    root->setIcon(NAME_POSITION,global.getIconResource(":searchIcon"));
}