File: frmMainConfig.cpp

package info (click to toggle)
pgadmin3 1.20.0~beta2-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 73,704 kB
  • ctags: 18,591
  • sloc: cpp: 193,786; ansic: 18,736; sh: 5,154; pascal: 1,120; yacc: 927; makefile: 516; lex: 421; xml: 126; perl: 40
file content (717 lines) | stat: -rw-r--r-- 17,734 bytes parent folder | download
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
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2014, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// frmMainConfig.cpp - Backend configuration tool
//
//////////////////////////////////////////////////////////////////////////

#include "pgAdmin3.h"

#ifdef __WXMSW__
#include <io.h>
#include <fcntl.h>
#endif

#include <wx/imaglist.h>

#include "ctl/ctlMenuToolbar.h"
#include "frm/frmMainConfig.h"
#include "frm/frmMain.h"
#include "dlg/dlgMainConfig.h"
#include "utils/utffile.h"
#include "schema/pgServer.h"
#include "frm/menu.h"
#include "utils/pgfeatures.h"

#include <wx/arrimpl.cpp>
WX_DEFINE_OBJARRAY(pgConfigOrgLineArray);

#define CTL_CFGVIEW 345


BEGIN_EVENT_TABLE(frmMainConfig, frmConfig)
	EVT_MENU(MNU_UNDO,                      frmMainConfig::OnUndo)
	EVT_MENU(MNU_CONTENTS,                  frmMainConfig::OnContents)
	EVT_LIST_ITEM_ACTIVATED(CTL_CFGVIEW,    frmMainConfig::OnEditSetting)
	EVT_LIST_ITEM_SELECTED(CTL_CFGVIEW,     frmMainConfig::OnSelectSetting)
END_EVENT_TABLE()


#define BCE_TITLE _("Backend Configuration Editor")


frmMainConfig::frmMainConfig(frmMain *parent, pgServer *server)
	: frmConfig(parent, BCE_TITLE, 0)
{
	wxString applicationname = appearanceFactory->GetLongAppName() + _(" - Configuration Editor");
	if (server)
	{
		conn = server->CreateConn(wxEmptyString, 0, applicationname);
		serverVersionNumber = server->GetVersionNumber();
	}
	else
		serverVersionNumber = wxEmptyString;

	InitForm();
	Init();

	if (conn)
	{
		if (serverFileName.IsEmpty())
			serverFileName = wxT("postgresql.conf");


		wxString txt;
		txt.Printf(_(" - %s on %s (%s:%d)"),
		           serverFileName.c_str(), server->GetDescription().c_str(),
		           server->GetName().c_str(), server->GetPort());
		SetTitle(BCE_TITLE + txt);

		wxString str;
		str = conn->ExecuteScalar(wxT("SELECT pg_file_read('") + serverFileName + wxT("', 0, ")
		                          wxT("pg_file_length('") + serverFileName + wxT("'))"));

		DisplayFile(str);

		statusBar->SetStatusText(wxString::Format(_(" Configuration read from %s"), conn->GetHost().c_str()));
	}
}


frmMainConfig::frmMainConfig(const wxString &title, const wxString &configFile)
	: frmConfig(title + wxT(" - ") + _("Backend Configuration Editor"), configFile)
{
	InitForm();
	Init();
	OpenLastFile();
}


frmMainConfig::~frmMainConfig()
{
	options.clear();
	categories.clear();
	lines.Clear();
}


void frmMainConfig::Init(pgSettingReader *reader)
{
	pgSettingItem *item;
	do
	{
		item = reader->GetNextItem();
		if (item)
		{
			if (item->context == pgSettingItem::PGC_INTERNAL)
				delete item;
			else
			{
				if (options[item->name])
					delete item;
				else
				{
					options[item->name] = item;

					wxArrayString *category = categories[item->category];
					if (!category)
					{
						category = new wxArrayString;
						categories[item->category] = category;
					}
					category->Add(item->name);
				}
			}
		}
	}
	while (item);

	editMenu->Enable(MNU_DELETE, false);
	toolBar->EnableTool(MNU_DELETE, false);
}


void frmMainConfig::Init()
{
	// Cleanup first, in case we're re-initing
	options.clear();
	categories.clear();
	lines.Clear();

	pgSettingReader *reader;
	if (conn)
	{
		// read settings from server
		reader = new pgSettingDbReader(conn);
	}
	else
	{
		// read settings from file. First, use localized file...
		reader = new pgSettingFileReader(true);

		if (reader->IsValid())
			Init(reader);
		delete reader;

		// ... then add default file
		reader = new pgSettingFileReader(false);
	}

	if (reader->IsValid())
		Init(reader);

	delete reader;
}

void frmMainConfig::InitForm()
{
	appearanceFactory->SetIcons(this);

	InitFrame(wxT("frmMainConfig"));
	RestorePosition(50, 50, 600, 600, 300, 200);

	cfgList = new ctlListView(this, CTL_CFGVIEW, wxDefaultPosition, wxDefaultSize, wxSIMPLE_BORDER);

	cfgList->SetImageList(configImageList, wxIMAGE_LIST_SMALL);

	cfgList->AddColumn(_("Setting name"), 120);
	cfgList->AddColumn(_("Value"), 80);
	if (conn)
		cfgList->AddColumn(_("Current value"), 80);
	cfgList->AddColumn(_("Comment"), 400);
}

void frmMainConfig::OnSelectSetting(wxListEvent &event)
{

	// Disable undo because we don't want to undo the wrong line.
	editMenu->Enable(MNU_UNDO, false);
	toolBar->EnableTool(MNU_UNDO, false);
}

void frmMainConfig::OnEditSetting(wxListEvent &event)
{
	wxString name = cfgList->GetText(event.GetIndex());
	if (!name.IsEmpty())
	{
		pgSettingItem *item = options[name];
		wxASSERT(item);
		dlgMainConfig dlg(this, item);
		dlg.Go();

		if (item->orgLine && !item->newLine->Differs(item->orgLine))
		{
			delete item->newLine;
			item->newLine = 0;
		}
		else
		{
			changed = true;
			fileMenu->Enable(MNU_SAVE, true);
			editMenu->Enable(MNU_UNDO, true);
			toolBar->EnableTool(MNU_SAVE, true);
			toolBar->EnableTool(MNU_UNDO, true);


		}
		UpdateLine(event.GetIndex());
	}
}


void frmMainConfig::OnContents(wxCommandEvent &event)
{
	DisplayHelp(wxT("index"), HELP_PGADMIN);
}


wxString frmMainConfig::GetHelpPage() const
{
	wxString page;
	if (page.IsEmpty())
		page = wxT("runtime-config");

	return page;
}


void frmMainConfig::OnUndo(wxCommandEvent &ev)
{
	wxString name = cfgList->GetText(cfgList->GetSelection());
	if (!name.IsEmpty())
	{
		pgSettingItem *item = options[name];
		if (item->newLine)
		{
			delete item->newLine;
			item->newLine = 0;
			UpdateLine(cfgList->GetSelection());
		}
	}
}



void frmMainConfig::UpdateLine(int pos)
{
	wxString name = cfgList->GetText(pos);
	if (!name.IsEmpty())
	{
		pgSettingItem *item = options[name];

		pgConfigLine *line = item->newLine;
		if (!line)
			line = item->orgLine;

		wxString value, comment;
		int imgIndex = 0;
		if (line)
		{
			value = line->value;
			comment = line->comment;
			if (!line->isComment)
				imgIndex = 1;
		}
		cfgList->SetItem(pos, 1, value);

		if (conn)
			cfgList->SetItem(pos, 3, comment);
		else
			cfgList->SetItem(pos, 2, comment);

		cfgList->SetItemImage(pos, imgIndex, imgIndex);
	}
}


void frmMainConfig::WriteFile(pgConn *conn)
{

	size_t i;

	wxString str;
	for (i = 0 ; i < lines.GetCount() ; i++)
		str.Append(lines.Item(i).GetNewText() + wxT("\n"));

	for (i = 0 ; i < (size_t)cfgList->GetItemCount() ; i++)
	{
		pgSettingItem *item = options[cfgList->GetText(i)];

		if (item && item->newLine && item->newLine->item && !item->orgLine)
			str.Append(item->newLine->GetNewText() + wxT("\n"));
	}


	if (DoWriteFile(str, conn))
	{
		changed = false;
		fileMenu->Enable(MNU_SAVE, false);
		editMenu->Enable(MNU_UNDO, false);
		toolBar->EnableTool(MNU_SAVE, false);
		toolBar->EnableTool(MNU_UNDO, false);

		size_t i;
		for (i = 0 ; i < (size_t)cfgList->GetItemCount() ; i++)
		{
			pgSettingItem *item = options[cfgList->GetText(i)];

			if (item && item->newLine)
			{
				if (!item->orgLine)
				{
					item->orgLine = new pgConfigOrgLine(item->newLine);
					lines.Add(item->orgLine);
					item->orgLine->item = item;
				}
				else
				{
					item->orgLine->comment = item->newLine->comment;
					item->orgLine->isComment = item->newLine->isComment;
					item->orgLine->value = item->newLine->value;
					item->orgLine->text = item->orgLine->GetNewText();
				}
			}
		}


		for (i = 0 ; i < lines.GetCount() ; i++)
		{
			pgConfigOrgLine &line = lines.Item(i);
			if (line.item && line.item->newLine)
			{
				line.text = line.GetNewText();
				delete line.item->newLine;
				line.item->newLine = 0;
			}
		}
	}
}



void frmMainConfig::DisplayFile(const wxString &str)
{
	Init();

	filetype = wxTextFileType_Unix;
	wxStringTokenizer strtok;
	wxArrayString *unknownCategory = 0;

	if (str.Find('\r') >= 0)
	{
		if (str.Find(wxT("\n\r")) >= 0 || str.Find(wxT("\r\n")))
			filetype = wxTextFileType_Dos;
		else
			filetype = wxTextFileType_Mac;

		strtok.SetString(wxTextBuffer::Translate(str, wxTextFileType_Unix), wxT("\n"), wxTOKEN_RET_EMPTY);
	}
	else
		strtok.SetString(str, wxT("\n"), wxTOKEN_RET_EMPTY);

	while (strtok.HasMoreTokens())
	{
		pgConfigOrgLine *line = new pgConfigOrgLine(strtok.GetNextToken());
		lines.Add(line);

		// identify option
		bool isComment = false;
		const wxChar *p = line->text.c_str();

		// identify keywords
		while (*p && wxStrchr(wxT("# \n"), *p))
		{
			if (*p == '#')
				isComment = true;
			p++;
		}

		if (!*p)
			isComment = true;

		line->isComment = isComment;

		const wxChar *p2 = p;
		while (*p2 && *p2 != '#' && *p2 != ' ' && *p2 != '\t' && *p2 != '=')
			p2++;

		if (p2 != p)
		{
			wxString keyword = line->text.Mid(p - line->text.c_str(), p2 - p);

			pgSettingItemHashmap::iterator it = options.find(keyword);

			pgSettingItem *item;
			if (it == options.end())
			{
				if (isComment)
					continue;

				item = new pgSettingItem;
				item->name = keyword;
				item->category = _("Unknown");
				item->short_desc = _("Unknown option");
				item->extra_desc = _("This option is present in the configuration file, but not known to the configuration tool.");
				item->SetType(wxT("string"));

				options[item->name] = item;

				if (!unknownCategory)
				{
					unknownCategory = new wxArrayString;
					categories[item->category] = unknownCategory;
				}
				unknownCategory->Add(item->name);
			}
			else
				item = it->second;


			if (!isComment || !item->orgLine || item->orgLine->isComment)
			{
				line->item = item;
				if (item->orgLine)
					item->orgLine->item = 0;
				item->orgLine = line;
			}
			while (*p2 && *p2 != '=')
				p2++;

			p2++;   // skip =
			while (*p2 && wxStrchr(wxT(" \t"), *p2))
				p2++;

			wxChar quoteChar = 0;
			if (wxStrchr(wxT("'\""), *p2))
				quoteChar = *p2++;

			const wxChar *p3 = p2;
			while (*p3)
			{
				if (*p3 == quoteChar || (!quoteChar && wxStrchr(wxT(" \t#"), *p3)))
					break;
				p3++;
			}
			if (p2 != p3)
			{
				line->value = line->text.Mid(p2 - line->text.c_str(), p3 - p2);
				if (quoteChar)
					p3++;

				const wxChar *p4 = p3;
				while (*p4 && wxStrchr(wxT(" \t#"), *p4))
					p4++;

				line->commentIndent = line->text.Mid(p3 - line->text.c_str(), p4 - p3);
				line->comment = p4;
			}
		}
	}

	cfgList->DeleteAllItems();

	double versionNum;
	bool versionRetVal = serverVersionNumber.ToDouble(&versionNum);

	// we want to show options ordered by category/name
	// category might be localized, and we want a distinct category ordering

	FillList(wxT("listen_addresses"));          // Connections and Authentication / Connection Settings
	FillList(wxT("authentication_timeout"));    // Connections and Authentication / Security and Authentication
	FillList(wxT("check_function_bodies"));     // Client Connection Defaults / Statement Behaviour
	FillList(wxT("lc_messages"));               // Client Connection Defaults / Locale and Formatting
	if (versionRetVal && versionNum < 8.4)
		FillList(wxT("explain_pretty_print"));      // Client Connection Defaults / Other Defaults
	FillList(wxT("enable_hashjoin"));           // Query Tuning / Planner Method Configuration
	FillList(wxT("cpu_operator_cost"));         // Query Tuning / Planner Cost Constants
	if (!conn || !conn->GetIsGreenplum())       // Greenplum doesn't have the Genetic Query Optimizer
		FillList(wxT("geqo"));                  // Query Tuning / Genetic Query Optimizer
	FillList(wxT("default_statistics_target")); // Query Tuning / Other Planner Options
	FillList(wxT("deadlock_timeout"));          // Lock Management
	FillList(wxT("shared_buffers"));            // Resource Usage / Memory
	if (versionRetVal && versionNum < 8.4)
		FillList(wxT("max_fsm_pages"));             // Resource Usage / Free Space Map
	FillList(wxT("bgwriter_delay"));            // Resource Usage
	FillList(wxT("max_files_per_process"));     // Resource Usage / Kernel Resources
	FillList(wxT("log_connections"));           // Reporting and Logging / What to Log
	FillList(wxT("client_min_messages"));       // Reporting and Logging / When to Log
	FillList(wxT("log_destination"));           // Reporting and Logging / Where to Log
	FillList(wxT("stats_command_string"), wxT("track_activities"));      // Statistics / Query and Index Statistics Collector
	FillList(wxT("log_executor_stats"));        // Statistics / Monitoring
	FillList(wxT("fsync"));                     // Write-Ahead Log / Settings
	FillList(wxT("checkpoint_segments"));       // Write-Ahead Log / Checkpoints
	if (versionRetVal && versionNum <= 8.4)
		FillList(wxT("add_missing_from"));          // Version and Platform Compatibility / Previous PostgreSQL Version
	FillList(wxT("transform_null_equals"));     // Version and Platform Compatibility / Other Platforms and Clients
	if (!conn || !conn->GetIsGreenplum())       // Greenplum doesn't have trace_notify visible
		FillList(wxT("trace_notify"));          // Developer Options
	FillList(wxT("hba_file"));                  // Ungrouped


	// for all we didn't get
	while (!categories.empty())
	{
		pgCategoryHashmap::iterator it = categories.begin();
		wxString missed = it->first;
		FillList(it->second);
		categories.erase(it);
	}
}


void frmMainConfig::FillList(const wxString &categoryMember, const wxString &altCategoryMember)
{
	pgSettingItem *categoryItem = options[categoryMember];

	if (!categoryItem && !altCategoryMember.IsEmpty())
		categoryItem = options[altCategoryMember];

	wxASSERT_MSG(categoryItem, wxString::Format(wxT("%s/%s"), categoryMember.c_str(), altCategoryMember.c_str()));

	if (categoryItem)
	{
		FillList(categories[categoryItem->category]);
		categories.erase(categoryItem->category);
	}
}


void frmMainConfig::FillList(wxArrayString *category)
{
	if (category)
	{
		size_t i;
		for (i = 0 ; i < category->GetCount() ; i++)
		{
			pgSettingItem *item = options[category->Item(i)];
			wxASSERT(item);

			wxString value;
			wxString comment;
			int imgIndex = 0;
			if (item->orgLine)
			{
				if (!item->orgLine->isComment)
					imgIndex = 1;
				value = item->orgLine->value;
				comment = item->orgLine->comment;
				comment.Replace(wxT("\t"), wxT(" "));
			}
			long pos = cfgList->AppendItem(imgIndex, item->name, value);
			if (conn)
			{
				cfgList->SetItem(pos, 2, item->value);
				cfgList->SetItem(pos, 3, comment);
			}
			else
				cfgList->SetItem(pos, 2, comment);
		}
		delete category;
	}
}



enum
{
    HINT_LISTEN_ADDRESSES,
    HINT_AUTOVACUUM_CFG
};


const wxChar *hintString[] =
{
	_("The PostgreSQL server engine is currently configured to listen for local connections only.\nYou might want to check \"listen_addresses\" to enable accessing the server over the network too."),
	_("The autovacuum backend process is not running.\nIt is recommended to enable it by setting 'track_counts' and 'autovacuum' to 'on' in PostgreSQL 8.3 and above or 'stats_start_collector', 'stats_row_level' and 'autovacuum' to 'on' in earlier versions.")
};


wxString frmMainConfig::GetHintString()
{
	wxArrayInt hints;
	size_t i;
	int autovacuum = 0;
	bool autovacuumPresent = false;

	for (i = 0 ; i < (size_t)cfgList->GetItemCount() ; i++)
	{
		pgSettingItem *item = options[cfgList->GetText(i)];

		if (item)
		{
			wxString name = item->name;
			wxString value = item->GetActiveValue();
			if (name == wxT("listen_addresses"))
			{
				if (value.IsEmpty() || value == wxT("localhost"))
					hints.Add(HINT_LISTEN_ADDRESSES);
			}
			else if (name == wxT("autovacuum"))
			{
				autovacuumPresent = true;
				if (StrToBool(value))
					autovacuum++;
			}
			else if (name == wxT("stats_start_collector") || name == wxT("stats_row_level"))
			{
				if (StrToBool(value))
					autovacuum++;
			}
			else if (name == wxT("track_counts"))
			{
				// Double increment, because track_counts in 8.3 is worth both previous options.
				if (StrToBool(value))
					autovacuum = autovacuum + 2;
			}
		}
	}

	if (autovacuumPresent && autovacuum < 3)
		hints.Add(HINT_AUTOVACUUM_CFG);

	wxString str;
	for (i = 0 ; i < hints.GetCount() ; i++)
	{
		if (i)
			str.Append(wxT("\n\n"));
		str.Append(hintString[hints.Item(i)]);
	}

	return str;
}

void frmMainConfig::OnOpen(wxCommandEvent &event)
{
	if (CheckChanged(true))
		return;

#ifdef __WXMSW__
	wxFileDialog dlg(this, _("Open configuration file"), lastDir, wxT(""),
	                 _("Configuration files (*.conf)|*.conf|All files (*.*)|*.*"), wxFD_OPEN);
#else
	wxFileDialog dlg(this, _("Open configuration file"), lastDir, wxT(""),
	                 _("Configuration files (*.conf)|*.conf|All files (*)|*"), wxFD_OPEN);
#endif
	if (dlg.ShowModal() == wxID_OK)
	{
		Init();

		lastFilename = dlg.GetFilename();
		lastDir = dlg.GetDirectory();
		lastPath = dlg.GetPath();
		OpenLastFile();
		UpdateRecentFiles();
	}
}

mainConfigFactory::mainConfigFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : actionFactory(list)
{
	mnu->Append(id, wxT("postgresql.conf"), _("Edit general server configuration file."));
}


wxWindow *mainConfigFactory::StartDialog(frmMain *form, pgObject *obj)
{
	pgServer *server = obj->GetServer();
	if (server)
	{
		frmConfig *frm = new frmMainConfig(form, server);
		frm->Go();
		return frm;
	}
	return 0;
}


bool mainConfigFactory::CheckEnable(pgObject *obj)
{
	if (obj)
	{
		pgServer *server = obj->GetServer();
		if (server)
		{
			pgConn *conn = server->GetConnection();
			return conn && server->GetSuperUser() &&  conn->HasFeature(FEATURE_FILEREAD);
		}
	}
	return false;
}


mainConfigFileFactory::mainConfigFileFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : actionFactory(list)
{
	mnu->Append(id, _("Open postgresql.conf..."), _("Open configuration editor with postgresql.conf."));
}


wxWindow *mainConfigFileFactory::StartDialog(frmMain *form, pgObject *obj)
{
	frmConfig *dlg = new frmMainConfig(form);
	dlg->Go();
	dlg->DoOpen();
	return dlg;
}