added 'remove extra files' implementation
[swftools.git] / installer / installer.c
1 /* installer.c
2
3    Part of the swftools installer (Main program).
4    
5    Copyright (c) 2004 Matthias Kramm <kramm@quiss.org> 
6  
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
20
21 #include <windows.h>
22 #include <commctrl.h>
23 #include <commdlg.h>
24 #include <shlobj.h>
25 #include <prsht.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include "installer.h"
29 #ifndef DEINSTALL
30 #include "archive.h"
31 #endif
32 #include "utils.h"
33
34 #include "../config.h" //for swftools version
35
36 static int config_forAllUsers = 0;
37 static int config_createLinks = 0;
38 static int config_createStartmenu = 1;
39 static int config_createDesktop = 1;
40 static int config_deleteextra = 1;
41
42 static char path_startmenu[MAX_PATH] = "\0";
43 static char path_desktop[MAX_PATH] = "\0";
44 static char path_programfiles[MAX_PATH] = "\0";
45
46 static char pathBuf[MAX_PATH];
47 static int do_abort = 0;
48
49 static char* pdf2swf_path;
50
51 static char registry_path[1024];
52
53 static char*install_path = "c:\\swftools\\";
54 #define SOFTWARE_DOMAIN "quiss.org"
55 #define SOFTWARE_NAME "SWFTools"
56 #define INSTALLER_NAME "SWFTools Installer"
57
58 static HBITMAP logo = 0;
59
60 static HINSTANCE me;
61
62 #define USER_SETMESSAGE 0x7f01
63
64 #ifndef DEINSTALL
65 extern char*crndata;
66 extern int crndata_len;
67 extern int crn_decompressed_size;
68 extern char*license_text;
69
70 #include "background.c"
71 #endif
72
73 typedef struct _filelist
74 {
75     const char*filename;
76     struct _filelist*next;
77     char type;
78 } filelist_t;
79
80 static filelist_t* registerFile(filelist_t*next, const char*filename, char type)
81 {
82     filelist_t*file = malloc(sizeof(filelist_t));
83     file->filename = strdup(filename);
84     file->type = type;
85     file->next = next;
86     return file;
87 }
88
89 static filelist_t* readFileList(char*filename)
90 {
91     FILE*fi = fopen(filename, "rb");
92     if(!fi) {
93         return 0;
94     }
95     fseek(fi, 0, SEEK_END);
96     int len = ftell(fi);
97     fseek(fi, 0, SEEK_SET);
98     char*data = malloc(len);
99     fread(data, len, 1, fi);
100     fclose(fi);
101     int t=0;
102     char*line = data;
103     filelist_t*list = 0,*lpos=0;;
104     while(t<len) {
105         if(data[t]=='\r' || data[t]=='\n') {
106             data[t++] = 0;
107             if(strchr("DFI", line[0]) && line[1]==' ' && line[2]!=' ') {
108                 filelist_t*f = malloc(sizeof(filelist_t));
109                 f->type=line[0];
110                 f->filename=strdup(line+2);
111                 f->next = 0;
112                 if(!list) {
113                     list = lpos = f;
114                 } else {
115                     lpos->next = f;
116                     lpos = f;
117                 }
118             } else {
119                 // skip line- this usually only happens if somebody tampered
120                 // with the file
121             }
122             while(t<len && (data[t]=='\0' || data[t]=='\r' || data[t]=='\n'))
123                 t++;
124             line = &data[t];
125         } else {
126             t++;
127         }
128     }
129     return list;
130 }
131
132 static void writeFileList(filelist_t*file, const char*filename)
133 {
134     FILE*fi = fopen(filename, "wb");
135     fprintf(fi, "[%s installed files]\r\n", SOFTWARE_NAME);
136     if(!fi) {
137         char buf[1024];
138         sprintf(buf, "Couldn't write file %s", filename);
139         MessageBox(0, buf, INSTALLER_NAME, MB_OK|MB_ICONERROR);
140         do_abort=1;
141         exit(1);
142     }
143     while(file) {
144         fprintf(fi, "%c %s\r\n", file->type, file->filename);
145         file = file->next;
146     }
147     fclose(fi);
148 }
149
150 static filelist_t*installedFiles = 0;
151
152 static void addFile(const char*filename)
153 {
154     installedFiles = registerFile(installedFiles, filename, 'F');
155 }
156 static void addDir(const char*filename)
157 {
158     installedFiles = registerFile(installedFiles, filename, 'D');
159 }
160
161 static void handleTemplateFile(const char*filename)
162 {
163     FILE*fi = fopen(filename, "rb");
164     fseek(fi, 0, SEEK_END);
165     int len = ftell(fi);
166     fseek(fi, 0, SEEK_SET);
167     char*file = malloc(len);
168     fread(file, len, 1, fi);
169     fclose(fi);
170     int l = strlen(install_path);
171     fi = fopen(filename, "wb");
172     char*pos = file;
173     char*lastpos = file;
174     while(1) {
175         pos = strstr(pos, "%%PATH%%");
176         if(!pos) {
177             pos = &file[len];
178             break;
179         }
180         if(pos!=lastpos)
181             fwrite(lastpos, pos-lastpos, 1, fi);
182         fwrite(install_path, l, 1, fi);
183         pos+=8; // length of "%%PATH%%"
184         lastpos = pos;
185     }
186     fwrite(lastpos, pos-lastpos, 1, fi);
187     fclose(fi);
188     free(file);
189 }
190
191 static int setRegistryEntry(char*key,char*value)
192 {
193     HKEY hkey1;
194     HKEY hkey2;
195     int ret1 = -1, ret2= -1;
196     ret1 = RegCreateKey(HKEY_CURRENT_USER, key, &hkey1);
197     if(config_forAllUsers) {
198         ret2 = RegCreateKey(HKEY_LOCAL_MACHINE, key, &hkey2);
199     }
200
201     if(ret1 && ret2) {
202         fprintf(stderr, "registry: CreateKey %s failed\n", key);
203         return 0;
204     }
205     if(ret1) {
206         installedFiles = registerFile(installedFiles, key, 'k');
207     }
208     if(ret2) {
209         installedFiles = registerFile(installedFiles, key, 'K');
210     }
211
212     if(!ret1)
213         ret1 = RegSetValue(hkey1, NULL, REG_SZ, value, strlen(value)+1);
214     if(!ret2)
215         ret2 = RegSetValue(hkey2, NULL, REG_SZ, value, strlen(value)+1);
216     if(ret1 && ret2) {
217         fprintf(stderr, "registry: SetValue %s failed\n", key);
218         return 0;
219     }
220     return 1;
221 }
222
223
224 static char* getRegistryEntry(char*path)
225 {
226     int res = 0;
227     HKEY key;
228     long rc;
229     long size = 0;
230     DWORD type;
231     char*buf;
232     rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, path, 0, KEY_ALL_ACCESS/* KEY_READ*/, &key);
233     if (rc != ERROR_SUCCESS) {
234         fprintf(stderr, "RegOpenKeyEx failed\n");
235         return 0;
236     }
237     rc = RegQueryValueEx(key, NULL, 0, 0, 0, (LPDWORD)&size) ;
238     if(rc != ERROR_SUCCESS) {
239         fprintf(stderr, "RegQueryValueEx(1) failed: %d\n", rc);
240         return 0;
241     }
242     buf = (char*)malloc(size+1);
243     rc = RegQueryValueEx(key, NULL, 0, &type, (BYTE*)buf, (LPDWORD)&size);
244     if(rc != ERROR_SUCCESS) {
245         fprintf(stderr, "RegQueryValueEx(2) failed: %d\n", rc);
246         return 0;
247     }
248     if(type == REG_SZ || type == REG_EXPAND_SZ) {
249         while(size && buf[size-1] == '\0')
250           --size;
251         buf[size] = 0;
252         /* TODO: convert */
253         return buf;
254     } else if(type == REG_BINARY) {
255         return buf;
256     }
257 }
258
259 void processMessages()
260 {
261     MSG msg;
262     while(PeekMessage(&msg,NULL,0,0,0))
263     {
264         GetMessage(&msg, NULL, 0, 0);
265         TranslateMessage(&msg);
266         DispatchMessage(&msg);
267     }
268 }
269
270 int addRegistryEntries(char*install_dir)
271 {
272     int ret;
273     ret = setRegistryEntry(registry_path, install_dir);
274     if(!ret) return 0;
275     return 1;
276 }
277
278 int CreateShortcut(char*path, char*description, char*filename, char*arguments, int iconindex, char*iconpath, char*workdir)
279 {
280     printf("Creating %s -> %s\n", filename, path);
281     WCHAR wszFilename[MAX_PATH];
282     IShellLink *ps1 = NULL;
283     IPersistFile *pPf = NULL;
284     HRESULT hr;
285     hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLink, (void*)&ps1);
286     if(FAILED(hr)) return 0;
287     hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile, (void **)&pPf);
288     if(FAILED(hr)) return 0;
289     hr = ps1->lpVtbl->SetPath(ps1, path);
290     if(FAILED(hr)) return 0;
291     hr = ps1->lpVtbl->SetDescription(ps1, description);
292     
293     if (arguments) {
294         hr = ps1->lpVtbl->SetArguments(ps1, arguments);
295         if(FAILED(hr)) return 0;
296     }
297     if (iconpath) {
298         hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex);
299         if (FAILED(hr)) return 0;
300     }
301     if (workdir) {
302         hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir);
303         if (FAILED(hr)) return 0;
304     }
305     MultiByteToWideChar(CP_ACP, 0, filename, -1, wszFilename, MAX_PATH);
306     hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE);
307     if(FAILED(hr)) {
308         return 0;
309     }
310     pPf->lpVtbl->Release(pPf);
311     ps1->lpVtbl->Release(ps1);
312     addFile(filename);
313     return 1;
314 }
315
316 static int CreateURL(const char*url, const char*path)
317 {
318     FILE*fi = fopen(path, "wb");
319     if(!fi)
320         return 0;
321     fprintf(fi, "[InternetShortcut]\r\n");
322     fprintf(fi, "URL=http://localhost:8081/\r\n");
323     fclose(fi);
324     addFile(path);
325     return 1;
326 }
327
328
329 BOOL CALLBACK PropertySheetFuncCommon(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam, int buttons)
330 {
331     LPNMHDR lpnm;
332         
333     HWND dialog = GetParent(hwnd);
334
335     if(message == WM_INITDIALOG) {
336         if(logo)
337             SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)logo);
338
339         RECT rc;
340         GetWindowRect(dialog, &rc);
341         int width = rc.right - rc.left;
342         int height = rc.bottom - rc.top;
343         MoveWindow(dialog, (GetSystemMetrics(SM_CXSCREEN) - width)/2, (GetSystemMetrics(SM_CYSCREEN) - height)/2, width, height, FALSE);
344         return FALSE;
345      }
346
347     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_SETACTIVE)) {
348         PropSheet_SetWizButtons(dialog, buttons);
349         return FALSE;
350     }
351     return FALSE;
352 }
353
354 #ifndef DEINSTALL
355 BOOL CALLBACK PropertySheetFunc1(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
356     if(message == WM_INITDIALOG) {
357         SetDlgItemText(hwnd, IDC_LICENSE, license_text);
358     }
359     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_NEXT);
360 }
361 BOOL CALLBACK PropertySheetFunc2(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
362     if(message == WM_INITDIALOG) {
363         SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path);
364
365         config_forAllUsers = 0;
366         SendDlgItemMessage(hwnd, IDC_ALLUSERS, BM_SETCHECK, config_forAllUsers, 0);
367         SendDlgItemMessage(hwnd, IDC_CURRENTUSER, BM_SETCHECK, config_forAllUsers^1, 0);
368     }
369     if(message == WM_COMMAND) {
370         if((wParam&0xffff) == IDC_BROWSE) {
371             BROWSEINFOA browse;
372             memset(&browse, 0, sizeof(browse));
373             browse.ulFlags = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_USENEWUI;// | BIF_RETURNONLYFSDIRS; //BIF_VALIDATE
374             browse.pszDisplayName = (CHAR*)malloc(MAX_PATH);
375             memset(browse.pszDisplayName, 0, MAX_PATH);
376             browse.lpszTitle = "Select installation directory";
377             browse.pidlRoot = SHBrowseForFolder(&browse);
378             if(browse.pszDisplayName) {
379                 if(SHGetPathFromIDList(browse.pidlRoot, browse.pszDisplayName)) {
380                     install_path = browse.pszDisplayName;
381                     int l = strlen(install_path);
382                     while(l && install_path[l-1]=='\\') {
383                         install_path[--l]=0;
384                     }   
385                 }
386             }
387             SendDlgItemMessage(hwnd, IDC_INSTALL_PATH, WM_SETTEXT, 0, (LPARAM)install_path);
388             return 0;
389
390         }
391         else if((wParam&0xffff) == IDC_ALLUSERS) {
392             config_forAllUsers = 1;
393             SendDlgItemMessage(hwnd, IDC_ALLUSERS, BM_SETCHECK, config_forAllUsers, 0);
394             SendDlgItemMessage(hwnd, IDC_CURRENTUSER, BM_SETCHECK, config_forAllUsers^1, 0);
395         }
396         else if((wParam&0xffff) == IDC_CURRENTUSER) {
397             config_forAllUsers = 0;
398             SendDlgItemMessage(hwnd, IDC_ALLUSERS, BM_SETCHECK, config_forAllUsers, 0);
399             SendDlgItemMessage(hwnd, IDC_CURRENTUSER, BM_SETCHECK, config_forAllUsers^1, 0);
400         }
401         else if((wParam&0xffff) == IDC_INSTALL_PATH) {
402             SendDlgItemMessage(hwnd, IDC_INSTALL_PATH, WM_GETTEXT, sizeof(pathBuf), (LPARAM)&(pathBuf[0]));
403             if(pathBuf[0]) {
404                 install_path = pathBuf;
405                 int l = strlen(install_path);
406                 while(l && install_path[l-1]=='\\') {
407                     install_path[--l]=0;
408                 }   
409             }
410             return 0;
411         }
412     }
413     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_BACK|PSWIZB_NEXT);
414 }
415 HWND statuswnd;
416 static int progress_pos = 0;
417
418 void PropertyArchiveError(char*text)
419 {
420     while(1) {
421         int ret = MessageBox(0, text, "Error", MB_RETRYCANCEL|MB_ICONERROR);
422         if(ret==IDRETRY) continue;
423         else break;
424     }
425 }
426
427 void PropertyArchive_NewFile(char*filename)
428 {
429     addFile(filename);
430     processMessages();
431 }
432 void PropertyArchive_NewDirectory(char*filename)
433 {
434     addDir(filename);
435     processMessages();
436 }
437
438 static int lastlen = 0;
439 void PropertyArchiveStatus(int pos, int len)
440 {
441     if(len!=lastlen) {
442         SendDlgItemMessage(statuswnd, IDC_PROGRESS, PBM_SETRANGE, 0, (LPARAM)MAKELONG(0,len));
443         lastlen = len;
444     }
445     SendDlgItemMessage(statuswnd, IDC_PROGRESS, PBM_SETPOS, pos, 0);
446     processMessages();
447     Sleep(30);
448 }
449 void PropertyArchiveMessage(char*text)
450 {
451     if(text && text[0]=='[') {
452         return;
453     }
454     SetDlgItemText(statuswnd, IDC_INFO, strdup(text));
455     processMessages();
456 }
457
458 void print_space(char*dest, char*msg, ULONGLONG size)
459 {
460     if(size < 1024)
461         sprintf(dest, "%s%d Bytes", msg, size);
462     else if(size < 1048576l)
463         sprintf(dest, "%s%.2f Kb", msg, size/1024.0);
464     else if(size < 1073741824l)
465         sprintf(dest, "%s%.2f Mb", msg, size/1048576.0);
466     else if(size < 1099511627776ll)
467         sprintf(dest, "%s%.2f Gb", msg, size/1073741824.0);
468     else
469         sprintf(dest, "%s%.2f Tb", msg, size/1125899906842624.0);
470 }
471
472 BOOL CALLBACK PropertySheetFunc3(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
473     HWND dialog = GetParent(hwnd);
474     if(message == WM_INITDIALOG) {
475         SetDlgItemText(hwnd, IDC_INFO, "Ready to install");
476
477         char buf[256];
478         print_space(buf, "Space required: ", crn_decompressed_size);
479         SetDlgItemText(hwnd, IDC_SPACE1, buf);
480         ULARGE_INTEGER available,total,totalfree;
481         available.QuadPart=0;
482         total.QuadPart=0;
483         totalfree.QuadPart=0;
484         if(GetDiskFreeSpaceEx(install_path, &available, &total, &totalfree)) {
485             print_space(buf, "Space available: ", available.QuadPart);
486         } else {
487             sprintf(buf, "Space available: [Error %d]", GetLastError());
488             if(GetLastError() == ERROR_FILE_NOT_FOUND && install_path[0] && install_path[1]==':') {
489                 /* installation directory does not yet exist */
490                 char path[3]={'c',':',0};
491                 path[0] = install_path[0];
492                 if(GetDiskFreeSpaceEx(path, &available, &total, &totalfree)) {
493                     print_space(buf, "Space available: ", available.QuadPart);
494                 }
495             } 
496         }
497         SetDlgItemText(hwnd, IDC_SPACE2, buf);
498     }
499     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZNEXT)) {
500         SetDlgItemText(hwnd, IDC_SPACE1, "");
501         SetDlgItemText(hwnd, IDC_SPACE2, "");
502         PropSheet_SetWizButtons(dialog, 0);
503         SendMessage(dialog, PSM_CANCELTOCLOSE, 0, 0); //makes wine display a warning
504         SetDlgItemText(hwnd, IDC_TITLE, "Installing files...");
505         statuswnd = hwnd;
506         status_t status;
507         status.status = PropertyArchiveStatus;
508         status.message = PropertyArchiveMessage;
509         status.error = PropertyArchiveError;
510         status.new_file = PropertyArchive_NewFile;
511         status.new_directory = PropertyArchive_NewDirectory;
512         int success = unpack_archive(crndata, crndata_len, install_path, &status);
513         memset(&status, 0, sizeof(status_t));
514         if(!success) {
515             MessageBox(0, "Couldn't extract all installation files", INSTALLER_NAME, MB_OK|MB_ICONERROR);
516             do_abort=1;
517             exit(1);
518         }
519         return 0;
520     }
521     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_BACK|PSWIZB_NEXT);
522 }
523
524 static HRESULT (WINAPI *f_SHGetSpecialFolderPath)(HWND hwnd, LPTSTR lpszPath, int nFolder, BOOL fCreate);
525
526 BOOL CALLBACK PropertySheetFunc4(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
527     if(message == WM_INITDIALOG) {
528         pdf2swf_path = concatPaths(install_path, "pdf2swf_gui.exe");
529         FILE*fi = fopen(pdf2swf_path, "rb");
530         if(fi) {
531             printf("a GUI program exists, creating desktop/startmenu links\n");
532             config_createLinks = 1;
533             fclose(fi);
534         }
535         if(!config_createLinks) {
536             SendDlgItemMessage(hwnd, IDC_STARTMENU, SW_HIDE, 0, 0);
537             SendDlgItemMessage(hwnd, IDC_DESKTOP, SW_HIDE, 0, 0);
538         }
539
540         SendDlgItemMessage(hwnd, IDC_STARTMENU, BM_SETCHECK, config_createStartmenu, 0);
541         SendDlgItemMessage(hwnd, IDC_DESKTOP, BM_SETCHECK, config_createDesktop, 0);
542     }
543     if(message == WM_COMMAND) {
544         if((wParam&0xffff) == IDC_STARTMENU) {
545             config_createStartmenu = SendDlgItemMessage(hwnd, IDC_STARTMENU, BM_GETCHECK, 0, 0);
546             config_createStartmenu^=1;
547             SendDlgItemMessage(hwnd, IDC_STARTMENU, BM_SETCHECK, config_createStartmenu, 0);
548             return 0;
549         }
550         if((wParam&0xffff) == IDC_DESKTOP) {
551             config_createDesktop = SendDlgItemMessage(hwnd, IDC_DESKTOP, BM_GETCHECK, 0, 0);
552             config_createDesktop^=1;
553             SendDlgItemMessage(hwnd, IDC_DESKTOP, BM_SETCHECK, config_createDesktop, 0);
554             return 0;
555         }
556     }
557
558     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZFINISH)) {
559         if(!addRegistryEntries(install_path)) {
560             MessageBox(0, "Couldn't create Registry Entries", INSTALLER_NAME, MB_OK|MB_ICONERROR);
561             return 1;
562         }
563
564         char mypath[MAX_PATH];
565         path_startmenu[0] = 0;
566         path_desktop[0] = 0;
567         if(config_forAllUsers) {
568             f_SHGetSpecialFolderPath(NULL, path_desktop, CSIDL_COMMON_DESKTOPDIRECTORY, 0);
569             f_SHGetSpecialFolderPath(NULL, path_startmenu, CSIDL_COMMON_PROGRAMS, 0);
570         }
571         /* get local program/desktop directory- this is both for forAllUsers=0 as well
572            as a fallback if the above didn't return any paths */
573         if(!path_startmenu[0]) {
574             f_SHGetSpecialFolderPath(NULL, path_startmenu, CSIDL_PROGRAMS, 0);
575         }
576         if(!path_desktop[0]) {
577             f_SHGetSpecialFolderPath(NULL, path_desktop, CSIDL_DESKTOPDIRECTORY, 0);
578         }
579         
580         char*uninstall_path = concatPaths(install_path, "uninstall.exe");
581
582         if(config_createLinks) {
583             if(config_createDesktop && path_desktop[0]) {
584                 char* linkName = concatPaths(path_desktop, "pdf2swf.lnk");
585                 printf("Creating desktop link %s -> %s\n", linkName, pdf2swf_path);
586                 if(!CreateShortcut(pdf2swf_path, "pdf2swf", linkName, 0, 0, 0, install_path)) {
587                     MessageBox(0, "Couldn't create desktop shortcut", INSTALLER_NAME, MB_OK);
588                     return 1;
589                 }
590             }
591             if(config_createStartmenu && path_startmenu[0]) {
592                 char* group = concatPaths(path_startmenu, "pdf2swf");
593                 CreateDirectory(group, 0);
594                 char* linkName = concatPaths(group, "pdf2swf.lnk");
595                 if(!CreateShortcut(pdf2swf_path, "pdf2swf", concatPaths(group, "pdf2swf.lnk"), 0, 0, 0, install_path) ||
596                    !CreateShortcut(uninstall_path, "uninstall", concatPaths(group, "uninstall.lnk"), 0, 0, 0, install_path)) {
597                     MessageBox(0, "Couldn't create start menu entry", INSTALLER_NAME, MB_OK);
598                     return 1;
599                 }
600             }
601         } else {
602             printf("not creating desktop/startmenu links\n");
603         }
604
605         char*uninstall_ini = concatPaths(install_path, "uninstall.ini");
606         addFile(uninstall_ini);
607         writeFileList(installedFiles, uninstall_ini);
608     }
609     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_FINISH);
610 }
611 #endif
612
613 #ifdef DEINSTALL
614
615 void findfiles(char*path, int*pos, char*data, int len, char del)
616 {
617     WIN32_FIND_DATA findFileData;
618     HANDLE hFind = FindFirstFile(concatPaths(path, "*"), &findFileData);
619     if(hFind == INVALID_HANDLE_VALUE)
620         return;
621     do {
622         if(findFileData.cFileName[0] == '.' &&
623            (findFileData.cFileName[0] == '.' || findFileData.cFileName == '\0'))
624             continue;
625         char*f = concatPaths(path, findFileData.cFileName);
626         if(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
627             findfiles(f, pos, data, len, del);
628             if(del) {
629                 RemoveDirectory(f);
630             }
631         } else {
632             int l = strlen(f);
633
634             /* don't list the uninstaller as file- it's going to be removed *after*
635                everything else is done */
636             char*uninstaller="uninstall.exe";
637             int ll = strlen(uninstaller);
638             if(l>=ll) {
639                 if(!strcasecmp(&f[l-ll],uninstaller)) {
640                     continue;
641                 }
642             }
643
644             if(data) {
645                 if(*pos+l <= len) {
646                     memcpy(&data[*pos], f, l);(*pos)+=l;
647                     data[(*pos)++] = '\r';
648                     data[(*pos)++] = '\n';
649                     data[(*pos)] = 0;
650                 }
651             } else {
652                 (*pos) += l+2;
653             }
654             if(del) {
655                 DeleteFile(f);
656             }
657         }
658     } while(FindNextFile(hFind, &findFileData));
659     FindClose(hFind);
660 }
661
662 static char*extrafiles = 0;
663
664 BOOL CALLBACK PropertySheetFunc5(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
665     HWND dialog = GetParent(hwnd);
666     if(message == WM_INITDIALOG) {
667         SetDlgItemText(hwnd, IDC_INFO, "Ready to deinstall");
668     }
669     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZNEXT)) {
670
671         filelist_t* list = readFileList("uninstall.ini");
672         if(!list) {
673             list = readFileList(concatPaths(install_path, "uninstall.ini"));
674             if(!list) {
675                 //Don't abort. If there's still something there, it'll be catched by the "extra files"
676                 //functionality later
677                 //MessageBox(0, "Couldn't determine installed files list- did you run uninstall twice?", INSTALLER_NAME, MB_OK);
678                 //exit(-1);
679             }
680         }
681         filelist_t* l = list;
682         int num = 0;
683         while(l) {num++;l=l->next;}
684
685         PropSheet_SetWizButtons(dialog, 0);
686         SendMessage(dialog, PSM_CANCELTOCLOSE, 0, 0);
687         SetDlgItemText(hwnd, IDC_TITLE, "Uninstalling files...");
688         SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, (LPARAM)MAKELONG(0,num));
689         num = 0;
690         l = list;
691         while(l) {
692             SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, num, 0);
693             if(l->type=='F')
694                 DeleteFile(l->filename);
695             else if(l->type=='D')
696                 RemoveDirectory(l->filename);
697             else if(l->type=='I') 
698                 /* skip- we will remove ourselves later */;
699             num++;l = l->next;
700         }
701
702         int len = 0;
703         findfiles(install_path, &len, 0, 0, 0);
704         if(len) {
705             extrafiles = malloc(len);
706             int pos = 0;
707             findfiles(install_path, &pos, extrafiles, len, 0);
708         } else {
709             PropSheet_RemovePage(dialog, 1, 0);
710         }
711         return 0;
712     }
713     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_BACK|PSWIZB_NEXT);
714 }
715
716 BOOL CALLBACK PropertySheetFunc6(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
717     if(message == WM_INITDIALOG) {
718         SendDlgItemMessage(hwnd, IDC_DELETEEXTRA, BM_SETCHECK, config_deleteextra, 0);
719         if(extrafiles) {
720             SetDlgItemText(hwnd, IDC_FILELIST, extrafiles);
721         }
722     }
723     if(message == WM_COMMAND) {
724         if((wParam&0xffff) == IDC_DELETEEXTRA) {
725             config_deleteextra = SendDlgItemMessage(hwnd, IDC_DELETEEXTRA, BM_GETCHECK, 0, 0);
726             config_deleteextra ^=1;
727             SendDlgItemMessage(hwnd, IDC_DELETEEXTRA, BM_SETCHECK, config_deleteextra, 0);
728             return 0;
729         }
730     }
731     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZNEXT)) {
732         if(config_deleteextra) {
733             int pos = 0;
734             findfiles(install_path, &pos, 0, 0, 1);
735         }
736     }
737     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_NEXT);
738 }
739
740 BOOL CALLBACK PropertySheetFunc7(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
741     if(message == WM_INITDIALOG) {
742         // ...
743     }
744     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_FINISH);
745 }
746 #endif
747
748 #ifndef PSP_HIDEHEADER
749 #define PSP_HIDEHEADER  2048
750 #endif
751
752 typedef struct _wizardpage {
753     DLGPROC function;
754     int resource;
755 } wizardpage_t;
756
757 void runPropertySheet(HWND parent)
758 {
759     PROPSHEETHEADER sheet;
760
761     wizardpage_t wpage[5] = {
762 #ifndef DEINSTALL
763         {PropertySheetFunc1, IDD_LICENSE},
764         {PropertySheetFunc2, IDD_INSTALLDIR},
765         {PropertySheetFunc3, IDD_PROGRESS},
766         {PropertySheetFunc4, IDD_FINISH},
767 #else
768         {PropertySheetFunc5, IDD_SURE},
769         {PropertySheetFunc6, IDD_EXTRAFILES},
770         {PropertySheetFunc7, IDD_DEINSTALLED},
771 #endif
772     };
773     int num = sizeof(wpage)/sizeof(wpage[0]);
774     HPROPSHEETPAGE pages[num];
775     int t;
776     for(t=0;t<num;t++) {
777         PROPSHEETPAGE page;
778         memset(&page, 0, sizeof(PROPSHEETPAGE));
779         page.dwSize = sizeof(PROPSHEETPAGE);
780         page.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
781         page.hInstance = me;
782         page.pfnDlgProc = wpage[t].function;
783         page.pszTemplate = MAKEINTRESOURCE(wpage[t].resource);
784         pages[t] = CreatePropertySheetPage(&page);
785     }
786
787     memset(&sheet, 0, sizeof(PROPSHEETHEADER));
788     sheet.dwSize = sizeof(PROPSHEETHEADER);
789     sheet.hInstance = me;
790     sheet.hwndParent = parent;
791     sheet.phpage = pages;
792     sheet.dwFlags = PSH_WIZARD;
793     sheet.nPages = num;
794     PropertySheet(&sheet);
795 }
796
797 #ifdef DEINSTALL
798
799 static void remove_self()
800 {
801     char exename[MAX_PATH];
802     char batname[MAX_PATH];
803     FILE *fp;
804
805     GetModuleFileName(NULL, exename, sizeof(exename));
806     sprintf(batname, "%s.bat", exename);
807     fp = fopen(batname, "w");
808     fprintf(fp, ":Repeat\n");
809     fprintf(fp, "del \"%s\"\n", exename);
810     fprintf(fp, "if exist \"%s\" goto Repeat\n", exename);
811     fprintf(fp, "del \"%s\"\n", batname);
812     fclose(fp);
813
814     STARTUPINFO si;
815     PROCESS_INFORMATION pi;
816     memset(&si, 0, sizeof(si));
817     si.dwFlags = STARTF_USESHOWWINDOW;
818     si.wShowWindow = SW_HIDE;
819     si.cb = sizeof(si);
820     if (CreateProcess(NULL, batname, NULL, NULL, FALSE,
821                       CREATE_SUSPENDED | IDLE_PRIORITY_CLASS,
822                       NULL, "\\", &si, &pi)) {
823             SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE);
824             SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
825             SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
826             CloseHandle(pi.hProcess);
827             ResumeThread(pi.hThread);
828             CloseHandle(pi.hThread);
829     }
830
831 }
832
833 int WINAPI WinMain(HINSTANCE _me,HINSTANCE hPrevInst,LPSTR lpszArgs, int nWinMode)
834 {
835     me = _me;
836     sprintf(registry_path, "Software\\%s\\%s\\InstallPath", SOFTWARE_DOMAIN, SOFTWARE_NAME);
837
838     HWND background = 0;
839     logo = LoadBitmap(me, "LOGO");
840
841     install_path = getRegistryEntry(registry_path);
842     if(!install_path || !install_path[0]) {
843         MessageBox(0, "Couldn't find software installation directory- did you run the deinstallation twice?", INSTALLER_NAME, MB_OK);
844         return 1;
845     }
846
847     CoInitialize(0);
848     InitCommonControls();
849
850     runPropertySheet(background);
851
852     remove_self();
853     return 0;
854 }
855 #else
856 int WINAPI WinMain(HINSTANCE _me,HINSTANCE hPrevInst,LPSTR lpszArgs, int nWinMode)
857 {
858     me = _me;
859     WNDCLASSEX wcl_background;
860     wcl_background.hInstance    = me;
861     wcl_background.lpfnWndProc  = WindowFunc;
862     wcl_background.lpszClassName= INSTALLER_NAME;
863     wcl_background.style        = CS_HREDRAW | CS_VREDRAW;
864     wcl_background.hIcon        = LoadIcon(NULL, IDI_APPLICATION);
865     wcl_background.hIconSm      = LoadIcon(NULL, IDI_APPLICATION);
866     wcl_background.hCursor      = LoadCursor(NULL, IDC_ARROW);
867     wcl_background.lpszMenuName = NULL; //no menu
868     wcl_background.cbClsExtra   = 0;
869     wcl_background.cbWndExtra   = 0;
870     wcl_background.hbrBackground= CreateSolidBrush(RGB(0, 0, 128));
871     wcl_background.cbSize       = sizeof(WNDCLASSEX);
872
873     sprintf(registry_path, "Software\\%s\\%s\\InstallPath", SOFTWARE_DOMAIN, SOFTWARE_NAME);
874
875     HINSTANCE shell32 = LoadLibrary("shell32.dll");
876     if(!shell32) {
877         MessageBox(0, "Could not load shell32.dll", INSTALLER_NAME, MB_OK);
878         return 1;
879     }
880     f_SHGetSpecialFolderPath = (HRESULT (WINAPI*)(HWND,LPTSTR,int,BOOL))GetProcAddress(shell32, "SHGetSpecialFolderPathA");
881     if(!f_SHGetSpecialFolderPath) {
882         MessageBox(0, "Could not load shell32.dll", INSTALLER_NAME, MB_OK);
883         return 1;
884     }
885         
886     HRESULT coret = CoInitialize(NULL);
887     if(FAILED(coret)) {
888         MessageBox(0, "Could not initialize COM interface", INSTALLER_NAME, MB_OK);
889         return 1;
890     }
891
892     path_programfiles[0] = 0;
893     f_SHGetSpecialFolderPath(NULL, path_programfiles, CSIDL_PROGRAM_FILES, 0);
894
895     if(!RegisterClassEx(&wcl_background)) {
896         MessageBox(0, "Could not register window background class", INSTALLER_NAME, MB_OK);
897         return 1;
898     }
899
900     HWND background = CreateWindow(wcl_background.lpszClassName, INSTALLER_NAME,
901                          0, 0, 0, 
902                          GetSystemMetrics(SM_CXFULLSCREEN),
903                          GetSystemMetrics(SM_CYFULLSCREEN),
904                          NULL, NULL, me, 
905                          (void*)"background");
906     
907     if(!background) {
908         MessageBox(0, "Could not create installation background window", INSTALLER_NAME, MB_OK);
909         return 1;
910     }
911
912     ShowWindow(background, SW_SHOWMAXIMIZED);
913     SetForegroundWindow(background);
914     UpdateWindow(background);
915
916     logo = LoadBitmap(me, "LOGO");
917
918     install_path = getRegistryEntry(registry_path);
919     if(!install_path || !install_path[0]) {
920         if(path_programfiles[0]) {
921             install_path = concatPaths(path_programfiles, SOFTWARE_NAME);
922         } else {
923             install_path = concatPaths("c:\\", SOFTWARE_NAME);
924         }
925     }
926
927     InitCommonControls();
928
929     runPropertySheet(background);
930     return 0;
931 }
932 #endif