summaryrefslogtreecommitdiffstats
path: root/kexi/main/startup/KexiStartup.cpp
blob: c479a4e089d235811eac1b4ebbd1d522451af3a5 (plain)
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
/* This file is part of the KDE project
   Copyright (C) 2003-2007 Jaroslaw Staniek <js@iidea.pl>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include "KexiStartup.h"
#ifdef TQ_WS_WIN
# include "KexiStartup_p_win.h"
#else
# include "KexiStartup_p.h"
#endif

#include "kexiproject.h"
#include "kexiprojectdata.h"
#include "kexiprojectset.h"
#include "kexiguimsghandler.h"

#include <kexidb/driver.h>
#include <kexidb/drivermanager.h>
#include "KexiStartupDialog.h"
#include "KexiConnSelector.h"
#include "KexiProjectSelectorBase.h"
#include "KexiProjectSelector.h"
#include "KexiNewProjectWizard.h"
#include <kexidbconnectionwidget.h>
#include <kexidbshortcutfile.h>

#include <kdebug.h>
#include <klocale.h>
#include <kmimetype.h>
#include <kmessagebox.h>
#include <kcmdlineargs.h>
#include <tdeversion.h>
#include <kprogress.h>
#include <ktextedit.h>
#include <kstaticdeleter.h>
#include <kuser.h>

#include <unistd.h>

#include <tqcstring.h>
#include <tqapplication.h>
#include <tqlayout.h>

namespace Kexi {
	static KStaticDeleter<KexiStartupHandler> Kexi_startupHandlerDeleter;
	KexiStartupHandler* _startupHandler = 0;

	KexiStartupHandler& startupHandler()
	{
		if (!_startupHandler)
			Kexi_startupHandlerDeleter.setObject( _startupHandler, new KexiStartupHandler() );
		return *_startupHandler; 
	}
}

//---------------------------------

//! @internal
class KexiStartupHandlerPrivate
{
	public:
		KexiStartupHandlerPrivate()
		 : passwordDialog(0)//, showConnectionDetailsExecuted(false)
			, shortcutFile(0), connShortcutFile(0), connDialog(0), startupDialog(0)
		{
		}

		~KexiStartupHandlerPrivate()
		{
			delete passwordDialog;
			delete connDialog;
			delete startupDialog;
		}

		KexiDBPasswordDialog* passwordDialog;
//		bool showConnectionDetailsExecuted : 1;
		KexiDBShortcutFile *shortcutFile;
		KexiDBConnShortcutFile *connShortcutFile;
		KexiDBConnectionDialog *connDialog;
		TQString shortcutFileGroupKey;
		KexiStartupDialog *startupDialog;
};

//---------------------------------

static bool stripQuotes(const TQString &item, TQString &name)
{
	if (item.left(1)=="\"" && item.right(1)=="\"") {
		name = item.mid(1, item.length()-2);
		return true;
	}
	name = item;
	return false;
}

void updateProgressBar(KProgressDialog *pd, char *buffer, int buflen)
{
	char *p = buffer;
	TQCString line(80);
	for (int i=0; i<buflen; i++, p++) {
		if ((i==0 || buffer[i-1]=='\n') && buffer[i]=='%') {
			bool ok;
			int j=0;
//			char *q=++p;
			++i;
			line="";
			for (;i<buflen && *p>='0' && *p<='9'; j++, i++, p++)
				line+=TQChar(*p).latin1();
			--i; --p;
			int percent = line.toInt(&ok);
			if (ok && percent>=0 && percent<=100 && pd->progressBar()->progress()<percent) {
//				kdDebug() << percent << endl;
				pd->progressBar()->setProgress(percent);
				tqApp->tqprocessEvents(100);
			}
		}
	}
}

//---------------------------------

KexiDBPasswordDialog::KexiDBPasswordDialog(TQWidget *parent, KexiDB::ConnectionData& cdata, bool showDetailsButton)
 : KPasswordDialog( KPasswordDialog::Password, false/*keep*/, 
	showDetailsButton ? (int)KDialogBase::User1 : 0, parent )
 , m_cdata(&cdata)
 , m_showConnectionDetailsRequested(false)
{
	TQString msg = "<H2>" + i18n("Opening database") + "</H2><p>"
	 + i18n("Please enter the password.") + "</p>";
/*		msg += cdata.userName.isEmpty() ?
			"<p>"+i18n("Please enter the password.")
			: "<p>"+i18n("Please enter the password for user.").tqarg("<b>"+cdata.userName+"</b>");*/

	TQString srv = cdata.serverInfoString(false);
	if (srv.isEmpty() || srv.lower()=="localhost")
		srv = i18n("local database server");

	msg += ("</p><p>"+i18n("Database server: %1").tqarg(TQString("<nobr>")+srv+"</nobr>")+"</p>");
		
	TQString usr;
	if (cdata.userName.isEmpty())
		usr = i18n("unspecified user", "(unspecified)");
	else
		usr = cdata.userName;
	
	msg += ("<p>"+i18n("Username: %1").tqarg(usr)+"</p>");

	setPrompt( msg );
	if (showDetailsButton) {
		connect( this, TQT_SIGNAL(user1Clicked()), 
			this, TQT_SLOT(slotShowConnectionDetails()) );
		setButtonText(KDialogBase::User1, i18n("&Details")+ " >>");
	}
	setButtonOK(KGuiItem(i18n("&Open"), "fileopen"));
}

KexiDBPasswordDialog::~KexiDBPasswordDialog()
{
}

void KexiDBPasswordDialog::done(int r)
{
	if (r == TQDialog::Accepted) {
		m_cdata->password = TQString::tqfromLatin1(password());
	}
//	if (d->showConnectionDetailsExecuted || ret == TQDialog::Accepted) {
/*			} else {
				m_action = Exit;
				return true;
			}
		}*/
	KPasswordDialog::done(r);
}

void KexiDBPasswordDialog::slotShowConnectionDetails()
{
	m_showConnectionDetailsRequested = true;
	close();
}

//---------------------------------
KexiStartupHandler::KexiStartupHandler()
 : TQObject(0,"KexiStartupHandler")
 , KexiStartupData()
 , d( new KexiStartupHandlerPrivate() )
{
}

KexiStartupHandler::~KexiStartupHandler()
{
	delete d;
}

bool KexiStartupHandler::getAutoopenObjects(KCmdLineArgs *args, const TQCString &action_name)
{
	QCStringList list = args->getOptionList(action_name);
	QCStringList::ConstIterator it;
	bool atLeastOneFound = false;
	for ( it = list.constBegin(); it!=list.constEnd(); ++it) {
		TQString type_name, obj_name, item=*it;
		int idx;
		bool name_required = true;
		if (action_name=="new") {
			obj_name = "";
			stripQuotes(item, type_name);
			name_required = false;
		}
		else {//open, design, text...
			TQString defaultType;
			if (action_name=="execute")
				defaultType = "macro";
			else
				defaultType = "table";

			//option with " " (set default type)
			if (stripQuotes(item, obj_name)) {
				type_name = defaultType;
			}
			else if ((idx = item.find(':'))!=-1) {
				//option with type name specified:
				type_name = item.left(idx).lower();
				obj_name = item.mid(idx+1);
				//optional: remove ""
				if (obj_name.left(1)=="\"" && obj_name.right(1)=="\"")
					obj_name = obj_name.mid(1, obj_name.length()-2);
			}
			else {
				//just obj. name: set default type name
				obj_name = item;
				type_name = defaultType;
			}
		}
		if (type_name.isEmpty())
			continue;
		if (name_required && obj_name.isEmpty())
			continue;

		KexiProjectData::ObjectInfo info;
		info["name"]=obj_name;
		info["type"]=type_name;
		info["action"]=action_name;
		//ok, now add info for this object
		atLeastOneFound = true;
		if (projectData())
			projectData()->autoopenObjects.append( info );
		else
			return true; //no need to find more because we do not have projectData() anyway
	} //for
	return atLeastOneFound;
}

tristate KexiStartupHandler::init(int /*argc*/, char ** /*argv*/)
{
	m_action = DoNothing;
//	d->showConnectionDetailsExecuted = false;
	KCmdLineArgs *args = KCmdLineArgs::parsedArgs(0);
	if (!args)
		return true;

	KexiDB::ConnectionData cdata;

	const TQString connectionShortcutFileName( args->getOption("connection") );
	if (!connectionShortcutFileName.isEmpty()) {
		KexiDBConnShortcutFile connectionShortcut( connectionShortcutFileName );
		if (!connectionShortcut.loadConnectionData(cdata)) {
//! @todo Show error message from KexiDBConnShortcutFile when there's one implemented.
//!       For we're displaying generic error msg.
			KMessageBox::sorry( 0, "<qt>"
				+i18n("Could not read connection information from connection shortcut "
				"file <nobr>\"%1\"</nobr>.<br><br>Check whether the file has valid contents.")
				.tqarg(TQDir::convertSeparators(connectionShortcut.fileName())));
			return false;
		}
	}
	
	if (!args->getOption("dbdriver").isEmpty())
		cdata.driverName = args->getOption("dbdriver");

	TQString fileType( args->getOption("type").lower() );
	if (args->count()>0 && (!fileType.isEmpty() && fileType!="project" && fileType!="shortcut" && fileType!="connection")) {
		KMessageBox::sorry( 0, 
			i18n("You have specified invalid argument (\"%1\") for \"type\" command-line option.")
			.tqarg(fileType));
		return false;
	}

//	if (cdata.driverName.isEmpty())
//		cdata.driverName = KexiDB::Driver::defaultFileBasedDriverName();
	if (!args->getOption("host").isEmpty())
		cdata.hostName = args->getOption("host");
	if (!args->getOption("local-socket").isEmpty())
		cdata.localSocketFileName = args->getOption("local-socket");
	if (!args->getOption("user").isEmpty())
		cdata.userName = args->getOption("user");
//	cdata.password = args->getOption("password");
	bool fileDriverSelected;
	if (cdata.driverName.isEmpty())
		fileDriverSelected = true;
	else {
		KexiDB::DriverManager dm;
		KexiDB::Driver::Info dinfo = dm.driverInfo(cdata.driverName);
		if (dinfo.name.isEmpty()) {
			//driver name provided explicitly, but not found
			KMessageBox::sorry(0, dm.errorMsg());
			return false;
		}
		fileDriverSelected = dinfo.fileBased;
	}
	bool projectFileExists = false;

	//obfuscate the password, if present
//removed
/*
	for (int i=1; i<(argc-1); i++) {
		if (qstrcmp("--password",argv[i])==0
			|| qstrcmp("-password",argv[i])==0)
		{
			TQCString pwd(argv[i+1]);
			if (!pwd.isEmpty()) {
				pwd.fill(' ');
				pwd[0]='x';
				qstrcpy(argv[i+1], (const char*)pwd);
			}
			break;
		}
	}
	*/
	
	const TQString portStr = args->getOption("port");
	if (!portStr.isEmpty()) {
		bool ok;
		const int p = portStr.toInt(&ok);
		if (ok && p > 0)
			cdata.port = p;
		else {
			KMessageBox::sorry( 0, 
				i18n("You have specified invalid port number \"%1\"."));
			return false;
		}
	}

	m_forcedUserMode = args->isSet("user-mode");
	m_forcedDesignMode = args->isSet("design-mode");
	m_isProjectNavigatorVisible = args->isSet("show-navigator");
	bool createDB = args->isSet("createdb");
	const bool alsoOpenDB = args->isSet("create-opendb");
	if (alsoOpenDB)
		createDB = true;
	const bool dropDB = args->isSet("dropdb");
	const bool openExisting = !createDB && !dropDB;
	const bool readOnly = args->isSet("readonly");
	const TQString couldnotMsg = TQString::tqfromLatin1("\n")
		+i18n("Could not start Kexi application this way.");

	if (createDB && dropDB) {
		KMessageBox::sorry( 0, i18n(
			"You have used both \"createdb\" and \"dropdb\" startup options.")+couldnotMsg);
		return false;
	};

	if (createDB || dropDB) {
		if (args->count()<1) {
			KMessageBox::sorry( 0, i18n("No project name specified.") );
			return false;
		}
		m_action = Exit;
	}

//TODO: add option for non-gui; integrate with KWallet; 
//      move to static KexiProject method
	if (!fileDriverSelected && !cdata.driverName.isEmpty() && cdata.password.isEmpty()) {

		if (cdata.password.isEmpty()) {
			delete d->passwordDialog;
			d->passwordDialog = new KexiDBPasswordDialog(0, cdata, true);
//			connect( d->passwordDialog, TQT_SIGNAL(user1Clicked()), 
//				this, TQT_SLOT(slotShowConnectionDetails()) );
			const int ret = d->passwordDialog->exec();
			if (d->passwordDialog->showConnectionDetailsRequested() || ret == TQDialog::Accepted) {
//				if ( ret == TQDialog::Accepted ) {
		//		if (TQDialog::Accepted == KPasswordDialog::getPassword(pwd, msg)) {
//moved				cdata.password = TQString(pwd);
//				}
			} else {
				m_action = Exit;
				return true;
			}
		}
	}

/*	kdDebug() << "ARGC==" << args->count() << endl;
	for (int i=0;i<args->count();i++) {
		kdDebug() << "ARG" <<i<< "= " << args->arg(i) <<endl;
	}*/

	if (m_forcedUserMode && m_forcedDesignMode) {
		KMessageBox::sorry( 0, i18n(
		"You have used both \"user-mode\" and \"design-mode\" startup options.")+couldnotMsg);
		return false;
	}

	//database filenames, shortcut filenames or db names on a server
	if (args->count()>=1) {
		TQString prjName;
		TQString fileName;
		if (fileDriverSelected) {
			fileName = TQFile::decodeName(args->arg(0));
		}
		else {
			prjName = TQString::fromLocal8Bit(args->arg(0));
		}
		
		if (fileDriverSelected) {
			TQFileInfo finfo(fileName);
			prjName = finfo.fileName(); //filename only, to avoid messy names like when Kexi is started with "../../db" arg
			cdata.setFileName( finfo.absFilePath() );
			projectFileExists = finfo.exists();

			if (dropDB && !projectFileExists) {
				KMessageBox::sorry(0, 
					i18n("Could not remove project.\nThe file \"%1\" does not exist.")
					.tqarg(TQDir::convertSeparators(cdata.dbFileName())));
				return 0;
			}
		}

		if (createDB) {
			if (cdata.driverName.isEmpty())
				cdata.driverName = KexiDB::Driver::defaultFileBasedDriverName();
			m_projectData = new KexiProjectData(cdata, prjName); //dummy
		}
		else {
			if (fileDriverSelected) {
				int detectOptions = 0;
				if (fileType=="project")
					detectOptions |= ThisIsAProjectFile;
				else if (fileType=="shortcut")
					detectOptions |= ThisIsAShortcutToAProjectFile;
				else if (fileType=="connection")
					detectOptions |= ThisIsAShortcutToAConnectionData;

				if (dropDB)
					detectOptions |= DontConvert;

				TQString detectedDriverName;
				const tristate res = detectActionForFile( m_importActionData, detectedDriverName, 
					cdata.driverName, cdata.fileName(), 0, detectOptions );
				if (true != res)
					return res;

				if (m_importActionData) { //importing action
					m_action = ImportProject;
					return true;
				}

				//opening action
				cdata.driverName = detectedDriverName;
				if (cdata.driverName=="shortcut") {
					//get information for a shortcut file
					d->shortcutFile = new KexiDBShortcutFile(cdata.fileName());
					m_projectData = new KexiProjectData();
					if (!d->shortcutFile->loadProjectData(*m_projectData, &d->shortcutFileGroupKey)) {
						KMessageBox::sorry(0, i18n("Could not open shortcut file\n\"%1\".")
							.tqarg(TQDir::convertSeparators(cdata.fileName())));
						delete m_projectData;
						m_projectData = 0;
						delete d->shortcutFile;
						d->shortcutFile = 0;
						return false;
					}
					d->connDialog = new KexiDBConnectionDialog(
						*m_projectData, d->shortcutFile->fileName());
					connect(d->connDialog, TQT_SIGNAL(saveChanges()), 
						this, TQT_SLOT(slotSaveShortcutFileChanges()));
					int res = d->connDialog->exec();
					if (res == TQDialog::Accepted) {
						//get (possibly changed) prj data
						*m_projectData = d->connDialog->currentProjectData();
					}

					delete d->connDialog;
					d->connDialog = 0;
					delete d->shortcutFile;
					d->shortcutFile = 0;

					if (res == TQDialog::Rejected) {
						delete m_projectData;
						m_projectData = 0;
						return cancelled;
					}
				}
				else if (cdata.driverName=="connection") {
					//get information for a connection file
					d->connShortcutFile = new KexiDBConnShortcutFile(cdata.fileName());
					if (!d->connShortcutFile->loadConnectionData(cdata, &d->shortcutFileGroupKey)) {
						KMessageBox::sorry(0, i18n("Could not open connection data file\n\"%1\".")
							.tqarg(TQDir::convertSeparators(cdata.fileName())));
						delete d->connShortcutFile;
						d->connShortcutFile = 0;
						return false;
					}
					bool cancel = false;
					const bool showConnectionDialog = !args->isSet("skip-conn-dialog");
					while (true) {
						if (showConnectionDialog) {
							//show connection dialog, so user can change parameters
							if (!d->connDialog) {
								d->connDialog = new KexiDBConnectionDialog(
									cdata, d->connShortcutFile->fileName());
								connect(d->connDialog, TQT_SIGNAL(saveChanges()), 
									this, TQT_SLOT(slotSaveShortcutFileChanges()));
							}
							const int res = d->connDialog->exec();
							if (res == TQDialog::Accepted) {
								//get (possibly changed) prj data
								cdata = *d->connDialog->currentProjectData().constConnectionData();
							}
							else {
								cancel = true;
								break;
							}
						}
						m_projectData = selectProject(&cdata, cancel);
						if (m_projectData || cancel || !showConnectionDialog)
							break;
					}

					delete d->connShortcutFile;
					d->connShortcutFile = 0;
					delete d->connDialog;
					d->connDialog = 0;

					if (cancel)
						return cancelled;
				}
				else
					m_projectData = new KexiProjectData(cdata, prjName);
			}
			else
				m_projectData = new KexiProjectData(cdata, prjName);

		}
//		if (!m_projectData)
//			return false;
	}
	if (args->count()>1) {
		//TODO: KRun another Kexi instances
	}

	//let's show connection details, user asked for that in the "password dialog"
	if (d->passwordDialog && d->passwordDialog->showConnectionDetailsRequested()) {
		d->connDialog = new KexiDBConnectionDialog(*m_projectData);
//		connect(d->connDialog->tabWidget->mainWidget, TQT_SIGNAL(saveChanges()), 
//			this, TQT_SLOT(slotSaveShortcutFileChanges()));
		int res = d->connDialog->exec();

		if (res == TQDialog::Accepted) {
			//get (possibly changed) prj data
			*m_projectData = d->connDialog->currentProjectData();
		}

		delete d->connDialog;
		d->connDialog = 0;

		if (res == TQDialog::Rejected) {
			delete m_projectData;
			m_projectData = 0;
			return cancelled;
		}
	}

	//---autoopen objects:
	const bool atLeastOneAOOFound = getAutoopenObjects(args, "open")
		|| getAutoopenObjects(args, "design")
		|| getAutoopenObjects(args, "edittext")
		|| getAutoopenObjects(args, "execute")
		|| getAutoopenObjects(args, "new")
		|| getAutoopenObjects(args, "print")
		|| getAutoopenObjects(args, "print-preview");

	if (atLeastOneAOOFound && !openExisting) {
		KMessageBox::information( 0, 
			i18n("You have specified a few database objects to be opened automatically, "
				"using startup options.\n"
				"These options will be ignored because it is not available while creating "
				"or dropping projects."));
	}

	if (createDB) {
		bool creationNancelled;
		KexiGUIMessageHandler gui;
		KexiProject *prj = KexiProject::createBlankProject(creationNancelled, projectData(), &gui);
		bool ok = prj!=0;
		delete prj;
		if (creationNancelled)
			return cancelled;
		if (!alsoOpenDB) {
			if (ok) {
				KMessageBox::information( 0, i18n("Project \"%1\" created successfully.")
					.tqarg( TQDir::convertSeparators(projectData()->databaseName()) ));
			}
			return ok;
		}
	}
	else if (dropDB) {
		KexiGUIMessageHandler gui;
		tristate res = KexiProject::dropProject(projectData(), &gui, false/*ask*/);
		if (res==true)
			KMessageBox::information( 0, i18n("Project \"%1\" dropped successfully.")
				.tqarg( TQDir::convertSeparators(projectData()->databaseName()) ));
		return res!=false;
	}

	//------

/*	if (m_forcedFinalMode || (m_projectData && projectData->finalMode())) {
		//TODO: maybe also auto allow to open objects...
		KexiMainWindowImpl::initFinal(m_projectData);
		return;
	}*/

	if (!m_projectData) {
		cdata = KexiDB::ConnectionData(); //clear

		if (args->isSet("skip-startup-dialog") || !KexiStartupDialog::shouldBeShown())
			return true;

		if (!d->startupDialog) {
			//create d->startupDialog for reuse because it can be used again after conn err.
			d->startupDialog = new KexiStartupDialog(
				KexiStartupDialog::Everything, KexiStartupDialog::CheckBoxDoNotShowAgain,
				Kexi::connset(), Kexi::recentProjects(), 0, "KexiStartupDialog");
		}
		if (d->startupDialog->exec()!=TQDialog::Accepted)
			return true;

		const int r = d->startupDialog->result();
		if (r == KexiStartupDialog::CreateBlankResult) {
			m_action = CreateBlankProject;
			return true;
		}
		else if (r == KexiStartupDialog::ImportResult) {
			m_action = ImportProject;
			return true;
		}
		else if (r == KexiStartupDialog::CreateFromTemplateResult) {
			const TQString selFile( d->startupDialog->selectedFileName() );
			cdata.setFileName( selFile );
			TQString detectedDriverName;
			const tristate res = detectActionForFile( m_importActionData, detectedDriverName, 
				cdata.driverName, selFile );
			if (true != res)
				return res;
			if (m_importActionData || detectedDriverName.isEmpty())
				return false;
			cdata.driverName = detectedDriverName;
			m_projectData = new KexiProjectData(cdata, selFile);
			m_projectData->autoopenObjects = d->startupDialog->autoopenObjects();
			m_action = CreateFromTemplate;
			return true;
		}
		else if (r == KexiStartupDialog::OpenExistingResult) {
//			kdDebug() << "Existing project --------" << endl;
			const TQString selFile( d->startupDialog->selectedFileName() );
			if (!selFile.isEmpty()) {
				//file-based project
//				kdDebug() << "Project File: " << selFile << endl;
				cdata.setFileName( selFile );
				TQString detectedDriverName;
				const tristate res = detectActionForFile( m_importActionData, detectedDriverName, 
					cdata.driverName, selFile );
				if (true != res)
					return res;
				if (m_importActionData) { //importing action
					m_action = ImportProject;
					return true;
				}

				if (detectedDriverName.isEmpty())
					return false;
				cdata.driverName = detectedDriverName;
				m_projectData = new KexiProjectData(cdata, selFile);
			}
			else if (d->startupDialog->selectedExistingConnection()) {
//				kdDebug() << "Existing connection: " <<
//					d->startupDialog->selectedExistingConnection()->serverInfoString() << endl;
				KexiDB::ConnectionData *cdata = d->startupDialog->selectedExistingConnection();
				//ok, now we will try to show projects for this connection to the user
				bool cancelled;
				m_projectData = selectProject( cdata, cancelled );
				if (!m_projectData && !cancelled || cancelled) {
						//try again
						return init(0, 0);
				}
				//not needed anymore
				delete d->startupDialog;
				d->startupDialog = 0;
			}
		}
		else if (r==KexiStartupDialog::OpenRecentResult) {
//			kdDebug() << "Recent project --------" << endl;
			const KexiProjectData *data = d->startupDialog->selectedProjectData();
			if (data) {
//				kdDebug() << "Selected project: database=" << data->databaseName()
//					<< " connection=" << data->constConnectionData()->serverInfoString() << endl;
			}
//! @todo
			return data!=0;
		}

		if (!m_projectData)
			return true;
	}
	
	if (m_projectData && (openExisting || (createDB && alsoOpenDB))) {
		m_projectData->setReadOnly( readOnly );
		m_action = OpenProject;
	}
	//show if wasn't show yet
//	importantInfo(true);
	
	return true;
}

tristate KexiStartupHandler::detectActionForFile( 
	KexiStartupData::Import& detectedImportAction, TQString& detectedDriverName,
	const TQString& _suggestedDriverName, const TQString &dbFileName, TQWidget *parent, int options )
{
	detectedImportAction = KexiStartupData::Import(); //clear
	TQString suggestedDriverName(_suggestedDriverName); //safe
	detectedDriverName = TQString();
	TQFileInfo finfo(dbFileName);
	if (dbFileName.isEmpty() || !finfo.isReadable()) {
		if (!(options & SkipMessages))
			KMessageBox::sorry(parent, i18n("<p>Could not open project.</p>")
				+i18n("<p>The file <nobr>\"%1\"</nobr> does not exist or is not readable.</p>")
				.tqarg(TQDir::convertSeparators(dbFileName))
				+i18n("Check the file's permissions and whether it is already opened "
				"and locked by another application."));
		return false;
	}

	KMimeType::Ptr ptr;
	TQString mimename;

	const bool thisIsShortcut = (options & ThisIsAShortcutToAProjectFile) 
		|| (options & ThisIsAShortcutToAConnectionData);

	if ((options & ThisIsAProjectFile) || !thisIsShortcut) {
		//try this detection if "project file" mode is forced or no type is forced:
		ptr = KMimeType::findByFileContent(dbFileName);
		mimename = ptr.data()->name();
		kdDebug() << "KexiStartupHandler::detectActionForFile(): found mime is: " 
			<< mimename << endl;
		if (mimename.isEmpty() || mimename=="application/octet-stream" || mimename=="text/plain") {
			//try by URL:
			ptr = KMimeType::findByURL(dbFileName);
			mimename = ptr.data()->name();
		}
	}
	if (mimename.isEmpty() || mimename=="application/octet-stream") {
		// perhaps the file is locked
		TQFile f(dbFileName);
		if (!f.open(IO_ReadOnly)) {
			// BTW: similar error msg is provided in SQLiteConnection::drv_useDatabase()
			if (!(options & SkipMessages))
				KMessageBox::sorry(parent, i18n("<p>Could not open project.</p>")
					+i18n("<p>The file <nobr>\"%1\"</nobr> is not readable.</p>")
					.tqarg(TQDir::convertSeparators(dbFileName))
					+i18n("Check the file's permissions and whether it is already opened "
						"and locked by another application."));
			return false;
		}
	}
	if ((options & ThisIsAShortcutToAProjectFile) || mimename=="application/x-kexiproject-shortcut") {
		detectedDriverName = "shortcut";
		return true;
	}

	if ((options & ThisIsAShortcutToAConnectionData) || mimename=="application/x-kexi-connectiondata") {
		detectedDriverName = "connection";
		return true;
	}

	//! @todo rather check this using migration drivers' 
	//! X-KexiSupportedMimeTypes [strlist] property
	if (ptr.data()) {
		if (mimename=="application/x-msaccess") {
			if ((options & SkipMessages) || KMessageBox::Yes != KMessageBox::questionYesNo(
				parent, i18n("\"%1\" is an external file of type:\n\"%2\".\n"
				"Do you want to import the file as a Kexi project?")
				.tqarg(TQDir::convertSeparators(dbFileName)).tqarg(ptr.data()->comment()),
				i18n("Open External File"), KGuiItem(i18n("Import...")), KStdGuiItem::cancel() ) )
			{
				return cancelled;
			}
			detectedImportAction.mimeType = mimename;
			detectedImportAction.fileName = dbFileName;
			return true;
		}
	}

	if (!finfo.isWritable()) {
		//! @todo if file is ro: change project mode (but do not care if we're jsut importing)
	}

	// "application/x-kexiproject-sqlite", etc.:
	TQString tmpDriverName = Kexi::driverManager().lookupByMime(mimename).latin1();
//@todo What about trying to reuse KOFFICE FILTER CHAINS here?
	bool useDetectedDriver = suggestedDriverName.isEmpty() || suggestedDriverName.lower()==detectedDriverName.lower();
	if (!useDetectedDriver) {
		int res = KMessageBox::Yes;
		if (!(options & SkipMessages))
			res = KMessageBox::warningYesNoCancel(parent, i18n(
			 "The project file \"%1\" is recognized as compatible with \"%2\" database driver, "
			 "while you have asked for \"%3\" database driver to be used.\n"
			 "Do you want to use \"%4\" database driver?")
			 .tqarg(TQDir::convertSeparators(dbFileName))
			 .tqarg(tmpDriverName).tqarg(suggestedDriverName).tqarg(tmpDriverName));
		if (KMessageBox::Yes == res)
			useDetectedDriver = true;
		else if (KMessageBox::Cancel == res)
			return cancelled;
	}
	if (useDetectedDriver) {
		detectedDriverName = tmpDriverName;
	}
	else {//use suggested driver
		detectedDriverName = suggestedDriverName;
	}
//	kdDebug() << "KexiStartupHandler::detectActionForFile(): driver name: " << detectedDriverName << endl;
//hardcoded for convenience:
	const TQString newFileFormat = "SQLite3";
	if (!(options & DontConvert || options & SkipMessages) 
		&& detectedDriverName.lower()=="sqlite2" && detectedDriverName.lower()!=suggestedDriverName.lower()
		&& KMessageBox::Yes == KMessageBox::questionYesNo(parent, i18n(
			"Previous version of database file format (\"%1\") is detected in the \"%2\" "
			"project file.\nDo you want to convert the project to a new \"%3\" format (recommended)?")
			.tqarg(detectedDriverName).tqarg(TQDir::convertSeparators(dbFileName)).tqarg(newFileFormat)) )
	{
//		SQLite2ToSQLite3Migration *migr = new 
		SQLite2ToSQLite3Migration migr( finfo.absFilePath() );
		tristate res = migr.run();
//		kdDebug() << "--- migr.run() END ---" <<endl;
		if (!res) {
			//TODO msg
			KMessageBox::sorry(parent, i18n(
				"Failed to convert project file \"%1\" to a new \"%2\" format.\n"
				"The file format remains unchanged.")
				.tqarg(TQDir::convertSeparators(dbFileName)).tqarg(newFileFormat) );
			//continue...
		}
		if (res==true)
			detectedDriverName = newFileFormat;
	}
//	action.driverName = detectedDriverName;
	if (detectedDriverName.isEmpty()) {
		TQString possibleProblemsInfoMsg( Kexi::driverManager().possibleProblemsInfoMsg() );
		if (!possibleProblemsInfoMsg.isEmpty()) {
			possibleProblemsInfoMsg.prepend(TQString::tqfromLatin1("<p>")+i18n("Possible problems:"));
			possibleProblemsInfoMsg += TQString::tqfromLatin1("</p>");
		}
		if (!(options & SkipMessages))
			KMessageBox::detailedSorry(parent, 
				i18n( "The file \"%1\" is not recognized as being supported by Kexi.")
					.tqarg(TQDir::convertSeparators(dbFileName)),
				TQString::tqfromLatin1("<p>")
				+i18n("Database driver for this file type not found.\nDetected MIME type: %1")
					.tqarg(mimename)
				+(ptr.data()->comment().isEmpty() 
					? TQString::tqfromLatin1(".") : TQString::tqfromLatin1(" (%1).").tqarg(ptr.data()->comment()))
				+TQString::tqfromLatin1("</p>")
				+possibleProblemsInfoMsg);
		return false;
	}
	return true;
}

KexiProjectData*
KexiStartupHandler::selectProject(KexiDB::ConnectionData *cdata, bool& cancelled, TQWidget *parent)
{
	cleartqStatus();
	cancelled = false;
	if (!cdata)
		return 0;
	if (!cdata->savePassword && cdata->password.isEmpty()) {
		if (!d->passwordDialog)
			d->passwordDialog = new KexiDBPasswordDialog(0, *cdata, false);
		const int ret = d->passwordDialog->exec();
		if (d->passwordDialog->showConnectionDetailsRequested() || ret == TQDialog::Accepted) {

		} else {
			cancelled = true;
			return 0;
		}
	}
	KexiProjectData* projectData = 0;
	//dialog for selecting a project
	KexiProjectSelectorDialog prjdlg( parent, "prjdlg", cdata, true, false );
	if (!prjdlg.projectSet() || prjdlg.projectSet()->error()) {
		KexiGUIMessageHandler msgh;
		if (prjdlg.projectSet())
			msgh.showErrorMessage(prjdlg.projectSet(), 
				i18n("Could not load list of available projects for <b>%1</b> database server.")
				.tqarg(cdata->serverInfoString(true)));
		else
			msgh.showErrorMessage(
				i18n("Could not load list of available projects for <b>%1</b> database server.")
				.tqarg(cdata->serverInfoString(true)));
//		settqStatus(i18n("Could not load list of available projects for database server \"%1\"")
//		.tqarg(cdata->serverInfoString(true)), prjdlg.projectSet()->errorMsg());
		return 0;
	}
	if (prjdlg.exec()!=TQDialog::Accepted) {
		cancelled = true;
		return 0;
	}
	if (prjdlg.selectedProjectData()) {
		//deep copy
		projectData = new KexiProjectData(*prjdlg.selectedProjectData());
	}
	return projectData;
}

void KexiStartupHandler::slotSaveShortcutFileChanges()
{
	bool ok = true;
	if (d->shortcutFile)
		ok = d->shortcutFile->saveProjectData(d->connDialog->currentProjectData(), 
			d->connDialog->savePasswordOptionSelected(), 
			&d->shortcutFileGroupKey );
	else if (d->connShortcutFile)
		ok = d->connShortcutFile->saveConnectionData(
			*d->connDialog->currentProjectData().connectionData(), 
			d->connDialog->savePasswordOptionSelected(), 
			&d->shortcutFileGroupKey );

	if (!ok) {
		KMessageBox::sorry(0, i18n("Failed saving connection data to\n\"%1\" file.")
			.tqarg(TQDir::convertSeparators(d->shortcutFile->fileName())));
	}
}

/*void KexiStartupHandler::slotShowConnectionDetails()
{
	d->passwordDialog->close();
	d->showConnectionDetailsExecuted = true;
}*/

#include "KexiStartup.moc"