-
-
Notifications
You must be signed in to change notification settings - Fork 240
/
Copy pathCompact.vb
750 lines (481 loc) · 24.6 KB
/
Compact.vb
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
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Text.RegularExpressions
Imports Ookii.Dialogs 'Uses Ookii Dialogs for the non-archaic filebrowser dialog. http://www.ookii.org/Software/Dialogs
Public Class Compact
Dim version = "1.3.1"
Private WithEvents MyProcess As Process
Private Delegate Sub AppendOutputTextDelegate(ByVal text As String)
Private Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(CompactGUI.Compact)
End Sub
'Status Monitors
Dim compressFinished = 0
Dim uncompressFinished = 0
Dim isQueryMode = 0
Dim isQueryCalledByCompact = 0
Dim byteComparisonRaw As String = ""
Dim byteComparisonRawFilesCompressed As String = ""
Dim dirCountProgress As UInteger
Dim dirCountTotal As UInteger
Dim fileCountTotal As UInteger = 0
Dim fileCountProgress As UInteger
Dim fileCountOutputCompressed As UInteger
Dim QdirCountProgress As UInteger
Private Sub MyProcess_ErrorDataReceived _
(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) _
Handles MyProcess.ErrorDataReceived
AppendOutputText(vbCrLf & e.Data) 'Ensures error data is printed to the output console
End Sub
Private Sub MyProcess_OutputDataReceived _
(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) _
Handles MyProcess.OutputDataReceived
AppendOutputText(vbCrLf & e.Data) 'Sends output to the embedded console
Try
If e.Data.Contains("total bytes of data are stored in") Then 'Gets the output line that contains both the pre- and post-compression folder sizes
byteComparisonRaw = e.Data
End If
If e.Data.Contains("The compression ratio is") Then 'Gets the output line that contains the compression ratio and forces the progress bar to 100% (indirectly due to threading)
compressFinished = 1
dirCountProgress = dirCountTotal
fileCountProgress = fileCountTotal
End If
If e.Data.Contains("directories were uncompressed") Then 'Gets the output line that identifies that an uncompression event has finished.
dirCountProgress = 0
fileCountProgress = fileCountTotal
uncompressFinished = 1
End If
If e.Data.StartsWith(" Compressing files in") Then 'Gets each directory that is compressed. Used for the old progressbar.
dirCountProgress += 1
End If
If e.Data.EndsWith("[OK]") Then 'Gets each file that was successfully compressed OR uncompressed.
fileCountProgress += 1
End If
If e.Data.EndsWith(" are not compressed.") Then 'Gets the output line that identifies the total number of files compressed.
byteComparisonRawFilesCompressed = e.Data
End If
If e.Data.StartsWith(" Listing ") Then 'Gets the output line that identifies the query folder count
QdirCountProgress += 1
End If
Catch ex As Exception
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With dirChooser
.LinkBehavior = LinkBehavior.HoverUnderline
.LinkColor = Color.FromArgb(37, 110, 196)
End With
RCMenu.WriteLocRegistry()
progressTimer.Start() 'Starts a timer that keeps track of changes during any operation.
For Each arg In My.Application.CommandLineArgs
If arg.ToString IsNot Nothing Then
SelectFolder(arg, "cmdlineargs")
End If
Next
End Sub
Private Sub ShowInfoPopup_Click(sender As Object, e As EventArgs) Handles showinfopopup.Click
Info.semVersion.Text = "V " + version
Info.Show()
End Sub
Private Sub ProgressTimer_Tick(sender As Object, e As EventArgs) Handles progressTimer.Tick
If fileCountTotal <> 0 Then 'Makes sure that there are actually files being counted before attempting a calculation
If isQueryMode = 0 Then
progresspercent.Text = Math.Round _
((fileCountProgress / fileCountTotal * 100), 0).ToString + " %" 'Generates an estimate of progress based on how many files have been processed out of the total.
Try
If compactprogressbar.Value >= 101 Then 'Avoids a /r/softwaregore scenario
compactprogressbar.Value = 1
Else
compactprogressbar.Value = Math.Round _
((fileCountProgress / fileCountTotal * 100), 0)
End If
Catch ex As Exception
End Try
ElseIf isQueryMode = 1 Then
progresspercent.Text = Math.Round _
((QdirCountProgress / dirCountTotal * 100), 0).ToString + " %" 'Generates an estimate of progress for the Query command.
Try
If compactprogressbar.Value >= 101 Then 'Avoids a /r/softwaregore scenario
compactprogressbar.Value = 1
Else
compactprogressbar.Value = Math.Round _
((QdirCountProgress / dirCountTotal * 100), 0)
End If
Catch ex As Exception
End Try
End If
End If
If compressFinished = 1 Then 'Hides and shows certain UI elements when compression is finished or if a compression status is being checked
If isQueryMode And isQueryCalledByCompact = 0 Then
progressPageLabel.Text = "This folder contains compressed items"
progresspercent.Visible = False
End If
compressFinished = 0
buttonRevert.Visible = True
returnArrow.Visible = True
CalculateSaving()
QdirCountProgress = 0
End If
If uncompressFinished = 1 Then 'Hides and shows certain UI elements when uncompression is finished
uncompressFinished = 0
buttonCompress.Visible = True
buttonRevert.Visible = False
progressPageLabel.Text = "Folder Uncompressed."
returnArrow.Visible = True
End If
End Sub
Private Sub AppendOutputText(ByVal text As String) 'Attach output to the embedded console
Try
If conOut.InvokeRequired Then
Dim serverOutDelegate As New AppendOutputTextDelegate(AddressOf AppendOutputText)
Me.Invoke(serverOutDelegate, text)
Else
conOut.AppendText(text.Replace("ÿ", " "))
conOut.Select(conOut.TextLength, 1)
conOut.ScrollToCaret()
End If
Catch ex As Exception
End Try
End Sub
'Set variables for the advanced compression checkboxes.
Dim workingDir As String = ""
Dim recursiveScan As String = ""
Dim hiddenFiles As String = ""
Dim forceCompression As String = "" 'Not actually implemented - yet
'Set variables for minor security and error handling
Dim overrideCompressFolderButton = 0
Dim directorysizeexceptionCount = 0 'Used in the DirectorySize() Function to ensure the error message only shows up once, even if multiple UnauthorizedAccessException errors get thrown
Dim uncompressedfoldersize
Private Sub SelectFolderToCompress _
(sender As Object, e As EventArgs) Handles dirChooser.LinkClicked, chosenDirDisplay.Click
overrideCompressFolderButton = 0
Dim folderChoice As New VistaFolderBrowserDialog
folderChoice.ShowDialog()
SelectFolder(folderChoice.SelectedPath, "button")
folderChoice.Dispose()
End Sub
Private Sub SelectFolder(selectedDir As String, senderID As String)
Dim wDString = selectedDir
If wDString.Contains("C:\Windows") Then 'Makes sure you're not trying to compact the Windows directory. I should Regex this to catch all possible drives hey?
MsgBox("Compressing items in the Windows folder using this program
is not recommended. Please use the command line if you still
wish to compress the Windows folder")
ElseIf wDString.EndsWith(":\") Then
MsgBox("Compressing an entire drive with this tool is not allowed")
Else
If wDString.Length >= 3 Then 'Makes sure the chosen folder isn't a null value or an exception
Dim DIwDString = New DirectoryInfo(wDString)
workingDir = Chr(34) + wDString.ToString() + Chr(34)
chosenDirDisplay.Text = DIwDString.Parent.ToString + " ❯ " + DIwDString.Name.ToString
uncompressedfoldersize = Math.Round(DirectorySize(DIwDString, True), 0)
preSize.Text = "Uncompressed Size: " + GetOutputSize _
(Math.Round(DirectorySize(DIwDString, True), 0), True)
preSize.Visible = True
buttonQueryCompact.Visible = True
Try
Dim directories() As String = System.IO.Directory.GetDirectories _
(wDString, "*", IO.SearchOption.AllDirectories)
dirCountTotal = directories.Length + 1
Dim numberOfFiles As Integer = Directory.GetFiles _
(wDString, "*", IO.SearchOption.AllDirectories).Length
fileCountTotal = numberOfFiles '- (dirCountTotal + 1) ' 'Windows seems to do a funny thing where it counts "files" as the number of files + folders
Catch ex As Exception
End Try
If overrideCompressFolderButton = 0 Then 'Used as a security measure to stop accidental compression of folders that should not be compressed - even though the compact.exe process will throw an error if you try, I'd prefer to catch it here anyway.
buttonCompress.Enabled = True
Else
buttonCompress.Enabled = False
End If
Else
If senderID = "button" Then Console.Write("No folder selected")
End If
End If
End Sub
Dim compactArgs As String
Private Sub CompressFolder_Click(sender As System.Object, e As System.EventArgs) Handles buttonCompress.Click
CreateProcess("compact")
End Sub
Private Sub buttonQueryCompact_Click(sender As Object, e As EventArgs) Handles buttonQueryCompact.Click
CreateProcess("query")
End Sub
Private Sub CreateProcess(passthrougharg As String)
Try
MyProcess.Close()
Catch ex As Exception
End Try
Try
If passthrougharg = "compact" Then isQueryMode = 0
If passthrougharg = "query" Then isQueryMode = 1
progresspercent.Visible = True
conOut.Clear()
MyProcess = New Process
With MyProcess.StartInfo
.FileName = "CMD.exe"
.Arguments = ""
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
End With
MyProcess.Start()
MyProcess.EnableRaisingEvents = True
MyProcess.BeginErrorReadLine()
MyProcess.BeginOutputReadLine()
Try
MyProcess.StandardInput.WriteLine("cd /d " + workingDir)
MyProcess.StandardInput.Flush()
MyProcess.StandardInput.WriteLine("") 'Required for the embedded console to show the next line in the buffer after the 'cd' command. No idea why
MyProcess.StandardInput.Flush()
RunCompact(passthrougharg)
If passthrougharg = "compact" Then progressPageLabel.Text = "Compressing, Please Wait"
If passthrougharg = "query" Then progressPageLabel.Text = "Analyzing"
TabControl1.SelectedTab = ProgressPage
Catch ex As Exception
End Try
Catch ex As Exception
Console.WriteLine(ex.Data)
End Try
End Sub
Private Sub ButtonRevert_Click(sender As Object, e As EventArgs) Handles buttonRevert.Click 'Handles uncompressing. For now, uncompressing can only be done through the program only to revert a compression that's just been done.
isQueryMode = 0
fileCountProgress = 0
dirCountProgress = 0
progresspercent.Visible = True
CompResultsPanel.Visible = False
buttonRevert.Visible = False
progressPageLabel.Text = "Reverting Changes, Please Wait"
Try
RunCompact("uncompact")
Catch ex As Exception
End Try
End Sub
Private Sub compressLZX_CheckedChanged(sender As Object, e As EventArgs) Handles compressLZX.CheckedChanged 'Cautions the user if they're about to use LZX compression
If compressLZX.Checked = True Then
If MsgBox("LZX is recommended only for folders that are not going to be used very often. Do not use this on program or game folders!" _
& vbCrLf & vbCrLf & "Do you wish to continue?", MsgBoxStyle.YesNo, "Warning") = MsgBoxResult.No Then
compressX8.Checked = True
End If
End If
End Sub
Private Sub ReturnArrow_Click(sender As Object, e As EventArgs) Handles returnArrow.Click 'Returns you to the first screen and cleans up some stuff
returnArrow.Visible = False
buttonRevert.Visible = False
CompResultsPanel.Visible = False
TabControl1.SelectedTab = InputPage
dirCountProgress = 0
fileCountProgress = 0
isQueryCalledByCompact = 0
MyProcess.Close()
End Sub
Private Sub CheckShowConOut_CheckedChanged(sender As Object, e As EventArgs) Handles checkShowConOut.CheckedChanged 'Handles showing the embedded console
If checkShowConOut.Checked Then
conOut.Visible = True
Else
conOut.Visible = False
End If
End Sub
Private Sub dirChooser_MouseEnter(sender As Object, e As EventArgs) Handles dirChooser.MouseEnter
dirChooser.LinkColor = Color.FromArgb(10, 80, 150)
End Sub
Private Sub dirChooser_MouseLeave(sender As Object, e As EventArgs) Handles dirChooser.MouseLeave
dirChooser.LinkColor = Color.FromArgb(37, 110, 196)
End Sub
'/////////////FUNCTIONS//////////////
Private Sub CalculateSaving() 'Calculations for all the relevant information after compression is completed. All the data is parsed from the console ouput using basic strings, but because that occurs on a different thread, information is stored to variables first (The Status Monitors at the top) then those values are used.
Dim numberFilesCompressed = 0
Dim querySize = 0
If isQueryMode = 0 Then querySize = Long.Parse(Regex.Replace(byteComparisonRaw.Substring _
(0, byteComparisonRaw.IndexOf("t")), "[^\d]", ""))
Dim oldFolderSize = Long.Parse(Regex.Replace(byteComparisonRaw.Substring _
(0, byteComparisonRaw.IndexOf("t")), "[^\d]", ""))
Dim newFolderSizem1 = byteComparisonRaw.Substring _
(byteComparisonRaw.LastIndexOf("n"c) + 1)
Dim newfoldersize = Long.Parse(Regex.Replace(newFolderSizem1.Substring _
(0, newFolderSizem1.Length - 7), "[^\d]", ""))
Try
numberFilesCompressed = Long.Parse(Regex.Replace(byteComparisonRawFilesCompressed.Substring _
(0, byteComparisonRawFilesCompressed.IndexOf("a")), "[^\d]", ""))
Catch ex As Exception
End Try
If GetOutputSize((oldFolderSize - newfoldersize), False) = "0" And isQueryMode = 1 Then
progressPageLabel.Text = "Folder is not compressed"
buttonRevert.Visible = False
isQueryCalledByCompact = 0
Else
progressPageLabel.Text = "Folder is compressed"
If isQueryMode = 1 And isQueryCalledByCompact = 0 Then
origSizeLabel.Text = GetOutputSize(oldFolderSize, True)
Else
origSizeLabel.Text = GetOutputSize(uncompressedfoldersize, True)
End If
compressedSizeLabel.Text = GetOutputSize _
(uncompressedfoldersize - (oldFolderSize - newfoldersize), True)
compRatioLabel.Text = Math.Round _
(oldFolderSize / newfoldersize, 1)
compRatioLabel.Text = Math.Round _
(uncompressedfoldersize / (uncompressedfoldersize - (oldFolderSize - newfoldersize)), 1)
spaceSavedLabel.Text = GetOutputSize _
((oldFolderSize - newfoldersize), True) + " Saved"
labelFilesCompressed.Text =
numberFilesCompressed.ToString + " / " + fileCountTotal.ToString + " files compressed"
Try
compressedSizeVisual.Width = CInt(368 / compRatioLabel.Text)
If hasqueryfinished = 1 Then
isQueryCalledByCompact = 0
isQueryMode = 0
buttonRevert.Visible = True
End If
Catch ex As System.OverflowException
compressedSizeVisual.Width = 368
End Try
If isQueryCalledByCompact = 0 Then
CompResultsPanel.Visible = True
ElseIf isQueryCalledByCompact = 1 Then
buttonRevert.Visible = False
CompResultsPanel.Visible = False
progressPageLabel.Text = "Analyzing..."
End If
End If
If isQueryCalledByCompact = 1 Then Queryaftercompact()
If isQueryCalledByCompact = 0 Then isQueryMode = 0
End Sub
Private Sub Queryaftercompact()
isQueryMode = 1
hasqueryfinished = 1
RunCompact("query")
End Sub
Dim hasqueryfinished = 0
Private Sub RunCompact(desiredfunction As String)
If desiredfunction = "compact" Then
isQueryCalledByCompact = 0
compactArgs = "compact /C"
If checkRecursiveScan.Checked = True Then
compactArgs = compactArgs + " /S"
End If
If checkForceCompression.Checked = True Then
compactArgs = compactArgs + " /F"
End If
If checkHiddenFiles.Checked = True Then
compactArgs = compactArgs + " /A"
End If
If compressX4.Checked = True Then
compactArgs = compactArgs + " /EXE:XPRESS4K"
End If
If compressX8.Checked = True Then
compactArgs = compactArgs + " /EXE:XPRESS8K"
End If
If compressX16.Checked = True Then
compactArgs = compactArgs + " /EXE:XPRESS16K"
End If
If compressLZX.Checked = True Then
compactArgs = compactArgs + " /EXE:LZX"
End If
MyProcess.StandardInput.WriteLine(compactArgs)
MyProcess.StandardInput.Flush()
isQueryCalledByCompact = 1
hasqueryfinished = 0
ElseIf desiredfunction = "uncompact" Then
isQueryCalledByCompact = 0
compactArgs = "compact /U /EXE /S"
If checkForceCompression.Checked = True Then
compactArgs = compactArgs + " /F"
End If
If checkHiddenFiles.Checked = True Then
compactArgs = compactArgs + " /A"
End If
MyProcess.StandardInput.WriteLine(compactArgs)
MyProcess.StandardInput.Flush()
ElseIf desiredfunction = "query" Then
compactArgs = "compact /S /Q /EXE"
MyProcess.StandardInput.WriteLine(compactArgs)
MyProcess.StandardInput.Flush()
End If
End Sub
Public Function GetOutputSize(ByVal inputsize As Long, Optional ByVal showSizeType As Boolean = False) As String 'Function for converting from Bytes into various units
Dim sizeType As String = ""
If inputsize < 1024 Then
sizeType = " B"
Else
If inputsize < (1024 ^ 3) * 9 Then
If inputsize < (1024 ^ 2) * 9 Then
sizeType = " KB"
inputsize = inputsize / 1024
Else
sizeType = " MB"
inputsize = inputsize / 1024 ^ 2
End If
Else
sizeType = " GB"
inputsize = inputsize / 1024 ^ 3
End If
End If
If showSizeType = True Then
Return inputsize & sizeType
Else
Return inputsize
End If
End Function
Private Function DirectorySize _
(ByVal dInfo As IO.DirectoryInfo, ByVal includeSubdirectories As Boolean) As Long
Try
Dim totalSize As Long = dInfo.EnumerateFiles().Sum(Function(file) file.Length)
If includeSubdirectories Then
totalSize += dInfo.EnumerateDirectories().Sum(Function(dir) DirectorySize(dir, True))
End If
Return totalSize
directorysizeexceptionCount = 0
Catch generatedexceptionname As UnauthorizedAccessException
If directorysizeexceptionCount = 0 Then
MsgBox("This directory contains a subfolder that you do not have permission to access. Please try running the program again as an Administrator." _
& vbCrLf & vbCrLf & "If the problem persists, the subfolder is most likely protected by the System, and by design this program will refuse to let you proceed.")
overrideCompressFolderButton = 1
directorysizeexceptionCount = 1
End If
Catch ex As Exception
End Try
End Function
'////////////////////TESTING////////////////////
Private Sub ExecuteButton_Click _
(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Code to run the manual testing input box
Dim input As String
input = TextBox1.Text
Try
MyProcess.StandardInput.WriteLine(input)
MyProcess.StandardInput.Flush()
conOut.Refresh()
fileCountProgress = 0
dirCountProgress = 0
Catch ex As Exception
End Try
TextBox1.Text = ""
End Sub
Private Sub TestArguments(sender As Object, e As EventArgs) Handles testcompactargs.Click
compactArgs = "compact /C"
If checkRecursiveScan.Checked = True Then
compactArgs = compactArgs + " /S"
End If
If checkForceCompression.Checked = True Then
compactArgs = compactArgs + " /F"
End If
If checkHiddenFiles.Checked = True Then
compactArgs = compactArgs + " /A"
End If
If compressX4.Checked = True Then
compactArgs = compactArgs + " /EXE:XPRESS4K"
End If
If compressX8.Checked = True Then
compactArgs = compactArgs + " /EXE:XPRESS8K"
End If
If compressX16.Checked = True Then
compactArgs = compactArgs + " /EXE:XPRESS16K"
End If
If compressLZX.Checked = True Then
compactArgs = compactArgs + " /EXE:LZX"
End If
'MsgBox(compactArgs)
End Sub
End Class