File: FileBrowserForm.cs

package info (click to toggle)
keepass2 2.19%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 11,496 kB
  • sloc: cs: 87,098; xml: 6,569; cpp: 311; makefile: 49; sh: 9
file content (582 lines) | stat: -rw-r--r-- 15,967 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
/*
  KeePass Password Safe - The Open-Source Password Manager
  Copyright (C) 2003-2012 Dominik Reichl <dominik.reichl@t-online.de>

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

  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; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

using KeePass.Native;
using KeePass.Resources;
using KeePass.UI;

using KeePassLib;
using KeePassLib.Utility;

namespace KeePass.Forms
{
	public partial class FileBrowserForm : Form
	{
		private bool m_bSaveMode = false;
		private string m_strTitle = PwDefs.ShortProductName;
		private string m_strHint = string.Empty;

		private ImageList m_ilFolders = null;
		private List<Image> m_vFolderImages = new List<Image>();
		private ImageList m_ilFiles = null;
		private List<Image> m_vFileImages = new List<Image>();

		private int m_nIconDim = 16;

		private const string StrDummyNode = "66913D76EA3F4F2A8B1A0899B7322EC3";

		private sealed class FbfPrivTviComparer : IComparer<TreeNode>
		{
			public int Compare(TreeNode x, TreeNode y)
			{
				Debug.Assert((x != null) && (y != null));
				return StrUtil.CompareNaturally(x.Text, y.Text);
			}
		}

		private sealed class FbfPrivLviComparer : IComparer<ListViewItem>
		{
			public int Compare(ListViewItem x, ListViewItem y)
			{
				Debug.Assert((x != null) && (y != null));
				return StrUtil.CompareNaturally(x.Text, y.Text);
			}
		}

		private string m_strSelectedFile = null;
		public string SelectedFile
		{
			get { return m_strSelectedFile; }
		}

		public void InitEx(bool bSaveMode, string strTitle, string strHint)
		{
			m_bSaveMode = bSaveMode;
			if(strTitle != null) m_strTitle = strTitle;
			if(strHint != null) m_strHint = strHint;
		}

		public FileBrowserForm()
		{
			InitializeComponent();
			Program.Translation.ApplyTo(this);
		}

		private void OnFormLoad(object sender, EventArgs e)
		{
			GlobalWindowManager.AddWindow(this);

			this.Icon = new Icon("/usr/share/keepass2/KeePass.ico");
			this.Text = m_strTitle;

			m_nIconDim = m_tvFolders.ItemHeight;

			if(UIUtil.VistaStyleListsSupported)
			{
				m_tvFolders.ShowLines = false;

				UIUtil.SetExplorerTheme(m_tvFolders, true);
				UIUtil.SetExplorerTheme(m_lvFiles, true);
			}

			m_btnOK.Text = (m_bSaveMode ? KPRes.SaveCmd : KPRes.OpenCmd);
			m_lblHint.Text = m_strHint;

			if(UIUtil.ColorsEqual(m_lblHint.ForeColor, Color.Black))
				m_lblHint.ForeColor = Color.FromArgb(96, 96, 96);

			int nWidth = m_lvFiles.ClientRectangle.Width - UIUtil.GetVScrollBarWidth();
			m_lvFiles.Columns.Add(KPRes.Name, (nWidth * 3) / 4);
			m_lvFiles.Columns.Add(KPRes.Size, nWidth / 4, HorizontalAlignment.Right);

			InitialPopulateFolders();
			BrowseToFolder(Environment.CurrentDirectory);

			EnableControlsEx();
		}

		private void OnFormClosed(object sender, FormClosedEventArgs e)
		{
			m_tvFolders.Nodes.Clear();
			m_lvFiles.Items.Clear();
			m_tvFolders.ImageList = null;
			m_lvFiles.SmallImageList = null;

			if(m_ilFolders != null) { m_ilFolders.Dispose(); m_ilFolders = null; }
			if(m_ilFiles != null) { m_ilFiles.Dispose(); m_ilFiles = null; }

			foreach(Image imgFld in m_vFolderImages) imgFld.Dispose();
			m_vFolderImages.Clear();
			foreach(Image imgFile in m_vFileImages) imgFile.Dispose();
			m_vFileImages.Clear();

			GlobalWindowManager.RemoveWindow(this);
		}

		private void EnableControlsEx()
		{
			m_btnOK.Enabled = (m_lvFiles.SelectedIndices.Count == 1);
		}

		private void InitialPopulateFolders()
		{
			List<TreeNode> l = new List<TreeNode>();

			string str = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
			if(!string.IsNullOrEmpty(str))
			{
				TreeNode tn = CreateFolderNode(str, false, null);
				if(tn != null) l.Add(tn);
			}

			str = Environment.GetEnvironmentVariable("USERPROFILE");
			if(!string.IsNullOrEmpty(str))
			{
				TreeNode tn = CreateFolderNode(str, false, null);
				if(tn != null) l.Add(tn);
			}

			DriveInfo[] vDrives = DriveInfo.GetDrives();
			foreach(DriveInfo drv in vDrives)
			{
				try
				{
					DirectoryInfo diDrive = drv.RootDirectory;
					TreeNode tn = CreateFolderNode(diDrive.FullName, true, drv);
					if(tn != null) l.Add(tn);
				}
				catch(Exception) { Debug.Assert(false); }
			}

			RebuildFolderImageList();
			m_tvFolders.Nodes.AddRange(l.ToArray());
		}

		private void GetObjectProps(string strPath, DriveInfo drvHint,
			out Image img, ref string strDisplayName)
		{
			GetObjectPropsUnscaled(strPath, drvHint, out img, ref strDisplayName);

			if(img != null)
			{
				if((img.Width != m_nIconDim) || (img.Height != m_nIconDim))
				{
					Bitmap bmp = new Bitmap(m_nIconDim, m_nIconDim, PixelFormat.Format32bppArgb);
					using(Graphics g = Graphics.FromImage(bmp))
					{
						g.Clear(Color.Transparent);
						g.InterpolationMode = InterpolationMode.HighQualityBicubic;
						g.SmoothingMode = SmoothingMode.HighQuality;
						g.DrawImage(img, new Rectangle(0, 0, m_nIconDim, m_nIconDim));
					}

					img.Dispose();
					img = bmp;
				}
			}
		}

		private void GetObjectPropsUnscaled(string strPath, DriveInfo drvHint,
			out Image img, ref string strDisplayName)
		{
			img = null;

			try
			{
				string strName;
				NativeMethods.SHGetFileInfo(strPath, m_nIconDim, out img,
					out strName);

				if(!string.IsNullOrEmpty(strName) && (strName.IndexOf(
					Path.DirectorySeparatorChar) < 0))
					strDisplayName = strName;

				if(img != null) return;
			}
			catch(Exception) { Debug.Assert(false); }

			ImageList.ImageCollection icons = Program.MainForm.ClientIcons.Images;

			if((strPath.Length <= 3) && (drvHint != null))
			{
				switch(drvHint.DriveType)
				{
					case DriveType.Fixed:
						img = new Bitmap(icons[(int)PwIcon.Drive]);
						break;
					case DriveType.CDRom:
						img = new Bitmap(icons[(int)PwIcon.CDRom]);
						break;
					case DriveType.Network:
						img = new Bitmap(icons[(int)PwIcon.NetworkServer]);
						break;
					case DriveType.Ram:
						img = new Bitmap(icons[(int)PwIcon.Memory]);
						break;
					case DriveType.Removable:
						img = new Bitmap(icons[(int)PwIcon.Disk]);
						break;
					default:
						img = new Bitmap(icons[(int)PwIcon.Folder]);
						break;
				}

				return;
			}

			try
			{
				Icon ico = Icon.ExtractAssociatedIcon(strPath);
				img = new Bitmap(m_nIconDim, m_nIconDim, PixelFormat.Format32bppArgb);
				using(Graphics g = Graphics.FromImage(img))
				{
					g.Clear(Color.Transparent);
					g.InterpolationMode = InterpolationMode.HighQualityBicubic;
					g.SmoothingMode = SmoothingMode.HighQuality;
					g.DrawIcon(ico, new Rectangle(0, 0, m_nIconDim, m_nIconDim));
				}
				ico.Dispose();

				return;
			}
			catch(Exception) { }

			if(Directory.Exists(strPath))
			{
				img = new Bitmap(icons[(int)PwIcon.Folder]);
				return;
			}
			if(File.Exists(strPath))
			{
				img = new Bitmap(icons[(int)PwIcon.PaperNew]);
				return;
			}

			Debug.Assert(false);
			img = new Bitmap(icons[(int)PwIcon.Star]);
		}

		private TreeNode CreateFolderNode(string strDir, bool bForcePlusMinus,
			DriveInfo drvHint)
		{
			try
			{
				DirectoryInfo di = new DirectoryInfo(strDir);

				Image img;
				string strText = di.Name;
				GetObjectProps(di.FullName, drvHint, out img, ref strText);

				m_vFolderImages.Add(img);

				TreeNode tn = new TreeNode(strText, m_vFolderImages.Count - 1,
					m_vFolderImages.Count - 1);
				tn.Tag = di.FullName;

				InitNodePlusMinus(tn, di, bForcePlusMinus);
				return tn;
			}
			catch(Exception) { Debug.Assert(false); }

			return null;
		}

		private static void InitNodePlusMinus(TreeNode tn, DirectoryInfo di,
			bool bForce)
		{
			bool bMark = true;

			if(!bForce)
			{
				try
				{
					DirectoryInfo[] vDirs = di.GetDirectories();
					bool bFoundDir = false;
					foreach(DirectoryInfo diSub in vDirs)
					{
						if(!IsValidFileSystemObject(diSub)) continue;

						bFoundDir = true;
						break;
					}

					if(!bFoundDir) bMark = false;
				}
				catch(Exception) { bMark = false; } // Usually unauthorized
			}

			if(bMark)
			{
				tn.Nodes.Add(StrDummyNode);
				tn.Collapse();
			}
		}

		private void RebuildFolderImageList()
		{
			ImageList imgNew = UIUtil.BuildImageListUnscaled(
				m_vFolderImages, m_nIconDim, m_nIconDim);
			m_tvFolders.ImageList = imgNew;

			if(m_ilFolders != null) m_ilFolders.Dispose();
			m_ilFolders = imgNew;
		}

		private void BuildFilesList(DirectoryInfo di)
		{
			m_lvFiles.BeginUpdate();
			m_lvFiles.Items.Clear();

			DirectoryInfo[] vDirs;
			FileInfo[] vFiles;
			try
			{
				vDirs = di.GetDirectories();
				vFiles = di.GetFiles();
			}
			catch(Exception) { m_lvFiles.EndUpdate(); return; } // Unauthorized

			foreach(Image imgFile in m_vFileImages) imgFile.Dispose();
			m_vFileImages.Clear();

			List<ListViewItem> lDirItems = new List<ListViewItem>();
			List<ListViewItem> lFileItems = new List<ListViewItem>();

			foreach(DirectoryInfo diSub in vDirs)
			{
				AddFileItem(diSub, m_vFileImages, lDirItems, -1);
			}
			foreach(FileInfo fi in vFiles)
			{
				AddFileItem(fi, m_vFileImages, lFileItems, fi.Length);
			}

			m_lvFiles.SmallImageList = null;
			if(m_ilFiles != null) m_ilFiles.Dispose();
			m_ilFiles = UIUtil.BuildImageListUnscaled(m_vFileImages, m_nIconDim, m_nIconDim);
			m_lvFiles.SmallImageList = m_ilFiles;

			lDirItems.Sort(new FbfPrivLviComparer());
			m_lvFiles.Items.AddRange(lDirItems.ToArray());
			lFileItems.Sort(new FbfPrivLviComparer());
			m_lvFiles.Items.AddRange(lFileItems.ToArray());
			m_lvFiles.EndUpdate();

			EnableControlsEx();
		}

		private static bool IsValidFileSystemObject(FileSystemInfo fsi)
		{
			if(fsi == null) { Debug.Assert(false); return false; }

			string strName = fsi.Name;
			if(string.IsNullOrEmpty(strName) || (strName == ".") ||
				(strName == "..")) return false;
			if(strName.EndsWith(".lnk", StrUtil.CaseIgnoreCmp)) return false;
			if(strName.EndsWith(".url", StrUtil.CaseIgnoreCmp)) return false;

			FileAttributes fa = fsi.Attributes;
			if((long)(fa & FileAttributes.ReparsePoint) != 0) return false;
			if(((long)(fa & FileAttributes.System) != 0) &&
				((long)(fa & FileAttributes.Hidden) != 0)) return false;

			return true;
		}

		private void AddFileItem(FileSystemInfo fsi, List<Image> lImages,
			List<ListViewItem> lItems, long lFileLength)
		{
			if(!IsValidFileSystemObject(fsi)) return;

			Image img;
			string strText = fsi.Name;
			GetObjectProps(fsi.FullName, null, out img, ref strText);

			lImages.Add(img);

			ListViewItem lvi = new ListViewItem(strText, lImages.Count - 1);
			lvi.Tag = fsi.FullName;

			if(lFileLength < 0) lvi.SubItems.Add(string.Empty);
			else lvi.SubItems.Add(StrUtil.FormatDataSizeKB((ulong)lFileLength));

			lItems.Add(lvi);
		}

		private bool PerformFileSelection()
		{
			ListView.SelectedListViewItemCollection lvsic = m_lvFiles.SelectedItems;
			if((lvsic == null) || (lvsic.Count != 1)) { Debug.Assert(false); return false; }

			string str = (lvsic[0].Tag as string);
			if(string.IsNullOrEmpty(str)) { Debug.Assert(false); return false; }

			try
			{
				if(Directory.Exists(str))
				{
					TreeNode tn = m_tvFolders.SelectedNode;
					if(tn == null) { Debug.Assert(false); return false; }

					if(!tn.IsExpanded) tn.Expand();

					foreach(TreeNode tnSub in tn.Nodes)
					{
						string strSub = (tnSub.Tag as string);
						if(string.IsNullOrEmpty(strSub)) { Debug.Assert(false); continue; }

						if(strSub.Equals(str, StrUtil.CaseIgnoreCmp))
						{
							m_tvFolders.SelectedNode = tnSub;
							tnSub.EnsureVisible();
							return false; // Success, but not a file selection!
						}
					}

					Debug.Assert(false);
				}
				else if(File.Exists(str))
				{
					m_strSelectedFile = str;
					return true;
				}
				else { Debug.Assert(false); }
			}
			catch(Exception) { Debug.Assert(false); }

			return false;
		}

		private void OnBtnOK(object sender, EventArgs e)
		{
			if(!PerformFileSelection()) this.DialogResult = DialogResult.None;
		}

		private void OnFilesItemActivate(object sender, EventArgs e)
		{
			if(PerformFileSelection()) this.DialogResult = DialogResult.OK;
		}

		private void OnFoldersBeforeExpand(object sender, TreeViewCancelEventArgs e)
		{
			TreeNode tn = e.Node;
			if(tn == null) { Debug.Assert(false); e.Cancel = true; return; }

			if((tn.Nodes.Count == 1) && (tn.Nodes[0].Text == StrDummyNode))
			{
				tn.Nodes.Clear();
				List<TreeNode> lNodes = new List<TreeNode>();

				try
				{
					DirectoryInfo di = new DirectoryInfo(tn.Tag as string);
					DirectoryInfo[] vSubDirs = di.GetDirectories();
					foreach(DirectoryInfo diSub in vSubDirs)
					{
						if(!IsValidFileSystemObject(diSub)) continue;

						TreeNode tnSub = CreateFolderNode(diSub.FullName, false, null);
						if(tnSub != null) lNodes.Add(tnSub);
					}
				}
				catch(Exception) { Debug.Assert(false); }

				RebuildFolderImageList();
				lNodes.Sort(new FbfPrivTviComparer());
				tn.Nodes.AddRange(lNodes.ToArray());
			}
		}

		private void BrowseToFolder(string strPath)
		{
			try
			{
				DirectoryInfo di = new DirectoryInfo(strPath);
				string[] vPath = di.FullName.Split(new char[]{ Path.DirectorySeparatorChar });
				if((vPath == null) || (vPath.Length == 0)) { Debug.Assert(false); return; }

				TreeNode tn = null;
				string str = string.Empty;
				for(int i = 0; i < vPath.Length; ++i)
				{
					if(i > 0) str = UrlUtil.EnsureTerminatingSeparator(str, false);
					str += vPath[i];
					if(i == 0) str = UrlUtil.EnsureTerminatingSeparator(str, false);

					TreeNodeCollection tnc = ((tn != null) ? tn.Nodes : m_tvFolders.Nodes);
					tn = null;

					foreach(TreeNode tnSub in tnc)
					{
						string strSub = (tnSub.Tag as string);
						if(string.IsNullOrEmpty(strSub)) { Debug.Assert(false); continue; }

						if(strSub.Equals(str, StrUtil.CaseIgnoreCmp))
						{
							tn = tnSub;
							break;
						}
					}

					if(tn == null) { Debug.Assert(false); break; }

					if((i != (vPath.Length - 1)) && !tn.IsExpanded) tn.Expand();
				}

				if(tn != null)
				{
					m_tvFolders.SelectedNode = tn;
					tn.EnsureVisible();
				}
				else { Debug.Assert(false); }
			}
			catch(Exception) { Debug.Assert(false); }
		}

		private void OnFoldersAfterSelect(object sender, TreeViewEventArgs e)
		{
			TreeNode tn = e.Node;
			string strPath = (tn.Tag as string);
			if(strPath == null) { Debug.Assert(false); return; }

			try
			{
				DirectoryInfo di = new DirectoryInfo(strPath);
				BuildFilesList(di);
			}
			catch(Exception) { Debug.Assert(false); }
		}

		private void OnFilesSelectedIndexChanged(object sender, EventArgs e)
		{
			EnableControlsEx();
		}
	}
}