added Vista elevation code
[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 && config_forAllUsers) {
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         }
567         if(!config_createLinks) {
568             SendDlgItemMessage(hwnd, IDC_STARTMENU, SW_HIDE, 0, 0);
569             SendDlgItemMessage(hwnd, IDC_DESKTOP, SW_HIDE, 0, 0);
570         }
571
572         SendDlgItemMessage(hwnd, IDC_STARTMENU, BM_SETCHECK, config_createStartmenu, 0);
573         SendDlgItemMessage(hwnd, IDC_DESKTOP, BM_SETCHECK, config_createDesktop, 0);
574     }
575     if(message == WM_COMMAND) {
576         if((wParam&0xffff) == IDC_STARTMENU) {
577             config_createStartmenu = SendDlgItemMessage(hwnd, IDC_STARTMENU, BM_GETCHECK, 0, 0);
578             config_createStartmenu^=1;
579             SendDlgItemMessage(hwnd, IDC_STARTMENU, BM_SETCHECK, config_createStartmenu, 0);
580             return 0;
581         }
582         if((wParam&0xffff) == IDC_DESKTOP) {
583             config_createDesktop = SendDlgItemMessage(hwnd, IDC_DESKTOP, BM_GETCHECK, 0, 0);
584             config_createDesktop^=1;
585             SendDlgItemMessage(hwnd, IDC_DESKTOP, BM_SETCHECK, config_createDesktop, 0);
586             return 0;
587         }
588     }
589
590     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZFINISH)) {
591         if(!addRegistryEntries(install_path)) {
592             MessageBox(0, "Couldn't create Registry Entries", INSTALLER_NAME, MB_OK|MB_ICONERROR);
593             return 1;
594         }
595
596         char mypath[MAX_PATH];
597         path_startmenu[0] = 0;
598         path_desktop[0] = 0;
599         if(config_forAllUsers) {
600             f_SHGetSpecialFolderPath(NULL, path_desktop, CSIDL_COMMON_DESKTOPDIRECTORY, 0);
601             f_SHGetSpecialFolderPath(NULL, path_startmenu, CSIDL_COMMON_PROGRAMS, 0);
602         }
603         /* get local program/desktop directory- this is both for forAllUsers=0 as well
604            as a fallback if the above didn't return any paths */
605         if(!path_startmenu[0]) {
606             f_SHGetSpecialFolderPath(NULL, path_startmenu, CSIDL_PROGRAMS, 0);
607         }
608         if(!path_desktop[0]) {
609             f_SHGetSpecialFolderPath(NULL, path_desktop, CSIDL_DESKTOPDIRECTORY, 0);
610         }
611         
612         char*uninstall_path = concatPaths(install_path, "uninstall.exe");
613
614         if(config_createLinks) {
615             if(config_createDesktop && path_desktop[0]) {
616                 char* linkName = concatPaths(path_desktop, "pdf2swf.lnk");
617                 printf("Creating desktop link %s -> %s\n", linkName, pdf2swf_path);
618                 if(!CreateShortcut(pdf2swf_path, "pdf2swf", linkName, 0, 0, 0, install_path)) {
619                     MessageBox(0, "Couldn't create desktop shortcut", INSTALLER_NAME, MB_OK);
620                     return 1;
621                 }
622             }
623             if(config_createStartmenu && path_startmenu[0]) {
624                 char* group = concatPaths(path_startmenu, "pdf2swf");
625                 CreateDirectory(group, 0);
626                 addDir(group);
627                 char* linkName = concatPaths(group, "pdf2swf.lnk");
628                 if(!CreateShortcut(pdf2swf_path, "pdf2swf", concatPaths(group, "pdf2swf.lnk"), 0, 0, 0, install_path) ||
629                    !CreateShortcut(uninstall_path, "uninstall", concatPaths(group, "uninstall.lnk"), 0, 0, 0, install_path)) {
630                     MessageBox(0, "Couldn't create start menu entry", INSTALLER_NAME, MB_OK);
631                     return 1;
632                 }
633             }
634         } else {
635             printf("not creating desktop/startmenu links\n");
636         }
637
638         char*uninstall_ini = concatPaths(install_path, "uninstall.ini");
639         addFile(uninstall_ini);
640         writeFileList(installedFiles, uninstall_ini);
641     }
642     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_FINISH);
643 }
644 #endif
645
646 #ifdef DEINSTALL
647
648 void findfiles(char*path, int*pos, char*data, int len, char del)
649 {
650     WIN32_FIND_DATA findFileData;
651     HANDLE hFind = FindFirstFile(concatPaths(path, "*"), &findFileData);
652     if(hFind == INVALID_HANDLE_VALUE)
653         return;
654     do {
655         if(findFileData.cFileName[0] == '.' &&
656            (findFileData.cFileName[0] == '.' || findFileData.cFileName == '\0'))
657             continue;
658         char*f = concatPaths(path, findFileData.cFileName);
659         if(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
660             findfiles(f, pos, data, len, del);
661             /* always try to remove directories- if they are empty, this
662                will work, and they won't prevent superdirectory deletion later */
663             RemoveDirectory(f);
664         } else {
665             int l = strlen(f);
666
667             /* don't list the uninstaller as file- it's going to be removed *after*
668                everything else is done */
669             char*uninstaller="uninstall.exe";
670             int ll = strlen(uninstaller);
671             if(l>=ll) {
672                 if(!strcasecmp(&f[l-ll],uninstaller)) {
673                     continue;
674                 }
675             }
676
677             if(data) {
678                 if(*pos+l <= len) {
679                     memcpy(&data[*pos], f, l);(*pos)+=l;
680                     data[(*pos)++] = '\r';
681                     data[(*pos)++] = '\n';
682                     data[(*pos)] = 0;
683                 }
684             } else {
685                 (*pos) += l+2;
686             }
687             if(del) {
688                 DeleteFile(f);
689             }
690         }
691     } while(FindNextFile(hFind, &findFileData));
692     FindClose(hFind);
693 }
694
695 static char*extrafiles = 0;
696
697 BOOL CALLBACK PropertySheetFunc5(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
698     HWND dialog = GetParent(hwnd);
699     if(message == WM_INITDIALOG) {
700         SetDlgItemText(hwnd, IDC_INFO, "Ready to uninstall");
701     }
702     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZNEXT)) {
703
704         filelist_t* list = readFileList("uninstall.ini");
705         if(!list) {
706             list = readFileList(concatPaths(install_path, "uninstall.ini"));
707             if(!list) {
708                 //Don't abort. If there's still something there, it'll be catched by the "extra files"
709                 //functionality later
710                 //MessageBox(0, "Couldn't determine installed files list- did you run uninstall twice?", INSTALLER_NAME, MB_OK);
711                 //exit(-1);
712             }
713         }
714         filelist_t* l = list;
715         int num = 0;
716         while(l) {num++;l=l->next;}
717
718         PropSheet_SetWizButtons(dialog, 0);
719         SendMessage(dialog, PSM_CANCELTOCLOSE, 0, 0);
720         SetDlgItemText(hwnd, IDC_TITLE, "Uninstalling files...");
721         SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, (LPARAM)MAKELONG(0,num));
722         num = 0;
723         l = list;
724         while(l) {
725             SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, num, 0);
726             if(l->type=='F')
727                 DeleteFile(l->filename);
728             else if(l->type=='D')
729                 RemoveDirectory(l->filename);
730             else if(l->type=='I') 
731                 /* skip- we will remove ourselves later */;
732             num++;l = l->next;
733         }
734
735         int len = 0;
736         findfiles(install_path, &len, 0, 0, 0);
737         if(len) {
738             extrafiles = malloc(len);
739             int pos = 0;
740             findfiles(install_path, &pos, extrafiles, len, 0);
741         } else {
742             PropSheet_RemovePage(dialog, 1, 0);
743         }
744         return 0;
745     }
746     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_BACK|PSWIZB_NEXT);
747 }
748
749 BOOL CALLBACK PropertySheetFunc6(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
750     if(message == WM_INITDIALOG) {
751         SendDlgItemMessage(hwnd, IDC_DELETEEXTRA, BM_SETCHECK, config_deleteextra, 0);
752         if(extrafiles) {
753             SetDlgItemText(hwnd, IDC_FILELIST, extrafiles);
754         }
755     }
756     if(message == WM_COMMAND) {
757         if((wParam&0xffff) == IDC_DELETEEXTRA) {
758             config_deleteextra = SendDlgItemMessage(hwnd, IDC_DELETEEXTRA, BM_GETCHECK, 0, 0);
759             config_deleteextra ^=1;
760             SendDlgItemMessage(hwnd, IDC_DELETEEXTRA, BM_SETCHECK, config_deleteextra, 0);
761             return 0;
762         }
763     }
764     if(message == WM_NOTIFY && (((LPNMHDR)lParam)->code == PSN_WIZNEXT)) {
765         if(config_deleteextra) {
766             int pos = 0;
767             findfiles(install_path, &pos, 0, 0, 1);
768         }
769     }
770     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_NEXT);
771 }
772
773 BOOL CALLBACK PropertySheetFunc7(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
774     if(message == WM_INITDIALOG) {
775         // ...
776     }
777     return PropertySheetFuncCommon(hwnd, message, wParam, lParam, PSWIZB_FINISH);
778 }
779 #endif
780
781 #ifndef PSP_HIDEHEADER
782 #define PSP_HIDEHEADER  2048
783 #endif
784
785 typedef struct _wizardpage {
786     DLGPROC function;
787     int resource;
788 } wizardpage_t;
789
790 void runPropertySheet(HWND parent)
791 {
792     PROPSHEETHEADER sheet;
793
794     wizardpage_t wpage[5] = {
795 #ifndef DEINSTALL
796         {PropertySheetFunc1, IDD_LICENSE},
797         {PropertySheetFunc2, IDD_INSTALLDIR},
798         {PropertySheetFunc3, IDD_PROGRESS},
799         {PropertySheetFunc4, IDD_FINISH},
800 #else
801         {PropertySheetFunc5, IDD_SURE},
802         {PropertySheetFunc6, IDD_EXTRAFILES},
803         {PropertySheetFunc7, IDD_DEINSTALLED},
804 #endif
805     };
806
807     int num = sizeof(wpage)/sizeof(wpage[0]);
808
809 #ifndef DEINSTALL
810     if(elevated) {
811         /* remove license.
812            TODO: remove installdir querying, too (pass installdir
813                  to second process) */
814         int t;
815         for(t=1;t<num;t++) {
816             wpage[t-1] = wpage[t];
817         }
818         num --;
819     }
820 #endif
821
822     HPROPSHEETPAGE pages[num];
823     int t;
824     for(t=0;t<num;t++) {
825         PROPSHEETPAGE page;
826         memset(&page, 0, sizeof(PROPSHEETPAGE));
827         page.dwSize = sizeof(PROPSHEETPAGE);
828         page.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
829         page.hInstance = me;
830         page.pfnDlgProc = wpage[t].function;
831         page.pszTemplate = MAKEINTRESOURCE(wpage[t].resource);
832         pages[t] = CreatePropertySheetPage(&page);
833     }
834
835     memset(&sheet, 0, sizeof(PROPSHEETHEADER));
836     sheet.dwSize = sizeof(PROPSHEETHEADER);
837     sheet.hInstance = me;
838     sheet.hwndParent = parent;
839     sheet.phpage = pages;
840     sheet.dwFlags = PSH_WIZARD;
841     sheet.nPages = num;
842     PropertySheet(&sheet);
843 }
844
845 #ifdef DEINSTALL
846
847 static void remove_self()
848 {
849     char exename[MAX_PATH];
850     char batdir[MAX_PATH];
851     char batfile[MAX_PATH];
852     char*batname;
853     FILE *fp;
854
855     memset(batdir, 0, sizeof(batdir));
856
857     GetModuleFileName(NULL, exename, sizeof(exename));
858     GetTempPath(MAX_PATH, batdir);
859     sprintf(batfile, "%08x.bat", rand());
860
861     batname = concatPaths(batdir, batfile);
862
863     fp = fopen(batname, "w");
864     if(!fp) {
865         return;
866     } 
867
868     fprintf(fp, ":Repeat\n");
869     fprintf(fp, "del \"%s\"\n", exename);
870     fprintf(fp, "if exist \"%s\" goto Repeat\n", exename);
871     fprintf(fp, "rmdir \"%s\"\n", install_path);
872     fprintf(fp, "del \"%s\"\n", batname);
873     fclose(fp);
874
875     STARTUPINFO si;
876     PROCESS_INFORMATION pi;
877     memset(&si, 0, sizeof(si));
878     si.dwFlags = STARTF_USESHOWWINDOW;
879     si.wShowWindow = SW_HIDE;
880     si.cb = sizeof(si);
881     if (CreateProcess(NULL, batname, NULL, NULL, FALSE,
882                       CREATE_SUSPENDED | IDLE_PRIORITY_CLASS,
883                       NULL, "\\", &si, &pi)) {
884             SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE);
885             SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
886             SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
887             CloseHandle(pi.hProcess);
888             ResumeThread(pi.hThread);
889             CloseHandle(pi.hThread);
890     }
891
892 }
893
894 int WINAPI WinMain(HINSTANCE _me,HINSTANCE hPrevInst,LPSTR lpszArgs, int nWinMode)
895 {
896     me = _me;
897     sprintf(registry_path, "Software\\%s\\%s\\InstallPath", SOFTWARE_DOMAIN, SOFTWARE_NAME);
898
899     HWND background = 0;
900     logo = LoadBitmap(me, "LOGO");
901
902     install_path = getRegistryEntry(registry_path);
903     if(!install_path || !install_path[0]) {
904         MessageBox(0, "Couldn't find software installation directory- did you run the uninstallation twice?", INSTALLER_NAME, MB_OK);
905         return 1;
906     }
907
908     CoInitialize(0);
909     InitCommonControls();
910
911     runPropertySheet(background);
912
913     remove_self();
914     return 0;
915 }
916 #else
917 int WINAPI WinMain(HINSTANCE _me,HINSTANCE hPrevInst,LPSTR lpszArgs, int nWinMode)
918 {
919     me = _me;
920     WNDCLASSEX wcl_background;
921     wcl_background.hInstance    = me;
922     wcl_background.lpfnWndProc  = WindowFunc;
923     wcl_background.lpszClassName= INSTALLER_NAME;
924     wcl_background.style        = CS_HREDRAW | CS_VREDRAW;
925     wcl_background.hIcon        = LoadIcon(NULL, IDI_APPLICATION);
926     wcl_background.hIconSm      = LoadIcon(NULL, IDI_APPLICATION);
927     wcl_background.hCursor      = LoadCursor(NULL, IDC_ARROW);
928     wcl_background.lpszMenuName = NULL; //no menu
929     wcl_background.cbClsExtra   = 0;
930     wcl_background.cbWndExtra   = 0;
931     wcl_background.hbrBackground= CreateSolidBrush(RGB(0, 0, 128));
932     wcl_background.cbSize       = sizeof(WNDCLASSEX);
933
934     sprintf(registry_path, "Software\\%s\\%s\\InstallPath", SOFTWARE_DOMAIN, SOFTWARE_NAME);
935
936     if(lpszArgs && strstr(lpszArgs, "elevated")) {
937         elevated = 1;
938     }
939     has_full_access = hasFullAccess();
940     config_forAllUsers = has_full_access;
941
942     HINSTANCE shell32 = LoadLibrary("shell32.dll");
943     if(!shell32) {
944         MessageBox(0, "Could not load shell32.dll", INSTALLER_NAME, MB_OK);
945         return 1;
946     }
947     f_SHGetSpecialFolderPath = (HRESULT (WINAPI*)(HWND,LPTSTR,int,BOOL))GetProcAddress(shell32, "SHGetSpecialFolderPathA");
948     if(!f_SHGetSpecialFolderPath) {
949         MessageBox(0, "Could not load shell32.dll", INSTALLER_NAME, MB_OK);
950         return 1;
951     }
952         
953     HRESULT coret = CoInitialize(NULL);
954     if(FAILED(coret)) {
955         MessageBox(0, "Could not initialize COM interface", INSTALLER_NAME, MB_OK);
956         return 1;
957     }
958
959     path_programfiles[0] = 0;
960     f_SHGetSpecialFolderPath(NULL, path_programfiles, CSIDL_PROGRAM_FILES, 0);
961
962     if(!RegisterClassEx(&wcl_background)) {
963         MessageBox(0, "Could not register window background class", INSTALLER_NAME, MB_OK);
964         return 1;
965     }
966
967     HWND background = CreateWindow(wcl_background.lpszClassName, INSTALLER_NAME,
968                          0, 0, 0, 
969                          GetSystemMetrics(SM_CXFULLSCREEN),
970                          GetSystemMetrics(SM_CYFULLSCREEN),
971                          NULL, NULL, me, 
972                          (void*)"background");
973     
974     if(!background) {
975         MessageBox(0, "Could not create installation background window", INSTALLER_NAME, MB_OK);
976         return 1;
977     }
978
979     ShowWindow(background, SW_SHOWMAXIMIZED);
980     SetForegroundWindow(background);
981     UpdateWindow(background);
982
983     logo = LoadBitmap(me, "LOGO");
984
985     install_path = getRegistryEntry(registry_path);
986     if(!install_path || !install_path[0]) {
987         if(path_programfiles[0]) {
988             install_path = concatPaths(path_programfiles, SOFTWARE_NAME);
989         } else {
990             install_path = concatPaths("c:\\", SOFTWARE_NAME);
991         }
992     }
993
994     InitCommonControls();
995
996     runPropertySheet(background);
997     return 0;
998 }
999 #endif