summaryrefslogtreecommitdiffstats
path: root/src/UiGuiSettings.cpp
blob: c3fccbbeb8ff59579cd556e513cdaff06dee65dc (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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
/***************************************************************************
*   Copyright (C) 2006-2012 by Thomas Schweitzer                          *
*   thomas-schweitzer(at)arcor.de                                         *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License version 2.0 as   *
*   published by the Free Software Foundation.                            *
*                                                                         *
*   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 in the file LICENSE.GPL; if not, write to the *
*   Free Software Foundation, Inc.,                                       *
*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/

#include "UiGuiSettings.h"
#include "SettingsPaths.h"

#include <tqdatetime.h>
#include <tqdir.h>
#include <tqpoint.h>
#include <tqregexp.h>
#include <tqsettings.h>
#include <tqsize.h>
#include <tqwidget.h>


/*
    \class UiGuiSettings
    \brief Handles the settings of the program. Reads them on startup and saves them on exit.
    Is a singleton class and can only be accessed via getInstance().
*/

// Inits the single class instance pointer.
UiGuiSettings *UiGuiSettings::m_instance = nullptr;

/*
    \brief The constructor for the settings.
*/
UiGuiSettings::UiGuiSettings() : TQObject()
{
	// Create the main application settings object from the UniversalIndentGUIrc file.
	m_qsettings = new TQSettings(TQSettings::Ini);
	// The next lines make user the settings are always stored in
	// $HOME/.universalindentgui/universalindentguirc
	m_qsettings->insertSearchPath(TQSettings::Unix, SettingsPaths::getSettingsPath());
  m_qsettings->setPath("UniversalIndentGUI", "UniversalIndentGUI", TQSettings::User);
	// settings are stored in the universalindentguirc file, group UniversalIndentGUI
	m_qsettings->beginGroup("universalindentgui/UniversalIndentGUI");

	m_indenterDirectoryStr = SettingsPaths::getGlobalFilesPath() + "/indenters";

  m_actionSettings["actionEnableSyntaxHighlighting"] = "SyntaxHighlightingEnabled";
  m_actionSettings["actionLoadLastOpenedFileOnStartup"] = "LoadLastOpenedFileOnStartup";
  m_actionSettings["actionWhiteSpaceIsVisible"] = "WhiteSpaceIsVisible";

	readAvailableTranslations();
	loadSettings();
}

/*
    \brief Returns the instance of the settings class. If no instance exists, one will be created.
 */
UiGuiSettings* UiGuiSettings::getInstance()
{
	if (!m_instance)
	{
		// Create the settings object, which loads all UiGui settings from a file.
		m_instance = new UiGuiSettings();
	}

	return m_instance;
}

/*
    \brief Deletes the existing instance of UiGuiSettings and removes the created temp dir.
 */
void UiGuiSettings::deleteInstance()
{
	SettingsPaths::cleanAndRemoveTempDir();
	if (m_instance)
	{
		delete m_instance;
		m_instance = nullptr;
	}
}

/*
    \brief The destructor saves the settings to a file.
 */
UiGuiSettings::~UiGuiSettings()
{
	saveSettings();
	delete m_qsettings;
}

/*
    \brief Scans the translations directory for available translation files and
    stores them in the TQList \a m_availableTranslations.
 */
void UiGuiSettings::readAvailableTranslations()
{
	TQStringList languageFileList;

	// English is the default language. A translation file does not exist but to have a menu entry,
	// added here.
	languageFileList << "universalindent_en.qm";

	// Find all translation files in the "translations" directory.
	TQDir translationDirectory = TQDir(SettingsPaths::getGlobalFilesPath() + "/translations");
	for (const TQString &file : translationDirectory.entryList(TQString("universalindent_*.qm")))
	{
		languageFileList << file;
	}

	// Loop for each found translation file
	for (TQString &languageShort : languageFileList)
	{
		// Remove the leading string "universalindent_" from the filename.
		languageShort.remove(0, 16);
		// Remove trailing file extension ".qm".
		languageShort.truncate(languageShort.length() - 3);

		m_availableTranslations.append(languageShort);
	}
}

/*
    \brief Returns a list of the mnemonics of the available translations.
 */
TQStringList& UiGuiSettings::getAvailableTranslations()
{
	return m_availableTranslations;
}

/*
    \brief Returns the value of the by \a settingsName defined setting as TQVariant.

    If the named setting does not exist, 0 is being returned.
*/
TQVariant UiGuiSettings::getValueByName(const TQString &settingName) const
{
	// Test if the named setting really exists.
	if (m_settings.contains(settingName))
	{
		return m_settings[settingName];
	}
	return TQVariant(0);
}

/*
    \brief Sets the value of the by \a settingsName defined setting to the value \a value.

    The to \a settingsName corresponding signal is emitted, if the value has changed.
 */
bool UiGuiSettings::setValueByName(const TQString &settingName, TQVariant value)
{
	// Test if the named setting really exists.
	if (m_settings.contains(settingName))
	{
		// Test if the new value is different to the one before.
		if (m_settings[settingName] != value)
		{
			m_settings[settingName] = value;
			// Emit the signal for the changed setting.
			emitSignalForSetting(settingName);
		}
		return true;
	}
	return false;
}

/*!
    \brief Loads the settings for the main application.

    Settings are for example last selected indenter, last loaded source code file and so on.
*/
void UiGuiSettings::loadSettings()
{
	// Read the version string
	m_settings["VersionInSettingsFile"] = m_qsettings->readEntry("version", TQString::null);

	// Read window's maximized status
	m_settings["WindowIsMaximized"] = m_qsettings->readBoolEntry("maximized", false);

	// Read window's position
	TQString positionString = m_qsettings->readEntry("position", "@Point(50 50)");
	TQRegExp posrx("@Point\\((-?\\d+)[ \\t]+(-?\\d+)\\)");
	TQPoint position(50, 50);
	if (posrx.exactMatch(positionString.stripWhiteSpace()))
	{
		TQStringList posList = posrx.capturedTexts();
		position.setX(posList[1].toInt());
		position.setY(posList[2].toInt());
	}
	m_settings["WindowPosition"] = position;

	// Read window's size
	TQString sizeString = m_qsettings->readEntry("size", "@Size(800 600)");
	TQRegExp sizerx("@Size\\((-?\\d+)[ \\t]+(-?\\d+)\\)");
	TQSize size(800, 600);
	if (sizerx.exactMatch(sizeString.stripWhiteSpace()))
	{
		TQStringList sizeList = sizerx.capturedTexts();
		size.setWidth(sizeList[1].toInt());
		size.setHeight(sizeList[2].toInt());
	}
	m_settings["WindowSize"] = size;

	// Read last selected encoding for the opened source code file.
	m_settings["FileEncoding"] = m_qsettings->readEntry("encoding", "UTF-8");

	// Read maximum length of list for recently opened files.
	m_settings["RecentlyOpenedListSize"] = m_qsettings->readNumEntry("recentlyOpenedListSize", 5);

	// Read if last opened source code file should be loaded on startup.
	m_settings["LoadLastOpenedFileOnStartup"] = m_qsettings->readBoolEntry(
	        "loadLastSourceCodeFileOnStartup", true);

	// Read last opened source code file from the settings file.
	m_settings["LastOpenedFiles"] = m_qsettings->readEntry("lastSourceCodeFile",
	        m_indenterDirectoryStr + "/example.cpp");

	// Read last selected indenter from the settings file.
	int selectedIndenter = m_qsettings->readNumEntry("selectedIndenter", 0);
	if (selectedIndenter < 0)
	{
		selectedIndenter = 0;
	}
	m_settings["SelectedIndenter"] = selectedIndenter;

	// Read if syntax highlighting is enabled.
	m_settings["SyntaxHighlightingEnabled"] = m_qsettings->readBoolEntry(
	        "SyntaxHighlightingEnabled", true);

	// Read if white space characters should be displayed.
	m_settings["WhiteSpaceIsVisible"] = m_qsettings->readBoolEntry("whiteSpaceIsVisible", false);

	// Read if indenter parameter tool tips are enabled.
	m_settings["IndenterParameterTooltipsEnabled"] = m_qsettings->readBoolEntry(
	        "indenterParameterTooltipsEnabled", true);

	// Read the tab width from the settings file.
	m_settings["TabWidth"] = m_qsettings->readNumEntry("tabWidth", 4);

	// Read the last selected language and stores the index it has in the list of available
	// translations.
	TQString language = m_qsettings->readEntry("language", "en");
	int idx = m_availableTranslations.findIndex(language);
	if (idx < 0)
	{
		idx = m_availableTranslations.findIndex("en"); // "en" is always present
	}
	m_settings["Language"] = idx;

	// TODO - MainWindow::saveState() missing in TQt3
	// Read the main window state.
	// m_settings["MainWindowState"] = m_qsettings->readEntry("MainWindowState", "@ByteArray()");
}

/*!
    \brief Saves the settings for the main application.

    Settings are for example last selected indenter, last loaded source code file and so on.
*/
void UiGuiSettings::saveSettings()
{
	// Write the version string
	m_qsettings->writeEntry("version", m_settings["VersionInSettingsFile"].toString());

	// Write window's maximized status
	m_qsettings->writeEntry("maximized", m_settings["WindowIsMaximized"].toBool());

	// Write window's position
	TQPoint position = m_settings["WindowPosition"].toPoint();
	TQString positionString = TQString("@Point(%1 %2)").arg(position.x()).arg(position.y());
	m_qsettings->writeEntry("position", positionString);

	// Write window's size
	TQSize size = m_settings["WindowSize"].toSize();
	TQString sizeString = TQString("@Size(%1 %2)").arg(size.width()).arg(size.height());
	m_qsettings->writeEntry("size", sizeString);

	// Write last selected encoding for the opened source code file.
	m_qsettings->writeEntry("encoding", m_settings["FileEncoding"].toString());

	// Write maximum length of list for recently opened files.
	m_qsettings->writeEntry("recentlyOpenedListSize", m_settings["RecentlyOpenedListSize"].toInt());

	// Write if last opened source code file should be loaded on startup.
	m_qsettings->writeEntry("loadLastSourceCodeFileOnStartup",
	        m_settings["LoadLastOpenedFileOnStartup"].toBool());

	// Write last opened source code file from the settings file.
	m_qsettings->writeEntry("lastSourceCodeFile", m_settings["LastOpenedFiles"].toString());

	// Write last selected indenter from the settings file.
	m_qsettings->writeEntry("selectedIndenter", m_settings["SelectedIndenter"].toInt());

	// Write if syntax highlighting is enabled.
	m_qsettings->writeEntry("SyntaxHighlightingEnabled",
	        m_settings["SyntaxHighlightingEnabled"].toBool());

	// Write if white space characters should be displayed.
	m_qsettings->writeEntry("whiteSpaceIsVisible", m_settings["WhiteSpaceIsVisible"].toBool());

	// Write if indenter parameter tool tips are enabled.
	m_qsettings->writeEntry("indenterParameterTooltipsEnabled",
	        m_settings["IndenterParameterTooltipsEnabled"].toBool());

	// Write the tab width from the settings file.
	m_qsettings->writeEntry("tabWidth", m_settings["TabWidth"].toInt());

	// Write the last selected language and stores the index it has in the list of available
	m_qsettings->writeEntry("language", m_availableTranslations[m_settings["Language"].toInt()]);

	// TODO - MainWindow::saveState() missing in TQt3
	// Write the main window state.
	//m_qsettings->writeEntry("MainWindowState", m_settings["MainWindowState"].toByteArray());
}

/*
    \brief Extern widgets can connect to this slot to change settings.

    According to the objects property "connectedSettingName" the corresponding
    setting is known and set.
 */
void UiGuiSettings::handleValueChangeFromExtern(bool value)
{
	if (sender())
	{
		// Get the corresponding setting name from the sender objects property
		TQString senderName = TQString(sender()->name());
		if (m_actionSettings.contains(senderName))
		{
			TQString settingName = m_actionSettings[senderName];

			// Set the value of the setting to the objects value.
			setValueByName(settingName, value);
		}
	}
}

void UiGuiSettings::emitSignalForSetting(TQString settingName)
{
	// Emit the signal for the changed value.
	if (settingName == "RecentlyOpenedListSize")
	{
		emit recentlyOpenedListSize(m_settings[settingName].toInt());
	}
	else if (settingName == "LoadLastOpenedFileOnStartup")
	{
		emit loadLastOpenedFileOnStartup(m_settings[settingName].toBool());
	}
	else if (settingName == "SyntaxHighlightingEnabled")
	{
		emit syntaxHighlightingEnabled(m_settings[settingName].toBool());
	}
	else if (settingName == "WhiteSpaceIsVisible")
	{
		emit whiteSpaceIsVisible(m_settings[settingName].toBool());
	}
	else if (settingName == "IndenterParameterTooltipsEnabled")
	{
		emit indenterParameterTooltipsEnabled(m_settings[settingName].toBool());
	}
	else if (settingName == "TabWidth")
	{
		emit tabWidth(m_settings[settingName].toInt());
	}
	else if (settingName == "Language")
	{
		emit language(m_settings[settingName].toInt());
	}
}

/*
    \brief Register the by \a propertyName defined property of \a obj to be connected to the setting defined by \a settingName.

    The \a propertyName must be one of those that are listed in the TQt "Properties" documentation section of a TQt Object.
    All further needed info is retrieved via the \a obj's MetaObject, like the to the property bound signal.
 * /
bool UiGuiSettings::registerObjectProperty(TQObject *obj, const TQString &propertyName,
        const TQString &settingName)
{
	const TQMetaObject *metaObject = obj->metaObject();
	bool connectSuccess = false;

	// Connect to the objects destroyed signal, so that it will be correctly unregistered.
	connectSuccess =
	        connect(obj, SIGNAL(destroyed(TQObject*)), this,
	        SLOT(unregisterObjectProperty(TQObject*)));

	int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
	if (connectSuccess && indexOfProp > -1)
	{
		TQMetaProperty mProp = metaObject->property(indexOfProp);

		// Connect to the property's value changed signal.
		if (mProp.hasNotifySignal())
		{
			TQMetaMethod signal = mProp.notifySignal();
			//TQString teststr = qPrintable(SIGNAL() + TQString(signal.signature()));
			// The command "SIGNAL() + TQString(signal.signature())" assembles the signal methods
			// signature to a valid TQt SIGNAL.
			connectSuccess =
			        connect(obj, qPrintable(SIGNAL() + TQString(signal.signature())), this,
			        SLOT(handleObjectPropertyChange()));
		}

		if (connectSuccess)
		{
			m_registeredObjectProperties[obj] = TQStringList() << propertyName << settingName;
		}
		else
		{
			//TODO: Write a debug warning to the log.
			disconnect(obj, SIGNAL(destroyed(TQObject*)), this,
			        SLOT(unregisterObjectProperty(TQObject*)));
			return false;
		}

		// If setting already exists, set the objects property to the setting value.
		if (m_qsettings->contains("UniversalIndentGUI/" + settingName))
		{
			mProp.write(obj, m_qsettings->value("UniversalIndentGUI/" + settingName));
		}
		// Otherwise add the setting and set it to the value of the objects property.
		else
		{
			m_qsettings->setValue("UniversalIndentGUI/" + settingName, mProp.read(obj));
		}
	}
	else
	{
		//TODO: Write a debug warning to the log.
		disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectProperty(TQObject*)));
		return false;
	}

	return true;
}

//*
    \brief Assigns the by \a settingName defined setting value to the by \a propertyName defined property of \a obj.

    Returns true, if the value could be assigned, otherwise returns false, which is the case if settingName doesn't exist
    within the settings or if the mentioned propertyName wasn't found for the \a obj.
 * /
bool UiGuiSettings::setObjectPropertyToSettingValue(TQObject *obj, const TQString &propertyName,
        const TQString &settingName)
{
	const TQMetaObject *metaObject = obj->metaObject();

	int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
	if (indexOfProp > -1)
	{
		TQMetaProperty mProp = metaObject->property(indexOfProp);

		// If setting already exists, set the objects property to the setting value.
		if (m_qsettings->contains("UniversalIndentGUI/" + settingName))
		{
			mProp.write(obj, m_qsettings->value("UniversalIndentGUI/" + settingName));
		}
		// The setting didn't exist so return that setting the objects property failed.
		else
		{
			//TODO: Write a debug warning to the log.
			return false;
		}
	}
	else
	{
		//TODO: Write a debug warning to the log.
		return false;
	}

	return true;
}

/*
    \brief Searches the child TQObjects of \a obj for a property name and setting name definition within
    their custom properties and sets each property to settings value.

    The custom properties, for which are searched, are "connectedPropertyName" and "connectedSettingName",
    where "connectedPropertyName" is the name of a TQObject property as it is documented in the TQtDocs, and
    "connectedSettingName" is the name of a setting here within UiGuiSettings.

    Returns true, if all found property and setting definitions could be successfully registered.
    Returns false, if any of those registrations fails.
 * /
bool UiGuiSettings::setObjectPropertyToSettingValueRecursive(TQObject *obj)
{
	return checkCustomPropertiesAndCallFunction(obj, &UiGuiSettings::setObjectPropertyToSettingValue);
}

/*
    \brief Assigns the by \a propertyName defined property's value of \a obj to the by \a settingName defined setting.

    If the \a settingName didn't exist yet, it will be created.

    Returns true, if the value could be assigned, otherwise returns false, which is the case if the mentioned
    propertyName wasn't found for the \a obj.
 * /
bool UiGuiSettings::setSettingToObjectPropertyValue(TQObject *obj, const TQString &propertyName,
        const TQString &settingName)
{
	const TQMetaObject *metaObject = obj->metaObject();

	int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
	if (indexOfProp > -1)
	{
		TQMetaProperty mProp = metaObject->property(indexOfProp);

		setValueByName(settingName, mProp.read(obj));
	}
	else
	{
		//TODO: Write a debug warning to the log.
		return false;
	}

	return true;
}

/*
    \brief Searches the child TQObjects of \a obj for a property name and setting name definition within
    their custom properties and sets each setting to the property value.

    The custom properties, for which are searched, are "connectedPropertyName" and "connectedSettingName",
    where "connectedPropertyName" is the name of a TQObject property as it is documented in the TQtDocs, and
    "connectedSettingName" is the name of a setting here within UiGuiSettings. If the settingName
    didn't exist yet, it will be created.

    Returns true, if all found property and setting definitions could be successfully registered.
    Returns false, if any of those registrations fails.
 * /
bool UiGuiSettings::setSettingToObjectPropertyValueRecursive(TQObject *obj)
{
	return checkCustomPropertiesAndCallFunction(obj, &UiGuiSettings::setSettingToObjectPropertyValue);
}

/*
    \brief Iterates over all \a objs child TQObjects and checks whether they have the custom properties
    "connectedPropertyName" and "connectedSettingName" set. If both are set, it invokes the \a callBackFunc
    with both.
 * /
bool UiGuiSettings::checkCustomPropertiesAndCallFunction(TQObject *obj, bool (UiGuiSettings::*callBackFunc)(
					TQObject *obj, const TQString &propertyName,
					const TQString &settingName))
{
	bool success = true;

	// Find all widgets that have PropertyName and SettingName defined in their style sheet.
	TQList<TQObject*> allObjects = obj->findChildren<TQObject*>();
	foreach(TQObject * object, allObjects)
	{
		TQString propertyName = object->property("connectedPropertyName").toString();
		TQString settingName  = object->property("connectedSettingName").toString();

		// If property and setting name were found, register that widget with the settings.
		if (!propertyName.isEmpty() && !settingName.isEmpty())
		{
			success &= (this->*callBackFunc)(object, propertyName, settingName);
		}
	}

	return success;
}

/*
    \brief The with a certain property registered \a obj gets unregistered.
 * /
void UiGuiSettings::unregisterObjectProperty(TQObject *obj)
{
	if (m_registeredObjectProperties.contains(obj))
	{
		const TQMetaObject *metaObject = obj->metaObject();
		TQString propertyName = m_registeredObjectProperties[obj].first();
		TQString settingName  = m_registeredObjectProperties[obj].last();

		bool connectSuccess = false;
		int  indexOfProp    = metaObject->indexOfProperty(qPrintable(propertyName));
		if (indexOfProp > -1)
		{
			TQMetaProperty mProp = metaObject->property(indexOfProp);

			// Disconnect to the property's value changed signal.
			if (mProp.hasNotifySignal())
			{
				TQMetaMethod signal = mProp.notifySignal();
				// The command "SIGNAL() + TQString(signal.signature())" assembles the signal methods
				// signature to a valid TQt SIGNAL.
				connectSuccess = disconnect(obj, qPrintable(SIGNAL() + TQString(
									signal.signature())), this, SLOT(handleObjectPropertyChange()));
			}
		}
		m_registeredObjectProperties.remove(obj);
	}
}

/*
    \brief Registers a slot form the \a obj by its \a slotName to be invoked, if the by \a settingName defined
    setting changes.

    The registered slot may have no parameters or exactly one. If it accepts one parameter, whenever the setting
    \a settingName changes the slot gets tried to be invoked with the settings value as parameter. This only works,
    if the slot parameter is of the same type as the setting.
 * /
bool UiGuiSettings::registerObjectSlot(TQObject *obj, const TQString &slotName,
        const TQString &settingName)
{
	const TQMetaObject *metaObject = obj->metaObject();

	bool connectSuccess = false;
	// Connect to the objects destroyed signal, so that it will be correctly unregistered.
	connectSuccess =
	        connect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*)));

	TQString normalizedSlotName = TQMetaObject::normalizedSignature(qPrintable(slotName));
	int      indexOfMethod      = metaObject->indexOfMethod(qPrintable(normalizedSlotName));
	if (connectSuccess && indexOfMethod > -1)
	{
		TQMetaMethod mMethod = metaObject->method(indexOfMethod);
		//TQMetaMethod::Access access = mMethod.access();
		//TQMetaMethod::MethodType methType = mMethod.methodType();

		// Since the method can at maximum be invoked with the setting value as argument,
		// only methods taking max one argument are allowed.
		if (mMethod.parameterTypes().size() <= 1)
		{
			m_registeredObjectSlots.insert(obj, TQStringList() << normalizedSlotName << settingName);
		}
		else
		{
			//TODO: Write a debug warning to the log.
			disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*)));
			return false;
		}
	}
	else
	{
		//TODO: Write a debug warning to the log.
		disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*)));
		return false;
	}

	return true;
}

/*
    \brief If \a obj, \a slotName and \a settingName are given, that certain connection is unregistered.
    If only \a obj is given, all to this object registered slot-setting connections are unregistered.
 * /
void UiGuiSettings::unregisterObjectSlot(TQObject *obj, const TQString &slotName,
        const TQString &settingName)
{
	//const TQMetaObject *metaObject = obj->metaObject();
	TQString normalizedSlotName = TQMetaObject::normalizedSignature(qPrintable(slotName));
	TQMutableMapIterator<TQObject*, TQStringList> it(m_registeredObjectSlots);
	while (it.hasNext())
	{
		it.next();
		if (it.key() == obj && slotName.isEmpty() && settingName.isEmpty())
		{
			it.remove();
		}
		else if (it.key() == obj && it.value().first() == slotName && it.value().last() == settingName)
		{
			it.remove();
		}
	}
}

/*
    \brief This private slot gets invoked whenever a registered objects property changes
    and distributes the new value to all other to the same settingName registered objects.
 * /
void UiGuiSettings::handleObjectPropertyChange()
{
	TQObject *obj       = TQObject::sender();
	TQString  className = obj->metaObject()->className();
	const TQMetaObject *metaObject = obj->metaObject();
	TQString propertyName = m_registeredObjectProperties[obj].first();
	TQString settingName  = m_registeredObjectProperties[obj].last();

	int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
	if (indexOfProp > -1)
	{
		TQMetaProperty mProp = metaObject->property(indexOfProp);
		setValueByName(settingName, mProp.read(obj));
	}
}

/*
    \brief Sets the setting defined by \a settingName to \a value.

    When setting a changed value, all to this settingName registered objects get
    the changed value set too.
    If the \a settingName didn't exist yet, it will be created.
 * /
void UiGuiSettings::setValueByName(const TQString &settingName, const TQVariant &value)
{
	// Do the updating only, if the setting was really changed.
	if (m_qsettings->value("UniversalIndentGUI/" + settingName) != value)
	{
		m_qsettings->setValue("UniversalIndentGUI/" + settingName, value);

		// Set the new value for all registered object properties for settingName.
		for (TQMap<TQObject*, TQStringList>::ConstIterator it = m_registeredObjectProperties.begin();
		        it != m_registeredObjectProperties.end(); ++it)
		{
			if (it.value().last() == settingName)
			{
				TQObject *obj = it.key();
				const TQMetaObject *metaObject = obj->metaObject();
				TQString propertyName = it.value().first();

				int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
				if (indexOfProp > -1)
				{
					TQMetaProperty mProp = metaObject->property(indexOfProp);
					mProp.write(obj, value);
				}
			}
		}

		// Invoke all registered object methods for settingName.
		for (TQMap<TQObject*, TQStringList>::ConstIterator it = m_registeredObjectSlots.begin();
		        it != m_registeredObjectSlots.end(); ++it)
		{
			if (it.value().last() == settingName)
			{
				TQObject *obj = it.key();
				const TQMetaObject *metaObject = obj->metaObject();
				TQString slotName = it.value().first();

				int indexOfMethod = metaObject->indexOfMethod(qPrintable(slotName));
				if (indexOfMethod > -1)
				{
					TQMetaMethod mMethod = metaObject->method(indexOfMethod);
					//TQMetaMethod::Access access = mMethod.access();
					//TQMetaMethod::MethodType methType = mMethod.methodType();

					bool success = false;

					// Handle registered slots taking one parameter.
					if (mMethod.parameterTypes().size() == 1)
					{
						if (mMethod.parameterTypes().first() == value.typeName())
						{
							success = invokeMethodWithValue(obj, mMethod, value);
						}
					}
					// Handle registered slots taking zero parameters.
					else
					{
						success = mMethod.invoke(obj, TQt::DirectConnection);
					}

					if (success == false)
					{
						// TODO: Write a warning to the log if no success.
					}
				}
			}
		}
	}
}

#include <tqbitarray.h>
#include <tqbitmap.h>
#include <tqbrush.h>
#include <tqcursor.h>
#include <tqdatetime.h>
#include <tqfont.h>
#include <tqicon.h>
#include <tqkeysequence.h>
#include <tqlocale.h>
#include <tqpalette.h>
#include <tqpen.h>
#include <tqsizepolicy.h>
#include <tqtextformat.h>
#include <tqtextlength.h>
#include <tqurl.h>
#if TQT_VERSION >= 0x040600
 #include <tqmatrix4x4.h>
 #include <tqvector2d.h>
#endif

bool UiGuiSettings::invokeMethodWithValue(TQObject *obj, TQMetaMethod mMethod, TQVariant value)
{
	switch (value.type())
	{
		case TQVariant::BitArray:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBitArray, value.toBitArray()));
		}

		case TQVariant::Bitmap:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBitmap, value.value<TQBitmap>()));
		}

		case TQVariant::Bool:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(bool, value.toBool()));
		}

		case TQVariant::Brush:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBrush, value.value<TQBrush>()));
		}

		case TQVariant::ByteArray:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQByteArray, value.toByteArray()));
		}

		case TQVariant::Char:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQChar, value.toChar()));
		}

		case TQVariant::Color:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQColor, value.value<TQColor>()));
		}

		case TQVariant::Cursor:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQCursor, value.value<TQCursor>()));
		}

		case TQVariant::Date:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQDate, value.toDate()));
		}

		case TQVariant::DateTime:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQDateTime, value.toDateTime()));
		}

		case TQVariant::Double:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(double, value.toDouble()));
		}

		case TQVariant::Font:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQFont, value.value<TQFont>()));
		}

		case TQVariant::Hash:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantHash, value.toHash()));
		}

		case TQVariant::Icon:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQIcon, value.value<TQIcon>()));
		}

		case TQVariant::Image:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQImage, value.value<TQImage>()));
		}

		case TQVariant::Int:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(int, value.toInt()));
		}

		case TQVariant::KeySequence:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQKeySequence,
			               value.value<TQKeySequence>()));
		}

		case TQVariant::Line:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLine, value.toLine()));
		}

		case TQVariant::LineF:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLineF, value.toLineF()));
		}

		case TQVariant::List:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantList, value.toList()));
		}

		case TQVariant::Locale:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLocale, value.toLocale()));
		}

		case TQVariant::LongLong:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(qlonglong, value.toLongLong()));
		}

		case TQVariant::Map:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantMap, value.toMap()));
		}

		case TQVariant::Matrix:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQMatrix, value.value<TQMatrix>()));
		}

		case TQVariant::Transform:
		{
			return mMethod.invoke(obj, TQt::DirectConnection,
			               Q_ARG(TQTransform, value.value<TQTransform>()));
		}

#if TQT_VERSION >= 0x040600
		case TQVariant::Matrix4x4:
		{
			return mMethod.invoke(obj, TQt::DirectConnection,
			               Q_ARG(TQMatrix4x4, value.value<TQMatrix4x4>()));
		}

#endif
		case TQVariant::Palette:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPalette, value.value<TQPalette>()));
		}

		case TQVariant::Pen:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPen, value.value<TQPen>()));
		}

		case TQVariant::Pixmap:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPixmap, value.value<TQPixmap>()));
		}

		case TQVariant::Point:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPoint, value.toPoint()));
		}

		//    case TQVariant::PointArray :
		//        return Q_ARG(TQPointArray, value.value<TQPointArray>()) );
		case TQVariant::PointF:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPointF, value.toPointF()));
		}

		case TQVariant::Polygon:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPolygon, value.value<TQPolygon>()));
		}

#if TQT_VERSION >= 0x040600
		case TQVariant::Quaternion:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQQuaternion,
			               value.value<TQQuaternion>()));
		}

#endif
		case TQVariant::Rect:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRect, value.toRect()));
		}

		case TQVariant::RectF:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRectF, value.toRectF()));
		}

		case TQVariant::RegExp:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRegExp, value.toRegExp()));
		}

		case TQVariant::Region:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRegion, value.value<TQRegion>()));
		}

		case TQVariant::Size:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQSize, value.toSize()));
		}

		case TQVariant::SizeF:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQSizeF, value.toSizeF()));
		}

		case TQVariant::SizePolicy:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQSizePolicy,
			               value.value<TQSizePolicy>()));
		}

		case TQVariant::String:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQString, value.toString()));
		}

		case TQVariant::StringList:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQStringList, value.toStringList()));
		}

		case TQVariant::TextFormat:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQTextFormat,
			               value.value<TQTextFormat>()));
		}

		case TQVariant::TextLength:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQTextLength,
			               value.value<TQTextLength>()));
		}

		case TQVariant::Time:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQTime, value.toTime()));
		}

		case TQVariant::UInt:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(uint, value.toUInt()));
		}

		case TQVariant::ULongLong:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(qulonglong, value.toULongLong()));
		}

		case TQVariant::Url:
		{
			return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQUrl, value.toUrl()));
		}

#if TQT_VERSION >= 0x040600
		case TQVariant::Vector2D:
		{
			return mMethod.invoke(obj, TQt::DirectConnection,
			               Q_ARG(TQVector2D, value.value<TQVector2D>()));
		}

		case TQVariant::Vector3D:
		{
			return mMethod.invoke(obj, TQt::DirectConnection,
			               Q_ARG(TQVector3D, value.value<TQVector3D>()));
		}

		case TQVariant::Vector4D:
		{
			return mMethod.invoke(obj, TQt::DirectConnection,
			               Q_ARG(TQVector4D, value.value<TQVector4D>()));
		}

#endif
		default:
		{
			return false;
		}
	}
}
*/

#include "UiGuiSettings.moc"