Welcome to mirror list, hosted at ThFree Co, Russian Federation.

7zipUninstall.c « 7zipUninstall « Util « C - github.com/kornelski/7z.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: cd66002a8ef04dc6aa852991d86af890c0b08973 (plain)
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
/* 7zipUninstall.c - 7-Zip Uninstaller
2015-12-26 : Igor Pavlov : Public domain */

#include "Precomp.h"

#define SZ_ERROR_ABORT 100

#ifdef _MSC_VER
#pragma warning(disable : 4201) // nonstandard extension used : nameless struct/union
#pragma warning(disable : 4011) // vs2010: identifier truncated to _CRT_SECURE_CPP_OVERLOAD_SECURE
#endif

#include <windows.h>
#include <ShlObj.h>

#include "../../7zVersion.h"

#include "resource.h"

#define LLL_(quote) L##quote
#define LLL(quote) LLL_(quote)

// static const WCHAR *k_7zip = L"7-Zip";

// #define _64BIT_INSTALLER 1

#ifdef _WIN64
  #define _64BIT_INSTALLER 1
#endif

#define k_7zip_with_Ver_base L"7-Zip " LLL(MY_VERSION)

#ifdef _64BIT_INSTALLER
  #define k_7zip_with_Ver k_7zip_with_Ver_base L" (x64)"
#else
  #define k_7zip_with_Ver k_7zip_with_Ver_base
#endif

// static const WCHAR *k_7zip_with_Ver_str = k_7zip_with_Ver;

static const WCHAR *k_Reg_Software_7zip = L"Software\\7-Zip";

static const WCHAR *k_Reg_Path = L"Path";
 
static const WCHAR *k_Reg_Path32 = L"Path"
  #ifdef _64BIT_INSTALLER
    L"64"
  #else
    L"32"
  #endif
  ;

#if defined(_64BIT_INSTALLER) && !defined(_WIN64)
  #define k_Reg_WOW_Flag KEY_WOW64_64KEY
#else
  #define k_Reg_WOW_Flag 0
#endif

#ifdef _WIN64
  #define k_Reg_WOW_Flag_32 KEY_WOW64_32KEY
#else
  #define k_Reg_WOW_Flag_32 0
#endif

#define k_7zip_CLSID L"{23170F69-40C1-278A-1000-000100020000}"

static const WCHAR *k_Reg_CLSID_7zip = L"CLSID\\" k_7zip_CLSID;
static const WCHAR *k_Reg_CLSID_7zip_Inproc = L"CLSID\\" k_7zip_CLSID L"\\InprocServer32";


#define g_AllUsers True

static Bool g_Install_was_Pressed;
static Bool g_Finished;
static Bool g_SilentMode;

static HWND g_HWND;
static HWND g_Path_HWND;
static HWND g_InfoLine_HWND;
static HWND g_Progress_HWND;

typedef WINADVAPI LONG (APIENTRY *Func_RegDeleteKeyExW)(HKEY hKey, LPCWSTR lpSubKey, REGSAM samDesired, DWORD Reserved);
static Func_RegDeleteKeyExW func_RegDeleteKeyExW;

static WCHAR path[MAX_PATH * 2 + 40];
static WCHAR workDir[MAX_PATH + 10];
static WCHAR modulePath[MAX_PATH + 10];
static WCHAR modulePrefix[MAX_PATH + 10];
static WCHAR tempPath[MAX_PATH * 2 + 40];
static WCHAR cmdLine[MAX_PATH * 3 + 40];
static WCHAR copyPath[MAX_PATH * 2 + 40];

static const WCHAR *kUninstallExe = L"Uninstall.exe";

#define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) -= 0x20 : (c)))

static Bool AreStringsEqual_NoCase(const wchar_t *s1, const wchar_t *s2)
{
  for (;;)
  {
    wchar_t c1 = *s1++;
    wchar_t c2 = *s2++;
    if (c1 != c2 && MAKE_CHAR_UPPER(c1) != MAKE_CHAR_UPPER(c2))
      return False;
    if (c2 == 0)
      return True;
  }
}

static Bool IsString1PrefixedByString2_NoCase(const wchar_t *s1, const wchar_t *s2)
{
  for (;;)
  {
    wchar_t c1;
    wchar_t c2 = *s2++;
    if (c2 == 0)
      return True;
    c1 = *s1++;
    if (c1 != c2 && MAKE_CHAR_UPPER(c1) != MAKE_CHAR_UPPER(c2))
      return False;
  }
}

static void NormalizePrefix(WCHAR *s)
{
  size_t len = wcslen(s);
  if (len != 0)
    if (s[len - 1] != WCHAR_PATH_SEPARATOR)
    {
      s[len] = WCHAR_PATH_SEPARATOR;
      s[len + 1] = 0;
    }
}

static int MyRegistry_QueryString(HKEY hKey, LPCWSTR name, LPWSTR dest)
{
  DWORD cnt = MAX_PATH * sizeof(name[0]);
  DWORD type = 0;
  LONG res = RegQueryValueExW(hKey, name, NULL, &type, (LPBYTE)dest, (DWORD *)&cnt);
  if (type != REG_SZ)
    return False;
  return res == ERROR_SUCCESS;
}

static int MyRegistry_QueryString2(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest)
{
  HKEY key = 0;
  LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag, &key);
  if (res != ERROR_SUCCESS)
    return False;
  {
    Bool res2 = MyRegistry_QueryString(key, valName, dest);
    RegCloseKey(key);
    return res2;
  }
}

static LONG MyRegistry_OpenKey_ReadWrite(HKEY parentKey, LPCWSTR name, HKEY *destKey)
{
  return RegOpenKeyExW(parentKey, name, 0, KEY_READ | KEY_WRITE | k_Reg_WOW_Flag, destKey);
}

static LONG MyRegistry_DeleteKey(HKEY parentKey, LPCWSTR name)
{
  #if k_Reg_WOW_Flag != 0
    if (func_RegDeleteKeyExW)
      return func_RegDeleteKeyExW(parentKey, name, k_Reg_WOW_Flag, 0);
    return E_FAIL;
  #else
    return RegDeleteKeyW(parentKey, name);
  #endif
}

#ifdef _64BIT_INSTALLER

static int MyRegistry_QueryString2_32(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest)
{
  HKEY key = 0;
  LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag_32, &key);
  if (res != ERROR_SUCCESS)
    return False;
  {
    Bool res2 = MyRegistry_QueryString(key, valName, dest);
    RegCloseKey(key);
    return res2;
  }
}

static LONG MyRegistry_OpenKey_ReadWrite_32(HKEY parentKey, LPCWSTR name, HKEY *destKey)
{
  return RegOpenKeyExW(parentKey, name, 0, KEY_READ | KEY_WRITE | k_Reg_WOW_Flag_32, destKey);
}

static LONG MyRegistry_DeleteKey_32(HKEY parentKey, LPCWSTR name)
{
  #if k_Reg_WOW_Flag_32 != 0
    if (func_RegDeleteKeyExW)
      return func_RegDeleteKeyExW(parentKey, name, k_Reg_WOW_Flag_32, 0);
    return E_FAIL;
  #else
    return RegDeleteKeyW(parentKey, name);
  #endif
}

#endif




static void MyReg_DeleteVal_Path_if_Equal(HKEY hKey, LPCWSTR name)
{
  WCHAR s[MAX_PATH + 10];
  if (MyRegistry_QueryString(hKey, name, s))
  {
    NormalizePrefix(s);
    if (AreStringsEqual_NoCase(s, path))
      RegDeleteValueW(hKey, name);
  }
}

static void SetRegKey_Path2(HKEY parentKey)
{
  HKEY key = 0;
  LONG res = MyRegistry_OpenKey_ReadWrite(parentKey, k_Reg_Software_7zip, &key);
  if (res == ERROR_SUCCESS)
  {
    MyReg_DeleteVal_Path_if_Equal(key, k_Reg_Path32);
    MyReg_DeleteVal_Path_if_Equal(key, k_Reg_Path);

    RegCloseKey(key);
    // MyRegistry_DeleteKey(parentKey, k_Reg_Software_7zip);
  }
}

static void SetRegKey_Path()
{
  SetRegKey_Path2(HKEY_CURRENT_USER);
  SetRegKey_Path2(HKEY_LOCAL_MACHINE);
}

static HRESULT CreateShellLink(LPCWSTR srcPath, LPCWSTR targetPath)
{
  IShellLinkW *sl;
 
  // CoInitialize has already been called.
  HRESULT hres = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLinkW, (LPVOID*)&sl);

  if (SUCCEEDED(hres))
  {
    IPersistFile *pf;
    
    hres = sl->lpVtbl->QueryInterface(sl, &IID_IPersistFile, (LPVOID *)&pf);
   
    if (SUCCEEDED(hres))
    {
      WCHAR s[MAX_PATH + 10];
      hres = pf->lpVtbl->Load(pf, srcPath, TRUE);
      pf->lpVtbl->Release(pf);

      if (SUCCEEDED(hres))
      {
        hres = sl->lpVtbl->GetPath(sl, s, MAX_PATH, NULL, 0); // SLGP_RAWPATH
        if (!AreStringsEqual_NoCase(s, targetPath))
          hres = S_FALSE;
      }
    }

    sl->lpVtbl->Release(sl);
  }

  return hres;
}

static void SetShellProgramsGroup(HWND hwndOwner)
{
  #ifdef UNDER_CE

  UNUSED_VAR(hwndOwner)

  #else

  unsigned i = (g_AllUsers ? 1 : 2);

  for (; i < 3; i++)
  {
    // Bool isOK = True;
    WCHAR link[MAX_PATH + 40];
    WCHAR destPath[MAX_PATH + 40];

    link[0] = 0;
    
    if (SHGetFolderPathW(hwndOwner,
        i == 1 ? CSIDL_COMMON_PROGRAMS : CSIDL_PROGRAMS,
        NULL, SHGFP_TYPE_CURRENT, link) != S_OK)
      continue;

    NormalizePrefix(link);
    wcscat(link, L"7-Zip\\");
    
    {
      const size_t baseLen = wcslen(link);
      unsigned k;
      Bool needDelete = False;

      for (k = 0; k < 2; k++)
      {
        wcscpy(link + baseLen, k == 0 ?
            L"7-Zip File Manager.lnk" :
            L"7-Zip Help.lnk");
        wcscpy(destPath, path);
        wcscat(destPath, k == 0 ?
            L"7zFM.exe" :
            L"7-zip.chm");
        
        if (CreateShellLink(link, destPath) == S_OK)
        {
          needDelete = True;
          DeleteFileW(link);
        }
      }

      if (needDelete)
      {
        link[baseLen] = 0;
        RemoveDirectoryW(link);
      }
    }
  }

  #endif
}


static const WCHAR * const k_ShellEx_Items[] =
{
    L"*\\shellex\\ContextMenuHandlers"
  , L"Directory\\shellex\\ContextMenuHandlers"
  , L"Folder\\shellex\\ContextMenuHandlers"
  , L"Directory\\shellex\\DragDropHandlers"
  , L"Drive\\shellex\\DragDropHandlers"
};

static const WCHAR *k_Shell_Approved = L"Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved";

static const WCHAR *k_AppPaths_7zFm = L"Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\7zFM.exe";
#define k_REG_Uninstall L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"
static const WCHAR *k_Uninstall_7zip = k_REG_Uninstall L"7-Zip";


static Bool AreEqual_Path_PrefixName(const wchar_t *s, const wchar_t *prefix, const wchar_t *name)
{
  if (!IsString1PrefixedByString2_NoCase(s, prefix))
    return False;
  return AreStringsEqual_NoCase(s + wcslen(prefix), name);
}

static void WriteCLSID()
{
  WCHAR s[MAX_PATH + 30];
  
  if (MyRegistry_QueryString2(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc, NULL, s))
  {
    if (AreEqual_Path_PrefixName(s, path, L"7-zip.dll"))
    {
      LONG res = MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc);
      if (res == ERROR_SUCCESS)
        MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip);

      {
        unsigned i;
        for (i = 0; i < sizeof(k_ShellEx_Items) / sizeof(k_ShellEx_Items[0]); i++)
        {
          WCHAR destPath[MAX_PATH];
          wcscpy(destPath, k_ShellEx_Items[i]);
          wcscat(destPath, L"\\7-Zip");
          
          MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, destPath);
        }
      }

      {
        HKEY destKey = 0;
        LONG res = MyRegistry_OpenKey_ReadWrite(HKEY_LOCAL_MACHINE, k_Shell_Approved, &destKey);
        if (res == ERROR_SUCCESS)
        {
          RegDeleteValueW(destKey, k_7zip_CLSID);
          /* res = */ RegCloseKey(destKey);
        }
      }
    }
  }

  
  #ifdef _64BIT_INSTALLER
  
  if (MyRegistry_QueryString2_32(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc, NULL, s))
  {
    if (AreEqual_Path_PrefixName(s, path, L"7-zip32.dll"))
    {
      LONG res = MyRegistry_DeleteKey_32(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc);
      if (res == ERROR_SUCCESS)
        MyRegistry_DeleteKey_32(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip);

      {
        unsigned i;
        for (i = 0; i < sizeof(k_ShellEx_Items) / sizeof(k_ShellEx_Items[0]); i++)
        {
          WCHAR destPath[MAX_PATH];
          wcscpy(destPath, k_ShellEx_Items[i]);
          wcscat(destPath, L"\\7-Zip");
          
          MyRegistry_DeleteKey_32(HKEY_CLASSES_ROOT, destPath);
        }
      }

      {
        HKEY destKey = 0;
        LONG res = MyRegistry_OpenKey_ReadWrite_32(HKEY_LOCAL_MACHINE, k_Shell_Approved, &destKey);
        if (res == ERROR_SUCCESS)
        {
          RegDeleteValueW(destKey, k_7zip_CLSID);
          /* res = */ RegCloseKey(destKey);
        }
      }
    }
  }
  
  #endif


  if (MyRegistry_QueryString2(HKEY_LOCAL_MACHINE, k_AppPaths_7zFm, NULL, s))
    if (AreEqual_Path_PrefixName(s, path, L"7zFM.exe"))
      MyRegistry_DeleteKey(HKEY_LOCAL_MACHINE, k_AppPaths_7zFm);

  if (MyRegistry_QueryString2(HKEY_LOCAL_MACHINE, k_Uninstall_7zip, L"UninstallString", s))
    if (AreEqual_Path_PrefixName(s, path, kUninstallExe))
      MyRegistry_DeleteKey(HKEY_LOCAL_MACHINE, k_Uninstall_7zip);
}


static const wchar_t *GetCmdParam(const wchar_t *s)
{
  Bool quoteMode = False;
  for (;; s++)
  {
    wchar_t c = *s;
    if (c == L'\"')
      quoteMode = !quoteMode;
    else if (c == 0 || (c == L' ' && !quoteMode))
      return s;
  }
}

static void RemoveQuotes(wchar_t *s)
{
  const wchar_t *src = s;
  for (;;)
  {
    wchar_t c = *src++;
    if (c == '\"')
      continue;
    *s++ = c;
    if (c == 0)
      return;
  }
}

static Bool DoesFileOrDirExist()
{
  return (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES);
}

static BOOL RemoveFileAfterReboot2(const WCHAR *s)
{
  #ifndef UNDER_CE
  return MoveFileExW(s, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
  #else
  UNUSED_VAR(s)
  return TRUE;
  #endif
}

static BOOL RemoveFileAfterReboot()
{
  return RemoveFileAfterReboot2(path);
}

#define IS_LIMIT_CHAR(c) (c == 0 || c == ' ')

static Bool IsThereSpace(const wchar_t *s)
{
  for (;;)
  {
    wchar_t c = *s++;
    if (c == 0)
      return False;
    if (c == ' ')
      return True;
  }
}

static void AddPathParam(wchar_t *dest, const wchar_t *src)
{
  Bool needQuote = IsThereSpace(src);
  if (needQuote)
    wcscat(dest, L"\"");
  wcscat(dest, src);
  if (needQuote)
    wcscat(dest, L"\"");
}



static Bool GetErrorMessage(DWORD errorCode, WCHAR *message)
{
  LPVOID msgBuf;
  if (FormatMessageW(
          FORMAT_MESSAGE_ALLOCATE_BUFFER
        | FORMAT_MESSAGE_FROM_SYSTEM
        | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, errorCode, 0, (LPWSTR) &msgBuf, 0, NULL) == 0)
    return False;
  wcscpy(message, msgBuf);
  LocalFree(msgBuf);
  return True;
}

static BOOL RemoveDir()
{
  DWORD attrib = GetFileAttributesW(path);
  if (attrib == INVALID_FILE_ATTRIBUTES)
    return TRUE;
  if (RemoveDirectoryW(path))
    return TRUE;
  return RemoveFileAfterReboot();
}





#define k_Lang L"Lang"

// NUM_LANG_TXT_FILES files are placed before en.ttt
#define NUM_LANG_TXT_FILES 87

#ifdef _64BIT_INSTALLER
  #define NUM_EXTRA_FILES_64BIT 1
#else
  #define NUM_EXTRA_FILES_64BIT 0
#endif

#define NUM_FILES (NUM_LANG_TXT_FILES + 1 + 13 + NUM_EXTRA_FILES_64BIT)

static const char *k_Names =
  "af an ar ast az ba be bg bn br ca co cs cy da de el eo es et eu ext"
  " fa fi fr fur fy ga gl gu he hi hr hu hy id io is it ja ka kaa kk ko ku ku-ckb ky"
  " lij lt lv mk mn mng mng2 mr ms nb ne nl nn pa-in pl ps pt pt-br ro ru"
  " sa si sk sl sq sr-spc sr-spl sv ta th tr tt ug uk uz va vi yo zh-cn zh-tw"
  " en.ttt"
  " descript.ion"
  " History.txt"
  " License.txt"
  " readme.txt"
  " 7-zip.chm"
  " 7z.sfx"
  " 7zCon.sfx"
  " 7z.exe"
  " 7zG.exe"
  " 7z.dll"
  " 7zFM.exe"
  #ifdef _64BIT_INSTALLER
  " 7-zip32.dll"
  #endif
  " 7-zip.dll"
  " Uninstall.exe";



static int Install()
{
  SRes res = SZ_OK;
  WRes winRes = 0;
  
  // Bool needReboot = False;
  const size_t pathLen = wcslen(path);

  if (!g_SilentMode)
  {
    ShowWindow(g_Progress_HWND, SW_SHOW);
    ShowWindow(g_InfoLine_HWND, SW_SHOW);
    SendMessage(g_Progress_HWND, PBM_SETRANGE32, 0, NUM_FILES);
  }

  {
    unsigned i;
    const char *curName = k_Names;

    for (i = 0; *curName != 0; i++)
    {
      WCHAR *temp;

      if (!g_SilentMode)
      {
        MSG msg;
        
        // g_HWND
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
          if (!IsDialogMessage(g_HWND, &msg))
          {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
          }
          if (!g_HWND)
            return 1;
        }

        // Sleep(1);
        SendMessage(g_Progress_HWND, PBM_SETPOS, i, 0);
      }

      path[pathLen] = 0;
      temp = path + pathLen;
      
      if (i <= NUM_LANG_TXT_FILES)
        wcscpy(temp, k_Lang L"\\");
      
      {
        WCHAR *dest = temp + wcslen(temp);

        for (;;)
        {
          char c = *curName;
          if (c == 0)
            break;
          curName++;
          if (c == ' ')
            break;
          *dest++ = (Byte)c;
        }

        *dest = 0;
      }

      if (i < NUM_LANG_TXT_FILES)
        wcscat(temp, L".txt");
  
      if (!g_SilentMode)
        SetWindowTextW(g_InfoLine_HWND, temp);

      {
        DWORD attrib = GetFileAttributesW(path);
        if (attrib == INVALID_FILE_ATTRIBUTES)
          continue;
        if (attrib & FILE_ATTRIBUTE_READONLY)
          SetFileAttributesW(path, 0);
        if (!DeleteFileW(path))
        {
          if (!RemoveFileAfterReboot())
          {
            winRes = GetLastError();
          }
          /*
          else
            needReboot = True;
          */
        }
      }
    }

    wcscpy(path + pathLen, k_Lang);
    RemoveDir();

    path[pathLen] = 0;
    RemoveDir();
    
    if (!g_SilentMode)
      SendMessage(g_Progress_HWND, PBM_SETPOS, i, 0);

    if (*curName == 0)
    {
      SetRegKey_Path();
      WriteCLSID();
      SetShellProgramsGroup(g_HWND);
      if (!g_SilentMode)
        SetWindowTextW(g_InfoLine_HWND, k_7zip_with_Ver L" is uninstalled");
    }
  }

  if (winRes != 0)
    res = SZ_ERROR_FAIL;

  if (res == SZ_OK)
  {
    // if (!g_SilentMode && needReboot);
    return 0;
  }

  if (!g_SilentMode)
  {
    WCHAR m[MAX_PATH + 100];
    m[0] = 0;
    if (winRes == 0 || !GetErrorMessage(winRes, m))
      wcscpy(m, L"ERROR");
    MessageBoxW(g_HWND, m, L"Error", MB_ICONERROR | MB_OK);
  }
  
  return 1;
}


static void OnClose()
{
  if (g_Install_was_Pressed && !g_Finished)
  {
    if (MessageBoxW(g_HWND,
        L"Do you want to cancel uninstallation?",
        k_7zip_with_Ver,
        MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2) != IDYES)
      return;
  }
  DestroyWindow(g_HWND);
  g_HWND = NULL;
}

static INT_PTR CALLBACK MyDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  UNUSED_VAR(lParam)

  switch (message)
  {
    case WM_INITDIALOG:
      g_Path_HWND = GetDlgItem(hwnd, IDE_EXTRACT_PATH);
      g_InfoLine_HWND = GetDlgItem(hwnd, IDT_CUR_FILE);
      g_Progress_HWND = GetDlgItem(hwnd, IDC_PROGRESS);

      SetWindowTextW(hwnd, k_7zip_with_Ver L" Uninstall");
      SetDlgItemTextW(hwnd, IDE_EXTRACT_PATH, path);

      ShowWindow(g_Progress_HWND, SW_HIDE);
      ShowWindow(g_InfoLine_HWND, SW_HIDE);

      break;

    case WM_COMMAND:
      switch (LOWORD(wParam))
      {
        case IDOK:
        {
          if (g_Finished)
          {
            OnClose();
            break;
          }
          if (!g_Install_was_Pressed)
          {
            SendMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(hwnd, IDCANCEL), TRUE);
            
            EnableWindow(g_Path_HWND, FALSE);
            EnableWindow(GetDlgItem(hwnd, IDOK), FALSE);
            
            g_Install_was_Pressed = True;
            return TRUE;
          }
          break;
        }
        
        case IDCANCEL:
        {
          OnClose();
          break;
        }

        default: return FALSE;
      }
      break;
    
    case WM_CLOSE:
      OnClose();
      break;
    /*
    case WM_DESTROY:
      PostQuitMessage(0);
      return TRUE;
    */
    default:
      return FALSE;
  }
  
  return TRUE;
}


int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    #ifdef UNDER_CE
      LPWSTR
    #else
      LPSTR
    #endif
    lpCmdLine, int nCmdShow)
{
  const wchar_t *cmdParams;
  Bool useTemp = True;

  UNUSED_VAR(hPrevInstance)
  UNUSED_VAR(lpCmdLine)
  UNUSED_VAR(nCmdShow)

  #ifndef UNDER_CE
  CoInitialize(NULL);
  #endif

  #ifndef UNDER_CE
  func_RegDeleteKeyExW = (Func_RegDeleteKeyExW)
      GetProcAddress(GetModuleHandleW(L"advapi32.dll"), "RegDeleteKeyExW");
  #endif

  {
    const wchar_t *s = GetCommandLineW();
    
    #ifndef UNDER_CE
    s = GetCmdParam(s);
    #endif

    cmdParams = s;

    for (;;)
    {
      {
        wchar_t c = *s;
        if (c == 0)
          break;
        if (c == ' ')
        {
          s++;
          continue;
        }
      }

      {
        const wchar_t *s2 = GetCmdParam(s);
        if (s[0] == '/')
        {
          if (s[1] == 'S' && IS_LIMIT_CHAR(s[2]))
            g_SilentMode = True;
          else if (s[1] == 'N' && IS_LIMIT_CHAR(s[2]))
            useTemp = False;
          else if (s[1] == 'D' && s[2] == '=')
          {
            size_t num;
            s += 3;
            num = s2 - s;
            if (num <= MAX_PATH)
            {
              wcsncpy(workDir, s, num);
              workDir[num] = 0;
              RemoveQuotes(workDir);
              useTemp = False;
            }
          }
        }
        s = s2;
      }
    }
  }


  {
    wchar_t *name;
    DWORD len = GetModuleFileNameW(NULL, modulePath, MAX_PATH);
    if (len == 0 || len > MAX_PATH)
      return 1;

    name = NULL;
    wcscpy(modulePrefix, modulePath);

    {
      wchar_t *s = modulePrefix;
      for (;;)
      {
        wchar_t c = *s++;
        if (c == 0)
          break;
        if (c == WCHAR_PATH_SEPARATOR)
          name = s;
      }
    }
    
    if (!name)
      return 1;

    if (!AreStringsEqual_NoCase(name, kUninstallExe))
      useTemp = False;

    *name = 0; // keep only prefix for modulePrefix
  }


  if (useTemp)
  {
    DWORD winRes = GetTempPathW(MAX_PATH, path);

    // GetTempPath: the returned string ends with a backslash
    /*
      {
        WCHAR s[MAX_PATH + 1];
        wcscpy(s, path);
        GetLongPathNameW(s, path, MAX_PATH);
      }
    */

    if (winRes != 0 && winRes <= MAX_PATH + 1
        && !IsString1PrefixedByString2_NoCase(modulePrefix, path))
    {
      unsigned i;
      DWORD d;
    
      const size_t pathLen = wcslen(path);
      d = (GetTickCount() << 12) ^ (GetCurrentThreadId() << 14) ^ GetCurrentProcessId();
      
      for (i = 0; i < 100; i++, d += GetTickCount())
      {
        wcscpy(path + pathLen, L"7z");
        
        {
          wchar_t *s = path + wcslen(path);
          UInt32 value = d;
          unsigned k;
          for (k = 0; k < 8; k++)
          {
            unsigned t = value & 0xF;
            value >>= 4;
            s[7 - k] = (wchar_t)((t < 10) ? ('0' + t) : ('A' + (t - 10)));
          }
          s[k] = 0;
        }
        
        if (DoesFileOrDirExist())
          continue;
        if (CreateDirectoryW(path, NULL))
        {
          wcscat(path, WSTRING_PATH_SEPARATOR);
          wcscpy(tempPath, path);
          break;
        }
        if (GetLastError() != ERROR_ALREADY_EXISTS)
          break;
      }
      
      if (tempPath[0] != 0)
      {
        wcscpy(copyPath, tempPath);
        wcscat(copyPath, L"Uninst.exe"); // we need not "Uninstall.exe" here
        
        if (CopyFileW(modulePath, copyPath, TRUE))
        {
          RemoveFileAfterReboot2(copyPath);
          RemoveFileAfterReboot2(tempPath);
          
          {
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
            cmdLine[0] = 0;
            
            // maybe CreateProcess supports path with spaces even without quotes.
            AddPathParam(cmdLine, copyPath);
            wcscat(cmdLine, L" /N /D=");
            AddPathParam(cmdLine, modulePrefix);
            
            if (cmdParams[0] != 0 && wcslen(cmdParams) < MAX_PATH * 2 + 10)
              wcscat(cmdLine, cmdParams);
            
            memset(&si, 0, sizeof(si));
            si.cb = sizeof(si);
            
            if (CreateProcessW(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, tempPath, &si, &pi))
            {
              CloseHandle(pi.hThread);
              if (pi.hProcess)
              {
                CloseHandle(pi.hProcess);
                return 0;
              }
            }
          }
        }
      }
    }
  }

  wcscpy(path, modulePrefix);

  if (workDir[0] != 0)
  {
    wcscpy(path, workDir);
    NormalizePrefix(path);
  }

  /*
  if (path[0] == 0)
  {
    HKEY key = 0;
    Bool ok = False;
    LONG res = RegOpenKeyExW(HKEY_CURRENT_USER, k_Reg_Software_7zip, 0, KEY_READ | k_Reg_WOW_Flag, &key);
    if (res == ERROR_SUCCESS)
    {
      ok = MyRegistry_QueryString(key, k_Reg_Path32, path);
      // ok = MyRegistry_QueryString(key, k_Reg_Path, path);
      RegCloseKey(key);
    }
  }
  */


  if (g_SilentMode)
    return Install();

  {
    int retCode = 1;
    g_HWND = CreateDialog(
        hInstance,
        // GetModuleHandle(NULL),
        MAKEINTRESOURCE(IDD_INSTALL), NULL, MyDlgProc);
    if (!g_HWND)
      return 1;

    {
      HICON hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON));
      // SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
      SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
    }

    {
      BOOL bRet;
      MSG msg;
      
      while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
      {
        if (bRet == -1)
          return retCode;
        if (!g_HWND)
          return retCode;

        if (!IsDialogMessage(g_HWND, &msg))
        {
          TranslateMessage(&msg);
          DispatchMessage(&msg);
        }
        if (!g_HWND)
          return retCode;

        if (g_Install_was_Pressed && !g_Finished)
        {
          retCode = Install();
          g_Finished = True;
          if (retCode != 0)
            break;
          if (!g_HWND)
            break;
          {
            SetDlgItemTextW(g_HWND, IDOK, L"Close");
            EnableWindow(GetDlgItem(g_HWND, IDOK), TRUE);
            EnableWindow(GetDlgItem(g_HWND, IDCANCEL), FALSE);
            SendMessage(g_HWND, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(g_HWND, IDOK), TRUE);
          }
        }
      }

      if (g_HWND)
      {
        DestroyWindow(g_HWND);
        g_HWND = NULL;
      }
    }

    return retCode;
  }
}