-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
main.cpp
591 lines (505 loc) · 18.8 KB
/
main.cpp
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/***************************************************************************
main.cpp - description
-------------------
begin : Fri Jun 21 10:48:28 AKDT 2002
copyright : (C) 2002 by Gary E.Sherman
email : sherman at mrcc.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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/* $Id$ */
//qt includes
#include <QBitmap>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFont>
#include <QMessageBox>
#include <QPixmap>
#include <QPixmap>
#include <QSettings>
#include <QSplashScreen>
#include <QString>
#include <QStringList>
#include <QStyle>
#include <QTextCodec>
#include <QTranslator>
#include <iostream>
#include <cstdio>
#include <stdio.h>
#include <stdlib.h>
#ifdef WIN32
// Open files in binary mode
#include <fcntl.h> /* _O_BINARY */
#undef _fmode
int _fmode = _O_BINARY;
#else
#include <getopt.h>
#endif
#ifdef Q_OS_MACX
#include <ApplicationServices/ApplicationServices.h>
#endif
#include "qgisapp.h"
#include "qgsapplication.h"
#include <qgsconfig.h>
#include "qgsexception.h"
#include "qgsproject.h"
static const char * const ident_ = "$Id$";
/** print usage text
*/
void usage( std::string const & appName )
{
std::cerr << "Quantum GIS - " << VERSION << " 'Simon'\n"
<< "Quantum GIS (QGIS) is a viewer for spatial data sets, including\n"
<< "raster and vector data.\n"
<< "Usage: " << appName << " [options] [FILES]\n"
<< " options:\n"
<< "\t[--snapshot filename]\temit snapshot of loaded datasets to given file\n"
<< "\t[--lang language]\tuse language for interface text\n"
<< "\t[--project projectfile]\tload the given QGIS project\n"
<< "\t[--extent xmin,ymin,xmax,ymax]\tset initial map extent\n"
<< "\t[--help]\t\tthis text\n\n"
<< " FILES:\n"
<< " Files specified on the command line can include rasters,\n"
<< " vectors, and QGIS project files (.qgs): \n"
<< " 1. Rasters - Supported formats include GeoTiff, DEM \n"
<< " and others supported by GDAL\n"
<< " 2. Vectors - Supported formats include ESRI Shapefiles\n"
<< " and others supported by OGR and PostgreSQL layers using\n"
<< " the PostGIS extension\n" ;
} // usage()
/////////////////////////////////////////////////////////////////
// Command line options 'behaviour' flag setup
////////////////////////////////////////////////////////////////
// These two are global so that they can be set by the OpenDocuments
// AppleEvent handler as well as by the main routine argv processing
// This behaviour will cause QGIS to autoload a project
static QString myProjectFileName="";
// This is the 'leftover' arguments collection
static QStringList myFileList;
#ifdef Q_OS_MACX
/* Mac OS OpenDocuments AppleEvent handler called when files are double-clicked.
* May be called at startup before application is initialized as well as
* at any time while the application is running.
*/
short openDocumentsAEHandler(const AppleEvent *event, AppleEvent *reply, long refCon)
{
AEDescList docs;
if (AEGetParamDesc(event, keyDirectObject, typeAEList, &docs) == noErr)
{
// Get count of files to open
long count = 0;
AECountItems(&docs, &count);
// Examine files and load first project file followed by all other non-project files
myProjectFileName.truncate(0);
myFileList.clear();
for (int i = 0; i < count; i++)
{
FSRef ref;
UInt8 strBuffer[256];
if (AEGetNthPtr(&docs, i + 1, typeFSRef, 0, 0, &ref, sizeof(ref), 0) == noErr &&
FSRefMakePath(&ref, strBuffer, 256) == noErr)
{
QString fileName(QString::fromUtf8(reinterpret_cast<char *>(strBuffer)));
if (fileName.endsWith(".qgs"))
{
// Load first project file and ignore all other project files
if (myProjectFileName.isEmpty())
{
myProjectFileName = fileName;
}
}
else
{
// Load all non-project files
myFileList.append(fileName);
}
}
}
// Open files now if application has been initialized
QgisApp *qgis = dynamic_cast<QgisApp *>(qApp->mainWidget());
if (qgis)
{
if (!myProjectFileName.isEmpty())
{
qgis->openProject(myProjectFileName);
}
for (QStringList::Iterator myIterator = myFileList.begin();
myIterator != myFileList.end(); ++myIterator )
{
QString fileName = *myIterator;
qgis->openLayer(fileName);
}
}
}
return noErr;
}
#endif
/* Test to determine if this program was started on Mac OS X by double-clicking
* the application bundle rather then from a command line. If clicked, argv[1]
* contains a process serial number in the form -psn_0_1234567. Don't process
* the command line arguments in this case because argv[1] confuses the processing.
*/
bool bundleclicked(int argc, char *argv[])
{
return ( argc > 1 && memcmp(argv[1], "-psn_", 5) == 0 );
}
/*
* Hook into the qWarning/qFatal mechanism so that we can channel messages
* from libpng to the user.
*
* Some JPL WMS images tend to overload the libpng 1.2.2 implementation
* somehow (especially when zoomed in)
* and it would be useful for the user to know why their picture turned up blank
*
* Based on qInstallMsgHandler example code in the Qt documentation.
*
*/
void myMessageOutput( QtMsgType type, const char *msg )
{
switch ( type ) {
case QtDebugMsg:
fprintf( stderr, "Debug: %s\n", msg );
break;
case QtWarningMsg:
fprintf( stderr, "Warning: %s\n", msg );
// TODO: Verify this code in action.
if ( 0 == strncmp(msg, "libpng error:", 13) )
{
// Let the user know
QMessageBox::warning( 0, "libpng Error",
msg,
QMessageBox::Ok,
Qt::NoButton);
}
break;
case QtFatalMsg:
fprintf( stderr, "Fatal: %s\n", msg );
abort(); // deliberately core dump
}
}
int main(int argc, char *argv[])
{
// Set up the custom qWarning/qDebug custom handler
qInstallMsgHandler( myMessageOutput );
/////////////////////////////////////////////////////////////////
// Command line options 'behaviour' flag setup
////////////////////////////////////////////////////////////////
//
// Parse the command line arguments, looking to see if the user has asked for any
// special behaviours. Any remaining non command arguments will be kept aside to
// be passed as a list of layers and / or a project that should be loaded.
//
// This behaviour is used to load the app, snapshot the map,
// save the image to disk and then exit
QString mySnapshotFileName="";
// This behaviour will set initial extent of map canvas
QString myInitialExtent="";
// This behaviour will allow you to force the use of a translation file
// which is useful for testing
QString myTranslationCode="";
#ifndef WIN32
if ( !bundleclicked(argc, argv) )
{
////////////////////////////////////////////////////////////////
// USe the GNU Getopts utility to parse cli arguments
// Invokes ctor `GetOpt (int argc, char **argv, char *optstring);'
///////////////////////////////////////////////////////////////
int optionChar;
while (1)
{
static struct option long_options[] =
{
/* These options set a flag. */
{"help", no_argument, 0, 'h'},
/* These options don't set a flag.
* We distinguish them by their indices. */
{"snapshot", required_argument, 0, 's'},
{"lang", required_argument, 0, 'l'},
{"project", required_argument, 0, 'p'},
{"extent", required_argument, 0, 'e'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
optionChar = getopt_long (argc, argv, "slpe",
long_options, &option_index);
/* Detect the end of the options. */
if (optionChar == -1)
break;
switch (optionChar)
{
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case 's':
mySnapshotFileName = QDir::convertSeparators(QFileInfo(QFile::decodeName(optarg)).absFilePath());
break;
case 'l':
myTranslationCode = optarg;
break;
case 'p':
myProjectFileName = QDir::convertSeparators(QFileInfo(QFile::decodeName(optarg)).absFilePath());
break;
case 'e':
myInitialExtent = optarg;
break;
case 'h':
case '?':
usage( argv[0] );
return 2; // XXX need standard exit codes
break;
default:
std::cerr << argv[0] << ": getopt returned character code " << optionChar << "\n";
return 1; // XXX need standard exit codes
}
}
// Add any remaining args to the file list - we will attempt to load them
// as layers in the map view further down....
#ifdef QGISDEBUG
std::cout << "Files specified on command line: " << optind << std::endl;
#endif
if (optind < argc)
{
while (optind < argc)
{
#ifdef QGISDEBUG
int idx = optind;
std::cout << idx << ": " << argv[idx] << std::endl;
#endif
myFileList.append(QDir::convertSeparators(QFileInfo(QFile::decodeName(argv[optind++])).absFilePath()));
}
}
}
#endif //WIN32
/////////////////////////////////////////////////////////////////////
// Now we have the handlers for the different behaviours...
////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// Initialise the application and the translation stuff
/////////////////////////////////////////////////////////////////////
#ifdef Q_WS_X11
bool myUseGuiFlag = getenv( "DISPLAY" ) != 0;
#else
bool myUseGuiFlag = TRUE;
#endif
if (!myUseGuiFlag)
{
std::cerr << "QGIS starting in non-interactive mode not supported.\n You are seeing this message most likely because you have no DISPLAY environment variable set." << std::endl;
exit(1); //exit for now until a version of qgis is capabable of running non interactive
}
QgsApplication a(argc, argv, myUseGuiFlag );
//
// Set up the QSettings environment must be done after qapp is created
QCoreApplication::setOrganizationName("QuantumGIS");
QCoreApplication::setOrganizationDomain("qgis.org");
QCoreApplication::setApplicationName("qgis");
#ifdef Q_OS_MACX
// Install OpenDocuments AppleEvent handler after application object is initialized
// but before any other event handling (including dialogs or splash screens) occurs.
// If an OpenDocuments event has been created before the application was launched,
// it must be handled before some other event handler runs and dismisses it as unknown.
// If run at startup, the handler will set either or both of myProjectFileName and myFileList.
AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments, openDocumentsAEHandler, 0, false);
// If the QtCore framework is bundled with the application, clear the library search path
// and look for Qt plugins only within the application bundle.
QString bundledQtCore(QCoreApplication::applicationDirPath().append("/lib/QtCore.framework"));
if (QFile::exists(bundledQtCore))
{
QCoreApplication::setLibraryPaths(QStringList(QCoreApplication::applicationDirPath()));
}
#endif
// Check to see if qgis was started from the source directory.
// This is done by looking for Makefile in the directory where qgis was
// started from. If running from the src directory, exit gracefully
// Get the application path. This method is required to support qt 3.1.2
// which does not support the applicationFilePath and applicationDirPath
// functions. We assume that OS X and Win32 systems will be using at least
// Qt 3.2 and therefore support the required functions.
#if defined(Q_OS_MACX) || defined(WIN32)
QString appPath = qApp->applicationFilePath();
QString appDir = qApp->applicationDirPath();
QString testFile = "libqgis.la";
#else
QString appPath = argv[0];
QString appDir = appPath.left(appPath.findRev("/"));
QString testFile = "lt-qgis";
#endif
if(appPath.contains("/src/"))
{
// check to see if configure is present in the directory
QFileInfo fi(appDir + "/" + testFile);
if(fi.exists())
{
QMessageBox::critical(0,"QGIS Not Installed",
"You appear to be running QGIS from the source directory.\n"
"You must install QGIS using make install and run it from the "
"installed directory.");
exit(1);
}
}
// a.setFont(QFont("helvetica", 11));
QString i18nPath = QgsApplication::i18nPath();
if (myTranslationCode.isEmpty())
{
myTranslationCode = QTextCodec::locale();
}
#ifdef QGISDEBUG
std::cout << "Setting translation to "
<< i18nPath.toLocal8Bit().data() << "/qgis_" << myTranslationCode.toLocal8Bit().data() << std::endl;
#endif
/* Translation file for Qt.
* The strings from the QMenuBar context section are used by Qt/Mac to shift
* the About, Preferences and Quit items to the Mac Application menu.
* These items must be translated identically in both qt_ and qgis_ files.
*/
QTranslator qttor(0);
if (qttor.load(QString("qt_") + myTranslationCode, i18nPath))
{
a.installTranslator(&qttor);
}
/* Translation file for QGIS.
*/
QTranslator qgistor(0);
if (qgistor.load(QString("qgis_") + myTranslationCode, i18nPath))
{
a.installTranslator(&qgistor);
}
//set up splash screen
QString mySplashPath(QgsApplication::splashPath());
QPixmap myPixmap(mySplashPath+QString("splash.png"));
QSplashScreen *mypSplash = new QSplashScreen(myPixmap);
QSettings mySettings;
if (mySettings.value("/qgis/hideSplash").toBool())
{
//splash screen hidden
}
else
{
QPixmap myMaskPixmap(mySplashPath+QString("splash_mask.png"), 0, Qt::ThresholdDither | Qt::ThresholdAlphaDither | Qt::AvoidDither );
mypSplash->setMask( myMaskPixmap.createHeuristicMask() );
mypSplash->show();
}
QgisApp *qgis = new QgisApp(mypSplash); // "QgisApp" used to find canonical instance
qgis->setName( "QgisApp" );
/////////////////////////////////////////////////////////////////////
// If no --project was specified, parse the args to look for a //
// .qgs file and set myProjectFileName to it. This allows loading //
// of a project file by clicking on it in various desktop managers //
// where an appropriate mime-type has been set up. //
/////////////////////////////////////////////////////////////////////
if(myProjectFileName.isEmpty())
{
// check for a .qgs
for(int i = 0; i < argc; i++)
{
QString arg = QDir::convertSeparators(QFileInfo(QFile::decodeName(argv[i])).absFilePath());
if(arg.contains(".qgs"))
{
myProjectFileName = arg;
break;
}
}
}
/////////////////////////////////////////////////////////////////////
// Load a project file if one was specified
/////////////////////////////////////////////////////////////////////
if( ! myProjectFileName.isEmpty() )
{
qgis->openProject(myProjectFileName);
}
/////////////////////////////////////////////////////////////////////
// autoload any filenames that were passed in on the command line
/////////////////////////////////////////////////////////////////////
#ifdef QGISDEBUG
std::cout << "Number of files in myFileList: " << myFileList.count() << std::endl;
#endif
for ( QStringList::Iterator myIterator = myFileList.begin(); myIterator != myFileList.end(); ++myIterator )
{
#ifdef QGISDEBUG
std::cout << "Trying to load file : " << (*myIterator).toLocal8Bit().data() << std::endl;
#endif
QString myLayerName = *myIterator;
// don't load anything with a .qgs extension - these are project files
if(!myLayerName.contains(".qgs"))
{
qgis->openLayer(myLayerName);
}
}
/////////////////////////////////////////////////////////////////////
// Set initial extent if requested
/////////////////////////////////////////////////////////////////////
if ( ! myInitialExtent.isEmpty() )
{
double coords[4];
int pos, posOld = 0;
bool ok;
// XXX is it necessary to switch to "C" locale?
// parse values from string
// extent is defined by string "xmin,ymin,xmax,ymax"
for (int i = 0; i < 3; i++)
{
// find comma and get coordinate
pos = myInitialExtent.find(',', posOld);
if (pos == -1) {
ok = false; break;
}
coords[i] = QString( myInitialExtent.mid(posOld, pos - posOld) ).toDouble(&ok);
if (!ok)
break;
posOld = pos+1;
}
// parse last coordinate
if (ok)
coords[3] = QString( myInitialExtent.mid(posOld) ).toDouble(&ok);
if (!ok)
std::cout << "Error while parsing initial extent!" << std::endl;
else
{
// set extent from parsed values
QgsRect rect(coords[0],coords[1],coords[2],coords[3]);
qgis->setExtent(rect);
}
}
/////////////////////////////////////////////////////////////////////
// Take a snapshot of the map view then exit if snapshot mode requested
/////////////////////////////////////////////////////////////////////
if(mySnapshotFileName!="")
{
/*You must have at least one paintEvent() delivered for the window to be
rendered properly.
It looks like you don't run the event loop in non-interactive mode, so the
event is never occuring.
To achieve this without runing the event loop: show the window, then call
qApp->processEvents(), grab the pixmap, save it, hide the window and exit.
*/
//qgis->show();
a.processEvents();
QPixmap * myQPixmap = new QPixmap(800,600);
myQPixmap->fill();
qgis->saveMapAsImage(mySnapshotFileName,myQPixmap);
a.processEvents();
qgis->hide();
return 1;
}
/////////////////////////////////////////////////////////////////////
// Continue on to interactive gui...
/////////////////////////////////////////////////////////////////////
qgis->show();
a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
mypSplash->finish(qgis);
delete mypSplash;
return a.exec();
}