~ubuntu-branches/ubuntu/quantal/qgis/quantal

« back to all changes in this revision

Viewing changes to src/qgsattributetable.cpp

  • Committer: Bazaar Package Importer
  • Author(s): William Grant
  • Date: 2007-05-06 13:42:32 UTC
  • mfrom: (1.1.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20070506134232-pyli6t388w5asd8x
Tags: 0.8.0-3ubuntu1
* Merge from Debian unstable. Remaining Ubuntu changes:
  - debian/rules, debian/qgis.install, debian/qgis.dirs debian/qgis.desktop:
    Add and install .desktop.
* debian/qgis.desktop: Remove Applications category; it's not real.
* Modify Maintainer value to match Debian-Maintainer-Field Spec

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/***************************************************************************
2
 
                          qgsattributetable.cpp  -  description
3
 
                             -------------------
4
 
    begin                : Sat Nov 23 2002
5
 
    copyright            : (C) 2002 by Gary E.Sherman
6
 
    email                : sherman at mrcc dot com
7
 
       Romans 3:23=>Romans 6:23=>Romans 5:8=>Romans 10:9,10=>Romans 12
8
 
 ***************************************************************************/
9
 
 
10
 
/***************************************************************************
11
 
 *                                                                         *
12
 
 *   This program is free software; you can redistribute it and/or modify  *
13
 
 *   it under the terms of the GNU General Public License as published by  *
14
 
 *   the Free Software Foundation; either version 2 of the License, or     *
15
 
 *   (at your option) any later version.                                   *
16
 
 *                                                                         *
17
 
 ***************************************************************************/
18
 
/* $Id: qgsattributetable.cpp,v 1.27.2.2 2005/08/16 19:35:55 mhugent Exp $ */
19
 
#include <qapplication.h>
20
 
#include <qcursor.h>
21
 
#include <qpopupmenu.h>
22
 
#include <qlabel.h>
23
 
#include <qfont.h>
24
 
#include "qgsattributetable.h"
25
 
#include "qgsfeature.h"
26
 
#include "qgsfield.h"
27
 
#include "qgsvectordataprovider.h"
28
 
#include "qgsvectorlayer.h"
29
 
#include <iostream>
30
 
#include <stdlib.h>
31
 
 
32
 
QgsAttributeTable::QgsAttributeTable(QWidget * parent, const char *name):QTable(parent, name), lockKeyPressed(false),
33
 
                                                                         sort_ascending(true), mActionPopup(0), mEditable(false), mEdited(false)
34
 
{
35
 
  QFont f(font());
36
 
  f.setFamily("Helvetica");
37
 
  f.setPointSize(11);
38
 
  setFont(f);
39
 
  setSelectionMode(QTable::MultiRow);
40
 
  QObject::connect(this, SIGNAL(selectionChanged()), this, SLOT(handleChangedSelections()));
41
 
  connect(this, SIGNAL(contextMenuRequested(int, int, const QPoint&)), this, SLOT(popupMenu(int, int, const QPoint&)));
42
 
  connect(this, SIGNAL(valueChanged(int, int)), this, SLOT(storeChangedValue(int,int)));
43
 
  setReadOnly(true);
44
 
  setFocus();
45
 
}
46
 
 
47
 
QgsAttributeTable::~QgsAttributeTable()
48
 
{
49
 
 
50
 
}
51
 
void QgsAttributeTable::columnClicked(int col)
52
 
{
53
 
  QApplication::setOverrideCursor(Qt::waitCursor);
54
 
 
55
 
  //store the ids of the selected rows in a list
56
 
  QValueList < int >idsOfSelected;
57
 
  for (int i = 0; i < numSelections(); i++)
58
 
    {
59
 
      for (int j = selection(i).topRow(); j <= selection(i).bottomRow(); j++)
60
 
        {
61
 
          idsOfSelected.append(text(j, 0).toInt());
62
 
        }
63
 
    }
64
 
 
65
 
  sortColumn(col, sort_ascending, true);
66
 
 
67
 
  //clear and rebuild rowIdMap. Overwrite sortColumn later and sort rowIdMap there
68
 
  rowIdMap.clear();
69
 
  int id;
70
 
  for (int i = 0; i < numRows(); i++)
71
 
    {
72
 
      id = text(i, 0).toInt();
73
 
      rowIdMap.insert(id, i);
74
 
    }
75
 
 
76
 
  QObject::disconnect(this, SIGNAL(selectionChanged()), this, SLOT(handleChangedSelections()));
77
 
  clearSelection(true);
78
 
 
79
 
  //select the rows again after sorting
80
 
 
81
 
  QValueList < int >::iterator it;
82
 
  for (it = idsOfSelected.begin(); it != idsOfSelected.end(); ++it)
83
 
    {
84
 
      selectRowWithId((*it));
85
 
    }
86
 
  QObject::connect(this, SIGNAL(selectionChanged()), this, SLOT(handleChangedSelections()));
87
 
 
88
 
  //change the sorting order after each sort
89
 
  (sort_ascending == true) ? sort_ascending = false : sort_ascending = true;
90
 
 
91
 
  QApplication::restoreOverrideCursor();
92
 
}
93
 
 
94
 
void QgsAttributeTable::keyPressEvent(QKeyEvent * ev)
95
 
{
96
 
  if (ev->key() == Qt::Key_Control || ev->key() == Qt::Key_Shift)
97
 
    {
98
 
      lockKeyPressed = true;
99
 
    }
100
 
}
101
 
 
102
 
void QgsAttributeTable::keyReleaseEvent(QKeyEvent * ev)
103
 
{
104
 
  if (ev->key() == Qt::Key_Control || ev->key() == Qt::Key_Shift)
105
 
    {
106
 
      lockKeyPressed = false;
107
 
    }
108
 
}
109
 
 
110
 
void QgsAttributeTable::handleChangedSelections()
111
 
{
112
 
  QTableSelection cselection;
113
 
  if (lockKeyPressed == false)
114
 
    {
115
 
      //clear the list and evaluate the last selection
116
 
      emit selectionRemoved();
117
 
    }
118
 
  //if there is no current selection, there is nothing to do
119
 
  if (currentSelection() == -1)
120
 
    {
121
 
      emit repaintRequested();
122
 
      return;
123
 
    }
124
 
 
125
 
  cselection = selection(currentSelection());
126
 
 
127
 
  for (int index = cselection.topRow(); index <= cselection.bottomRow(); index++)
128
 
    {
129
 
      emit selected(text(index, 0).toInt());
130
 
    }
131
 
 
132
 
  //emit repaintRequested();
133
 
 
134
 
}
135
 
 
136
 
void QgsAttributeTable::insertFeatureId(int id, int row)
137
 
{
138
 
  rowIdMap.insert(id, row);
139
 
}
140
 
 
141
 
void QgsAttributeTable::selectRowWithId(int id)
142
 
{
143
 
  QMap < int, int >::iterator it = rowIdMap.find(id);
144
 
  selectRow(it.data());
145
 
}
146
 
 
147
 
void QgsAttributeTable::sortColumn(int col, bool ascending, bool wholeRows)
148
 
{
149
 
  //if the first entry contains a letter, sort alphanumerically, otherwise numerically
150
 
  QString firstentry = text(0, col);
151
 
  bool containsletter = false;
152
 
  for (uint i = 0; i < firstentry.length(); i++)
153
 
    {
154
 
      if (firstentry.ref(i).isLetter())
155
 
        {
156
 
          containsletter = true;
157
 
        }
158
 
    }
159
 
 
160
 
  if (containsletter)
161
 
    {
162
 
      qsort(0, numRows() - 1, col, ascending, true);
163
 
  } else
164
 
    {
165
 
      qsort(0, numRows() - 1, col, ascending, false);
166
 
    }
167
 
 
168
 
  repaintContents();
169
 
}
170
 
 
171
 
 
172
 
/**
173
 
  XXX Doesn't QString have something ilke this already?
174
 
*/
175
 
int QgsAttributeTable::compareItems(QString s1, QString s2, bool ascending, bool alphanumeric)
176
 
{
177
 
  if (alphanumeric)
178
 
    {
179
 
      if (s1 > s2)
180
 
        {
181
 
          if (ascending)
182
 
            {
183
 
              return 1;
184
 
          } else
185
 
            {
186
 
              return -1;
187
 
            }
188
 
      } else if (s1 < s2)
189
 
        {
190
 
          if (ascending)
191
 
            {
192
 
              return -1;
193
 
          } else
194
 
            {
195
 
              return 1;
196
 
            }
197
 
      } else if (s1 == s2)
198
 
        {
199
 
          return 0;
200
 
        }
201
 
  } else                        //numeric
202
 
    {
203
 
      double d1 = s1.toDouble();
204
 
      double d2 = s2.toDouble();
205
 
      if (d1 > d2)
206
 
        {
207
 
          if (ascending)
208
 
            {
209
 
              return 1;
210
 
          } else
211
 
            {
212
 
              return -1;
213
 
            }
214
 
      } else if (d1 < d2)
215
 
        {
216
 
          if (ascending)
217
 
            {
218
 
              return -1;
219
 
          } else
220
 
            {
221
 
              return 1;
222
 
            }
223
 
      } else if (d1 == d2)
224
 
        {
225
 
          return 0;
226
 
        }
227
 
    }
228
 
 
229
 
  return 0;                     // XXX has to return something; is this reasonable?
230
 
 
231
 
}
232
 
 
233
 
void QgsAttributeTable::qsort(int lower, int upper, int col, bool ascending, bool alphanumeric)
234
 
{
235
 
  int i, j;
236
 
  QString v;
237
 
  if (upper > lower)
238
 
    {
239
 
      //chose a random element (this avoids n^2 worst case)
240
 
      int element = int ( (double)rand() / (double)RAND_MAX * (upper - lower) + lower);
241
 
      swapRows(element, upper);
242
 
      v = text(upper, col);
243
 
      i = lower - 1;
244
 
      j = upper;
245
 
      for (;;)
246
 
      {
247
 
          while (compareItems(text(++i, col), v, ascending, alphanumeric) == -1);
248
 
          while (compareItems(text(--j, col), v, ascending, alphanumeric) == 1 && j > 0); //make sure that j does not get negative
249
 
          if (i >= j)
250
 
            {
251
 
              break;
252
 
            }
253
 
          swapRows(i, j);
254
 
        }
255
 
      swapRows(i, upper);
256
 
      qsort(lower, i - 1, col, ascending, alphanumeric);
257
 
      qsort(i + 1, upper, col, ascending, alphanumeric);
258
 
    }
259
 
}
260
 
 
261
 
void QgsAttributeTable::contentsMouseReleaseEvent(QMouseEvent * e)
262
 
{
263
 
  contentsMouseMoveEvent(e);    //send out a move event to keep the selections updated 
264
 
  emit repaintRequested();
265
 
}
266
 
 
267
 
void QgsAttributeTable::popupMenu(int row, int col, const QPoint& pos)
268
 
{
269
 
  std::cerr << "context menu requested" << std::endl;
270
 
 
271
 
  // Duplication of code in qgsidentufyresults.cpp. Consider placing
272
 
  // in a seperate class
273
 
  if (mActionPopup == 0)
274
 
  {
275
 
    mActionPopup = new QPopupMenu();
276
 
 
277
 
    QLabel* popupLabel = new QLabel( mActionPopup );
278
 
    popupLabel->setText( tr("<center>Run action</center>") );
279
 
    mActionPopup->insertItem(popupLabel);
280
 
    mActionPopup->insertSeparator();
281
 
 
282
 
    QgsAttributeAction::aIter   iter = mActions.begin();
283
 
    for (int j = 0; iter != mActions.end(); ++iter, ++j)
284
 
    {
285
 
      int id = mActionPopup->insertItem(iter->name(), this, 
286
 
                                        SLOT(popupItemSelected(int)));
287
 
      mActionPopup->setItemParameter(id, j);
288
 
    }
289
 
  }
290
 
 
291
 
  // Get and store the attribute values and their column names are
292
 
  // these are needed for substituting into the actions if the user
293
 
  // chooses one.
294
 
  mActionValues.clear();
295
 
  QHeader* header = horizontalHeader();
296
 
 
297
 
#ifdef QGISDEBUG
298
 
  if (header->count() != numCols())
299
 
    std::cerr << "Something wrong with the table (file " 
300
 
              << __FILE__<< ", line " << __LINE__ 
301
 
              << ")." << std::endl;
302
 
#endif
303
 
 
304
 
  for (int i = 0; i < numCols(); ++i)
305
 
    mActionValues.push_back(std::make_pair(header->label(i), text(row, i)));
306
 
 
307
 
  // The item that was clicked on, stored as an index into the
308
 
  // mActionValues vector.
309
 
  mClickedOnValue = col;
310
 
 
311
 
  mActionPopup->popup(pos);  
312
 
}
313
 
 
314
 
void QgsAttributeTable::popupItemSelected(int id)
315
 
{
316
 
  mActions.doAction(id, mActionValues, mClickedOnValue);
317
 
}
318
 
 
319
 
bool QgsAttributeTable::addAttribute(const QString& name, const QString& type)
320
 
{
321
 
    //first test if an attribute with the same name is already in the table
322
 
    for(int i=0;i<horizontalHeader()->count();++i)
323
 
    {
324
 
        if(horizontalHeader()->label(i)==name)
325
 
        {
326
 
            //name conflict
327
 
            return false;
328
 
        }
329
 
    }
330
 
    mAddedAttributes.insert(std::make_pair(name,type));
331
 
#ifdef QGISDEBUG
332
 
    qWarning(("inserting attribute "+name+" of type "+type).local8Bit());
333
 
    //add a new column at the end of the table
334
 
    qWarning(("numCols: "+QString::number(numCols())).local8Bit());
335
 
#endif
336
 
    insertColumns(numCols());
337
 
    horizontalHeader()->setLabel(numCols()-1,name);
338
 
    mEdited=true;
339
 
    return true;
340
 
}
341
 
 
342
 
void QgsAttributeTable::deleteAttribute(const QString& name)
343
 
{
344
 
    //check, if there is already an attribute with this name in mAddedAttributes
345
 
    std::map<QString,QString>::iterator iter=mAddedAttributes.find(name);
346
 
    if(iter!=mAddedAttributes.end())
347
 
    {
348
 
        mAddedAttributes.erase(iter);
349
 
        removeAttrColumn(name);
350
 
    }
351
 
    else
352
 
    {
353
 
#ifdef QGISDEBUG
354
 
        qWarning(("QgsAttributeTable: deleteAttribute "+name).local8Bit());
355
 
#endif
356
 
        mDeletedAttributes.insert(name);
357
 
        removeAttrColumn(name);
358
 
    }
359
 
    mEdited=true;
360
 
}
361
 
 
362
 
bool QgsAttributeTable::commitChanges(QgsVectorLayer* layer)
363
 
{
364
 
    bool returnvalue=true;
365
 
    if(layer)
366
 
    {
367
 
        if(!layer->commitAttributeChanges(mDeletedAttributes, mAddedAttributes, mChangedValues))
368
 
        {
369
 
            returnvalue=false;
370
 
        }
371
 
    }
372
 
    else
373
 
    {
374
 
        returnvalue=false;
375
 
    }
376
 
    mEdited=false;
377
 
    clearEditingStructures();
378
 
    return returnvalue;
379
 
}
380
 
 
381
 
bool QgsAttributeTable::rollBack(QgsVectorLayer* layer)
382
 
{
383
 
    if(layer)
384
 
    {
385
 
        layer->fillTable(this);
386
 
    }
387
 
    mEdited=false;
388
 
    clearEditingStructures();
389
 
    return true;
390
 
}
391
 
 
392
 
//todo: replace some of the lines in QgsVectorLayer::table() with this function
393
 
void QgsAttributeTable::fillTable(QgsVectorLayer* layer)
394
 
{
395
 
    QgsVectorDataProvider* provider=layer->getDataProvider();
396
 
    if(provider)
397
 
    {
398
 
        int row = 0;
399
 
        // set up the column headers
400
 
        QHeader *colHeader = horizontalHeader();
401
 
        colHeader->setLabel(0, "id"); //label for the id-column
402
 
        std::vector < QgsField > fields = provider->fields();
403
 
        int fieldcount=provider->fieldCount();
404
 
        setNumCols(fieldcount+1);
405
 
 
406
 
        for (int h = 1; h <= fieldcount; h++)
407
 
        {
408
 
            colHeader->setLabel(h, fields[h - 1].name());
409
 
#ifdef QGISDEBUG
410
 
            qWarning(("Setting column label "+fields[h - 1].name()).local8Bit());
411
 
#endif
412
 
        }
413
 
        QgsFeature *fet;
414
 
        provider->reset();
415
 
        while ((fet = provider->getNextFeature(true)))
416
 
        {
417
 
            //id-field
418
 
            setText(row, 0, QString::number(fet->featureId()));
419
 
            insertFeatureId(fet->featureId(), row);  //insert the id into the search tree of qgsattributetable
420
 
            std::vector < QgsFeatureAttribute > attr = fet->attributeMap();
421
 
            for (int i = 0; i < attr.size(); i++)
422
 
            {
423
 
                // get the field values
424
 
                setText(row, i + 1, attr[i].fieldValue());
425
 
#ifdef QGISDEBUG
426
 
                //qWarning("Setting value for "+QString::number(i+1)+"//"+QString::number(row)+"//"+attr[i].fieldValue());
427
 
#endif
428
 
            }
429
 
            row++;
430
 
            delete fet;
431
 
        }
432
 
    }
433
 
}
434
 
 
435
 
void QgsAttributeTable::storeChangedValue(int row, int column)
436
 
{
437
 
    //id column is not editable
438
 
    if(column>0)
439
 
    {
440
 
        //find feature id
441
 
        int id=text(row,0).toInt();
442
 
        QString attribute=horizontalHeader()->label(column);
443
 
#ifdef QGISDEBUG
444
 
        qWarning(("feature id: "+QString::number(id)).local8Bit());
445
 
        qWarning(("attribute: "+attribute).local8Bit());
446
 
#endif
447
 
        std::map<int,std::map<QString,QString> >::iterator iter=mChangedValues.find(id);
448
 
        if(iter==mChangedValues.end())
449
 
        {
450
 
            std::map<QString,QString> themap;
451
 
            mChangedValues.insert(std::make_pair(id,themap));
452
 
            iter=mChangedValues.find(id);
453
 
        }
454
 
        iter->second.erase(attribute);
455
 
        iter->second.insert(std::make_pair(attribute,text(row,column)));
456
 
#ifdef QGISDEBUG
457
 
        qWarning(("value: "+text(row,column)).local8Bit());
458
 
#endif  
459
 
        mEdited=true;
460
 
    }
461
 
}
462
 
 
463
 
void QgsAttributeTable::clearEditingStructures()
464
 
{
465
 
    mDeletedAttributes.clear();
466
 
    mAddedAttributes.clear();
467
 
    for(std::map<int,std::map<QString,QString> >::iterator iter=mChangedValues.begin();iter!=mChangedValues.end();++iter)
468
 
    {
469
 
        iter->second.clear();
470
 
    }
471
 
    mChangedValues.clear();
472
 
}
473
 
 
474
 
void QgsAttributeTable::removeAttrColumn(const QString& name)
475
 
{
476
 
    QHeader* header=horizontalHeader();
477
 
    for(int i=0;i<header->count();++i)
478
 
    {
479
 
        if(header->label(i)==name)
480
 
        {
481
 
            removeColumn(i);
482
 
            break;
483
 
        }
484
 
    }
485
 
}
486
 
 
487
 
void QgsAttributeTable::bringSelectedToTop()
488
 
{
489
 
    blockSignals(true);
490
 
    int swaptorow=0;
491
 
    std::list<QTableSelection> selections;
492
 
    bool removeselection;
493
 
 
494
 
    for(int i=0;i<numSelections();++i)
495
 
    {
496
 
        selections.push_back(selection(i));
497
 
    }
498
 
 
499
 
    QTableSelection sel;  
500
 
 
501
 
    for(std::list<QTableSelection>::iterator iter=selections.begin();iter!=selections.end();++iter)
502
 
    {
503
 
        removeselection=true;
504
 
        while(isRowSelected(swaptorow, true))//selections are not necessary stored in ascending order
505
 
            {
506
 
                ++swaptorow;
507
 
            }
508
 
        
509
 
        for(int j=iter->topRow();j<=iter->bottomRow();++j)
510
 
        {   
511
 
            if(j>swaptorow)//selections are not necessary stored in ascending order
512
 
            {
513
 
                swapRows(j,swaptorow);
514
 
                selectRow(swaptorow);
515
 
                ++swaptorow;    
516
 
                
517
 
            }
518
 
            else
519
 
            {
520
 
                removeselection=false;//keep selection
521
 
            }
522
 
        }
523
 
        if(removeselection)
524
 
        {           
525
 
            removeSelection(*iter);
526
 
        }
527
 
    }
528
 
 
529
 
    //clear and rebuild rowIdMap.
530
 
    rowIdMap.clear();
531
 
    int id;
532
 
    for (int i = 0; i < numRows(); i++)
533
 
    {
534
 
      id = text(i, 0).toInt();
535
 
      rowIdMap.insert(id, i);
536
 
    }
537
 
 
538
 
    blockSignals(false);
539
 
}