aboutsummaryrefslogtreecommitdiff
path: root/mp/src/vgui2/vgui_controls/DirectorySelectDialog.cpp
blob: 0e9eac52400552f8df5bcd334d2375483465b4fe (plain) (blame)
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
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: 
//
//=============================================================================//

#define PROTECTED_THINGS_DISABLE

#include <vgui_controls/Button.h>
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/DirectorySelectDialog.h>
#include <vgui_controls/TreeView.h>
#include <vgui_controls/ImageList.h>
#include <vgui_controls/MessageBox.h>
#include <vgui/Cursor.h>
#include <KeyValues.h>
#include <vgui/IInput.h>
#include <vgui/ISurface.h>
#include <vgui/ISystem.h>
#include <filesystem.h>

#ifdef WIN32
#include <direct.h>
#include <stdio.h>
#include <io.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>

// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>

using namespace vgui;

DirectoryTreeView::DirectoryTreeView(DirectorySelectDialog *parent, const char *name) : TreeView(parent, name)
{
	m_pParent = parent;
}

void DirectoryTreeView::GenerateChildrenOfNode(int itemIndex)
{
	m_pParent->GenerateChildrenOfDirectoryNode(itemIndex);
}

//-----------------------------------------------------------------------------
// Purpose: Used to prompt the user to create a directory
//-----------------------------------------------------------------------------
class CreateDirectoryDialog : public Frame
{
	DECLARE_CLASS_SIMPLE(CreateDirectoryDialog, Frame);

public:
	CreateDirectoryDialog(Panel *parent, const char *defaultCreateDirName) : BaseClass(parent, NULL)
	{
		SetSize(320, 100);
		SetSizeable(false);
		SetTitle("Choose directory name", false);
		MoveToCenterOfScreen();

		m_pOKButton = new Button(this, "OKButton", "#vgui_ok");
		m_pCancelButton = new Button(this, "OKButton", "#vgui_cancel");
		m_pNameEntry = new TextEntry(this, "NameEntry");

		m_pOKButton->SetCommand("OK");
		m_pCancelButton->SetCommand("Close");
		m_pNameEntry->SetText(defaultCreateDirName);
		m_pNameEntry->RequestFocus();
		m_pNameEntry->SelectAllText(true);
	
		// If some other window was hogging the input focus, then we have to hog it or else we'll never get input.
		m_PrevAppFocusPanel = vgui::input()->GetAppModalSurface();
		if ( m_PrevAppFocusPanel )
			vgui::input()->SetAppModalSurface( GetVPanel() );
	}

	~CreateDirectoryDialog()
	{
		if ( m_PrevAppFocusPanel )
			vgui::input()->SetAppModalSurface( m_PrevAppFocusPanel );
	}

	virtual void PerformLayout()
	{
		BaseClass::PerformLayout();

		m_pNameEntry->SetBounds(24, 32, GetWide() - 48, 24);
		m_pOKButton->SetBounds(GetWide() - 176, 64, 72, 24);
		m_pCancelButton->SetBounds(GetWide() - 94, 64, 72, 24);
	}

	virtual void OnCommand(const char *command)
	{
		if (!stricmp(command, "OK"))
		{
			PostActionSignal(new KeyValues("CreateDirectory", "dir", GetControlString("NameEntry")));
			Close();
		}
		else
		{
			BaseClass::OnCommand(command);
		}
	}

	virtual void OnClose()
	{
		BaseClass::OnClose();
		MarkForDeletion();
	}

private:
	vgui::Button *m_pOKButton;
	vgui::Button *m_pCancelButton;
	vgui::TextEntry *m_pNameEntry;
	vgui::VPANEL m_PrevAppFocusPanel;
};

//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
DirectorySelectDialog::DirectorySelectDialog(vgui::Panel *parent, const char *title) : Frame(parent, NULL)
{
	SetTitle(title, true);
	SetSize(320, 360);
	SetMinimumSize(300, 240);
	m_szCurrentDir[0] = 0;
	m_szDefaultCreateDirName[0] = 0;

	m_pDirTree = new DirectoryTreeView(this, "DirTree");
	m_pDriveCombo = new ComboBox(this, "DriveCombo", 6, false);
	m_pCancelButton = new Button(this, "CancelButton", "#VGui_Cancel");
	m_pSelectButton = new Button(this, "SelectButton", "#VGui_Select");
	m_pCreateButton = new Button(this, "CreateButton", "#VGui_CreateFolder");
	m_pCancelButton->SetCommand("Cancel");
	m_pSelectButton->SetCommand("Select");
	m_pCreateButton->SetCommand("Create");
}

//-----------------------------------------------------------------------------
// Purpose: lays out controls
//-----------------------------------------------------------------------------
void DirectorySelectDialog::PerformLayout()
{
	BaseClass::PerformLayout();

	// lay out all the controls
	m_pDriveCombo->SetBounds(24, 30, GetWide() - 48, 24);
	m_pDirTree->SetBounds(24, 64, GetWide() - 48, GetTall() - 128);

	m_pCreateButton->SetBounds(24, GetTall() - 48, 104, 24);
	m_pSelectButton->SetBounds(GetWide() - 172, GetTall() - 48, 72, 24);
	m_pCancelButton->SetBounds(GetWide() - 96, GetTall() - 48, 72, 24);
}

//-----------------------------------------------------------------------------
// Purpose: lays out controls
//-----------------------------------------------------------------------------
void DirectorySelectDialog::ApplySchemeSettings(IScheme *pScheme)
{
	ImageList *imageList = new ImageList(false);
	imageList->AddImage(scheme()->GetImage("Resource/icon_folder", false));
	imageList->AddImage(scheme()->GetImage("Resource/icon_folder_selected", false));
	m_pDirTree->SetImageList(imageList, true);

	BaseClass::ApplySchemeSettings(pScheme);
}

//-----------------------------------------------------------------------------
// Purpose: Move the start string forward until we hit a slash and return the
//			the first character past the trailing slash
//-----------------------------------------------------------------------------
inline const char *MoveToNextSubDir( const char *pStart, int *nCount )
{
	int nMoved = 0;

	// Move past pre-pended slash
	if ( pStart[nMoved] == '\\' )
	{
		nMoved++;
	}

	// Move past the current block of text until we've hit the next path seperator (or end)
	while ( pStart[nMoved] != '\\' && pStart[nMoved] != '\0' )
	{
		nMoved++;
	}

	// Move past trailing slash
	if ( pStart[nMoved] == '\\' )
	{
		nMoved++;
	}

	// Give back a count if they've supplied a pointer
	if ( nCount != NULL )
	{
		*nCount = nMoved;
	}
	
	// The beginning of the next string, past slash
	return (pStart+nMoved);
}

//-----------------------------------------------------------------------------
// Purpose: Walk through our directory structure given a path as our guide, while expanding
//			and populating the nodes of the tree view to match
// Input  : *path - path (with drive letter) to show
//-----------------------------------------------------------------------------
void DirectorySelectDialog::ExpandTreeToPath( const char *lpszPath, bool bSelectFinalDirectory /*= true*/ )
{
	// Make sure our slashes are correct!
	char workPath[MAX_PATH];
	Q_strncpy( workPath, lpszPath, sizeof(workPath) );
	Q_FixSlashes( workPath );
	
	// Set us to the work drive
	SetStartDirectory( workPath );

	// Check that the path is valid
	if ( workPath[0] == '\0' || DoesDirectoryHaveSubdirectories( m_szCurrentDrive, "" ) == false )
	{
		// Failing, start in C:
		SetStartDirectory( "C:\\" );
	}

	// Start at the root of our tree
	int nItemIndex = m_pDirTree->GetRootItemIndex();
	
	// Move past the drive letter to the first subdir
	int nPathPos = 0;
	const char *lpszSubDirName = MoveToNextSubDir( workPath, &nPathPos ); 
	const char *lpszLastSubDirName = NULL;
	int nPathIncr = 0;
	char subDirName[MAX_PATH];

	// While there are subdirectory names present, expand and populate the tree with their subdirectories
	while ( lpszSubDirName[0] != '\0' )
	{
		// Move our string pointer forward while keeping where our last subdir started off
		lpszLastSubDirName = lpszSubDirName;
		lpszSubDirName = MoveToNextSubDir( lpszSubDirName, &nPathIncr );

		// Get the span between the last subdir and the new one
		Q_StrLeft( lpszLastSubDirName, nPathIncr, subDirName, sizeof(subDirName) );
		Q_StripTrailingSlash( subDirName );

		// Increment where we are in the string for use later
		nPathPos += nPathIncr;

		// Run through the list and expand to our currently selected directory
		for ( int i = 0; i < m_pDirTree->GetNumChildren( nItemIndex ); i++ )
		{
			// Get the child and data for it
			int nChild = m_pDirTree->GetChild( nItemIndex, i );
			KeyValues *pValues = m_pDirTree->GetItemData( nChild );

			// See if this matches
			if ( Q_stricmp( pValues->GetString( "Text" ), subDirName ) == 0 )
			{
				// This is the new root item
				nItemIndex = nChild;

				// Get the full path (starting from the drive letter) up to our current subdir
				Q_strncpy( subDirName, workPath, nPathPos );
				Q_AppendSlash( subDirName, sizeof(subDirName) );

				// Expand the tree node and populate its subdirs for our next iteration
				ExpandTreeNode( subDirName, nItemIndex );
				break;
			}
		}
	}

	// Select our last directory if we've been asked to (and it's valid)
	if ( bSelectFinalDirectory && m_pDirTree->IsItemIDValid( nItemIndex ) )
	{
		// If we don't call this once before selecting an item, the tree will not be properly expanded
		// before it calculates how to show the selected item in the view
		PerformLayout();

		// Select that item
		m_pDirTree->AddSelectedItem( nItemIndex, true );
	}
}

//-----------------------------------------------------------------------------
// Purpose: sets where it should start searching
//-----------------------------------------------------------------------------
void DirectorySelectDialog::SetStartDirectory(const char *path)
{
	strncpy(m_szCurrentDir, path, sizeof(m_szCurrentDir));
	strncpy(m_szCurrentDrive, path, sizeof(m_szCurrentDrive));
	m_szCurrentDrive[sizeof(m_szCurrentDrive) - 1] = 0;
	char *firstSlash = strstr(m_szCurrentDrive, "\\");
	if (firstSlash)
	{
		firstSlash[1] = 0;
	}

	BuildDirTree();
	BuildDriveChoices();

	// update state of create directory button
	int selectedIndex = m_pDirTree->GetFirstSelectedItem();
	if (m_pDirTree->IsItemIDValid(selectedIndex))
	{
		m_pCreateButton->SetEnabled(true);
	}
	else
	{
		m_pCreateButton->SetEnabled(false);
	}
}

//-----------------------------------------------------------------------------
// Purpose: sets what name should show up by default in the create directory dialog
//-----------------------------------------------------------------------------
void DirectorySelectDialog::SetDefaultCreateDirectoryName(const char *defaultCreateDirName)
{
	strncpy(m_szDefaultCreateDirName, defaultCreateDirName, sizeof(m_szDefaultCreateDirName));
	m_szDefaultCreateDirName[sizeof(m_szDefaultCreateDirName) - 1] = 0;
}

//-----------------------------------------------------------------------------
// Purpose: opens the dialog
//-----------------------------------------------------------------------------
void DirectorySelectDialog::DoModal()
{
	input()->SetAppModalSurface(GetVPanel());
	BaseClass::Activate();
	MoveToCenterOfScreen();
}

//-----------------------------------------------------------------------------
// Purpose: Builds drive choices
//-----------------------------------------------------------------------------
void DirectorySelectDialog::BuildDriveChoices()
{
	m_pDriveCombo->DeleteAllItems();

	char drives[256] = { 0 };
	int len = system()->GetAvailableDrives(drives, sizeof(drives));
	char *pBuf = drives;
	KeyValues *kv = new KeyValues("drive");
	for (int i = 0; i < len / 4; i++)
	{
		kv->SetString("drive", pBuf);
		int itemID = m_pDriveCombo->AddItem(pBuf, kv);
		if (!stricmp(pBuf, m_szCurrentDrive))
		{
			m_pDriveCombo->ActivateItem(itemID);
		}

		pBuf += 4;
	}
	kv->deleteThis();
}

//-----------------------------------------------------------------------------
// Purpose: Builds the base tree directory
//-----------------------------------------------------------------------------
void DirectorySelectDialog::BuildDirTree()
{
	// clear current tree
	m_pDirTree->RemoveAll();

	// add in a root
	int rootIndex = m_pDirTree->AddItem(new KeyValues("root", "Text", m_szCurrentDrive), -1);

	// build first level of the tree
	ExpandTreeNode(m_szCurrentDrive, rootIndex);
	
	// start the root expanded
	m_pDirTree->ExpandItem(rootIndex, true);
}

//-----------------------------------------------------------------------------
// Purpose: expands a path
//-----------------------------------------------------------------------------
void DirectorySelectDialog::ExpandTreeNode(const char *path, int parentNodeIndex)
{
	// set the small wait cursor
	surface()->SetCursor(dc_waitarrow);

	// get all the subfolders of the current drive
	char searchString[512];
	sprintf(searchString, "%s*.*", path);

	FileFindHandle_t h;
	const char *pFileName = g_pFullFileSystem->FindFirstEx( searchString, NULL, &h );
	for ( ; pFileName; pFileName = g_pFullFileSystem->FindNext( h ) )
	{
		if ( !Q_stricmp( pFileName, ".." ) || !Q_stricmp( pFileName, "." ) )
			continue;

		KeyValues *kv = new KeyValues("item");
		kv->SetString("Text", pFileName);
		// set the folder image
		kv->SetInt("Image", 1);
		kv->SetInt("SelectedImage", 1);
		kv->SetInt("Expand", DoesDirectoryHaveSubdirectories(path, pFileName));	
		m_pDirTree->AddItem(kv, parentNodeIndex);
	}
	g_pFullFileSystem->FindClose( h );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
bool DirectorySelectDialog::DoesDirectoryHaveSubdirectories(const char *path, const char *dir)
{
	char searchString[512];
	sprintf(searchString, "%s%s\\*.*", path, dir);

	FileFindHandle_t h;
	const char *pFileName = g_pFullFileSystem->FindFirstEx( searchString, NULL, &h );
	for ( ; pFileName; pFileName = g_pFullFileSystem->FindNext( h ) )
	{
		char szFullPath[ MAX_PATH ];
		Q_snprintf( szFullPath, sizeof(szFullPath), "%s\\%s", path, pFileName );
		Q_FixSlashes( szFullPath ); 
		if ( g_pFullFileSystem->IsDirectory( szFullPath ) )
		{
			g_pFullFileSystem->FindClose( h );
			return true;
		}
	}
	g_pFullFileSystem->FindClose( h );
	return false;
}

//-----------------------------------------------------------------------------
// Purpose: Generates the children for the specified node
//-----------------------------------------------------------------------------
void DirectorySelectDialog::GenerateChildrenOfDirectoryNode(int nodeIndex)
{
	// generate path
	char path[512];
	GenerateFullPathForNode(nodeIndex, path, sizeof(path));

	// expand out
	ExpandTreeNode(path, nodeIndex);
}

//-----------------------------------------------------------------------------
// Purpose: creates the full path for a node
//-----------------------------------------------------------------------------
void DirectorySelectDialog::GenerateFullPathForNode(int nodeIndex, char *path, int pathBufferSize)
{
	// get all the nodes
	CUtlLinkedList<int, int> nodes;
	nodes.AddToTail(nodeIndex);
	int parentIndex = nodeIndex;
	while (1)
	{
		parentIndex = m_pDirTree->GetItemParent(parentIndex);
		if (parentIndex == -1)
			break;
		nodes.AddToHead(parentIndex);
	}

	// walk the nodes, adding to the path
	path[0] = 0;
	bool bFirst = true;
	FOR_EACH_LL( nodes, i )
	{
		KeyValues *kv = m_pDirTree->GetItemData( nodes[i] );
		strcat(path, kv->GetString("Text"));

		if (!bFirst)
		{
			strcat(path, "\\");
		}
		bFirst = false;
	}
}

//-----------------------------------------------------------------------------
// Purpose: Handles combo box changes
//-----------------------------------------------------------------------------
void DirectorySelectDialog::OnTextChanged()
{
	KeyValues *kv = m_pDriveCombo->GetActiveItemUserData();
	if (!kv)
		return;
	const char *newDrive = kv->GetString("drive");
	if (stricmp(newDrive, m_szCurrentDrive))
	{
		// drive changed, reset
		SetStartDirectory(newDrive);
	}
}

//-----------------------------------------------------------------------------
// Purpose: creates a directory
//-----------------------------------------------------------------------------
void DirectorySelectDialog::OnCreateDirectory(const char *dir)
{
	int selectedIndex = m_pDirTree->GetFirstSelectedItem();
	if (m_pDirTree->IsItemIDValid(selectedIndex))
	{
		char fullPath[512];
		GenerateFullPathForNode(selectedIndex, fullPath, sizeof(fullPath));

		// create the new directory underneath
		strcat(fullPath, dir);
		if (_mkdir(fullPath) == 0)
		{
			// add new path to tree view
			KeyValues *kv = new KeyValues("item");
			kv->SetString("Text", dir);
			// set the folder image
			kv->SetInt("Image", 1);
			kv->SetInt("SelectedImage", 1);
			int itemID = m_pDirTree->AddItem(kv, selectedIndex);

			// select the item
			m_pDirTree->AddSelectedItem( itemID, true );
		}
		else
		{
			// print error message
			MessageBox *box = new MessageBox("#vgui_CreateDirectoryFail_Title", "#vgui_CreateDirectoryFail_Info");
			box->DoModal(this);
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose: dialog closes
//-----------------------------------------------------------------------------
void DirectorySelectDialog::OnClose()
{
	BaseClass::OnClose();
	MarkForDeletion();
}

//-----------------------------------------------------------------------------
// Purpose: handles button commands
//-----------------------------------------------------------------------------
void DirectorySelectDialog::OnCommand(const char *command)
{
	if (!stricmp(command, "Cancel"))
	{
		Close();
	}
	else if (!stricmp(command, "Select"))
	{
		// path selected
		int selectedIndex = m_pDirTree->GetFirstSelectedItem();
		if (m_pDirTree->IsItemIDValid(selectedIndex))
		{
			char fullPath[512];
			GenerateFullPathForNode(selectedIndex, fullPath, sizeof(fullPath));
			PostActionSignal(new KeyValues("DirectorySelected", "dir", fullPath));
			Close();
		}
	}
	else if (!stricmp(command, "Create"))
	{
		int selectedIndex = m_pDirTree->GetFirstSelectedItem();
		if (m_pDirTree->IsItemIDValid(selectedIndex))
		{
			CreateDirectoryDialog *dlg = new CreateDirectoryDialog(this, m_szDefaultCreateDirName);
			dlg->AddActionSignalTarget(this);
			dlg->Activate();
		}
	}
	else
	{
		BaseClass::OnCommand(command);
	}
}

//-----------------------------------------------------------------------------
// Purpose: Update the text in the combo
//-----------------------------------------------------------------------------
void DirectorySelectDialog::OnTreeViewItemSelected()
{
	int selectedIndex = m_pDirTree->GetFirstSelectedItem();
	if (!m_pDirTree->IsItemIDValid(selectedIndex))
	{
		m_pCreateButton->SetEnabled(false);
		return;
	}
	m_pCreateButton->SetEnabled(true);

	// build the string
	char fullPath[512];
	GenerateFullPathForNode(selectedIndex, fullPath, sizeof(fullPath));

	int itemID = m_pDriveCombo->GetActiveItem();
	m_pDriveCombo->UpdateItem(itemID, fullPath, NULL);
	m_pDriveCombo->SetText(fullPath);
}