File: events.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 (1172 lines) | stat: -rw-r--r-- 30,343 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
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
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2014, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// events.cpp - Event handlers for frmMain
//
//
//////////////////////////////////////////////////////////////////////////

#include "pgAdmin3.h"

// wxWindows headers
#include <wx/wx.h>
#include <wx/settings.h>
#include <wx/treectrl.h>
#include <wx/listctrl.h>
#include <wx/imaglist.h>
#include <wx/stc/stc.h>
#include <wx/busyinfo.h>
#include <wx/aui/aui.h>

// App headers
#include "utils/misc.h"
#include "frm/menu.h"
#include "frm/frmMain.h"
#include "frm/frmOptions.h"
#include "ctl/ctlSQLBox.h"
#include "ctl/ctlMenuToolbar.h"
#include "db/pgConn.h"
#include "schema/pgDatabase.h"
#include "db/pgSet.h"
#include "schema/pgServer.h"
#include "schema/pgObject.h"
#include "schema/pgCollection.h"
#include "schema/pgTable.h"
#include "schema/edbPrivateSynonym.h"
#include "dlg/dlgProperty.h"

// Mutex to protect the "currentObject" from race conditions.
//
static wxMutex s_currentObjectMutex;

// Event table
BEGIN_EVENT_TABLE(frmMain, pgFrame)
	EVT_CHILD_FOCUS(			frmMain::OnChildFocus)
	EVT_ERASE_BACKGROUND(                   frmMain::OnEraseBackground)
	EVT_SIZE(                               frmMain::OnSize)
	EVT_MENU(MNU_ACTION,                    frmMain::OnAction)

	EVT_MENU(MNU_COPY,			frmMain::OnCopy)
	EVT_MENU(MNU_DELETE,                    frmMain::OnDelete)
	EVT_MENU(MNU_SAVEDEFINITION,            frmMain::OnSaveDefinition)
	EVT_MENU(MNU_SQLPANE,                   frmMain::OnToggleSqlPane)
	EVT_MENU(MNU_OBJECTBROWSER,             frmMain::OnToggleObjectBrowser)
	EVT_MENU(MNU_TOOLBAR,                   frmMain::OnToggleToolBar)
	EVT_MENU(MNU_DEFAULTVIEW,               frmMain::OnDefaultView)
	EVT_MENU(MNU_CHECKALIVE,                frmMain::OnCheckAlive)
	EVT_MENU(MNU_CONTEXTMENU,               frmMain::OnContextMenu)

	EVT_AUINOTEBOOK_PAGE_CHANGED(wxID_ANY,	frmMain::OnPageChange)
	EVT_LIST_ITEM_SELECTED(CTL_PROPVIEW,    frmMain::OnPropSelChanged)
	EVT_LIST_ITEM_ACTIVATED(CTL_PROPVIEW,   frmMain::OnPropSelActivated)
	EVT_LIST_ITEM_RIGHT_CLICK(CTL_PROPVIEW, frmMain::OnPropRightClick)
	EVT_LIST_ITEM_SELECTED(CTL_STATVIEW,    frmMain::OnSelectItem)
	EVT_LIST_ITEM_SELECTED(CTL_DEPVIEW,     frmMain::OnSelectItem)
	EVT_LIST_ITEM_SELECTED(CTL_REFVIEW,     frmMain::OnSelectItem)
	EVT_TREE_SEL_CHANGED(CTL_BROWSER,       frmMain::OnTreeSelChanged)
	EVT_TREE_ITEM_EXPANDING(CTL_BROWSER,    frmMain::OnExpand)
	EVT_TREE_ITEM_COLLAPSING(CTL_BROWSER,   frmMain::OnCollapse)
	EVT_TREE_ITEM_ACTIVATED(CTL_BROWSER,    frmMain::OnSelActivated)
	EVT_TREE_ITEM_RIGHT_CLICK(CTL_BROWSER,  frmMain::OnSelRightClick)
	EVT_STC_UPDATEUI(CTL_SQLPANE,           frmMain::OnPositionStc)
	EVT_CLOSE(                              frmMain::OnClose)

	EVT_AUI_PANE_CLOSE(                     frmMain::OnAuiUpdate)
	EVT_AUINOTEBOOK_PAGE_CLOSE(wxID_ANY,    frmMain::OnAuiNotebookPageClose)

#ifdef __WXGTK__
	EVT_TREE_KEY_DOWN(CTL_BROWSER,          frmMain::OnTreeKeyDown)
#endif

#if defined(HAVE_OPENSSL_CRYPTO) || defined(HAVE_GCRYPT)
	EVT_COMMAND (wxID_ANY, SSH_TUNNEL_ERROR_EVENT, frmMain::OnSSHTunnelEvent)
#endif

END_EVENT_TABLE()

void frmMain::OnChildFocus(wxChildFocusEvent &event)
{
	// Grab the focussed control and stash it away for later use
	currentControl = dynamic_cast<wxControl *>(event.GetEventObject());

	// Setup the menu controls according to the control that's selected
	// and it's status.

	// Defaults.
	editMenu->Enable(MNU_COPY, false);

	// ctlSQLBox?
	ctlSQLBox *sb = dynamic_cast<ctlSQLBox *>(event.GetEventObject());
	if (sb)
	{
		// Copy
		editMenu->Enable(MNU_COPY, !sb->GetSelectedText().IsEmpty());
	}

	// Listview?
	ctlListView *lv = dynamic_cast<ctlListView *>(event.GetEventObject());
	if (lv)
	{
		// Copy
		editMenu->Enable(MNU_COPY, lv->GetSelectedItemCount() > 0);
	}
}

void frmMain::OnEraseBackground(wxEraseEvent &event)
{
	event.Skip();
}

void frmMain::OnSize(wxSizeEvent &event)
{
	event.Skip();
}

// unfortunately, under GTK we won't get the original wxKeyEvent
// to reset m_metaDown
void frmMain::OnTreeKeyDown(wxTreeEvent &event)
{
	switch (event.GetKeyCode())
	{
		case WXK_F1:
			OnHelp(event);
			break;
		case WXK_F5:
			Refresh(currentObject);
			break;
		case WXK_DELETE:
			OnDelete(event);
			break;
		default:
			event.Skip();
			break;
	}
}

void frmMain::OnExit(wxCommandEvent &event)
{
	Close(false);   // Allow sub windows to stop us
	event.Skip();
}



void frmMain::OnClose(wxCloseEvent &event)
{
	wxWindow *fr;
	windowList::Node *node;
	while ((node = frames.GetFirst()) != NULL)
	{
		fr = node->GetData();

		// if crashes occur here when closing the app,
		// some actionFactory::StartDialog returned a wxWindow* (which is registered in frames)
		// without code to handle OnClose (esp. removing itself with RemoveFrame)

		if (!fr->Close(!event.CanVeto()))
		{
			if (event.CanVeto())
			{
				event.Veto();
				return;
			}
		}
		delete node;
		fr->Destroy();
	}
	Destroy();
}


void frmMain::UpdateAllRecentFiles()
{
	wxWindow *fr;
	windowList::Node *node;
	node = frames.GetFirst();
	while (node)
	{
		fr = node->GetData();
		((frmQuery *)fr)->UpdateRecentFiles(false);
		node = node->GetNext();
	}
}


void frmMain::UpdateAllFavouritesList()
{
	wxWindow *fr;
	windowList::Node *node;
	node = frames.GetFirst();
	while (node)
	{
		fr = node->GetData();
		((frmQuery *)fr)->UpdateFavouritesList();
		node = node->GetNext();
	}
}

void frmMain::UpdateAllMacrosList()
{
	wxWindow *fr;
	windowList::Node *node;
	node = frames.GetFirst();
	while (node)
	{
		fr = node->GetData();
		((frmQuery *)fr)->UpdateMacrosList();
		node = node->GetNext();
	}
}


void frmMain::OnAction(wxCommandEvent &ev)
{
	actionFactory *af = menuFactories->GetFactory(ev.GetId());
	if (af)
	{
		wxWindow *wnd = af->StartDialog(this, currentObject);
		if (wnd)
			AddFrame(wnd);
	}
}

wxString frmMain::GetHelpPage() const
{
	wxString page;

	if (currentObject)
		page = currentObject->GetHelpPage(true);

	if (page.IsEmpty())
		page = wxT("pg/sql-commands");

	return page;
}

void frmMain::OnCollapse(wxTreeEvent &event)
{
#ifdef WIN32
	// This is weird stuff, but somewhere comes a collapse after we have done
	// connecting the server and expanding the tree.
	// Possibly not necessary
	if (event.GetItem() == denyCollapseItem)
		event.Veto();
#endif
	denyCollapseItem = wxTreeItemId();
}


void frmMain::OnExpand(wxTreeEvent &event)
{
	wxCookieType cookie;
	wxTreeItemId item = browser->GetFirstChild(event.GetItem(), cookie);
	if (item && !browser->GetItemData(item))
	{
		// the expanding node has a dummy item.
		// delete dummy item, and expand kids.
		execSelChange(event.GetItem(), browser->GetSelection() == item);

		// we don't have any kids, so don't expand
		if (!browser->GetChildrenCount(event.GetItem()))
			event.Veto();
	}
}


void frmMain::OnCheckAlive(wxCommandEvent &event)
{
	CheckAlive();
}



void frmMain::OnPropSelChanged(wxListEvent &event)
{
	if (properties->GetSelectedItemCount() == 1)
	{
		wxTreeItemId item = browser->GetSelection();
		if (item)
		{
			pgObject *data = browser->GetObject(item);
			if (data && data->IsCollection())
			{
				currentObject = ((pgCollection *)data)->FindChild(browser, event.GetIndex());
				if (currentObject)
				{
					setDisplay(currentObject);
					sqlPane->SetReadOnly(false);
					sqlPane->SetText(currentObject->GetSql(browser));
					sqlPane->SetReadOnly(true);
				}
			}
		}
	}

	editMenu->Enable(MNU_COPY, properties->GetSelectedItemCount() > 0);

// The generic list view control on the Mac doesn't fire focus events
// as it should, so we set currentControl here instead of relying on
// the ChildFocusEvent. The native list view does fire the events, but
// does weird things with multi-select items so we currently disable
// it (see the creation of the listviews in frmMain.cpp).
#ifdef __WXMAC__
	currentControl = properties;
#endif
}


void frmMain::OnSelectItem(wxListEvent &event)
{
	ctlListView *list;

	switch(listViews->GetSelection())
	{
		case NBP_STATISTICS:
			list = statistics;
			break;
		case NBP_DEPENDENCIES:
			list = dependencies;
			break;
		case NBP_DEPENDENTS:
			list = dependents;
			break;
		default:
			// This shouldn't happen.
			// If it does, it's no big deal, we just need to get out.
			return;
			break;
	}

	editMenu->Enable(MNU_COPY, list->GetSelectedItemCount() > 0);

// The generic list view control on the Mac doesn't fire focus events
// as it should, so we set currentControl here instead of relying on
// the ChildFocusEvent. The native list view does fire the events, but
// does weird things with multi-select items so we currently disable
// it (see the creation of the listviews in frmMain.cpp).
#ifdef __WXMAC__
	currentControl = list;
#endif
}

void frmMain::OnPropSelActivated(wxListEvent &event)
{
	if (propFactory->CheckEnable(currentObject))
		propFactory->StartDialog(this, currentObject);
}


void frmMain::OnPropRightClick(wxListEvent &event)
{
	OnPropSelChanged(event);

	if (currentObject)
		doPopup(properties, event.GetPoint(), currentObject);
}


void frmMain::OnTreeSelChanged(wxTreeEvent &event)
{
	/*
	    * Do not honour the tree selection change, while a property dialog is
	    * closed and refresh is in progress
	*/
	if (m_refreshing)
		return;

	denyCollapseItem = wxTreeItemId();
	// Reset the listviews/SQL pane
	if (event.GetItem())
		execSelChange(event.GetItem(), true);
}


// Reset the list controls
void frmMain::ResetLists()
{
	properties->ClearAll();
	properties->AddColumn(_("Properties"), properties->GetSize().GetWidth() - 10);
	properties->InsertItem(0, _("No properties are available for the current selection"), PGICON_PROPERTY);
	statistics->ClearAll();
	statistics->AddColumn(_("Statistics"), properties->GetSize().GetWidth() - 10);
	statistics->InsertItem(0, _("No statistics are available for the current selection"), PGICON_PROPERTY);
	dependencies->ClearAll();
	dependencies->AddColumn(_("Dependencies"), properties->GetSize().GetWidth() - 10);
	dependencies->InsertItem(0, _("No dependency information is available for the current selection"), PGICON_PROPERTY);
	dependents->ClearAll();
	dependents->AddColumn(_("Dependents"), properties->GetSize().GetWidth() - 10);
	dependents->InsertItem(0, _("No dependent information is available for the current selection"), PGICON_PROPERTY);
}


void frmMain::execSelChange(wxTreeItemId item, bool currentNode)
{
	static bool refresh = true;

	if (currentNode)
	{
		ResetLists();
		sqlPane->Clear();
	}

	// Get the item data, and feed it to the relevant handler,
	// cast as required.
	//
	// Lock the assignment to prevent the race conditions between onSelRightClick and execSelChange.
	//
	s_currentObjectMutex.Lock();
	currentObject = browser->GetObject(item);
	s_currentObjectMutex.Unlock();

	// If we didn't get an object, then we may have a right click, or
	// invalid click, so ignore.
	if (!currentObject)
	{
		menuFactories->CheckMenu(currentObject, menuBar, toolBar);
	}
	else
	{
		int settingRefreshOnClick = settings->GetRefreshOnClick();

		if (settingRefreshOnClick != REFRESH_OBJECT_NONE
		        && refresh
		        && currentObject->GetTypeName() != wxT("Server")
		        && currentObject->GetTypeName() != wxT("Servers")
		        && currentObject->GetTypeName() != wxT("Database")
		        && !currentObject->IsCollection())
		{
			refresh = false;

			if (settingRefreshOnClick == REFRESH_OBJECT_ONLY )
			{
				// We can not update the schema, because it would cause an update to the entire tree.
				if (currentObject->GetTypeName() != wxT("Schema"))
				{
					wxTreeItemId currentItem = currentObject->GetId();

					// Do not refresh and instead bail out if dialog of the currently selected
					// node or it's child node is open, as refresh would delete this node's object
					// and could cause a crash
					pgObject *obj = NULL;
					if (currentItem)
						obj = browser->GetObject(currentItem);

					if (obj && obj->CheckOpenDialogs(browser, currentItem))
					{
						properties->Freeze();
						setDisplay(currentObject, properties, sqlPane);
						properties->Thaw();
						refresh = true;
						return;
					}

					pgObject *newData = currentObject->Refresh(browser, currentItem);

					if (newData != 0)
					{
						wxLogInfo(wxT("Replacing with new node %s %s for refresh"), newData->GetTypeName().c_str(), newData->GetQuotedFullIdentifier().c_str());

						browser->DeleteChildren(currentItem);
						newData->SetId(currentItem);    // not done automatically
						browser->SetItemData(currentItem, newData);

						// Update the node text if this is an object, as it may have been renamed
						if (!newData->IsCollection())
							browser->SetItemText(currentItem, newData->GetDisplayName());

						delete currentObject;
						currentObject = newData;
					}
					else
					{
						// OK, we failed to refresh, so select the parent and delete the child.
						browser->SelectItem(browser->GetItemParent(currentItem));
						browser->Delete(currentItem);
					}
				}
			}
			else
				Refresh(currentObject);

			refresh = true;
		}


		if (currentNode)
		{
			properties->Freeze();
			setDisplay(currentObject, properties, sqlPane);
			properties->Thaw();
		}
		else
			setDisplay(currentObject, 0, 0);
	}
}


void frmMain::setDisplay(pgObject *data, ctlListView *props, ctlSQLBox *sqlbox)
{
	pgServer *server = 0;


	bool showTree = false;

	pgaFactory *factory = data->GetFactory();
	if (factory)
	{
		if (factory == &serverFactory)
		{
			server = (pgServer *)data;

			data->ShowTree(this, browser, props, sqlbox);
			showTree = false;
		}
		else
			showTree = true;
	}
	else
		showTree = false;

	if (showTree)
		data->ShowTree(this, browser, props, sqlbox);

	if (sqlbox)
	{
		sqlbox->SetReadOnly(false);
		sqlbox->SetText(data->GetSql(browser));
		sqlbox->SetReadOnly(true);
	}

	pgConn *conn = data->GetConnection();
	if (conn && (conn->GetStatus() == PGCONN_BROKEN || conn->GetStatus() == PGCONN_BAD))
	{
		CheckAlive();
		return;
	}

	unsigned int i;
	wxMenuItem *menuItem;
	i = newMenu->GetMenuItemCount();
	while (i--)
	{
		menuItem = newMenu->GetMenuItems().Item(i)->GetData();
		if (menuItem)
			delete newMenu->Remove(menuItem);
	}

	i = newContextMenu->GetMenuItemCount();
	while (i--)
	{
		menuItem = newContextMenu->GetMenuItems().Item(i)->GetData();
		if (menuItem)
			delete newContextMenu->Remove(menuItem);
	}

	editMenu->Enable(newMenuFactory->GetId(), false);

	wxMenu *indivMenu = data->GetNewMenu();
	if (indivMenu)
	{
		if (indivMenu->GetMenuItemCount())
		{
			editMenu->Enable(newMenuFactory->GetId(), true);

			for (i = 0 ; i < indivMenu->GetMenuItemCount() ; i++)
			{
				menuItem = indivMenu->GetMenuItems().Item(i)->GetData();
#if wxCHECK_VERSION(2, 9, 0)
				wxString lab = menuItem->GetItemLabelText();
#else
				wxString lab = menuItem->GetLabel(); // deprecated
#endif

				newMenu->Append(menuItem->GetId(), lab, menuItem->GetHelp());
				newContextMenu->Append(menuItem->GetId(), lab, menuItem->GetHelp());
			}
		}
		delete indivMenu;
	}

	menuFactories->CheckMenu(data, menuBar, toolBar);

	menuFactories->EnableSubmenu(menuBar, MNU_CONFIGSUBMENU);
	menuFactories->EnableSubmenu(menuBar, MNU_SLONY_SUBMENU);
}


void frmMain::OnSelActivated(wxTreeEvent &event)
{
	// This handler will primarily deal with displaying item
	// properties in seperate windows and 'Add xxx...' clicks

	// Get the item data, and feed it to the relevant handler,
	// cast as required.

	wxTreeItemId item = event.GetItem();
	pgObject *data = browser->GetObject(item);
	if (!data)
		return;
	pgServer *server;
	wxCommandEvent nullEvent;

	if (data->IsCreatedBy(serverFactory))
	{
		server = (pgServer *)data;
		if (!server->GetConnected())
		{
			if (ReconnectServer(server) == PGCONN_OK)
			{
				// prevent from being collapsed immediately

				denyCollapseItem = item;
			}
		}
	}
	else
	{
		if (settings->GetDoubleClickProperties() && propFactory->CheckEnable(data))
		{
			propFactory->StartDialog(this, data);
			event.Skip();
			return;
		}
	}

	browser->Expand(item);
}

void frmMain::doPopup(wxWindow *win, wxPoint point, pgObject *object)
{
	if (treeContextMenu)
		delete treeContextMenu;

	treeContextMenu = new wxMenu();

	menuFactories->AppendEnabledMenus(menuBar, treeContextMenu);

	wxMenuItem *newItem = treeContextMenu->FindItem(newMenuFactory->GetId());

	if (newItem)
	{
		size_t newItemPos;

		wxMenuItemList mil = treeContextMenu->GetMenuItems();
		for (newItemPos = 0 ; newItemPos < mil.GetCount() ; newItemPos++)
		{
			if (mil.Item(newItemPos)->GetData()->GetId() == newItem->GetId())
				break;
		}

		if (object)
		{
			wxMenu *indivMenu = object->GetNewMenu();
			if (indivMenu)
			{

				if (indivMenu->GetMenuItemCount() > 1)
				{
					wxMenuItem *menuItem = menuBar->FindItem(newMenuFactory->GetId());
#if wxCHECK_VERSION(2, 9, 0)
					wxString lab = menuItem->GetItemLabelText();
#else
					wxString lab = menuItem->GetLabel(); // deprecated
#endif

					treeContextMenu->Insert(newItemPos, newMenuFactory->GetId(), lab, indivMenu, menuItem->GetHelp());
				}
				else
				{
					if (indivMenu->GetMenuItemCount() == 1)
					{
						wxMenuItem *menuItem = indivMenu->GetMenuItems().Item(0)->GetData();
#if wxCHECK_VERSION(2, 9, 0)
						wxString lab = menuItem->GetItemLabelText();
#else
						wxString lab = menuItem->GetLabel(); // deprecated
#endif
						treeContextMenu->Insert(newItemPos, menuItem->GetId(), lab, menuItem->GetHelp());
					}
					delete indivMenu;
				}
			}
		}
		treeContextMenu->Remove(newItem);
		delete newItem;
	}

	if (treeContextMenu->GetMenuItemCount())
		win->PopupMenu(treeContextMenu, point);
}

////////////////////////////////////////////////////////////////////////////////
// This handler will display a popup menu for the currently selected item
////////////////////////////////////////////////////////////////////////////////
void frmMain::OnContextMenu(wxCommandEvent &event)
{
	wxPoint point;

	if (FindFocus() == browser)
	{
		wxRect rect;
		wxTreeItemId item = browser->GetSelection();

		browser->GetBoundingRect(item, rect);
		point = rect.GetPosition();
		wxPoint origin = GetClientAreaOrigin();

		// Because this Tree is inside a vertical splitter, we
		// must compensate for the size of the other elements
		point.x += origin.x;
		point.y += origin.y;

		doPopup(this, point, browser->GetObject(item));
	}

}


////////////////////////////////////////////////////////////////////////////////
// This handler will display a popup menu for the item at the mouse position
////////////////////////////////////////////////////////////////////////////////
void frmMain::OnSelRightClick(wxTreeEvent &event)
{
	wxTreeItemId item = event.GetItem();
	if (item != browser->GetSelection())
	{
		browser->SelectItem(item);

		// Prevent changes to "currentObject" by "execSelchange" function by another thread.
		// Will hold the lock until we do popup on the respective object.
		//
		s_currentObjectMutex.Lock();
		currentObject = browser->GetObject(item);
	}

	if (currentObject)
		doPopup(browser, event.GetPoint(), currentObject);
	s_currentObjectMutex.Unlock();
}


void frmMain::OnDelete(wxCommandEvent &ev)
{
	if (currentObject->CanDrop())
		ExecDrop(false);
}


void frmMain::ExecDrop(bool cascaded)
{
	wxTreeItemId item = browser->GetSelection();
	pgCollection *collection = (pgCollection *)browser->GetObject(item);

	// Get any table object for later update
	wxTreeItemId owneritem;
	pgObject *node = (pgObject *)browser->GetObject(item);

	int metatype = node->GetMetaType();

	switch (metatype)
	{
		case PGM_COLUMN:
			owneritem = node->GetTable()->GetId();
			break;

		case PGM_CHECK:
		case PGM_CONSTRAINT:
		case PGM_EXCLUDE:
		case PGM_FOREIGNKEY:
		case PGM_INDEX:
		case PGM_PRIMARYKEY:
		case PGM_UNIQUE:
		case PGM_TRIGGER:
		case PGM_RULE: // Rules are technically table objects! Yeuch
		case EDB_PACKAGEFUNCTION:
		case EDB_PACKAGEVARIABLE:
		case PGM_SCHEDULE:
		case PGM_STEP:
			if (node->IsCollection())
				owneritem = browser->GetParentObject(node->GetId())->GetId();
			else
				owneritem = browser->GetParentObject(browser->GetParentObject(node->GetId())->GetId())->GetId();
			break;

		default:
			break;
	}

	// Grab the parent item to re-focus on.
	wxString parent = GetNodePath(item).BeforeLast('/');

	bool success = false;
	if (collection == currentObject)
		success = dropSingleObject(currentObject, true, cascaded);
	else
	{
		if (collection && collection->IsCollection())
		{
			long index = properties->GetFirstSelected();

			if (index >= 0)
			{
				pgObject *data = collection->FindChild(browser, index);

				if (!data || !data->CanDrop())
					return;

				if (properties->GetSelectedItemCount() == 1)
				{
					success = dropSingleObject(data, true, cascaded);
				}
				else
				{
					if (cascaded || data->RequireDropConfirm() || settings->GetConfirmDelete())
					{
						wxString text, caption;
						if (cascaded)
						{
							text = _("Are you sure you wish to drop multiple objects including all objects that depend on them?");
							caption = _("Drop multiple objects cascaded?");
						}
						else
						{
							text = _("Are you sure you wish to drop multiple objects?");
							caption = _("Drop multiple objects?");
						}
						wxMessageDialog msg(this, text, caption, wxYES_NO | wxICON_QUESTION | wxNO_DEFAULT);
						if (msg.ShowModal() != wxID_YES)
						{
							return;
						}
					}

					bool done = true;
					long count = 0;
					while (done && data && index >= 0)
					{
						if (data->GetSystemObject())
						{
							wxMessageDialog msg(this,
							                    data->GetTranslatedMessage(CANNOTDROPSYSTEM),
							                    _("Trying to drop system object"), wxICON_EXCLAMATION);
							msg.ShowModal();
							return;
						}

						done = dropSingleObject(data, false, cascaded);

						if (done)
						{
							properties->DeleteItem(index);
							count++;
							index = properties->GetFirstSelected();

							if (index >= 0)
								data = collection->FindChild(browser, index);

							success = true;
						}
					}
				}
			}
		}
	}

	if (success)
	{
		// If the collection has a table, refresh that as well.
		if (owneritem)
		{
			ObjectBrowserRefreshing(true);
			Refresh(browser->GetObject(owneritem));
			ObjectBrowserRefreshing(false);
		}

		// Now re-focus on the parent of the deleted node
		if (!parent.IsEmpty())
			SetCurrentNode(browser->GetRootItem(), parent);
	}
}


bool frmMain::dropSingleObject(pgObject *data, bool updateFinal, bool cascaded)
{
	if (updateFinal)
	{
		// accelerator can bypass disabled menu, so we need to check
		if (!data || !data->CanDrop())
			return false;

		if (data->CheckOpenDialogs(browser, browser->GetSelection()))
		{
			wxString msg = _("There are properties dialogues open for one or more objects that would be dropped. Please close the properties dialogues and try again.");
			wxMessageBox(msg, _("Cannot drop object"), wxICON_WARNING | wxOK);
			return false;
		}

		if (data->GetSystemObject())
		{
			wxMessageDialog msg(this, data->GetTranslatedMessage(CANNOTDROPSYSTEM),
			                    _("Trying to drop system object"), wxICON_EXCLAMATION);
			msg.ShowModal();
			return false;
		}

		if (cascaded || data->RequireDropConfirm() || settings->GetConfirmDelete())
		{
			wxString text, caption;
			if (cascaded)
			{
				text = data->GetTranslatedMessage(DROPINCLUDINGDEPS);
				caption = data->GetTranslatedMessage(DROPCASCADETITLE);
			}
			else
			{
				/*
				*  currentObject is set using the following command.
				*  i.e. currentObject = browser->GetObject(item);
				*  While fetching this object using this code, somehow it looses its virtual table pointer.
				*  Hence, it is not able to call the GetFullIdentifier - virtual function from the
				*  particular class, but it will always call this functions from pgObject class always.
				*  To rectify this problem, we need to explicitly check the meta data type and call the
				*  function from the particular class.
				*/
				if (data->GetMetaType() == PGM_SERVER)
					text = wxString::Format(_("Are you sure you wish to drop server \"%s\"?"),
					                        ((pgServer *)data)->GetFullIdentifier().c_str());
				else if (data->GetMetaType() == EDB_SYNONYM)
					text = ((edbPrivateSynonym *)data)->GetTranslatedMessage(DROPEXCLUDINGDEPS);
				else
					text = data->GetTranslatedMessage(DROPEXCLUDINGDEPS);
				caption = data->GetTranslatedMessage(DROPTITLE);
			}
			wxMessageDialog msg(this, text, caption, wxYES_NO | wxICON_QUESTION | wxNO_DEFAULT);
			if (msg.ShowModal() != wxID_YES)
			{
				return false;
			}
		}
	}
	bool done = data->DropObject(this, browser, cascaded);

	if (done)
	{
		wxLogInfo(wxT("Dropping %s %s"), data->GetTypeName().c_str(), data->GetIdentifier().c_str());

		wxTreeItemId parentItem = browser->GetItemParent(data->GetId());

		if (updateFinal)
		{
			wxTreeItemId nextItem;
			if (browser->IsVisible(data->GetId()))
				nextItem = browser->GetNextVisible(data->GetId());

			if (nextItem)
			{
				pgObject *nextData = browser->GetObject(nextItem);
				if (!nextData || nextData->GetType() != data->GetType())
					nextItem = browser->GetPrevSibling(data->GetId());
			}
			else
				nextItem = browser->GetPrevSibling(data->GetId());

			if (nextItem)
				browser->SelectItem(nextItem);
		}
		pgaFactory *droppedCollFactory = data->GetFactory()->GetCollectionFactory();

		wxTreeItemId oldgroupitem;
		wxString oldgroupname;
		if (data->IsCreatedBy(serverFactory))
		{
			oldgroupname = ((pgServer *)data)->GetGroup();
			oldgroupitem = browser->GetItemParent(data->GetId());
		}

		browser->Delete(data->GetId());
		// data is invalid now

		if (updateFinal)
		{
			if (!oldgroupname.IsEmpty())
			{
				int total = browser->GetChildrenCount(oldgroupitem, false);
				if (total == 0)
					browser->Delete(oldgroupitem);
				else
				{
					wxString label = oldgroupname + wxT(" (") + NumToStr((long)total) + wxT(")");
					browser->SetItemText(oldgroupitem, label);
				}
			}
			else
			{
				pgCollection *collection = 0;

				while (parentItem)
				{
					collection = (pgCollection *)browser->GetObject(parentItem);
					if (collection && collection->IsCollection() && collection->GetFactory() == droppedCollFactory)
					{
						collection->UpdateChildCount(browser);
						break;
					}
					parentItem = browser->GetItemParent(parentItem);
				}
			}
		}

		// Update the server list, if we dropped a server
		StoreServers();
	}
	return done;
}


void frmMain::OnNew(wxCommandEvent &ev)
{
	pgaFactory *factory = pgaFactory::GetFactory(ev.GetId() - MNU_NEW);

	if (factory == &serverFactory)
	{
		if (currentObject && currentObject->IsCreatedBy(serverFactory))
		{
			pgServer *server = (pgServer *)currentObject;
			if (!server->GetConnected())
				ReconnectServer(server);
		}
		return;
	}

	if (currentObject)
	{
		if (!dlgProperty::CreateObjectDialog(this, currentObject, factory))
			CheckAlive();
	}
}


void frmMain::OnSaveDefinition(wxCommandEvent &event)
{

	wxLogInfo(wxT("Saving object definition"));

	if (sqlPane->GetText().IsNull())
	{
		wxLogError(__("There is nothing in the SQL pane to save!"));
		return;
	}

	wxString file;
	settings->Read(wxT("frmMain/LastFile"), &file, wxEmptyString);

#ifdef __WXMSW__
	wxFileDialog filename(this, _("Select output file"), ::wxPathOnly(file), file, _("SQL Scripts (*.sql)|*.sql|All files (*.*)|*.*"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
#else
	wxFileDialog filename(this, _("Select output file"), ::wxPathOnly(file), file, _("SQL Scripts (*.sql)|*.sql|All files (*)|*"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
#endif

	// Show the dialogue
	if (filename.ShowModal() == wxID_OK)
	{
		// Write the file
		if (!FileWrite(filename.GetPath(), sqlPane->GetText()))
		{
			wxLogError(__("Could not write the file %s: Errcode=%d."), filename.GetPath().c_str(), wxSysErrorCode());
		}
	}
	else
	{
		wxLogInfo(wxT("User cancelled"));
	}

	settings->Write(wxT("frmMain/LastFile"), filename.GetPath());
}

void frmMain::OnToggleSqlPane(wxCommandEvent &event)
{
	if (viewMenu->IsChecked(MNU_SQLPANE))
		manager.GetPane(wxT("sqlPane")).Show(true);
	else
		manager.GetPane(wxT("sqlPane")).Show(false);
	manager.Update();
}

void frmMain::OnToggleObjectBrowser(wxCommandEvent &event)
{
	if (viewMenu->IsChecked(MNU_OBJECTBROWSER))
		manager.GetPane(wxT("objectBrowser")).Show(true);
	else
		manager.GetPane(wxT("objectBrowser")).Show(false);
	manager.Update();
}

void frmMain::OnToggleToolBar(wxCommandEvent &event)
{
	if (viewMenu->IsChecked(MNU_TOOLBAR))
		manager.GetPane(wxT("toolBar")).Show(true);
	else
		manager.GetPane(wxT("toolBar")).Show(false);
	manager.Update();
}

void frmMain::OnAuiUpdate(wxAuiManagerEvent &event)
{
	if(event.pane->name == wxT("objectBrowser"))
	{
		viewMenu->Check(MNU_OBJECTBROWSER, false);
	}
	else if(event.pane->name == wxT("sqlPane"))
	{
		viewMenu->Check(MNU_SQLPANE, false);
	}
	else if(event.pane->name == wxT("toolBar"))
	{
		viewMenu->Check(MNU_TOOLBAR, false);
	}
	event.Skip();
}

void frmMain::OnAuiNotebookPageClose(wxAuiNotebookEvent &event)
{
	// Prevent the user closing the four main tabs.
	if (event.GetSelection() < 4)
	{
		wxMessageBox(_("This tab cannot be closed."), _("Close tab"), wxICON_INFORMATION | wxOK);
		event.Veto();
		return;
	}

	event.Skip();
}

void frmMain::OnDefaultView(wxCommandEvent &event)
{
	manager.LoadPerspective(FRMMAIN_DEFAULT_PERSPECTIVE, true);

	// Reset the captions for the current language
	manager.GetPane(wxT("objectBrowser")).Caption(_("Object browser"));
	manager.GetPane(wxT("listViews")).Caption(_("Info pane"));
	manager.GetPane(wxT("sqlPane")).Caption(_("SQL pane"));
	manager.GetPane(wxT("toolBar")).Caption(_("Tool bar"));

	// tell the manager to "commit" all the changes just made
	manager.Update();

	// Sync the View menu options
	viewMenu->Check(MNU_SQLPANE, manager.GetPane(wxT("sqlPane")).IsShown());
	viewMenu->Check(MNU_OBJECTBROWSER, manager.GetPane(wxT("objectBrowser")).IsShown());
	viewMenu->Check(MNU_TOOLBAR, manager.GetPane(wxT("toolBar")).IsShown());
}

void frmMain::OnPositionStc(wxStyledTextEvent &event)
{
	if (sqlPane->GetSelectedText().IsNull())
		editMenu->Enable(MNU_COPY, false);
	else
		editMenu->Enable(MNU_COPY, true);
}