always elevate on Vista
[swftools.git] / installer / installer.c
1 /* installer.c
2
3    Part of the rfx installer (Main program).
4    
5    Copyright (c) 2004-2008 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 static int config_forAllUsers = 0;
35 static int config_createLinks = 0;
36 static int config_createStartmenu = 1;
37 static int config_createDesktop = 1;
38 static int config_deleteextra = 1;
39
40 static char path_startmenu[MAX_PATH] = "\0";
41 static char path_desktop[MAX_PATH] = "\0";
42 static char path_programfiles[MAX_PATH] = "\0";
43
44 static char pathBuf[MAX_PATH];
45 static int do_abort = 0;
46
47 static char* pdf2swf_path;
48
49 static char registry_path[1024];
50
51 static char elevated = 0;
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+1);
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+1);
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 static int has_full_access = 0;
260 static char hasFullAccess()
261 {
262     /* find out whether we can write keys in HKEY_LOCAL_MACHINE */
263     HKEY hKey;
264     int ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall", 0,
265                            KEY_CREATE_SUB_KEY, &hKey);
266     if(!ret) {
267         RegCloseKey(hKey);
268         return 1;
269     } else {
270         return 0;
271     }
272 }
273
274 void processMessages()
275 {
276     MSG msg;
277     while(PeekMessage(&msg,NULL,0,0,0))
278     {
279         GetMessage(&msg, NULL, 0, 0);
280         TranslateMessage(&msg);
281         DispatchMessage(&msg);
282     }
283 }
284
285 int addRegistryEntries(char*install_dir)
286 {
287     int ret;
288     ret = setRegistryEntry(registry_path, install_dir);
289     if(!ret) return 0;
290     return 1;
291 }
292
293 int CreateShortcut(char*path, char*description, char*filename, char*arguments, int iconindex, char*iconpath, char*workdir)
294 {
295     printf("Creating %s -> %s\n", filename, path);
296     WCHAR wszFilename[MAX_PATH];
297     IShellLink *ps1 = NULL;
298     IPersistFile *pPf = NULL;
299     HRESULT hr;
300     hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLink, (void*)&ps1);
301     if(FAILED(hr)) return 0;
302     hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile, (void **)&pPf);
303     if(FAILED(hr)) return 0;
304     hr = ps1->lpVtbl->SetPath(ps1, path);
305     if(FAILED(hr)) return 0;
306     hr = ps1->lpVtbl->SetDescription(ps1, description);
307     
308     if (arguments) {
309         hr = ps1->lpVtbl->SetArguments(ps1, arguments);
310         if(FAILED(hr)) return 0;
311     }
312     if (iconpath) {
313         hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex);
314         if (FAILED(hr)) return 0;
315     }
316     if (workdir) {
317         hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir);
318         if (FAILED(hr)) return 0;
319     }
320     MultiByteToWideChar(CP_ACP, 0, filename, -1, wszFilename, MAX_PATH);
321     hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE);
322     if(FAILED(hr)) {
323         return 0;
324     }
325     pPf->lpVtbl->Release(pPf);
326     ps1->lpVtbl->Release(ps1);
327     addFile(filename);
328     return 1;
329 }
330
331 static int CreateURL(const char*url, const char*path)
332 {
333     FILE*fi = fopen(path, "wb");
334     if(!fi)
335         return 0;
336     fprintf(fi, "[InternetShortcut]\r\n");
337     fprintf(fi, "URL=http://localhost:8081/\r\n");
338     fclose(fi);
339     addFile(path);
340     return 1;
341 }
342
343
344 BOOL CALLBACK PropertySheetFuncCommon(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam, int buttons)
345 {
346     LPNMHDR lpnm;
347         
348     HWND dialog = GetParent(hwnd);
349
350     if(message == WM_INITDIALOG) {
351         if(logo)
352             SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)logo);
353
354         RECT rc;
355         GetWindowRect(dialog, &rc);
356         int width = rc.right - rc.left;
357         int height = rc.bottom - rc.top;
358         MoveWindow(dialog, (GetSystemMetrics(SM_CXSCREEN) - width)/2, (GetSystemMetrics(SM_CYSCREEN) - height)/2, width, height, FALSE);
359         return FALSE;
360      }
361
362     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_SETACTIVE)) {
363         PropSheet_SetWizButtons(dialog, buttons);
364         return FALSE;
365     }
366     return FALSE;
367 }
368
369 #ifndef DEINSTALL
370 BOOL CALLBACK PropertySheetFunc1(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
371     if(message == WM_INITDIALOG) {
372         SetDlgItemText(hwnd, IDC_LICENSE, license_text);
373     }
374     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_NEXT);
375 }
376 BOOL CALLBACK PropertySheetFunc2(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
377     if(message == WM_INITDIALOG) {
378         SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path);
379
380         SendDlgItemMessage(hwnd, IDC_ALLUSERS, BM_SETCHECK, config_forAllUsers, 0);
381         SendDlgItemMessage(hwnd, IDC_CURRENTUSER, BM_SETCHECK, config_forAllUsers^1, 0);
382     }
383     if(message == WM_COMMAND) {
384         if((wParam&0xffff) == IDC_BROWSE) {
385             BROWSEINFOA browse;
386             memset(&browse, 0, sizeof(browse));
387             browse.ulFlags = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_USENEWUI;// | BIF_RETURNONLYFSDIRS; //BIF_VALIDATE
388             browse.pszDisplayName = (CHAR*)malloc(MAX_PATH);
389             memset(browse.pszDisplayName, 0, MAX_PATH);
390             browse.lpszTitle = "Select installation directory";
391             browse.pidlRoot = SHBrowseForFolder(&browse);
392             if(browse.pszDisplayName) {
393                 if(SHGetPathFromIDList(browse.pidlRoot, browse.pszDisplayName)) {
394                     install_path = browse.pszDisplayName;
395                     int l = strlen(install_path);
396                     while(l && install_path[l-1]=='\\') {
397                         install_path[--l]=0;
398                     }   
399                 }
400             }
401             SendDlgItemMessage(hwnd, IDC_INSTALL_PATH, WM_SETTEXT, 0, (LPARAM)install_path);
402             return 0;
403
404         }
405         else if((wParam&0xffff) == IDC_ALLUSERS) {
406             config_forAllUsers = 1;
407             SendDlgItemMessage(hwnd, IDC_ALLUSERS, BM_SETCHECK, config_forAllUsers, 0);
408             SendDlgItemMessage(hwnd, IDC_CURRENTUSER, BM_SETCHECK, config_forAllUsers^1, 0);
409         }
410         else if((wParam&0xffff) == IDC_CURRENTUSER) {
411             config_forAllUsers = 0;
412             SendDlgItemMessage(hwnd, IDC_ALLUSERS, BM_SETCHECK, config_forAllUsers, 0);
413             SendDlgItemMessage(hwnd, IDC_CURRENTUSER, BM_SETCHECK, config_forAllUsers^1, 0);
414         }
415         else if((wParam&0xffff) == IDC_INSTALL_PATH) {
416             SendDlgItemMessage(hwnd, IDC_INSTALL_PATH, WM_GETTEXT, sizeof(pathBuf), (LPARAM)&(pathBuf[0]));
417             if(pathBuf[0]) {
418                 install_path = pathBuf;
419                 int l = strlen(install_path);
420                 while(l && install_path[l-1]=='\\') {
421                     install_path[--l]=0;
422                 }   
423             }
424             return 0;
425         }
426     }
427     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_SETACTIVE)) {
428         if(!elevated && !has_full_access) {
429             OSVERSIONINFO winverinfo;
430             memset(&winverinfo, 0, sizeof(OSVERSIONINFO));
431             winverinfo.dwOSVersionInfoSize = sizeof(winverinfo);
432             if (GetVersionEx(&winverinfo) && winverinfo.dwMajorVersion >= 5) {
433                 /* we're on Vista, were asked to install for all users, but don't have
434                    priviledges to do so. Ask to spawn the process elevated. */
435                 char exename[MAX_PATH];
436                 GetModuleFileName(NULL, exename, sizeof(exename));
437                 if((int)ShellExecute(0, "runas", exename, "elevated", NULL, SW_SHOWNORMAL)>32) {
438                     /* that worked- the second process will do the work */
439                     exit(0);
440                 }
441             }
442         }
443     }
444     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_BACK|PSWIZB_NEXT);
445 }
446 HWND statuswnd;
447 static int progress_pos = 0;
448
449 void PropertyArchiveError(char*text)
450 {
451     while(1) {
452         int ret = MessageBox(0, text, "Error", MB_RETRYCANCEL|MB_ICONERROR);
453         if(ret==IDRETRY) continue;
454         else break;
455     }
456 }
457
458 void PropertyArchive_NewFile(char*filename)
459 {
460     addFile(filename);
461     processMessages();
462 }
463 void PropertyArchive_NewDirectory(char*filename)
464 {
465     addDir(filename);
466     processMessages();
467 }
468
469 static int lastlen = 0;
470 void PropertyArchiveStatus(int pos, int len)
471 {
472     if(len!=lastlen) {
473         SendDlgItemMessage(statuswnd, IDC_PROGRESS, PBM_SETRANGE, 0, (LPARAM)MAKELONG(0,len));
474         lastlen = len;
475     }
476     SendDlgItemMessage(statuswnd, IDC_PROGRESS, PBM_SETPOS, pos, 0);
477     processMessages();
478     Sleep(30);
479 }
480 void PropertyArchiveMessage(char*text)
481 {
482     if(text && text[0]=='[') {
483         return;
484     }
485     SetDlgItemText(statuswnd, IDC_INFO, strdup(text));
486     processMessages();
487 }
488
489 void print_space(char*dest, char*msg, ULONGLONG size)
490 {
491     if(size < 1024)
492         sprintf(dest, "%s%d Bytes", msg, size);
493     else if(size < 1048576l)
494         sprintf(dest, "%s%.2f Kb", msg, size/1024.0);
495     else if(size < 1073741824l)
496         sprintf(dest, "%s%.2f Mb", msg, size/1048576.0);
497     else if(size < 1099511627776ll)
498         sprintf(dest, "%s%.2f Gb", msg, size/1073741824.0);
499     else
500         sprintf(dest, "%s%.2f Tb", msg, size/1125899906842624.0);
501 }
502
503 BOOL CALLBACK PropertySheetFunc3(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
504     HWND dialog = GetParent(hwnd);
505     if(message == WM_INITDIALOG) {
506         SetDlgItemText(hwnd, IDC_INFO, "Ready to install");
507
508         char buf[256];
509         print_space(buf, "Space required: ", crn_decompressed_size);
510         SetDlgItemText(hwnd, IDC_SPACE1, buf);
511         ULARGE_INTEGER available,total,totalfree;
512         available.QuadPart=0;
513         total.QuadPart=0;
514         totalfree.QuadPart=0;
515         if(GetDiskFreeSpaceEx(install_path, &available, &total, &totalfree)) {
516             print_space(buf, "Space available: ", available.QuadPart);
517         } else {
518             sprintf(buf, "Space available: [Error %d]", GetLastError());
519             if((GetLastError() == ERROR_FILE_NOT_FOUND || GetLastError() == ERROR_PATH_NOT_FOUND)
520                 && install_path[0] && install_path[1]==':') {
521                 /* installation directory does not yet exist */
522                 char path[3]={'c',':',0};
523                 path[0] = install_path[0];
524                 if(GetDiskFreeSpaceEx(path, &available, &total, &totalfree)) {
525                     print_space(buf, "Space available: ", available.QuadPart);
526                 }
527             } 
528         }
529         SetDlgItemText(hwnd, IDC_SPACE2, buf);
530     }
531     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZNEXT)) {
532         SetDlgItemText(hwnd, IDC_SPACE1, "");
533         SetDlgItemText(hwnd, IDC_SPACE2, "");
534         PropSheet_SetWizButtons(dialog, 0);
535         SendMessage(dialog, PSM_CANCELTOCLOSE, 0, 0); //makes wine display a warning
536         SetDlgItemText(hwnd, IDC_TITLE, "Installing files...");
537         statuswnd = hwnd;
538         status_t status;
539         status.status = PropertyArchiveStatus;
540         status.message = PropertyArchiveMessage;
541         status.error = PropertyArchiveError;
542         status.new_file = PropertyArchive_NewFile;
543         status.new_directory = PropertyArchive_NewDirectory;
544         int success = unpack_archive(crndata, crndata_len, install_path, &status);
545         memset(&status, 0, sizeof(status_t));
546         if(!success) {
547             MessageBox(0, "Couldn't extract all installation files", INSTALLER_NAME, MB_OK|MB_ICONERROR);
548             do_abort=1;
549             exit(1);
550         }
551         return 0;
552     }
553     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_BACK|PSWIZB_NEXT);
554 }
555
556 static HRESULT (WINAPI *f_SHGetSpecialFolderPath)(HWND hwnd, LPTSTR lpszPath, int nFolder, BOOL fCreate);
557
558 BOOL CALLBACK PropertySheetFunc4(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
559     if(message == WM_INITDIALOG) {
560         pdf2swf_path = concatPaths(install_path, "pdf2swf_gui.exe");
561         FILE*fi = fopen(pdf2swf_path, "rb");
562         if(fi) {
563             printf("a GUI program exists, creating desktop/startmenu links\n");
564             config_createLinks = 1;
565             fclose(fi);
566         } else {
567             config_createLinks = 0;
568             config_createStartmenu = 0;
569             config_createDesktop = 0;
570         }
571         if(!config_createLinks) {
572             SendDlgItemMessage(hwnd, IDC_STARTMENU, BN_DISABLE, 0, 0);
573             SendDlgItemMessage(hwnd, IDC_DESKTOP, BN_DISABLE, 0, 0);
574         }
575
576         SendDlgItemMessage(hwnd, IDC_STARTMENU, BM_SETCHECK, config_createStartmenu, 0);
577         SendDlgItemMessage(hwnd, IDC_DESKTOP, BM_SETCHECK, config_createDesktop, 0);
578     }
579     if(message == WM_COMMAND) {
580         if((wParam&0xffff) == IDC_STARTMENU) {
581             config_createStartmenu = SendDlgItemMessage(hwnd, IDC_STARTMENU, BM_GETCHECK, 0, 0);
582             if(config_createLinks) {
583                 config_createStartmenu^=1;
584             }
585             SendDlgItemMessage(hwnd, IDC_STARTMENU, BM_SETCHECK, config_createStartmenu, 0);
586             return 0;
587         }
588         if((wParam&0xffff) == IDC_DESKTOP) {
589             config_createDesktop = SendDlgItemMessage(hwnd, IDC_DESKTOP, BM_GETCHECK, 0, 0);
590             if(config_createLinks) {
591                 config_createDesktop^=1;
592             }
593             SendDlgItemMessage(hwnd, IDC_DESKTOP, BM_SETCHECK, config_createDesktop, 0);
594             return 0;
595         }
596     }
597
598     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZFINISH)) {
599         if(!addRegistryEntries(install_path)) {
600             MessageBox(0, "Couldn't create Registry Entries", INSTALLER_NAME, MB_OK|MB_ICONERROR);
601             return 1;
602         }
603
604         char mypath[MAX_PATH];
605         path_startmenu[0] = 0;
606         path_desktop[0] = 0;
607         if(config_forAllUsers) {
608             f_SHGetSpecialFolderPath(NULL, path_desktop, CSIDL_COMMON_DESKTOPDIRECTORY, 0);
609             f_SHGetSpecialFolderPath(NULL, path_startmenu, CSIDL_COMMON_PROGRAMS, 0);
610         }
611         /* get local program/desktop directory- this is both for forAllUsers=0 as well
612            as a fallback if the above didn't return any paths */
613         if(!path_startmenu[0]) {
614             f_SHGetSpecialFolderPath(NULL, path_startmenu, CSIDL_PROGRAMS, 0);
615         }
616         if(!path_desktop[0]) {
617             f_SHGetSpecialFolderPath(NULL, path_desktop, CSIDL_DESKTOPDIRECTORY, 0);
618         }
619         
620         char*uninstall_path = concatPaths(install_path, "uninstall.exe");
621
622         if(config_createLinks) {
623             if(config_createDesktop && path_desktop[0]) {
624                 char* linkName = concatPaths(path_desktop, "pdf2swf.lnk");
625                 printf("Creating desktop link %s -> %s\n", linkName, pdf2swf_path);
626                 if(!CreateShortcut(pdf2swf_path, "pdf2swf", linkName, 0, 0, 0, install_path)) {
627                     MessageBox(0, "Couldn't create desktop shortcut", INSTALLER_NAME, MB_OK);
628                     return 1;
629                 }
630             }
631             if(config_createStartmenu && path_startmenu[0]) {
632                 char* group = concatPaths(path_startmenu, "pdf2swf");
633                 CreateDirectory(group, 0);
634                 addDir(group);
635                 char* linkName = concatPaths(group, "pdf2swf.lnk");
636                 if(!CreateShortcut(pdf2swf_path, "pdf2swf", concatPaths(group, "pdf2swf.lnk"), 0, 0, 0, install_path) ||
637                    !CreateShortcut(uninstall_path, "uninstall", concatPaths(group, "uninstall.lnk"), 0, 0, 0, install_path)) {
638                     MessageBox(0, "Couldn't create start menu entry", INSTALLER_NAME, MB_OK);
639                     return 1;
640                 }
641             }
642         } else {
643             printf("not creating desktop/startmenu links\n");
644         }
645
646         char*uninstall_ini = concatPaths(install_path, "uninstall.ini");
647         addFile(uninstall_ini);
648         writeFileList(installedFiles, uninstall_ini);
649     }
650     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_FINISH);
651 }
652 #endif
653
654 #ifdef DEINSTALL
655
656 void findfiles(char*path, int*pos, char*data, int len, char del)
657 {
658     WIN32_FIND_DATA findFileData;
659     HANDLE hFind = FindFirstFile(concatPaths(path, "*"), &findFileData);
660     if(hFind == INVALID_HANDLE_VALUE)
661         return;
662     do {
663         if(findFileData.cFileName[0] == '.' &&
664            (findFileData.cFileName[0] == '.' || findFileData.cFileName == '\0'))
665             continue;
666         char*f = concatPaths(path, findFileData.cFileName);
667         if(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
668             findfiles(f, pos, data, len, del);
669             /* always try to remove directories- if they are empty, this
670                will work, and they won't prevent superdirectory deletion later */
671             RemoveDirectory(f);
672         } else {
673             int l = strlen(f);
674
675             /* don't list the uninstaller as file- it's going to be removed *after*
676                everything else is done */
677             char*uninstaller="uninstall.exe";
678             int ll = strlen(uninstaller);
679             if(l>=ll) {
680                 if(!strcasecmp(&f[l-ll],uninstaller)) {
681                     continue;
682                 }
683             }
684
685             if(data) {
686                 if(*pos+l <= len) {
687                     memcpy(&data[*pos], f, l);(*pos)+=l;
688                     data[(*pos)++] = '\r';
689                     data[(*pos)++] = '\n';
690                     data[(*pos)] = 0;
691                 }
692             } else {
693                 (*pos) += l+2;
694             }
695             if(del) {
696                 DeleteFile(f);
697             }
698         }
699     } while(FindNextFile(hFind, &findFileData));
700     FindClose(hFind);
701 }
702
703 static char*extrafiles = 0;
704
705 BOOL CALLBACK PropertySheetFunc5(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
706     HWND dialog = GetParent(hwnd);
707     if(message == WM_INITDIALOG) {
708         SetDlgItemText(hwnd, IDC_INFO, "Ready to uninstall");
709     }
710     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZNEXT)) {
711
712         filelist_t* list = readFileList("uninstall.ini");
713         if(!list) {
714             list = readFileList(concatPaths(install_path, "uninstall.ini"));
715             if(!list) {
716                 //Don't abort. If there's still something there, it'll be catched by the "extra files"
717                 //functionality later
718                 //MessageBox(0, "Couldn't determine installed files list- did you run uninstall twice?", INSTALLER_NAME, MB_OK);
719                 //exit(-1);
720             }
721         }
722         filelist_t* l = list;
723         int num = 0;
724         while(l) {num++;l=l->next;}
725
726         PropSheet_SetWizButtons(dialog, 0);
727         SendMessage(dialog, PSM_CANCELTOCLOSE, 0, 0);
728         SetDlgItemText(hwnd, IDC_TITLE, "Uninstalling files...");
729         SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, (LPARAM)MAKELONG(0,num));
730         num = 0;
731         l = list;
732         while(l) {
733             SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, num, 0);
734             if(l->type=='F')
735                 DeleteFile(l->filename);
736             else if(l->type=='D')
737                 RemoveDirectory(l->filename);
738             else if(l->type=='I') 
739                 /* skip- we will remove ourselves later */;
740             num++;l = l->next;
741         }
742
743         int len = 0;
744         findfiles(install_path, &len, 0, 0, 0);
745         if(len) {
746             extrafiles = malloc(len);
747             int pos = 0;
748             findfiles(install_path, &pos, extrafiles, len, 0);
749         } else {
750             PropSheet_RemovePage(dialog, 1, 0);
751         }
752         return 0;
753     }
754     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_BACK|PSWIZB_NEXT);
755 }
756
757 BOOL CALLBACK PropertySheetFunc6(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
758     if(message == WM_INITDIALOG) {
759         SendDlgItemMessage(hwnd, IDC_DELETEEXTRA, BM_SETCHECK, config_deleteextra, 0);
760         if(extrafiles) {
761             SetDlgItemText(hwnd, IDC_FILELIST, extrafiles);
762         }
763     }
764     if(message == WM_COMMAND) {
765         if((wParam&0xffff) == IDC_DELETEEXTRA) {
766             config_deleteextra = SendDlgItemMessage(hwnd, IDC_DELETEEXTRA, BM_GETCHECK, 0, 0);
767             config_deleteextra ^=1;
768             SendDlgItemMessage(hwnd, IDC_DELETEEXTRA, BM_SETCHECK, config_deleteextra, 0);
769             return 0;
770         }
771     }
772     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZNEXT)) {
773         if(config_deleteextra) {
774             int pos = 0;
775             findfiles(install_path, &pos, 0, 0, 1);
776         }
777     }
778     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_NEXT);
779 }
780
781 BOOL CALLBACK PropertySheetFunc7(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
782     if(message == WM_INITDIALOG) {
783         // ...
784     }
785     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_FINISH);
786 }
787 #endif
788
789 #ifndef PSP_HIDEHEADER
790 #define PSP_HIDEHEADER  2048
791 #endif
792
793 typedef struct _wizardpage {
794     DLGPROC function;
795     int resource;
796 } wizardpage_t;
797
798 void runPropertySheet(HWND parent)
799 {
800     PROPSHEETHEADER sheet;
801
802     wizardpage_t wpage[5] = {
803 #ifndef DEINSTALL
804         {PropertySheetFunc1, IDD_LICENSE},
805         {PropertySheetFunc2, IDD_INSTALLDIR},
806         {PropertySheetFunc3, IDD_PROGRESS},
807         {PropertySheetFunc4, IDD_FINISH},
808 #else
809         {PropertySheetFunc5, IDD_SURE},
810         {PropertySheetFunc6, IDD_EXTRAFILES},
811         {PropertySheetFunc7, IDD_DEINSTALLED},
812 #endif
813     };
814
815     int num = sizeof(wpage)/sizeof(wpage[0]);
816
817 #ifndef DEINSTALL
818     if(elevated) {
819         /* remove license.
820            TODO: remove installdir querying, too (pass installdir
821                  to second process) */
822         int t;
823         for(t=1;t<num;t++) {
824             wpage[t-1] = wpage[t];
825         }
826         num --;
827     }
828 #endif
829
830     HPROPSHEETPAGE pages[num];
831     int t;
832     for(t=0;t<num;t++) {
833         PROPSHEETPAGE page;
834         memset(&page, 0, sizeof(PROPSHEETPAGE));
835         page.dwSize = sizeof(PROPSHEETPAGE);
836         page.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
837         page.hInstance = me;
838         page.pfnDlgProc = wpage[t].function;
839         page.pszTemplate = MAKEINTRESOURCE(wpage[t].resource);
840         pages[t] = CreatePropertySheetPage(&page);
841     }
842
843     memset(&sheet, 0, sizeof(PROPSHEETHEADER));
844     sheet.dwSize = sizeof(PROPSHEETHEADER);
845     sheet.hInstance = me;
846     sheet.hwndParent = parent;
847     sheet.phpage = pages;
848     sheet.dwFlags = PSH_WIZARD;
849     sheet.nPages = num;
850     PropertySheet(&sheet);
851 }
852
853 #ifdef DEINSTALL
854
855 static void remove_self()
856 {
857     char exename[MAX_PATH];
858     char batdir[MAX_PATH];
859     char batfile[MAX_PATH];
860     char*batname;
861     FILE *fp;
862
863     memset(batdir, 0, sizeof(batdir));
864
865     GetModuleFileName(NULL, exename, sizeof(exename));
866     GetTempPath(MAX_PATH, batdir);
867     sprintf(batfile, "%08x.bat", rand());
868
869     batname = concatPaths(batdir, batfile);
870
871     fp = fopen(batname, "w");
872     if(!fp) {
873         return;
874     } 
875
876     fprintf(fp, ":Repeat\n");
877     fprintf(fp, "del \"%s\"\n", exename);
878     fprintf(fp, "if exist \"%s\" goto Repeat\n", exename);
879     fprintf(fp, "rmdir \"%s\"\n", install_path);
880     fprintf(fp, "del \"%s\"\n", batname);
881     fclose(fp);
882
883     STARTUPINFO si;
884     PROCESS_INFORMATION pi;
885     memset(&si, 0, sizeof(si));
886     si.dwFlags = STARTF_USESHOWWINDOW;
887     si.wShowWindow = SW_HIDE;
888     si.cb = sizeof(si);
889     if (CreateProcess(NULL, batname, NULL, NULL, FALSE,
890                       CREATE_SUSPENDED | IDLE_PRIORITY_CLASS,
891                       NULL, "\\", &si, &pi)) {
892             SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE);
893             SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
894             SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
895             CloseHandle(pi.hProcess);
896             ResumeThread(pi.hThread);
897             CloseHandle(pi.hThread);
898     }
899
900 }
901
902 int WINAPI WinMain(HINSTANCE _me,HINSTANCE hPrevInst,LPSTR lpszArgs, int nWinMode)
903 {
904     me = _me;
905     sprintf(registry_path, "Software\\%s\\%s\\InstallPath", SOFTWARE_DOMAIN, SOFTWARE_NAME);
906
907     HWND background = 0;
908     logo = LoadBitmap(me, "LOGO");
909
910     install_path = getRegistryEntry(registry_path);
911     if(!install_path || !install_path[0]) {
912         MessageBox(0, "Couldn't find software installation directory- did you run the uninstallation twice?", INSTALLER_NAME, MB_OK);
913         return 1;
914     }
915
916     CoInitialize(0);
917     InitCommonControls();
918
919     runPropertySheet(background);
920
921     remove_self();
922     return 0;
923 }
924 #else
925 int WINAPI WinMain(HINSTANCE _me,HINSTANCE hPrevInst,LPSTR lpszArgs, int nWinMode)
926 {
927     me = _me;
928     WNDCLASSEX wcl_background;
929     wcl_background.hInstance    = me;
930     wcl_background.lpfnWndProc  = WindowFunc;
931     wcl_background.lpszClassName= INSTALLER_NAME;
932     wcl_background.style        = CS_HREDRAW | CS_VREDRAW;
933     wcl_background.hIcon        = LoadIcon(NULL, IDI_APPLICATION);
934     wcl_background.hIconSm      = LoadIcon(NULL, IDI_APPLICATION);
935     wcl_background.hCursor      = LoadCursor(NULL, IDC_ARROW);
936     wcl_background.lpszMenuName = NULL; //no menu
937     wcl_background.cbClsExtra   = 0;
938     wcl_background.cbWndExtra   = 0;
939     wcl_background.hbrBackground= CreateSolidBrush(RGB(0, 0, 128));
940     wcl_background.cbSize       = sizeof(WNDCLASSEX);
941
942     sprintf(registry_path, "Software\\%s\\%s\\InstallPath", SOFTWARE_DOMAIN, SOFTWARE_NAME);
943
944     if(lpszArgs && strstr(lpszArgs, "elevated")) {
945         elevated = 1;
946     }
947     has_full_access = hasFullAccess();
948     config_forAllUsers = has_full_access;
949
950     HINSTANCE shell32 = LoadLibrary("shell32.dll");
951     if(!shell32) {
952         MessageBox(0, "Could not load shell32.dll", INSTALLER_NAME, MB_OK);
953         return 1;
954     }
955     f_SHGetSpecialFolderPath = (HRESULT (WINAPI*)(HWND,LPTSTR,int,BOOL))GetProcAddress(shell32, "SHGetSpecialFolderPathA");
956     if(!f_SHGetSpecialFolderPath) {
957         MessageBox(0, "Could not load shell32.dll", INSTALLER_NAME, MB_OK);
958         return 1;
959     }
960         
961     HRESULT coret = CoInitialize(NULL);
962     if(FAILED(coret)) {
963         MessageBox(0, "Could not initialize COM interface", INSTALLER_NAME, MB_OK);
964         return 1;
965     }
966
967     path_programfiles[0] = 0;
968     f_SHGetSpecialFolderPath(NULL, path_programfiles, CSIDL_PROGRAM_FILES, 0);
969
970     if(!RegisterClassEx(&wcl_background)) {
971         MessageBox(0, "Could not register window background class", INSTALLER_NAME, MB_OK);
972         return 1;
973     }
974
975     HWND background = CreateWindow(wcl_background.lpszClassName, INSTALLER_NAME,
976                          0, 0, 0, 
977                          GetSystemMetrics(SM_CXFULLSCREEN),
978                          GetSystemMetrics(SM_CYFULLSCREEN),
979                          NULL, NULL, me, 
980                          (void*)"background");
981     
982     if(!background) {
983         MessageBox(0, "Could not create installation background window", INSTALLER_NAME, MB_OK);
984         return 1;
985     }
986
987     ShowWindow(background, SW_SHOWMAXIMIZED);
988     SetForegroundWindow(background);
989     UpdateWindow(background);
990
991     logo = LoadBitmap(me, "LOGO");
992
993     install_path = getRegistryEntry(registry_path);
994     if(!install_path || !install_path[0]) {
995         if(path_programfiles[0]) {
996             install_path = concatPaths(path_programfiles, SOFTWARE_NAME);
997         } else {
998             install_path = concatPaths("c:\\", SOFTWARE_NAME);
999         }
1000     }
1001
1002     InitCommonControls();
1003
1004     runPropertySheet(background);
1005     return 0;
1006 }
1007 #endif