QGIS API Documentation  2.3.0-Master
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
qgsnewvectorlayerdialog.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsnewvectorlayerdialog.cpp - description
3  -------------------
4  begin : October 2004
5  copyright : (C) 2004 by Marco Hugentobler
6  email : marco.hugentobler@autoform.ch
7  ***************************************************************************/
8 
9 /***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
19 #include "qgsapplication.h"
20 #include "qgis.h"
21 #include "qgslogger.h"
24 #include "qgsproviderregistry.h"
25 #include "qgsvectordataprovider.h"
26 #include "qgsvectorfilewriter.h"
27 
28 #include <QPushButton>
29 #include <QComboBox>
30 #include <QLibrary>
31 #include <QSettings>
32 #include <QFileDialog>
33 
34 
35 QgsNewVectorLayerDialog::QgsNewVectorLayerDialog( QWidget *parent, Qt::WindowFlags fl )
36  : QDialog( parent, fl )
37 {
38  setupUi( this );
39 
40  QSettings settings;
41  restoreGeometry( settings.value( "/Windows/NewVectorLayer/geometry" ).toByteArray() );
42 
43  mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( "/mActionNewAttribute.png" ) );
44  mRemoveAttributeButton->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteAttribute.png" ) );
45  mTypeBox->addItem( tr( "Text data" ), "String" );
46  mTypeBox->addItem( tr( "Whole number" ), "Integer" );
47  mTypeBox->addItem( tr( "Decimal number" ), "Real" );
48  mTypeBox->addItem( tr( "Date" ), "Date" );
49 
50  mWidth->setValidator( new QIntValidator( 1, 255, this ) );
51  mPrecision->setValidator( new QIntValidator( 0, 15, this ) );
52 
53  mPointRadioButton->setChecked( true );
54  mFileFormatComboBox->addItem( tr( "ESRI Shapefile" ), "ESRI Shapefile" );
55 #if 0
56  // Disabled until provider properly supports editing the created file formats
57  mFileFormatComboBox->addItem( tr( "Comma Separated Value" ), "Comma Separated Value" );
58  mFileFormatComboBox->addItem( tr( "GML" ), "GML" );
59  mFileFormatComboBox->addItem( tr( "Mapinfo File" ), "Mapinfo File" );
60 #endif
61  if ( mFileFormatComboBox->count() == 1 )
62  {
63  mFileFormatComboBox->setVisible( false );
64  mFileFormatLabel->setVisible( false );
65  }
66 
67  mFileEncoding->addItems( QgsVectorDataProvider::availableEncodings() );
68 
69  // Use default encoding if none supplied
70  QString enc = QSettings().value( "/UI/encoding", "System" ).toString();
71 
72  // The specified decoding is added if not existing alread, and then set current.
73  // This should select it.
74  int encindex = mFileEncoding->findText( enc );
75  if ( encindex < 0 )
76  {
77  mFileEncoding->insertItem( 0, enc );
78  encindex = 0;
79  }
80  mFileEncoding->setCurrentIndex( encindex );
81 
82  mOkButton = buttonBox->button( QDialogButtonBox::Ok );
83 
84  mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << "id" << "Integer" << "10" << "" ) );
85 
87 
88  srs.createFromOgcWmsCrs( settings.value( "/Projections/layerDefaultCrs", GEO_EPSG_CRS_AUTHID ).toString() );
89  srs.validate();
90 
91  mCrsId = srs.srsid();
92  leSpatialRefSys->setText( srs.authid() + " - " + srs.description() );
93 
94  connect( mNameEdit, SIGNAL( textChanged( QString ) ), this, SLOT( nameChanged( QString ) ) );
95  connect( mAttributeView, SIGNAL( itemSelectionChanged() ), this, SLOT( selectionChanged() ) );
96 
97  mAddAttributeButton->setEnabled( false );
98  mRemoveAttributeButton->setEnabled( false );
99 }
100 
102 {
103  QSettings settings;
104  settings.setValue( "/Windows/NewVectorLayer/geometry", saveGeometry() );
105 }
106 
108 {
109  // FIXME: sync with providers/ogr/qgsogrprovider.cpp
110  switch ( index )
111  {
112  case 0: // Text data
113  if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 255 )
114  mWidth->setText( "80" );
115  mPrecision->setEnabled( false );
116  mWidth->setValidator( new QIntValidator( 1, 255, this ) );
117  break;
118 
119  case 1: // Whole number
120  if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 10 )
121  mWidth->setText( "10" );
122  mPrecision->setEnabled( false );
123  mWidth->setValidator( new QIntValidator( 1, 10, this ) );
124  break;
125 
126  case 2: // Decimal number
127  if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 20 )
128  mWidth->setText( "20" );
129  mPrecision->setEnabled( true );
130  mWidth->setValidator( new QIntValidator( 1, 20, this ) );
131  break;
132 
133  default:
134  QgsDebugMsg( "unexpected index" );
135  break;
136  }
137 }
138 
140 {
141  if ( mPointRadioButton->isChecked() )
142  {
143  return QGis::WKBPoint;
144  }
145  else if ( mLineRadioButton->isChecked() )
146  {
147  return QGis::WKBLineString;
148  }
149  else if ( mPolygonRadioButton->isChecked() )
150  {
151  return QGis::WKBPolygon;
152  }
153  return QGis::WKBUnknown;
154 }
155 
157 {
158  return mCrsId;
159 }
160 
162 {
163  QString myName = mNameEdit->text();
164  QString myWidth = mWidth->text();
165  QString myPrecision = mPrecision->isEnabled() ? mPrecision->text() : "";
166  //use userrole to avoid translated type string
167  QString myType = mTypeBox->itemData( mTypeBox->currentIndex(), Qt::UserRole ).toString();
168  mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << myName << myType << myWidth << myPrecision ) );
169  if ( mAttributeView->topLevelItemCount() > 0 )
170  {
171  mOkButton->setEnabled( true );
172  }
173  mNameEdit->clear();
174 }
175 
177 {
178  delete mAttributeView->currentItem();
179  if ( mAttributeView->topLevelItemCount() == 0 )
180  {
181  mOkButton->setEnabled( false );
182  }
183 }
184 
186 {
188  mySelector->setMessage();
189  mySelector->setSelectedCrsId( mCrsId );
190  if ( mySelector->exec() )
191  {
193  srs.createFromOgcWmsCrs( mySelector->selectedAuthId() );
194  mCrsId = srs.srsid();
195  leSpatialRefSys->setText( srs.authid() + " - " + srs.description() );
196  }
197  else
198  {
199  QApplication::restoreOverrideCursor();
200  }
201  delete mySelector;
202 }
203 
204 void QgsNewVectorLayerDialog::attributes( QList< QPair<QString, QString> >& at ) const
205 {
206  QTreeWidgetItemIterator it( mAttributeView );
207  while ( *it )
208  {
209  QTreeWidgetItem *item = *it;
210  QString type = QString( "%1;%2;%3" ).arg( item->text( 1 ) ).arg( item->text( 2 ) ).arg( item->text( 3 ) );
211  at.push_back( qMakePair( item->text( 0 ), type ) );
212  QgsDebugMsg( QString( "appending %1//%2" ).arg( item->text( 0 ) ).arg( type ) );
213  ++it;
214  }
215 }
216 
218 {
219  //use userrole to avoid translated type string
220  QString myType = mFileFormatComboBox->itemData( mFileFormatComboBox->currentIndex(), Qt::UserRole ).toString();
221  return myType;
222 }
223 
225 {
226  return mFileEncoding->currentText();
227 }
228 
230 {
231  mAddAttributeButton->setDisabled( name.isEmpty() || mAttributeView->findItems( name, Qt::MatchExactly ).size() > 0 );
232 }
233 
235 {
236  mRemoveAttributeButton->setDisabled( mAttributeView->selectedItems().size() == 0 );
237 }
238 
239 
240 // this is static
241 QString QgsNewVectorLayerDialog::runAndCreateLayer( QWidget* parent, QString* pEnc )
242 {
243  QgsNewVectorLayerDialog geomDialog( parent );
244  if ( geomDialog.exec() == QDialog::Rejected )
245  {
246  return QString();
247  }
248 
249  QGis::WkbType geometrytype = geomDialog.selectedType();
250  QString fileformat = geomDialog.selectedFileFormat();
251  QString enc = geomDialog.selectedFileEncoding();
252  int crsId = geomDialog.selectedCrsId();
253  QgsDebugMsg( QString( "New file format will be: %1" ).arg( fileformat ) );
254 
255  QList< QPair<QString, QString> > attributes;
256  geomDialog.attributes( attributes );
257 
258  QSettings settings;
259  QString lastUsedDir = settings.value( "/UI/lastVectorFileFilterDir", "." ).toString();
260  QString filterString = QgsVectorFileWriter::filterForDriver( fileformat );
261  QString fileName = QFileDialog::getSaveFileName( 0, tr( "Save layer as..." ), lastUsedDir, filterString );
262  if ( fileName.isNull() )
263  {
264  return fileName;
265  }
266 
267  if ( fileformat == "ESRI Shapefile" && !fileName.endsWith( ".shp", Qt::CaseInsensitive ) )
268  fileName += ".shp";
269 
270  settings.setValue( "/UI/lastVectorFileFilterDir", QFileInfo( fileName ).absolutePath() );
271  settings.setValue( "/UI/encoding", enc );
272 
273  //try to create the new layer with OGRProvider instead of QgsVectorFileWriter
275  QString ogrlib = pReg->library( "ogr" );
276  // load the data provider
277  QLibrary* myLib = new QLibrary( ogrlib );
278  bool loaded = myLib->load();
279  if ( loaded )
280  {
281  QgsDebugMsg( "ogr provider loaded" );
282 
283  typedef bool ( *createEmptyDataSourceProc )( const QString&, const QString&, const QString&, QGis::WkbType,
284  const QList< QPair<QString, QString> >&, const QgsCoordinateReferenceSystem * );
285  createEmptyDataSourceProc createEmptyDataSource = ( createEmptyDataSourceProc ) cast_to_fptr( myLib->resolve( "createEmptyDataSource" ) );
286  if ( createEmptyDataSource )
287  {
288  if ( geometrytype != QGis::WKBUnknown )
289  {
291  if ( !createEmptyDataSource( fileName, fileformat, enc, geometrytype, attributes, &srs ) )
292  {
293  return QString();
294  }
295  }
296  else
297  {
298  QgsDebugMsg( "geometry type not recognised" );
299  return QString();
300  }
301  }
302  else
303  {
304  QgsDebugMsg( "Resolving newEmptyDataSource(...) failed" );
305  return QString();
306  }
307  }
308 
309  if ( pEnc )
310  *pEnc = enc;
311  return fileName;
312 }
static unsigned index
QString selectedFileEncoding() const
Returns the file format for storage.
void on_mTypeBox_currentIndexChanged(int index)
static QgsProviderRegistry * instance(QString pluginPath=QString::null)
means of accessing canonical single instance
#define QgsDebugMsg(str)
Definition: qgslogger.h:36
QString library(const QString &providerKey) const
Return path for the library of the provider.
static QIcon getThemeIcon(const QString &theName)
Helper to get a theme icon.
A generic dialog to prompt the user for a Coordinate Reference System.
int selectedCrsId() const
Returns the selected crs id.
WkbType
Used for symbology operations.
Definition: qgis.h:53
QString selectedFileFormat() const
Returns the file format for storage.
static const QStringList & availableEncodings()
Returns a list of available encodings.
bool createFromOgcWmsCrs(QString theCrs)
Set up this CRS from the given OGC CRS.
static QString runAndCreateLayer(QWidget *parent=0, QString *enc=0)
void setMessage(QString theMessage="")
If no parameter is passed, the message will be a generic 'define the CRS for this layer'...
A registry / canonical manager of data providers.
QgsNewVectorLayerDialog(QWidget *parent=0, Qt::WindowFlags fl=QgisGui::ModalDialogFlags)
void attributes(QList< QPair< QString, QString > > &at) const
Appends the chosen attribute names and types to at.
QGis::WkbType selectedType() const
Returns the selected geometry type.
Class for storing a coordinate reference system (CRS)
void(*)() cast_to_fptr(void *p)
Definition: qgis.h:301
static QString filterForDriver(const QString &driverName)
Creates a filter for an OGR driver key.
const CORE_EXPORT QString GEO_EPSG_CRS_AUTHID
Geographic coord sys from EPSG authority.
Definition: qgis.cpp:71
#define tr(sourceText)