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