-
Notifications
You must be signed in to change notification settings - Fork 12
/
TAttacheCaseDelete.cpp
553 lines (436 loc) · 16.8 KB
/
TAttacheCaseDelete.cpp
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
//===========================================================================
/*
アタッシェケース(AttachéCase)
Copyright (c) 2002-2018, Mitsuhiro Hibara ( http://hibara.org )
All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
・Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
・Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
・Neither the name of the "HIBARA.ORG" nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//===========================================================================
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include "TAttacheCaseDelete.h"
#pragma package(smart_init)
// ---------------------------------------------------------------------------
// 注意:異なるスレッドが所有する VCL のメソッド/関数/プロパティを別の
// レッド所有のオブジェクトに対しては Synchronize を使用できます。
//
// Synchronize(&UpdateCaption);
//
// 例えば UpdateCaption を以下のように定義し
//
// void __fastcall TAttacheCaseDelete::UpdateCaption()
// {
// Form1->Caption = "スレッドから書き換えました";
// }
// ---------------------------------------------------------------------------
__fastcall TAttacheCaseDelete::TAttacheCaseDelete
(bool CreateSuspended) : TThread(CreateSuspended)
{
Opt = 0; //通常削除
RandClearNum = 0; //乱数書き込み回数
ZeroClearNum = 0; //ゼロ書き込み回数
ProgressPercentNum = -1; //進捗パーセント
ProgressStatusText = ""; //進捗ステータス
ProgressMsgText = ""; //進捗メッセージ
StatusNum = 0; //ステータス表示内容番号
MsgErrorString = ""; //エラーメッセージ
DeleteFileList = new TStringList; //削除ファイルリスト
}
//===========================================================================
//デストラクタ
//===========================================================================
__fastcall TAttacheCaseDelete::~TAttacheCaseDelete(void)
{
delete DeleteFileList;
}
//===========================================================================
//スレッド実行
//===========================================================================
void __fastcall TAttacheCaseDelete::Execute()
{
int i;
int FileCount = 0;
__int64 CountFileSize = 0;
int ret;
int ErrorNum;
TSearchRec sr;
int Attrs;
String FilePath;
//===================================
//デバッグ
//ShowMessage(DeleteFileList->Text);
//===================================
//-----------------------------------
// ゴミ箱の場合はファイル/フォルダ毎
// そのまま移動
//-----------------------------------
if (Opt == 2) {
for (i = 0; i < DeleteFileList->Count; i++) {
if (Terminated == true) {
goto LabelStop;
}
if ( GoToTrash(DeleteFileList->Strings[i]) == false ){
//エラー
goto LabelStop;
}
}
ProgressPercentNum = 100;
//'完了'
ProgressStatusText = LoadResourceString(&Msgdelete::_LABEL_STATUS_TITLE_COMPLETE);
//'削除が正常に完了しました。'
ProgressMsgText = LoadResourceString(&Msgdelete::_LABEL_STATUS_DETAIL_COMPLETE);
return;
}
//----------------------------------------------------
// 削除ファイルリスト情報(ファイル数、サイズ)を取得
//----------------------------------------------------
ProgressPercentNum = -1;
//'ファイルリストの生成'
ProgressStatusText = LoadResourceString(&Msgdelete::_LABEL_STATUS_TITLE_LISTING);
//'削除するための準備をしています...'
ProgressMsgText = LoadResourceString(&Msgdelete::_LABEL_STATUS_DETAIL_PREPARING);
//-----------------------------------
// 削除、または完全削除
//-----------------------------------
if ( Opt == 0){
//'削除しています...'
ProgressStatusText = LoadResourceString(&Msgdelete::_LABEL_STATUS_TITLE_DELETING);
}
else if ( Opt == 1 ) {
//'完全削除しています...'
ProgressStatusText = LoadResourceString(&Msgdelete::_LABEL_STATUS_TITLE_COMPLETE_DELETING);
//完全削除回数分×合計サイズが増える
TotalFileSize = TotalFileSize * (RandClearNum + ZeroClearNum > 0 ? RandClearNum + ZeroClearNum : 1 );
}
//-----------------------------------
// 削除実行
//-----------------------------------
for (i = DeleteFileList->Count-1; i > -1; i--) {
FilePath = DeleteFileList->Strings[i];
//-----------------------------------
// ファイル
//-----------------------------------
if (FileExists(FilePath) == true) {
//読み取り専用なら外してから
if ( FileIsReadOnly(FilePath) == true ){
FileSetReadOnly(FilePath, false);
}
//-----------------------------------
// 通常削除
//-----------------------------------
if ( Opt == 0){
DeleteFile(FilePath);
FileCount++;
//ファイル数でプログレス表示
ProgressPercentNum = ((float)FileCount/DeleteFileList->Count)*100;
}
//-----------------------------------
// 完全削除
//-----------------------------------
else if ( Opt == 1 ) {
//処理サイズでプログレス表示(「完全削除」関数内で処理)
if ( CompleteDeleteFile(FilePath, CountFileSize, TotalFileSize) == false ){
goto LabelError;
}
}
}
//-----------------------------------
// ディレクトリ
//-----------------------------------
else{
//ディレクトリは空行が入っているので
//前に削除したファイルの親ディレクトリを取得
FilePath = ExtractFileDir(DeleteFileList->Strings[i+1]);
if ( RemoveDir(FilePath) == false ){
//削除に失敗したときは属性を変更
Attrs = FileGetAttr(FilePath);
if (Attrs & faHidden){ //隠しファイル属性のときは外す
FileSetAttr( FilePath, Attrs & !faHidden);
}
if (Attrs & faReadOnly){ //読み取り専用属性のときも外す
FileSetAttr( FilePath, Attrs & !faReadOnly );
}
RemoveDir(FilePath); //再チャレンジ
}
}
if (Terminated == true) {
goto LabelStop;
}
}//end for (i = DeleteList->Count-1; i > -1; i--);
ProgressPercentNum = 100;
//'完了'
ProgressStatusText = LoadResourceString(&Msgdelete::_LABEL_STATUS_TITLE_COMPLETE);
//'削除が正常に完了しました。'
ProgressMsgText = LoadResourceString(&Msgdelete::_LABEL_STATUS_DETAIL_COMPLETE);
StatusNum = 1;
return;
//-----------------------------------
// エラー
//-----------------------------------
LabelError:
ProgressPercentNum = 0;
//'エラー'
ProgressStatusText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_TITLE_ERROR);
//'削除に失敗しました。'
ProgressMsgText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_DETAIL_FAILED);
StatusNum = -1;
return;
//-----------------------------------
// ユーザーキャンセル
//-----------------------------------
LabelStop:
ProgressPercentNum = 0;
//'キャンセル'
ProgressStatusText = LoadResourceString(&Msgdelete::_LABEL_STATUS_TITLE_USER_CANCEL);
//'削除が中止されました。'
ProgressMsgText = LoadResourceString(&Msgdelete::_LABEL_STATUS_DETAIL_STOPPED);
StatusNum = -2;
return;
}
//===========================================================================
//ファイルの完全削除
//===========================================================================
int __fastcall TAttacheCaseDelete::
CompleteDeleteFile(String FilePath, __int64 &CountSize, __int64 TotalFileSize)
{
int i, c;
int res;
char buffer[LARGE_BUF];
float ProgressPercentNumF;
HANDLE hFile;
DWORD uniWriteByte;
int fh = FileOpen(FilePath, fmShareDenyNone);
if ( fh == -1 )return(false);
__int64 uiWriteSize;
__int64 uiFileSize = FileSeek(fh,(__int64)0, 2);
FileClose(fh);
//読み取り専用なら外しておく
if ( FileIsReadOnly(FilePath) == true ){
FileSetReadOnly(FilePath, false);
}
//-----------------------------------
//ランダムな値で指定回数書き込みを行う
//-----------------------------------
for ( i = 0; i < RandClearNum; i++ ){
//'乱数を書き込み、完全削除を行っています...(Step:%d/%d)'
ProgressMsgText =
String().Format(LoadResourceString(&Msgdelete::_LABEL_STATUS_DETAIL_WRITE_RAND),
ARRAYOFCONST((i + 1, RandClearNum+ZeroClearNum))) + "\n" + FilePath;
//キャッシュを直接ディスクへ書き込む
hFile = CreateFileW(
FilePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
if ( hFile != INVALID_HANDLE_VALUE ){
uiWriteSize = 0;
while ( uiWriteSize < uiFileSize ){
fillrand(buffer, LARGE_BUF);
//ランダムの値で埋め尽くす
if ( WriteFile( hFile, buffer, LARGE_BUF, &uniWriteByte, NULL) == 0 ){
break;
}
uiWriteSize+=uniWriteByte;
CountSize+=uniWriteByte;
//途中キャンセルされたときの処理
if ( Terminated == true ){
CloseHandle( hFile );
DeleteFile(FilePath); //ふつうに削除する
return(-2);
}
//プログレス表示
ProgressPercentNumF = (float)CountSize/TotalFileSize;
ProgressPercentNum = (int)(ProgressPercentNumF*100);
if (TotalFileSize < 104857600) { // 100MB未満
ProgressPercentNumText = IntToStr(ProgressPercentNum)+"%";
}
else{
ProgressPercentNumText = FloatToStrF(ProgressPercentNumF*100, ffNumber, 4, 1)+"%";
}
}//while;
}
else{
//'ファイル削除中にエラーが発生しました。ファイルを開くことができません。'
MsgText = LoadResourceString(&Msgdelete::_MSG_ERROR_NOT_FILE_OPEN) + "\n" + FilePath;
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
CloseHandle( hFile );
return(-1);
}//end if;
CloseHandle( hFile );
}//loop;
//-----------------------------------
//NULL値で指定回数書き込む
//-----------------------------------
for ( c = 0; c < LARGE_BUF; c++ ){
buffer[c] = NULL;
}
for ( i = 0; i < ZeroClearNum; i++ ){
//'ゼロ(NULL)を書き込み、完全削除を行っています...(Step:%d/%d)'
ProgressMsgText =
String().Format(LoadResourceString(&Msgdelete::_LABEL_STATUS_DETAIL_WRITE_ZERO),
ARRAYOFCONST((i + 1 + RandClearNum, RandClearNum+ZeroClearNum))) +
"\n" + FilePath;
//キャッシュを直接ディスクへ書き込む
hFile = CreateFileW(
FilePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
if ( hFile != INVALID_HANDLE_VALUE ){
uiWriteSize = 0;
while ( uiWriteSize < uiFileSize ){
//NULL値で埋め尽くす
if ( WriteFile( hFile, buffer, LARGE_BUF, &uniWriteByte, NULL) == 0 ){
break;
}
uiWriteSize+=uniWriteByte;
CountSize+=uniWriteByte;
//途中キャンセルされたときの処理
if ( Terminated == true ){
CloseHandle( hFile );
DeleteFile(FilePath); //ふつうに削除する
return(-2);
}
//プログレス表示
ProgressPercentNumF = (float)CountSize/TotalFileSize;
ProgressPercentNum = (int)(ProgressPercentNumF*100);
if (TotalFileSize < 104857600) { // 100MB未満
ProgressPercentNumText = IntToStr(ProgressPercentNum)+"%";
}
else{
ProgressPercentNumText = FloatToStrF(ProgressPercentNumF*100, ffNumber, 4, 1)+"%";
}
}//while;
}
else{
//'ファイル削除中にエラーが発生しました。ファイルを開くことができません。'
MsgText = LoadResourceString(&Msgdelete::_MSG_ERROR_NOT_FILE_OPEN) + "\n" + FilePath;
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
CloseHandle( hFile );
return(-1);
}//end if;
CloseHandle( hFile );
}//loop;
//-----------------------------------
//さらにファイルサイズを0バイトにする
hFile = CreateFileW(
FilePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
NULL, TRUNCATE_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL);//FILE_FLAG_WRITE_THROUGH
CloseHandle( hFile );
//-----------------------------------
//ようやくここで削除
DeleteFile(FilePath);
return(1);
}//end CompleteDeleteFile;
//===========================================================================
//ごみ箱への移動
//===========================================================================
bool __fastcall TAttacheCaseDelete::GoToTrash(String Path)
{
ProgressPercentNum = -1;
//'ごみ箱へ移動しています...'
ProgressStatusText = LoadResourceString(&Msgdelete::_LABEL_STATUS_TITLE_GO_TO_TRASH);
ProgressMsgText = Path;
if (FileExists(Path) == true) {
}
else{
if (DirectoryExists(Path) == true) {
Path = ExcludeTrailingPathDelimiter(Path);
}
else{
//'ごみ箱への削除に失敗しました。'+#13+
//'一部のファイル/フォルダが削除できずに残ってしまった可能性があります。';
MsgText = LoadResourceString(&Msgdelete::_MSG_ERROR_GO_TO_TRASH_FAILED);
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
return(false);
}
}
const int len = Path.Length() + 2; //終端\0\0
wchar_t* from = new wchar_t[len];
wcscpy(from, Path.c_str());
from[len-1] = 0;
SHFILEOPSTRUCTW sh;
ZeroMemory(&sh, sizeof(SHFILEOPSTRUCT));
sh.hwnd = Application->Handle;
sh.wFunc = FO_DELETE; // ゴミ箱へ捨てる
sh.pFrom = from; // ファイルのポインタ
sh.pTo = NULL;
// Undo可, 確認なし(※でも結果的にUndoは不可能になるみたい)
sh.fFlags= FOF_ALLOWUNDO + FOF_NOCONFIRMATION;
if ( SHFileOperationW(&sh) != 0 ){
//'ごみ箱への削除に失敗しました。'+#13+
//'一部のファイル/フォルダが削除できずに残ってしまった可能性があります。';
MsgText = LoadResourceString(&Msgdelete::_MSG_ERROR_GO_TO_TRASH_FAILED);
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
return(false);
}
delete[] from;
//フォルダ内の表示更新
SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATH, Path.c_str(), 0);
return(true);
}//end GotoTrashOneFile;
//===========================================================================
// ランダム値の生成(CRNG)
//===========================================================================
void TAttacheCaseDelete::fillrand(char *buf, const int len)
{
static unsigned long count = 4;
static char r[4];
int i;
// ISAAC ( Cryptographic Random Number Generator )
randctx ctx;
// init
randinit(&ctx, 1);
for(i = 0; i < len; ++i){
if(count == 4){
*(unsigned long*)r = rand(&ctx);
count = 0;
}
buf[i] = r[count++];
}
}
//===========================================================================
//メインフォームに確認メッセージを投げて処理を中断する
//===========================================================================
void __fastcall TAttacheCaseDelete::PostConfirmMessageForm()
{
//グローバル変数(private)として定義してある
//String MsgText;
//TMsgDlgType MsgType;
//TMsgDlgButtons MsgButtons;
//TMsgDlgBtn MsgDefaultButton;
MsgReturnVal =
Form1->ShowConfirmMassageForm(MsgText, MsgType, MsgButtons, MsgDefaultButton);
}
//===========================================================================