blob: 0ea1fcdbaff6ae8a442953cf5ecf3172b7f48524 [file] [log] [blame]
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001/*
2 * Written by Thomas Heller, May 2000
3 *
4 * $Id$
5 */
6
7/*
8 * Windows Installer program for distutils.
9 *
10 * (a kind of self-extracting zip-file)
11 *
12 * At runtime, the exefile has appended:
13 * - compressed setup-data in ini-format, containing the following sections:
14 * [metadata]
15 * author=Greg Ward
16 * author_email=gward@python.net
17 * description=Python Distribution Utilities
18 * licence=Python
19 * name=Distutils
20 * url=http://www.python.org/sigs/distutils-sig/
21 * version=0.9pre
22 *
23 * [Setup]
24 * info= text to be displayed in the edit-box
25 * title= to be displayed by this program
26 * target_version = if present, python version required
27 * pyc_compile = if 0, do not compile py to pyc
28 * pyo_compile = if 0, do not compile py to pyo
29 *
30 * - a struct meta_data_hdr, describing the above
31 * - a zip-file, containing the modules to be installed.
32 * for the format see http://www.pkware.com/appnote.html
33 *
34 * What does this program do?
35 * - the setup-data is uncompressed and written to a temporary file.
36 * - setup-data is queried with GetPrivateProfile... calls
37 * - [metadata] - info is displayed in the dialog box
38 * - The registry is searched for installations of python
39 * - The user can select the python version to use.
40 * - The python-installation directory (sys.prefix) is displayed
41 * - When the start-button is pressed, files from the zip-archive
42 * are extracted to the file system. All .py filenames are stored
43 * in a list.
44 */
45/*
46 * Includes now an uninstaller.
47 */
48
49/*
50 * To Do:
51 *
52 * display some explanation when no python version is found
53 * instead showing the user an empty listbox to select something from.
54 *
55 * Finish the code so that we can use other python installations
56 * additionaly to those found in the registry,
57 * and then #define USE_OTHER_PYTHON_VERSIONS
58 *
59 * - install a help-button, which will display something meaningful
60 * to the poor user.
61 * text to the user
62 * - should there be a possibility to display a README file
63 * before starting the installation (if one is present in the archive)
64 * - more comments about what the code does(?)
65 *
66 * - evolve this into a full blown installer (???)
67 */
68
69#include <windows.h>
70#include <commctrl.h>
71#include <imagehlp.h>
72#include <objbase.h>
73#include <shlobj.h>
74#include <objidl.h>
75#include "resource.h"
76
77#include <stdio.h>
78#include <stdlib.h>
79#include <stdarg.h>
80#include <string.h>
81#include <time.h>
82
83#include "archive.h"
84
85/* Only for debugging!
86 static int dprintf(char *fmt, ...)
87 {
88 char Buffer[4096];
89 va_list marker;
90 int result;
91
92 va_start(marker, fmt);
93 result = wvsprintf(Buffer, fmt, marker);
94 OutputDebugString(Buffer);
95 return result;
96 }
97*/
98
99/* Bah: global variables */
100FILE *logfile;
101
102char modulename[MAX_PATH];
103
104HWND hwndMain;
105HWND hDialog;
106
107char *ini_file; /* Full pathname of ini-file */
108/* From ini-file */
109char info[4096]; /* [Setup] info= */
110char title[80]; /* [Setup] title=, contains package name
111 including version: "Distutils-1.0.1" */
112char target_version[10]; /* [Setup] target_version=, required python
113 version or empty string */
114char build_info[80]; /* [Setup] build_info=, distutils version
115 and build date */
116
117char meta_name[80]; /* package name without version like
118 'Distutils' */
119char install_script[MAX_PATH];
Thomas Hellera19cdad2004-02-20 14:43:21 +0000120char *pre_install_script; /* run before we install a single file */
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000121
122
123int py_major, py_minor; /* Python version selected for installation */
124
125char *arc_data; /* memory mapped archive */
126DWORD arc_size; /* number of bytes in archive */
127int exe_size; /* number of bytes for exe-file portion */
128char python_dir[MAX_PATH];
129char pythondll[MAX_PATH];
130BOOL pyc_compile, pyo_compile;
131
132BOOL success; /* Installation successfull? */
Thomas Hellera19cdad2004-02-20 14:43:21 +0000133char *failure_reason = NULL;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000134
135HANDLE hBitmap;
136char *bitmap_bytes;
137
138
139#define WM_NUMFILES WM_USER+1
140/* wParam: 0, lParam: total number of files */
141#define WM_NEXTFILE WM_USER+2
142/* wParam: number of this file */
143/* lParam: points to pathname */
144
145enum { UNSPECIFIED, ALWAYS, NEVER } allow_overwrite = UNSPECIFIED;
146
147static BOOL notify(int code, char *fmt, ...);
148
149/* Note: If scheme.prefix is nonempty, it must end with a '\'! */
150/* Note: purelib must be the FIRST entry! */
151SCHEME old_scheme[] = {
152 { "PURELIB", "" },
153 { "PLATLIB", "" },
154 { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */
155 { "SCRIPTS", "Scripts\\" },
156 { "DATA", "" },
157 { NULL, NULL },
158};
159
160SCHEME new_scheme[] = {
161 { "PURELIB", "Lib\\site-packages\\" },
162 { "PLATLIB", "Lib\\site-packages\\" },
163 { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */
164 { "SCRIPTS", "Scripts\\" },
165 { "DATA", "" },
166 { NULL, NULL },
167};
168
169static void unescape(char *dst, char *src, unsigned size)
170{
171 char *eon;
172 char ch;
173
174 while (src && *src && (size > 2)) {
175 if (*src == '\\') {
176 switch (*++src) {
177 case 'n':
178 ++src;
179 *dst++ = '\r';
180 *dst++ = '\n';
181 size -= 2;
182 break;
183 case 'r':
184 ++src;
185 *dst++ = '\r';
186 --size;
187 break;
188 case '0': case '1': case '2': case '3':
189 ch = (char)strtol(src, &eon, 8);
190 if (ch == '\n') {
191 *dst++ = '\r';
192 --size;
193 }
194 *dst++ = ch;
195 --size;
196 src = eon;
197 }
198 } else {
199 *dst++ = *src++;
200 --size;
201 }
202 }
203 *dst = '\0';
204}
205
206static struct tagFile {
207 char *path;
208 struct tagFile *next;
209} *file_list = NULL;
210
Thomas Hellera19cdad2004-02-20 14:43:21 +0000211static void set_failure_reason(char *reason)
212{
213 if (failure_reason)
214 free(failure_reason);
215 failure_reason = strdup(reason);
216 success = FALSE;
217}
218static char *get_failure_reason()
219{
220 if (!failure_reason)
221 return "Installation failed.";
222 return failure_reason;
223}
224
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000225static void add_to_filelist(char *path)
226{
227 struct tagFile *p;
228 p = (struct tagFile *)malloc(sizeof(struct tagFile));
229 p->path = strdup(path);
230 p->next = file_list;
231 file_list = p;
232}
233
234static int do_compile_files(int (__cdecl * PyRun_SimpleString)(char *),
235 int optimize)
236{
237 struct tagFile *p;
238 int total, n;
239 char Buffer[MAX_PATH + 64];
240 int errors = 0;
241
242 total = 0;
243 p = file_list;
244 while (p) {
245 ++total;
246 p = p->next;
247 }
248 SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0,
249 MAKELPARAM(0, total));
250 SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0);
251
252 n = 0;
253 p = file_list;
254 while (p) {
255 ++n;
256 wsprintf(Buffer,
257 "import py_compile; py_compile.compile (r'%s')",
258 p->path);
259 if (PyRun_SimpleString(Buffer)) {
260 ++errors;
261 }
262 /* We send the notification even if the files could not
263 * be created so that the uninstaller will remove them
264 * in case they are created later.
265 */
266 wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c');
267 notify(FILE_CREATED, Buffer);
268
269 SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0);
270 SetDlgItemText(hDialog, IDC_INFO, p->path);
271 p = p->next;
272 }
273 return errors;
274}
275
276#define DECLPROC(dll, result, name, args)\
277 typedef result (*__PROC__##name) args;\
278 result (*name)args = (__PROC__##name)GetProcAddress(dll, #name)
279
280
281#define DECLVAR(dll, type, name)\
282 type *name = (type*)GetProcAddress(dll, #name)
283
284typedef void PyObject;
285
286
287/*
288 * Returns number of files which failed to compile,
289 * -1 if python could not be loaded at all
290 */
291static int compile_filelist(HINSTANCE hPython, BOOL optimize_flag)
292{
293 DECLPROC(hPython, void, Py_Initialize, (void));
294 DECLPROC(hPython, void, Py_SetProgramName, (char *));
295 DECLPROC(hPython, void, Py_Finalize, (void));
296 DECLPROC(hPython, int, PyRun_SimpleString, (char *));
297 DECLPROC(hPython, PyObject *, PySys_GetObject, (char *));
298 DECLVAR(hPython, int, Py_OptimizeFlag);
299
300 int errors = 0;
301 struct tagFile *p = file_list;
302
303 if (!p)
304 return 0;
305
306 if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize)
307 return -1;
308
309 if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag)
310 return -1;
311
312 *Py_OptimizeFlag = optimize_flag ? 1 : 0;
313 Py_SetProgramName(modulename);
314 Py_Initialize();
315
316 errors += do_compile_files(PyRun_SimpleString, optimize_flag);
317 Py_Finalize();
318
319 return errors;
320}
321
322typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);
323
324struct PyMethodDef {
325 char *ml_name;
326 PyCFunction ml_meth;
327 int ml_flags;
328 char *ml_doc;
329};
330typedef struct PyMethodDef PyMethodDef;
331
332void *(*g_Py_BuildValue)(char *, ...);
333int (*g_PyArg_ParseTuple)(PyObject *, char *, ...);
334
335PyObject *g_PyExc_ValueError;
336PyObject *g_PyExc_OSError;
337
338PyObject *(*g_PyErr_Format)(PyObject *, char *, ...);
339
340#define DEF_CSIDL(name) { name, #name }
341
342struct {
343 int nFolder;
344 char *name;
345} csidl_names[] = {
346 /* Startup menu for all users.
347 NT only */
348 DEF_CSIDL(CSIDL_COMMON_STARTMENU),
349 /* Startup menu. */
350 DEF_CSIDL(CSIDL_STARTMENU),
351
352/* DEF_CSIDL(CSIDL_COMMON_APPDATA), */
353/* DEF_CSIDL(CSIDL_LOCAL_APPDATA), */
354 /* Repository for application-specific data.
355 Needs Internet Explorer 4.0 */
356 DEF_CSIDL(CSIDL_APPDATA),
357
358 /* The desktop for all users.
359 NT only */
360 DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY),
361 /* The desktop. */
362 DEF_CSIDL(CSIDL_DESKTOPDIRECTORY),
363
364 /* Startup folder for all users.
365 NT only */
366 DEF_CSIDL(CSIDL_COMMON_STARTUP),
367 /* Startup folder. */
368 DEF_CSIDL(CSIDL_STARTUP),
369
370 /* Programs item in the start menu for all users.
371 NT only */
372 DEF_CSIDL(CSIDL_COMMON_PROGRAMS),
373 /* Program item in the user's start menu. */
374 DEF_CSIDL(CSIDL_PROGRAMS),
375
376/* DEF_CSIDL(CSIDL_PROGRAM_FILES_COMMON), */
377/* DEF_CSIDL(CSIDL_PROGRAM_FILES), */
378
379 /* Virtual folder containing fonts. */
380 DEF_CSIDL(CSIDL_FONTS),
381};
382
383#define DIM(a) (sizeof(a) / sizeof((a)[0]))
384
385static PyObject *FileCreated(PyObject *self, PyObject *args)
386{
387 char *path;
388 if (!g_PyArg_ParseTuple(args, "s", &path))
389 return NULL;
390 notify(FILE_CREATED, path);
391 return g_Py_BuildValue("");
392}
393
394static PyObject *DirectoryCreated(PyObject *self, PyObject *args)
395{
396 char *path;
397 if (!g_PyArg_ParseTuple(args, "s", &path))
398 return NULL;
399 notify(DIR_CREATED, path);
400 return g_Py_BuildValue("");
401}
402
403static PyObject *GetSpecialFolderPath(PyObject *self, PyObject *args)
404{
405 char *name;
406 char lpszPath[MAX_PATH];
407 int i;
408 static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd,
409 LPTSTR lpszPath,
410 int nFolder,
411 BOOL fCreate);
412
413 if (!My_SHGetSpecialFolderPath) {
414 HINSTANCE hLib = LoadLibrary("shell32.dll");
415 if (!hLib) {
416 g_PyErr_Format(g_PyExc_OSError,
417 "function not available");
418 return NULL;
419 }
420 My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR,
421 int, BOOL))
422 GetProcAddress(hLib,
423 "SHGetSpecialFolderPathA");
424 }
425
426 if (!g_PyArg_ParseTuple(args, "s", &name))
427 return NULL;
428
429 if (!My_SHGetSpecialFolderPath) {
430 g_PyErr_Format(g_PyExc_OSError, "function not available");
431 return NULL;
432 }
433
434 for (i = 0; i < DIM(csidl_names); ++i) {
435 if (0 == strcmpi(csidl_names[i].name, name)) {
436 int nFolder;
437 nFolder = csidl_names[i].nFolder;
438 if (My_SHGetSpecialFolderPath(NULL, lpszPath,
439 nFolder, 0))
440 return g_Py_BuildValue("s", lpszPath);
441 else {
442 g_PyErr_Format(g_PyExc_OSError,
443 "no such folder (%s)", name);
444 return NULL;
445 }
446
447 }
448 };
449 g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name);
450 return NULL;
451}
452
453static PyObject *CreateShortcut(PyObject *self, PyObject *args)
454{
455 char *path; /* path and filename */
456 char *description;
457 char *filename;
458
459 char *arguments = NULL;
460 char *iconpath = NULL;
461 int iconindex = 0;
462 char *workdir = NULL;
463
464 WCHAR wszFilename[MAX_PATH];
465
466 IShellLink *ps1 = NULL;
467 IPersistFile *pPf = NULL;
468
469 HRESULT hr;
470
471 hr = CoInitialize(NULL);
472 if (FAILED(hr)) {
473 g_PyErr_Format(g_PyExc_OSError,
474 "CoInitialize failed, error 0x%x", hr);
475 goto error;
476 }
477
478 if (!g_PyArg_ParseTuple(args, "sss|sssi",
479 &path, &description, &filename,
480 &arguments, &workdir, &iconpath, &iconindex))
481 return NULL;
482
483 hr = CoCreateInstance(&CLSID_ShellLink,
484 NULL,
485 CLSCTX_INPROC_SERVER,
486 &IID_IShellLink,
487 &ps1);
488 if (FAILED(hr)) {
489 g_PyErr_Format(g_PyExc_OSError,
490 "CoCreateInstance failed, error 0x%x", hr);
491 goto error;
492 }
493
494 hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile,
495 (void **)&pPf);
496 if (FAILED(hr)) {
497 g_PyErr_Format(g_PyExc_OSError,
498 "QueryInterface(IPersistFile) error 0x%x", hr);
499 goto error;
500 }
501
502
503 hr = ps1->lpVtbl->SetPath(ps1, path);
504 if (FAILED(hr)) {
505 g_PyErr_Format(g_PyExc_OSError,
506 "SetPath() failed, error 0x%x", hr);
507 goto error;
508 }
509
510 hr = ps1->lpVtbl->SetDescription(ps1, description);
511 if (FAILED(hr)) {
512 g_PyErr_Format(g_PyExc_OSError,
513 "SetDescription() failed, error 0x%x", hr);
514 goto error;
515 }
516
517 if (arguments) {
518 hr = ps1->lpVtbl->SetArguments(ps1, arguments);
519 if (FAILED(hr)) {
520 g_PyErr_Format(g_PyExc_OSError,
521 "SetArguments() error 0x%x", hr);
522 goto error;
523 }
524 }
525
526 if (iconpath) {
527 hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex);
528 if (FAILED(hr)) {
529 g_PyErr_Format(g_PyExc_OSError,
530 "SetIconLocation() error 0x%x", hr);
531 goto error;
532 }
533 }
534
535 if (workdir) {
536 hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir);
537 if (FAILED(hr)) {
538 g_PyErr_Format(g_PyExc_OSError,
539 "SetWorkingDirectory() error 0x%x", hr);
540 goto error;
541 }
542 }
543
544 MultiByteToWideChar(CP_ACP, 0,
545 filename, -1,
546 wszFilename, MAX_PATH);
547
548 hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE);
549 if (FAILED(hr)) {
550 g_PyErr_Format(g_PyExc_OSError,
Thomas Hellera19cdad2004-02-20 14:43:21 +0000551 "Failed to create shortcut '%s' - error 0x%x", filename, hr);
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000552 goto error;
553 }
554
555 pPf->lpVtbl->Release(pPf);
556 ps1->lpVtbl->Release(ps1);
557 CoUninitialize();
558 return g_Py_BuildValue("");
559
560 error:
561 if (pPf)
562 pPf->lpVtbl->Release(pPf);
563
564 if (ps1)
565 ps1->lpVtbl->Release(ps1);
566
567 CoUninitialize();
568
569 return NULL;
570}
571
Thomas Hellera19cdad2004-02-20 14:43:21 +0000572static PyObject *PyMessageBox(PyObject *self, PyObject *args)
573{
574 int rc;
575 char *text, *caption;
576 int flags;
577 if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags))
578 return NULL;
579 rc = MessageBox(GetFocus(), text, caption, flags);
580 return g_Py_BuildValue("i", rc);
581}
582
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000583#define METH_VARARGS 0x0001
584
585PyMethodDef meth[] = {
586 {"create_shortcut", CreateShortcut, METH_VARARGS, NULL},
587 {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL},
588 {"file_created", FileCreated, METH_VARARGS, NULL},
589 {"directory_created", DirectoryCreated, METH_VARARGS, NULL},
Thomas Hellera19cdad2004-02-20 14:43:21 +0000590 {"message_box", PyMessageBox, METH_VARARGS, NULL},
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000591};
592
Thomas Hellera19cdad2004-02-20 14:43:21 +0000593static int prepare_script_environment(HINSTANCE hPython)
594{
595 PyObject *mod;
596 DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *));
597 DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *));
598 DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *));
599 DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *));
600 DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...));
601 DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...));
602 DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *));
603 if (!PyImport_ImportModule || !PyObject_GetAttrString ||
604 !PyObject_SetAttrString || !PyCFunction_New)
605 return 1;
606 if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format)
607 return 1;
608
609 mod = PyImport_ImportModule("__builtin__");
610 if (mod) {
611 int i;
612 g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError");
613 g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError");
614 for (i = 0; i < DIM(meth); ++i) {
615 PyObject_SetAttrString(mod, meth[i].ml_name,
616 PyCFunction_New(&meth[i], NULL));
617 }
618 }
619 g_Py_BuildValue = Py_BuildValue;
620 g_PyArg_ParseTuple = PyArg_ParseTuple;
621 g_PyErr_Format = PyErr_Format;
622
623 return 0;
624}
625
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000626/*
627 * This function returns one of the following error codes:
628 * 1 if the Python-dll does not export the functions we need
629 * 2 if no install-script is specified in pathname
630 * 3 if the install-script file could not be opened
631 * the return value of PyRun_SimpleFile() otherwise,
632 * which is 0 if everything is ok, -1 if an exception had occurred
633 * in the install-script.
634 */
635
636static int
637run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv)
638{
639 DECLPROC(hPython, void, Py_Initialize, (void));
640 DECLPROC(hPython, int, PySys_SetArgv, (int, char **));
641 DECLPROC(hPython, int, PyRun_SimpleFile, (FILE *, char *));
642 DECLPROC(hPython, void, Py_Finalize, (void));
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000643 DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...));
644 DECLPROC(hPython, PyObject *, PyCFunction_New,
645 (PyMethodDef *, PyObject *));
646 DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...));
647 DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *));
648
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000649 int result = 0;
650 FILE *fp;
651
652 if (!Py_Initialize || !PySys_SetArgv
653 || !PyRun_SimpleFile || !Py_Finalize)
654 return 1;
655
Thomas Hellera19cdad2004-02-20 14:43:21 +0000656 if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format)
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000657 return 1;
658
659 if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format)
660 return 1;
661
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000662 if (pathname == NULL || pathname[0] == '\0')
663 return 2;
664
665 fp = fopen(pathname, "r");
666 if (!fp) {
667 fprintf(stderr, "Could not open postinstall-script %s\n",
668 pathname);
669 return 3;
670 }
671
672 SetDlgItemText(hDialog, IDC_INFO, "Running Script...");
673
674 Py_Initialize();
675
Thomas Hellera19cdad2004-02-20 14:43:21 +0000676 prepare_script_environment(hPython);
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000677 PySys_SetArgv(argc, argv);
678 result = PyRun_SimpleFile(fp, pathname);
679 Py_Finalize();
680
681 fclose(fp);
682
683 return result;
684}
685
Thomas Hellera19cdad2004-02-20 14:43:21 +0000686static int do_run_simple_script(HINSTANCE hPython, char *script)
687{
688 int rc;
689 DECLPROC(hPython, void, Py_Initialize, (void));
690 DECLPROC(hPython, void, Py_SetProgramName, (char *));
691 DECLPROC(hPython, void, Py_Finalize, (void));
692 DECLPROC(hPython, int, PyRun_SimpleString, (char *));
693 DECLPROC(hPython, void, PyErr_Print, (void));
694
695 if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize ||
696 !PyRun_SimpleString || !PyErr_Print)
697 return -1;
698
699 Py_SetProgramName(modulename);
700 Py_Initialize();
701 prepare_script_environment(hPython);
702 rc = PyRun_SimpleString(script);
703 if (rc)
704 PyErr_Print();
705 Py_Finalize();
706 return rc;
707}
708
709static int run_simple_script(char *script)
710{
711 int rc;
712 char *tempname;
713 HINSTANCE hPython;
714 tempname = tmpnam(NULL);
715 freopen(tempname, "a", stderr);
716 freopen(tempname, "a", stdout);
717
718 hPython = LoadLibrary (pythondll);
719 if (!hPython) {
720 set_failure_reason("Can't load Python for pre-install script");
721 return -1;
722 }
723 rc = do_run_simple_script(hPython, script);
724 FreeLibrary(hPython);
725 fflush(stderr);
726 fflush(stdout);
727 /* We only care about the output when we fail. If the script works
728 OK, then we discard it
729 */
730 if (rc) {
731 int err_buf_size;
732 char *err_buf;
733 const char *prefix = "Running the pre-installation script failed\r\n";
734 int prefix_len = strlen(prefix);
735 FILE *fp = fopen(tempname, "rb");
736 fseek(fp, 0, SEEK_END);
737 err_buf_size = ftell(fp);
738 fseek(fp, 0, SEEK_SET);
739 err_buf = malloc(prefix_len + err_buf_size + 1);
740 if (err_buf) {
741 int n;
742 strcpy(err_buf, prefix);
743 n = fread(err_buf+prefix_len, 1, err_buf_size, fp);
744 err_buf[prefix_len+n] = '\0';
745 fclose(fp);
746 set_failure_reason(err_buf);
747 free(err_buf);
748 } else {
749 set_failure_reason("Out of memory!");
750 }
751 }
752 remove(tempname);
753 return rc;
754}
755
756
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000757static BOOL SystemError(int error, char *msg)
758{
759 char Buffer[1024];
760 int n;
761
762 if (error) {
763 LPVOID lpMsgBuf;
764 FormatMessage(
765 FORMAT_MESSAGE_ALLOCATE_BUFFER |
766 FORMAT_MESSAGE_FROM_SYSTEM,
767 NULL,
768 error,
769 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
770 (LPSTR)&lpMsgBuf,
771 0,
772 NULL
773 );
774 strncpy(Buffer, lpMsgBuf, sizeof(Buffer));
775 LocalFree(lpMsgBuf);
776 } else
777 Buffer[0] = '\0';
778 n = lstrlen(Buffer);
779 _snprintf(Buffer+n, sizeof(Buffer)-n, msg);
780 MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP);
781 return FALSE;
782}
783
784static BOOL AskOverwrite(char *filename)
785{
786 int result;
787 again:
788 if (allow_overwrite == ALWAYS)
789 return TRUE;
790 if (allow_overwrite == NEVER)
791 return FALSE;
792 result = MessageBox(hDialog,
793 "Overwrite existing files?\n"
794 "\n"
795 "Press YES to ALWAYS overwrite existing files,\n"
796 "press NO to NEVER overwrite existing files.",
797 "Overwrite options",
798 MB_YESNO | MB_ICONQUESTION);
799 if (result == IDYES)
800 allow_overwrite = ALWAYS;
801 else if (result == IDNO)
802 allow_overwrite = NEVER;
803 goto again;
804}
805
806static BOOL notify (int code, char *fmt, ...)
807{
808 char Buffer[1024];
809 va_list marker;
810 BOOL result = TRUE;
811 int a, b;
812 char *cp;
813
814 va_start(marker, fmt);
815 _vsnprintf(Buffer, sizeof(Buffer), fmt, marker);
816
817 switch (code) {
818/* Questions */
819 case CAN_OVERWRITE:
820 result = AskOverwrite(Buffer);
821 break;
822
823/* Information notification */
824 case DIR_CREATED:
825 if (logfile)
826 fprintf(logfile, "100 Made Dir: %s\n", fmt);
827 break;
828
829 case FILE_CREATED:
830 if (logfile)
831 fprintf(logfile, "200 File Copy: %s\n", fmt);
832 goto add_to_filelist_label;
833 break;
834
835 case FILE_OVERWRITTEN:
836 if (logfile)
837 fprintf(logfile, "200 File Overwrite: %s\n", fmt);
838 add_to_filelist_label:
839 if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py")))
840 add_to_filelist(fmt);
841 break;
842
843/* Error Messages */
844 case ZLIB_ERROR:
845 MessageBox(GetFocus(), Buffer, "Error",
846 MB_OK | MB_ICONWARNING);
847 break;
848
849 case SYSTEM_ERROR:
850 SystemError(GetLastError(), Buffer);
851 break;
852
853 case NUM_FILES:
854 a = va_arg(marker, int);
855 b = va_arg(marker, int);
856 SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a));
857 SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt);
858 }
859 va_end(marker);
860
861 return result;
862}
863
864static char *MapExistingFile(char *pathname, DWORD *psize)
865{
866 HANDLE hFile, hFileMapping;
867 DWORD nSizeLow, nSizeHigh;
868 char *data;
869
870 hFile = CreateFile(pathname,
871 GENERIC_READ, FILE_SHARE_READ, NULL,
872 OPEN_EXISTING,
873 FILE_ATTRIBUTE_NORMAL, NULL);
874 if (hFile == INVALID_HANDLE_VALUE)
875 return NULL;
876 nSizeLow = GetFileSize(hFile, &nSizeHigh);
877 hFileMapping = CreateFileMapping(hFile,
878 NULL, PAGE_READONLY, 0, 0, NULL);
879 CloseHandle(hFile);
880
881 if (hFileMapping == INVALID_HANDLE_VALUE)
882 return NULL;
883
884 data = MapViewOfFile(hFileMapping,
885 FILE_MAP_READ, 0, 0, 0);
886
887 CloseHandle(hFileMapping);
888 *psize = nSizeLow;
889 return data;
890}
891
892
893static void create_bitmap(HWND hwnd)
894{
895 BITMAPFILEHEADER *bfh;
896 BITMAPINFO *bi;
897 HDC hdc;
898
899 if (!bitmap_bytes)
900 return;
901
902 if (hBitmap)
903 return;
904
905 hdc = GetDC(hwnd);
906
907 bfh = (BITMAPFILEHEADER *)bitmap_bytes;
908 bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER));
909
910 hBitmap = CreateDIBitmap(hdc,
911 &bi->bmiHeader,
912 CBM_INIT,
913 bitmap_bytes + bfh->bfOffBits,
914 bi,
915 DIB_RGB_COLORS);
916 ReleaseDC(hwnd, hdc);
917}
918
Thomas Hellera19cdad2004-02-20 14:43:21 +0000919/* Extract everything we need to begin the installation. Currently this
920 is the INI filename with install data, and the raw pre-install script
921*/
922static BOOL ExtractInstallData(char *data, DWORD size, int *pexe_size,
923 char **out_ini_file, char **out_preinstall_script)
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000924{
925 /* read the end of central directory record */
926 struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof
927 (struct eof_cdir)];
928
929 int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir -
930 pe->ofsCDir;
931
932 int ofs = arc_start - sizeof (struct meta_data_hdr);
933
934 /* read meta_data info */
935 struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs];
936 char *src, *dst;
937 char *ini_file;
938 char tempdir[MAX_PATH];
939
Thomas Hellera19cdad2004-02-20 14:43:21 +0000940 /* ensure that if we fail, we don't have garbage out pointers */
941 *out_ini_file = *out_preinstall_script = NULL;
942
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000943 if (pe->tag != 0x06054b50) {
Thomas Hellera19cdad2004-02-20 14:43:21 +0000944 return FALSE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000945 }
946
947 if (pmd->tag != 0x1234567A || ofs < 0) {
Thomas Hellera19cdad2004-02-20 14:43:21 +0000948 return FALSE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000949 }
950
951 if (pmd->bitmap_size) {
952 /* Store pointer to bitmap bytes */
953 bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size;
954 }
955
956 *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size;
957
958 src = ((char *)pmd) - pmd->uncomp_size;
959 ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */
960 if (!ini_file)
Thomas Hellera19cdad2004-02-20 14:43:21 +0000961 return FALSE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000962 if (!GetTempPath(sizeof(tempdir), tempdir)
963 || !GetTempFileName(tempdir, "~du", 0, ini_file)) {
964 SystemError(GetLastError(),
965 "Could not create temporary file");
Thomas Hellera19cdad2004-02-20 14:43:21 +0000966 return FALSE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000967 }
968
969 dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size,
970 0, 0, NULL/*notify*/);
971 if (!dst)
Thomas Hellera19cdad2004-02-20 14:43:21 +0000972 return FALSE;
973 /* Up to the first \0 is the INI file data. */
974 strncpy(dst, src, pmd->uncomp_size);
975 src += strlen(dst) + 1;
976 /* Up to next \0 is the pre-install script */
977 *out_preinstall_script = strdup(src);
978 *out_ini_file = ini_file;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000979 UnmapViewOfFile(dst);
Thomas Hellera19cdad2004-02-20 14:43:21 +0000980 return TRUE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000981}
982
983static void PumpMessages(void)
984{
985 MSG msg;
986 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
987 TranslateMessage(&msg);
988 DispatchMessage(&msg);
989 }
990}
991
992LRESULT CALLBACK
993WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
994{
995 HDC hdc;
996 HFONT hFont;
997 int h;
998 PAINTSTRUCT ps;
999 switch (msg) {
1000 case WM_PAINT:
1001 hdc = BeginPaint(hwnd, &ps);
1002 h = GetSystemMetrics(SM_CYSCREEN) / 10;
1003 hFont = CreateFont(h, 0, 0, 0, 700, TRUE,
1004 0, 0, 0, 0, 0, 0, 0, "Times Roman");
1005 hFont = SelectObject(hdc, hFont);
1006 SetBkMode(hdc, TRANSPARENT);
1007 TextOut(hdc, 15, 15, title, strlen(title));
1008 SetTextColor(hdc, RGB(255, 255, 255));
1009 TextOut(hdc, 10, 10, title, strlen(title));
1010 DeleteObject(SelectObject(hdc, hFont));
1011 EndPaint(hwnd, &ps);
1012 return 0;
1013 }
1014 return DefWindowProc(hwnd, msg, wParam, lParam);
1015}
1016
1017static HWND CreateBackground(char *title)
1018{
1019 WNDCLASS wc;
1020 HWND hwnd;
1021 char buffer[4096];
1022
1023 wc.style = CS_VREDRAW | CS_HREDRAW;
1024 wc.lpfnWndProc = WindowProc;
1025 wc.cbWndExtra = 0;
1026 wc.cbClsExtra = 0;
1027 wc.hInstance = GetModuleHandle(NULL);
1028 wc.hIcon = NULL;
1029 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1030 wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128));
1031 wc.lpszMenuName = NULL;
1032 wc.lpszClassName = "SetupWindowClass";
1033
1034 if (!RegisterClass(&wc))
1035 MessageBox(hwndMain,
1036 "Could not register window class",
1037 "Setup.exe", MB_OK);
1038
1039 wsprintf(buffer, "Setup %s", title);
1040 hwnd = CreateWindow("SetupWindowClass",
1041 buffer,
1042 0,
1043 0, 0,
1044 GetSystemMetrics(SM_CXFULLSCREEN),
1045 GetSystemMetrics(SM_CYFULLSCREEN),
1046 NULL,
1047 NULL,
1048 GetModuleHandle(NULL),
1049 NULL);
1050 ShowWindow(hwnd, SW_SHOWMAXIMIZED);
1051 UpdateWindow(hwnd);
1052 return hwnd;
1053}
1054
1055/*
1056 * Center a window on the screen
1057 */
1058static void CenterWindow(HWND hwnd)
1059{
1060 RECT rc;
1061 int w, h;
1062
1063 GetWindowRect(hwnd, &rc);
1064 w = GetSystemMetrics(SM_CXSCREEN);
1065 h = GetSystemMetrics(SM_CYSCREEN);
1066 MoveWindow(hwnd,
1067 (w - (rc.right-rc.left))/2,
1068 (h - (rc.bottom-rc.top))/2,
1069 rc.right-rc.left, rc.bottom-rc.top, FALSE);
1070}
1071
1072#include <prsht.h>
1073
1074BOOL CALLBACK
1075IntroDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1076{
1077 LPNMHDR lpnm;
1078 char Buffer[4096];
1079
1080 switch (msg) {
1081 case WM_INITDIALOG:
1082 create_bitmap(hwnd);
1083 if(hBitmap)
1084 SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
1085 IMAGE_BITMAP, (LPARAM)hBitmap);
1086 CenterWindow(GetParent(hwnd));
1087 wsprintf(Buffer,
1088 "This Wizard will install %s on your computer. "
1089 "Click Next to continue "
1090 "or Cancel to exit the Setup Wizard.",
1091 meta_name);
1092 SetDlgItemText(hwnd, IDC_TITLE, Buffer);
1093 SetDlgItemText(hwnd, IDC_INTRO_TEXT, info);
1094 SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info);
1095 return FALSE;
1096
1097 case WM_NOTIFY:
1098 lpnm = (LPNMHDR) lParam;
1099
1100 switch (lpnm->code) {
1101 case PSN_SETACTIVE:
1102 PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT);
1103 break;
1104
1105 case PSN_WIZNEXT:
1106 break;
1107
1108 case PSN_RESET:
1109 break;
1110
1111 default:
1112 break;
1113 }
1114 }
1115 return FALSE;
1116}
1117
1118#ifdef USE_OTHER_PYTHON_VERSIONS
1119/* These are really private variables used to communicate
1120 * between StatusRoutine and CheckPythonExe
1121 */
1122char bound_image_dll[_MAX_PATH];
1123int bound_image_major;
1124int bound_image_minor;
1125
1126static BOOL __stdcall StatusRoutine(IMAGEHLP_STATUS_REASON reason,
1127 PSTR ImageName,
1128 PSTR DllName,
1129 ULONG Va,
1130 ULONG Parameter)
1131{
1132 char fname[_MAX_PATH];
1133 int int_version;
1134
1135 switch(reason) {
1136 case BindOutOfMemory:
1137 case BindRvaToVaFailed:
1138 case BindNoRoomInImage:
1139 case BindImportProcedureFailed:
1140 break;
1141
1142 case BindImportProcedure:
1143 case BindForwarder:
1144 case BindForwarderNOT:
1145 case BindImageModified:
1146 case BindExpandFileHeaders:
1147 case BindImageComplete:
1148 case BindSymbolsNotUpdated:
1149 case BindMismatchedSymbols:
1150 case BindImportModuleFailed:
1151 break;
1152
1153 case BindImportModule:
1154 if (1 == sscanf(DllName, "python%d", &int_version)) {
1155 SearchPath(NULL, DllName, NULL, sizeof(fname),
1156 fname, NULL);
1157 strcpy(bound_image_dll, fname);
1158 bound_image_major = int_version / 10;
1159 bound_image_minor = int_version % 10;
1160 OutputDebugString("BOUND ");
1161 OutputDebugString(fname);
1162 OutputDebugString("\n");
1163 }
1164 break;
1165 }
1166 return TRUE;
1167}
1168
1169/*
1170 */
1171static LPSTR get_sys_prefix(LPSTR exe, LPSTR dll)
1172{
1173 void (__cdecl * Py_Initialize)(void);
1174 void (__cdecl * Py_SetProgramName)(char *);
1175 void (__cdecl * Py_Finalize)(void);
1176 void* (__cdecl * PySys_GetObject)(char *);
1177 void (__cdecl * PySys_SetArgv)(int, char **);
1178 char* (__cdecl * Py_GetPrefix)(void);
1179 char* (__cdecl * Py_GetPath)(void);
1180 HINSTANCE hPython;
1181 LPSTR prefix = NULL;
1182 int (__cdecl * PyRun_SimpleString)(char *);
1183
1184 {
1185 char Buffer[256];
1186 wsprintf(Buffer, "PYTHONHOME=%s", exe);
1187 *strrchr(Buffer, '\\') = '\0';
1188// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK);
1189 _putenv(Buffer);
1190 _putenv("PYTHONPATH=");
1191 }
1192
1193 hPython = LoadLibrary(dll);
1194 if (!hPython)
1195 return NULL;
1196 Py_Initialize = (void (*)(void))GetProcAddress
1197 (hPython,"Py_Initialize");
1198
1199 PySys_SetArgv = (void (*)(int, char **))GetProcAddress
1200 (hPython,"PySys_SetArgv");
1201
1202 PyRun_SimpleString = (int (*)(char *))GetProcAddress
1203 (hPython,"PyRun_SimpleString");
1204
1205 Py_SetProgramName = (void (*)(char *))GetProcAddress
1206 (hPython,"Py_SetProgramName");
1207
1208 PySys_GetObject = (void* (*)(char *))GetProcAddress
1209 (hPython,"PySys_GetObject");
1210
1211 Py_GetPrefix = (char * (*)(void))GetProcAddress
1212 (hPython,"Py_GetPrefix");
1213
1214 Py_GetPath = (char * (*)(void))GetProcAddress
1215 (hPython,"Py_GetPath");
1216
1217 Py_Finalize = (void (*)(void))GetProcAddress(hPython,
1218 "Py_Finalize");
1219 Py_SetProgramName(exe);
1220 Py_Initialize();
1221 PySys_SetArgv(1, &exe);
1222
1223 MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK);
1224 MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK);
1225
1226 Py_Finalize();
1227 FreeLibrary(hPython);
1228
1229 return prefix;
1230}
1231
1232static BOOL
1233CheckPythonExe(LPSTR pathname, LPSTR version, int *pmajor, int *pminor)
1234{
1235 bound_image_dll[0] = '\0';
1236 if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES,
1237 pathname,
1238 NULL,
1239 NULL,
1240 StatusRoutine))
1241 return SystemError(0, "Could not bind image");
1242 if (bound_image_dll[0] == '\0')
1243 return SystemError(0, "Does not seem to be a python executable");
1244 *pmajor = bound_image_major;
1245 *pminor = bound_image_minor;
1246 if (version && *version) {
1247 char core_version[12];
1248 wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor);
1249 if (strcmp(version, core_version))
1250 return SystemError(0, "Wrong Python version");
1251 }
1252 get_sys_prefix(pathname, bound_image_dll);
1253 return TRUE;
1254}
1255
1256/*
1257 * Browse for other python versions. Insert it into the listbox specified
1258 * by hwnd. version, if not NULL or empty, is the version required.
1259 */
1260static BOOL GetOtherPythonVersion(HWND hwnd, LPSTR version)
1261{
1262 char vers_name[_MAX_PATH + 80];
1263 DWORD itemindex;
1264 OPENFILENAME of;
1265 char pathname[_MAX_PATH];
1266 DWORD result;
1267
1268 strcpy(pathname, "python.exe");
1269
1270 memset(&of, 0, sizeof(of));
1271 of.lStructSize = sizeof(OPENFILENAME);
1272 of.hwndOwner = GetParent(hwnd);
1273 of.hInstance = NULL;
1274 of.lpstrFilter = "python.exe\0python.exe\0";
1275 of.lpstrCustomFilter = NULL;
1276 of.nMaxCustFilter = 0;
1277 of.nFilterIndex = 1;
1278 of.lpstrFile = pathname;
1279 of.nMaxFile = sizeof(pathname);
1280 of.lpstrFileTitle = NULL;
1281 of.nMaxFileTitle = 0;
1282 of.lpstrInitialDir = NULL;
1283 of.lpstrTitle = "Python executable";
1284 of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
1285 of.lpstrDefExt = "exe";
1286
1287 result = GetOpenFileName(&of);
1288 if (result) {
1289 int major, minor;
1290 if (!CheckPythonExe(pathname, version, &major, &minor)) {
1291 return FALSE;
1292 }
1293 *strrchr(pathname, '\\') = '\0';
1294 wsprintf(vers_name, "Python Version %d.%d in %s",
1295 major, minor, pathname);
1296 itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1,
1297 (LPARAM)(LPSTR)vers_name);
1298 SendMessage(hwnd, LB_SETCURSEL, itemindex, 0);
1299 SendMessage(hwnd, LB_SETITEMDATA, itemindex,
1300 (LPARAM)(LPSTR)strdup(pathname));
1301 return TRUE;
1302 }
1303 return FALSE;
1304}
1305#endif /* USE_OTHER_PYTHON_VERSIONS */
1306
1307
1308/*
1309 * Fill the listbox specified by hwnd with all python versions found
1310 * in the registry. version, if not NULL or empty, is the version
1311 * required.
1312 */
1313static BOOL GetPythonVersions(HWND hwnd, HKEY hkRoot, LPSTR version)
1314{
1315 DWORD index = 0;
1316 char core_version[80];
1317 HKEY hKey;
1318 BOOL result = TRUE;
1319 DWORD bufsize;
1320
1321 if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot,
1322 "Software\\Python\\PythonCore",
1323 0, KEY_READ, &hKey))
1324 return FALSE;
1325 bufsize = sizeof(core_version);
1326 while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index,
1327 core_version, &bufsize, NULL,
1328 NULL, NULL, NULL)) {
1329 char subkey_name[80], vers_name[80], prefix_buf[MAX_PATH+1];
1330 int itemindex;
1331 DWORD value_size;
1332 HKEY hk;
1333
1334 bufsize = sizeof(core_version);
1335 ++index;
1336 if (version && *version && strcmp(version, core_version))
1337 continue;
1338
1339 wsprintf(vers_name, "Python Version %s (found in registry)",
1340 core_version);
1341 wsprintf(subkey_name,
1342 "Software\\Python\\PythonCore\\%s\\InstallPath",
1343 core_version);
1344 value_size = sizeof(subkey_name);
1345 if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) {
1346 if (ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL, prefix_buf,
1347 &value_size)) {
1348 itemindex = SendMessage(hwnd, LB_ADDSTRING, 0,
1349 (LPARAM)(LPSTR)vers_name);
1350 SendMessage(hwnd, LB_SETITEMDATA, itemindex,
1351 (LPARAM)(LPSTR)strdup(prefix_buf));
1352 }
1353 RegCloseKey(hk);
1354 }
1355 }
1356 RegCloseKey(hKey);
1357 return result;
1358}
1359
1360/* Return the installation scheme depending on Python version number */
1361SCHEME *GetScheme(int major, int minor)
1362{
1363 if (major > 2)
1364 return new_scheme;
1365 else if((major == 2) && (minor >= 2))
1366 return new_scheme;
1367 return old_scheme;
1368}
1369
1370BOOL CALLBACK
1371SelectPythonDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1372{
1373 LPNMHDR lpnm;
1374
1375 switch (msg) {
1376 case WM_INITDIALOG:
1377 if (hBitmap)
1378 SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
1379 IMAGE_BITMAP, (LPARAM)hBitmap);
1380 GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
1381 HKEY_LOCAL_MACHINE, target_version);
1382 GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
1383 HKEY_CURRENT_USER, target_version);
1384 { /* select the last entry which is the highest python
1385 version found */
1386 int count;
1387 count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1388 LB_GETCOUNT, 0, 0);
1389 if (count && count != LB_ERR)
1390 SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL,
1391 count-1, 0);
1392
1393 /* If a specific Python version is required,
1394 * display a prominent notice showing this fact.
1395 */
1396 if (target_version && target_version[0]) {
1397 char buffer[4096];
1398 wsprintf(buffer,
1399 "Python %s is required for this package. "
1400 "Select installation to use:",
1401 target_version);
1402 SetDlgItemText(hwnd, IDC_TITLE, buffer);
1403 }
1404
1405 if (count == 0) {
1406 char Buffer[4096];
1407 char *msg;
1408 if (target_version && target_version[0]) {
1409 wsprintf(Buffer,
1410 "Python version %s required, which was not found"
1411 " in the registry.", target_version);
1412 msg = Buffer;
1413 } else
1414 msg = "No Python installation found in the registry.";
1415 MessageBox(hwnd, msg, "Cannot install",
1416 MB_OK | MB_ICONSTOP);
1417 }
1418 }
1419 goto UpdateInstallDir;
1420 break;
1421
1422 case WM_COMMAND:
1423 switch (LOWORD(wParam)) {
1424/*
1425 case IDC_OTHERPYTHON:
1426 if (GetOtherPythonVersion(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
1427 target_version))
1428 goto UpdateInstallDir;
1429 break;
1430*/
1431 case IDC_VERSIONS_LIST:
1432 switch (HIWORD(wParam)) {
1433 int id;
1434 char *cp;
1435 case LBN_SELCHANGE:
1436 UpdateInstallDir:
1437 PropSheet_SetWizButtons(GetParent(hwnd),
1438 PSWIZB_BACK | PSWIZB_NEXT);
1439 id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1440 LB_GETCURSEL, 0, 0);
1441 if (id == LB_ERR) {
1442 PropSheet_SetWizButtons(GetParent(hwnd),
1443 PSWIZB_BACK);
1444 SetDlgItemText(hwnd, IDC_PATH, "");
1445 SetDlgItemText(hwnd, IDC_INSTALL_PATH, "");
1446 strcpy(python_dir, "");
1447 strcpy(pythondll, "");
1448 } else {
1449 char *pbuf;
1450 int result;
1451 PropSheet_SetWizButtons(GetParent(hwnd),
1452 PSWIZB_BACK | PSWIZB_NEXT);
1453 /* Get the python directory */
1454 cp = (LPSTR)SendDlgItemMessage(hwnd,
1455 IDC_VERSIONS_LIST,
1456 LB_GETITEMDATA,
1457 id,
1458 0);
1459 strcpy(python_dir, cp);
1460 SetDlgItemText(hwnd, IDC_PATH, python_dir);
1461 /* retrieve the python version and pythondll to use */
1462 result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1463 LB_GETTEXTLEN, (WPARAM)id, 0);
1464 pbuf = (char *)malloc(result + 1);
1465 if (pbuf) {
1466 /* guess the name of the python-dll */
1467 SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1468 LB_GETTEXT, (WPARAM)id,
1469 (LPARAM)pbuf);
1470 result = sscanf(pbuf, "Python Version %d.%d",
1471 &py_major, &py_minor);
1472 if (result == 2)
1473#ifdef _DEBUG
Thomas Hellera19cdad2004-02-20 14:43:21 +00001474 wsprintf(pythondll, "python%d%d_d.dll",
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001475 py_major, py_minor);
1476#else
1477 wsprintf(pythondll, "python%d%d.dll",
1478 py_major, py_minor);
1479#endif
1480 free(pbuf);
1481 } else
1482 strcpy(pythondll, "");
1483 /* retrieve the scheme for this version */
1484 {
1485 char install_path[_MAX_PATH];
1486 SCHEME *scheme = GetScheme(py_major, py_minor);
1487 strcpy(install_path, python_dir);
1488 if (install_path[strlen(install_path)-1] != '\\')
1489 strcat(install_path, "\\");
1490 strcat(install_path, scheme[0].prefix);
1491 SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path);
1492 }
1493 }
1494 }
1495 break;
1496 }
1497 return 0;
1498
1499 case WM_NOTIFY:
1500 lpnm = (LPNMHDR) lParam;
1501
1502 switch (lpnm->code) {
1503 int id;
1504 case PSN_SETACTIVE:
1505 id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1506 LB_GETCURSEL, 0, 0);
1507 if (id == LB_ERR)
1508 PropSheet_SetWizButtons(GetParent(hwnd),
1509 PSWIZB_BACK);
1510 else
1511 PropSheet_SetWizButtons(GetParent(hwnd),
1512 PSWIZB_BACK | PSWIZB_NEXT);
1513 break;
1514
1515 case PSN_WIZNEXT:
1516 break;
1517
1518 case PSN_WIZFINISH:
1519 break;
1520
1521 case PSN_RESET:
1522 break;
1523
1524 default:
1525 break;
1526 }
1527 }
1528 return 0;
1529}
1530
1531static BOOL OpenLogfile(char *dir)
1532{
1533 char buffer[_MAX_PATH+1];
1534 time_t ltime;
1535 struct tm *now;
1536 long result;
1537 HKEY hKey, hSubkey;
1538 char subkey_name[256];
1539 static char KeyName[] =
1540 "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
1541 DWORD disposition;
1542
1543 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
1544 KeyName,
1545 0,
1546 KEY_CREATE_SUB_KEY,
1547 &hKey);
1548 if (result != ERROR_SUCCESS) {
1549 if (result == ERROR_ACCESS_DENIED) {
1550 MessageBox(GetFocus(),
1551 "You do not seem to have sufficient access rights\n"
1552 "on this machine to install this software",
1553 NULL,
1554 MB_OK | MB_ICONSTOP);
1555 return FALSE;
1556 } else {
1557 MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK);
1558 }
1559 }
1560
1561 sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name);
1562 logfile = fopen(buffer, "a");
1563 time(&ltime);
1564 now = localtime(&ltime);
1565 strftime(buffer, sizeof(buffer),
1566 "*** Installation started %Y/%m/%d %H:%M ***\n",
1567 localtime(&ltime));
1568 fprintf(logfile, buffer);
1569 fprintf(logfile, "Source: %s\n", modulename);
1570
1571 sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor);
1572
1573 result = RegCreateKeyEx(hKey, subkey_name,
1574 0, NULL, 0,
1575 KEY_WRITE,
1576 NULL,
1577 &hSubkey,
1578 &disposition);
1579
1580 if (result != ERROR_SUCCESS)
1581 MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK);
1582
1583 RegCloseKey(hKey);
1584
1585 if (disposition == REG_CREATED_NEW_KEY)
1586 fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name);
1587
1588 sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title);
1589
1590 result = RegSetValueEx(hSubkey, "DisplayName",
1591 0,
1592 REG_SZ,
1593 buffer,
1594 strlen(buffer)+1);
1595
1596 if (result != ERROR_SUCCESS)
1597 MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK);
1598
1599 fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n",
1600 KeyName, subkey_name, "DisplayName", buffer);
1601
1602 {
1603 FILE *fp;
1604 sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name);
1605 fp = fopen(buffer, "wb");
1606 fwrite(arc_data, exe_size, 1, fp);
1607 fclose(fp);
1608
1609 sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"",
1610 dir, meta_name, dir, meta_name);
1611
1612 result = RegSetValueEx(hSubkey, "UninstallString",
1613 0,
1614 REG_SZ,
1615 buffer,
1616 strlen(buffer)+1);
1617
1618 if (result != ERROR_SUCCESS)
1619 MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK);
1620
1621 fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n",
1622 KeyName, subkey_name, "UninstallString", buffer);
1623 }
1624 return TRUE;
1625}
1626
1627static void CloseLogfile(void)
1628{
1629 char buffer[_MAX_PATH+1];
1630 time_t ltime;
1631 struct tm *now;
1632
1633 time(&ltime);
1634 now = localtime(&ltime);
1635 strftime(buffer, sizeof(buffer),
1636 "*** Installation finished %Y/%m/%d %H:%M ***\n",
1637 localtime(&ltime));
1638 fprintf(logfile, buffer);
1639 if (logfile)
1640 fclose(logfile);
1641}
1642
1643BOOL CALLBACK
1644InstallFilesDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1645{
1646 LPNMHDR lpnm;
1647 char Buffer[4096];
1648 SCHEME *scheme;
1649
1650 switch (msg) {
1651 case WM_INITDIALOG:
1652 if (hBitmap)
1653 SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
1654 IMAGE_BITMAP, (LPARAM)hBitmap);
1655 wsprintf(Buffer,
1656 "Click Next to begin the installation of %s. "
1657 "If you want to review or change any of your "
1658 " installation settings, click Back. "
1659 "Click Cancel to exit the wizard.",
1660 meta_name);
1661 SetDlgItemText(hwnd, IDC_TITLE, Buffer);
Thomas Hellera19cdad2004-02-20 14:43:21 +00001662 SetDlgItemText(hwnd, IDC_INFO, "Ready to install");
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001663 break;
1664
1665 case WM_NUMFILES:
1666 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam);
1667 PumpMessages();
1668 return TRUE;
1669
1670 case WM_NEXTFILE:
1671 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam,
1672 0);
1673 SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam);
1674 PumpMessages();
1675 return TRUE;
1676
1677 case WM_NOTIFY:
1678 lpnm = (LPNMHDR) lParam;
1679
1680 switch (lpnm->code) {
1681 case PSN_SETACTIVE:
1682 PropSheet_SetWizButtons(GetParent(hwnd),
1683 PSWIZB_BACK | PSWIZB_NEXT);
1684 break;
1685
1686 case PSN_WIZFINISH:
1687 break;
1688
1689 case PSN_WIZNEXT:
1690 /* Handle a Next button click here */
1691 hDialog = hwnd;
Thomas Hellera19cdad2004-02-20 14:43:21 +00001692 success = TRUE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001693
1694 /* Make sure the installation directory name ends in a */
1695 /* backslash */
1696 if (python_dir[strlen(python_dir)-1] != '\\')
1697 strcat(python_dir, "\\");
1698 /* Strip the trailing backslash again */
1699 python_dir[strlen(python_dir)-1] = '\0';
1700
1701 if (!OpenLogfile(python_dir))
1702 break;
1703
1704/*
1705 * The scheme we have to use depends on the Python version...
1706 if sys.version < "2.2":
1707 WINDOWS_SCHEME = {
1708 'purelib': '$base',
1709 'platlib': '$base',
1710 'headers': '$base/Include/$dist_name',
1711 'scripts': '$base/Scripts',
1712 'data' : '$base',
1713 }
1714 else:
1715 WINDOWS_SCHEME = {
1716 'purelib': '$base/Lib/site-packages',
1717 'platlib': '$base/Lib/site-packages',
1718 'headers': '$base/Include/$dist_name',
1719 'scripts': '$base/Scripts',
1720 'data' : '$base',
1721 }
1722*/
1723 scheme = GetScheme(py_major, py_minor);
Thomas Hellera19cdad2004-02-20 14:43:21 +00001724 /* Run the pre-install script. */
1725 if (pre_install_script && *pre_install_script) {
1726 SetDlgItemText (hwnd, IDC_TITLE,
1727 "Running pre-installation script");
1728 run_simple_script(pre_install_script);
1729 }
1730 if (!success) {
1731 break;
1732 }
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001733 /* Extract all files from the archive */
1734 SetDlgItemText(hwnd, IDC_TITLE, "Installing files...");
Thomas Hellera19cdad2004-02-20 14:43:21 +00001735 if (!unzip_archive (scheme,
1736 python_dir, arc_data,
1737 arc_size, notify))
1738 set_failure_reason("Failed to unzip installation files");
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001739 /* Compile the py-files */
Thomas Hellera19cdad2004-02-20 14:43:21 +00001740 if (success && pyc_compile) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001741 int errors;
1742 HINSTANCE hPython;
1743 SetDlgItemText(hwnd, IDC_TITLE,
1744 "Compiling files to .pyc...");
1745
1746 SetDlgItemText(hDialog, IDC_INFO, "Loading python...");
1747 hPython = LoadLibrary(pythondll);
1748 if (hPython) {
1749 errors = compile_filelist(hPython, FALSE);
1750 FreeLibrary(hPython);
1751 }
1752 /* Compilation errors are intentionally ignored:
1753 * Python2.0 contains a bug which will result
1754 * in sys.path containing garbage under certain
1755 * circumstances, and an error message will only
1756 * confuse the user.
1757 */
1758 }
Thomas Hellera19cdad2004-02-20 14:43:21 +00001759 if (success && pyo_compile) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001760 int errors;
1761 HINSTANCE hPython;
1762 SetDlgItemText(hwnd, IDC_TITLE,
1763 "Compiling files to .pyo...");
1764
1765 SetDlgItemText(hDialog, IDC_INFO, "Loading python...");
1766 hPython = LoadLibrary(pythondll);
1767 if (hPython) {
1768 errors = compile_filelist(hPython, TRUE);
1769 FreeLibrary(hPython);
1770 }
1771 /* Errors ignored: see above */
1772 }
1773
1774
1775 break;
1776
1777 case PSN_RESET:
1778 break;
1779
1780 default:
1781 break;
1782 }
1783 }
1784 return 0;
1785}
1786
1787
1788BOOL CALLBACK
1789FinishedDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1790{
1791 LPNMHDR lpnm;
1792
1793 switch (msg) {
1794 case WM_INITDIALOG:
1795 if (hBitmap)
1796 SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
1797 IMAGE_BITMAP, (LPARAM)hBitmap);
1798 if (!success)
Thomas Hellera19cdad2004-02-20 14:43:21 +00001799 SetDlgItemText(hwnd, IDC_INFO, get_failure_reason());
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001800
1801 /* async delay: will show the dialog box completely before
1802 the install_script is started */
1803 PostMessage(hwnd, WM_USER, 0, 0L);
1804 return TRUE;
1805
1806 case WM_USER:
1807
Thomas Hellera19cdad2004-02-20 14:43:21 +00001808 if (success && install_script && install_script[0]) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001809 char fname[MAX_PATH];
1810 char *tempname;
1811 FILE *fp;
1812 char buffer[4096];
1813 int n;
1814 HCURSOR hCursor;
1815 HINSTANCE hPython;
1816
1817 char *argv[3] = {NULL, "-install", NULL};
1818
1819 SetDlgItemText(hwnd, IDC_TITLE,
1820 "Please wait while running postinstall script...");
1821 strcpy(fname, python_dir);
1822 strcat(fname, "\\Scripts\\");
1823 strcat(fname, install_script);
1824
1825 if (logfile)
1826 fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname);
1827
1828 tempname = tmpnam(NULL);
1829
1830 if (!freopen(tempname, "a", stderr))
1831 MessageBox(GetFocus(), "freopen stderr", NULL, MB_OK);
1832 if (!freopen(tempname, "a", stdout))
1833 MessageBox(GetFocus(), "freopen stdout", NULL, MB_OK);
1834/*
1835 if (0 != setvbuf(stdout, NULL, _IONBF, 0))
1836 MessageBox(GetFocus(), "setvbuf stdout", NULL, MB_OK);
1837*/
1838 hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
1839
1840 argv[0] = fname;
1841
1842 hPython = LoadLibrary(pythondll);
1843 if (hPython) {
1844 int result;
1845 result = run_installscript(hPython, fname, 2, argv);
1846 if (-1 == result) {
1847 fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result);
1848 }
1849 FreeLibrary(hPython);
1850 } else {
1851 fprintf(stderr, "*** Could not load Python ***");
1852 }
1853 fflush(stderr);
1854 fflush(stdout);
1855
1856 fp = fopen(tempname, "rb");
1857 n = fread(buffer, 1, sizeof(buffer), fp);
1858 fclose(fp);
1859 remove(tempname);
1860
1861 buffer[n] = '\0';
1862
1863 SetDlgItemText(hwnd, IDC_INFO, buffer);
1864 SetDlgItemText(hwnd, IDC_TITLE,
1865 "Postinstall script finished.\n"
1866 "Click the Finish button to exit the Setup wizard.");
1867
1868 SetCursor(hCursor);
1869 CloseLogfile();
1870 }
1871
1872 return TRUE;
1873
1874 case WM_NOTIFY:
1875 lpnm = (LPNMHDR) lParam;
1876
1877 switch (lpnm->code) {
1878 case PSN_SETACTIVE: /* Enable the Finish button */
1879 PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH);
1880 break;
1881
1882 case PSN_WIZNEXT:
1883 break;
1884
1885 case PSN_WIZFINISH:
1886 break;
1887
1888 case PSN_RESET:
1889 break;
1890
1891 default:
1892 break;
1893 }
1894 }
1895 return 0;
1896}
1897
1898void RunWizard(HWND hwnd)
1899{
1900 PROPSHEETPAGE psp = {0};
1901 HPROPSHEETPAGE ahpsp[4] = {0};
1902 PROPSHEETHEADER psh = {0};
1903
1904 /* Display module information */
1905 psp.dwSize = sizeof(psp);
1906 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1907 psp.hInstance = GetModuleHandle (NULL);
1908 psp.lParam = 0;
1909 psp.pfnDlgProc = IntroDlgProc;
1910 psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO);
1911
1912 ahpsp[0] = CreatePropertySheetPage(&psp);
1913
1914 /* Select python version to use */
1915 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1916 psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON);
1917 psp.pfnDlgProc = SelectPythonDlgProc;
1918
1919 ahpsp[1] = CreatePropertySheetPage(&psp);
1920
1921 /* Install the files */
1922 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1923 psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES);
1924 psp.pfnDlgProc = InstallFilesDlgProc;
1925
1926 ahpsp[2] = CreatePropertySheetPage(&psp);
1927
1928 /* Show success or failure */
1929 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1930 psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED);
1931 psp.pfnDlgProc = FinishedDlgProc;
1932
1933 ahpsp[3] = CreatePropertySheetPage(&psp);
1934
1935 /* Create the property sheet */
1936 psh.dwSize = sizeof(psh);
1937 psh.hInstance = GetModuleHandle(NULL);
1938 psh.hwndParent = hwnd;
1939 psh.phpage = ahpsp;
1940 psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/;
1941 psh.pszbmWatermark = NULL;
1942 psh.pszbmHeader = NULL;
1943 psh.nStartPage = 0;
1944 psh.nPages = 4;
1945
1946 PropertySheet(&psh);
1947}
1948
1949int DoInstall(void)
1950{
1951 char ini_buffer[4096];
1952
1953 /* Read installation information */
1954 GetPrivateProfileString("Setup", "title", "", ini_buffer,
1955 sizeof(ini_buffer), ini_file);
1956 unescape(title, ini_buffer, sizeof(title));
1957
1958 GetPrivateProfileString("Setup", "info", "", ini_buffer,
1959 sizeof(ini_buffer), ini_file);
1960 unescape(info, ini_buffer, sizeof(info));
1961
1962 GetPrivateProfileString("Setup", "build_info", "", build_info,
1963 sizeof(build_info), ini_file);
1964
1965 pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1,
1966 ini_file);
1967 pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1,
1968 ini_file);
1969
1970 GetPrivateProfileString("Setup", "target_version", "",
1971 target_version, sizeof(target_version),
1972 ini_file);
1973
1974 GetPrivateProfileString("metadata", "name", "",
1975 meta_name, sizeof(meta_name),
1976 ini_file);
1977
1978 GetPrivateProfileString("Setup", "install_script", "",
1979 install_script, sizeof(install_script),
1980 ini_file);
1981
1982
1983 hwndMain = CreateBackground(title);
1984
1985 RunWizard(hwndMain);
1986
1987 /* Clean up */
1988 UnmapViewOfFile(arc_data);
1989 if (ini_file)
1990 DeleteFile(ini_file);
1991
1992 if (hBitmap)
1993 DeleteObject(hBitmap);
1994
1995 return 0;
1996}
1997
1998/*********************** uninstall section ******************************/
1999
2000static int compare(const void *p1, const void *p2)
2001{
2002 return strcmp(*(char **)p2, *(char **)p1);
2003}
2004
2005/*
2006 * Commit suicide (remove the uninstaller itself).
2007 *
2008 * Create a batch file to first remove the uninstaller
2009 * (will succeed after it has finished), then the batch file itself.
2010 *
2011 * This technique has been demonstrated by Jeff Richter,
2012 * MSJ 1/1996
2013 */
2014void remove_exe(void)
2015{
2016 char exename[_MAX_PATH];
2017 char batname[_MAX_PATH];
2018 FILE *fp;
2019 STARTUPINFO si;
2020 PROCESS_INFORMATION pi;
2021
2022 GetModuleFileName(NULL, exename, sizeof(exename));
2023 sprintf(batname, "%s.bat", exename);
2024 fp = fopen(batname, "w");
2025 fprintf(fp, ":Repeat\n");
2026 fprintf(fp, "del \"%s\"\n", exename);
2027 fprintf(fp, "if exist \"%s\" goto Repeat\n", exename);
2028 fprintf(fp, "del \"%s\"\n", batname);
2029 fclose(fp);
2030
2031 ZeroMemory(&si, sizeof(si));
2032 si.cb = sizeof(si);
2033 si.dwFlags = STARTF_USESHOWWINDOW;
2034 si.wShowWindow = SW_HIDE;
2035 if (CreateProcess(NULL,
2036 batname,
2037 NULL,
2038 NULL,
2039 FALSE,
2040 CREATE_SUSPENDED | IDLE_PRIORITY_CLASS,
2041 NULL,
2042 "\\",
2043 &si,
2044 &pi)) {
2045 SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE);
2046 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
2047 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
2048 CloseHandle(pi.hProcess);
2049 ResumeThread(pi.hThread);
2050 CloseHandle(pi.hThread);
2051 }
2052}
2053
2054void DeleteRegistryKey(char *string)
2055{
2056 char *keyname;
2057 char *subkeyname;
2058 char *delim;
2059 HKEY hKey;
2060 long result;
2061 char *line;
2062
2063 line = strdup(string); /* so we can change it */
2064
2065 keyname = strchr(line, '[');
2066 if (!keyname)
2067 return;
2068 ++keyname;
2069
2070 subkeyname = strchr(keyname, ']');
2071 if (!subkeyname)
2072 return;
2073 *subkeyname++='\0';
2074 delim = strchr(subkeyname, '\n');
2075 if (delim)
2076 *delim = '\0';
2077
2078 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
2079 keyname,
2080 0,
2081 KEY_WRITE,
2082 &hKey);
2083
2084 if (result != ERROR_SUCCESS)
2085 MessageBox(GetFocus(), string, "Could not open key", MB_OK);
2086 else {
2087 result = RegDeleteKey(hKey, subkeyname);
2088 if (result != ERROR_SUCCESS)
2089 MessageBox(GetFocus(), string, "Could not delete key", MB_OK);
2090 RegCloseKey(hKey);
2091 }
2092 free(line);
2093}
2094
2095void DeleteRegistryValue(char *string)
2096{
2097 char *keyname;
2098 char *valuename;
2099 char *value;
2100 HKEY hKey;
2101 long result;
2102 char *line;
2103
2104 line = strdup(string); /* so we can change it */
2105
2106/* Format is 'Reg DB Value: [key]name=value' */
2107 keyname = strchr(line, '[');
2108 if (!keyname)
2109 return;
2110 ++keyname;
2111 valuename = strchr(keyname, ']');
2112 if (!valuename)
2113 return;
2114 *valuename++ = '\0';
2115 value = strchr(valuename, '=');
2116 if (!value)
2117 return;
2118
2119 *value++ = '\0';
2120
2121 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
2122 keyname,
2123 0,
2124 KEY_WRITE,
2125 &hKey);
2126 if (result != ERROR_SUCCESS)
2127 MessageBox(GetFocus(), string, "Could not open key", MB_OK);
2128 else {
2129 result = RegDeleteValue(hKey, valuename);
2130 if (result != ERROR_SUCCESS)
2131 MessageBox(GetFocus(), string, "Could not delete value", MB_OK);
2132 RegCloseKey(hKey);
2133 }
2134 free(line);
2135}
2136
2137BOOL MyDeleteFile(char *line)
2138{
2139 char *pathname = strchr(line, ':');
2140 if (!pathname)
2141 return FALSE;
2142 ++pathname;
2143 while (isspace(*pathname))
2144 ++pathname;
2145 return DeleteFile(pathname);
2146}
2147
2148BOOL MyRemoveDirectory(char *line)
2149{
2150 char *pathname = strchr(line, ':');
2151 if (!pathname)
2152 return FALSE;
2153 ++pathname;
2154 while (isspace(*pathname))
2155 ++pathname;
2156 return RemoveDirectory(pathname);
2157}
2158
2159BOOL Run_RemoveScript(char *line)
2160{
2161 char *dllname;
2162 char *scriptname;
2163 static char lastscript[MAX_PATH];
2164
2165/* Format is 'Run Scripts: [pythondll]scriptname' */
2166/* XXX Currently, pythondll carries no path!!! */
2167 dllname = strchr(line, '[');
2168 if (!dllname)
2169 return FALSE;
2170 ++dllname;
2171 scriptname = strchr(dllname, ']');
2172 if (!scriptname)
2173 return FALSE;
2174 *scriptname++ = '\0';
2175 /* this function may be called more than one time with the same
2176 script, only run it one time */
2177 if (strcmp(lastscript, scriptname)) {
2178 HINSTANCE hPython;
2179 char *argv[3] = {NULL, "-remove", NULL};
2180 char buffer[4096];
2181 FILE *fp;
2182 char *tempname;
2183 int n;
2184
2185 argv[0] = scriptname;
2186
2187 tempname = tmpnam(NULL);
2188
2189 if (!freopen(tempname, "a", stderr))
2190 MessageBox(GetFocus(), "freopen stderr", NULL, MB_OK);
2191 if (!freopen(tempname, "a", stdout))
2192 MessageBox(GetFocus(), "freopen stdout", NULL, MB_OK);
2193
2194 hPython = LoadLibrary(dllname);
2195 if (hPython) {
2196 if (0x80000000 == run_installscript(hPython, scriptname, 2, argv))
2197 fprintf(stderr, "*** Could not load Python ***");
2198 FreeLibrary(hPython);
2199 }
2200
2201 fflush(stderr);
2202 fflush(stdout);
2203
2204 fp = fopen(tempname, "rb");
2205 n = fread(buffer, 1, sizeof(buffer), fp);
2206 fclose(fp);
2207 remove(tempname);
2208
2209 buffer[n] = '\0';
2210 if (buffer[0])
2211 MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK);
2212
2213 strcpy(lastscript, scriptname);
2214 }
2215 return TRUE;
2216}
2217
2218int DoUninstall(int argc, char **argv)
2219{
2220 FILE *logfile;
2221 char buffer[4096];
2222 int nLines = 0;
2223 int i;
2224 char *cp;
2225 int nFiles = 0;
2226 int nDirs = 0;
2227 int nErrors = 0;
2228 char **lines;
2229 int lines_buffer_size = 10;
2230
2231 if (argc != 3) {
2232 MessageBox(NULL,
2233 "Wrong number of args",
2234 NULL,
2235 MB_OK);
2236 return 1; /* Error */
2237 }
2238 if (strcmp(argv[1], "-u")) {
2239 MessageBox(NULL,
2240 "2. arg is not -u",
2241 NULL,
2242 MB_OK);
2243 return 1; /* Error */
2244 }
2245
2246 {
2247 DWORD result;
2248 HKEY hKey;
2249 static char KeyName[] =
2250 "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
2251
2252 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
2253 KeyName,
2254 0,
2255 KEY_CREATE_SUB_KEY,
2256 &hKey);
2257 if (result == ERROR_ACCESS_DENIED) {
2258 MessageBox(GetFocus(),
2259 "You do not seem to have sufficient access rights\n"
2260 "on this machine to uninstall this software",
2261 NULL,
2262 MB_OK | MB_ICONSTOP);
2263 return 1; /* Error */
2264 }
2265 RegCloseKey(hKey);
2266 }
2267
2268 logfile = fopen(argv[2], "r");
2269 if (!logfile) {
2270 MessageBox(NULL,
2271 "could not open logfile",
2272 NULL,
2273 MB_OK);
2274 return 1; /* Error */
2275 }
2276
2277 lines = (char **)malloc(sizeof(char *) * lines_buffer_size);
2278 if (!lines)
2279 return SystemError(0, "Out of memory");
2280
2281 /* Read the whole logfile, realloacting the buffer */
2282 while (fgets(buffer, sizeof(buffer), logfile)) {
2283 int len = strlen(buffer);
2284 /* remove trailing white space */
2285 while (isspace(buffer[len-1]))
2286 len -= 1;
2287 buffer[len] = '\0';
2288 lines[nLines++] = strdup(buffer);
2289 if (nLines >= lines_buffer_size) {
2290 lines_buffer_size += 10;
2291 lines = (char **)realloc(lines,
2292 sizeof(char *) * lines_buffer_size);
2293 if (!lines)
2294 return SystemError(0, "Out of memory");
2295 }
2296 }
2297 fclose(logfile);
2298
2299 /* Sort all the lines, so that highest 3-digit codes are first */
2300 qsort(&lines[0], nLines, sizeof(char *),
2301 compare);
2302
2303 if (IDYES != MessageBox(NULL,
2304 "Are you sure you want to remove\n"
2305 "this package from your computer?",
2306 "Please confirm",
2307 MB_YESNO | MB_ICONQUESTION))
2308 return 0;
2309
2310 cp = "";
2311 for (i = 0; i < nLines; ++i) {
2312 /* Ignore duplicate lines */
2313 if (strcmp(cp, lines[i])) {
2314 int ign;
2315 cp = lines[i];
2316 /* Parse the lines */
2317 if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) {
2318 if (MyRemoveDirectory(cp))
2319 ++nDirs;
2320 else {
2321 int code = GetLastError();
2322 if (code != 2 && code != 3) { /* file or path not found */
2323 ++nErrors;
2324 }
2325 }
2326 } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) {
2327 if (MyDeleteFile(cp))
2328 ++nFiles;
2329 else {
2330 int code = GetLastError();
2331 if (code != 2 && code != 3) { /* file or path not found */
2332 ++nErrors;
2333 }
2334 }
2335 } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) {
2336 if (MyDeleteFile(cp))
2337 ++nFiles;
2338 else {
2339 int code = GetLastError();
2340 if (code != 2 && code != 3) { /* file or path not found */
2341 ++nErrors;
2342 }
2343 }
2344 } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) {
2345 DeleteRegistryKey(cp);
2346 } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) {
2347 DeleteRegistryValue(cp);
2348 } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) {
2349 Run_RemoveScript(cp);
2350 }
2351 }
2352 }
2353
2354 if (DeleteFile(argv[2])) {
2355 ++nFiles;
2356 } else {
2357 ++nErrors;
2358 SystemError(GetLastError(), argv[2]);
2359 }
2360 if (nErrors)
2361 wsprintf(buffer,
2362 "%d files and %d directories removed\n"
2363 "%d files or directories could not be removed",
2364 nFiles, nDirs, nErrors);
2365 else
2366 wsprintf(buffer, "%d files and %d directories removed",
2367 nFiles, nDirs);
2368 MessageBox(NULL, buffer, "Uninstall Finished!",
2369 MB_OK | MB_ICONINFORMATION);
2370 remove_exe();
2371 return 0;
2372}
2373
2374int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst,
2375 LPSTR lpszCmdLine, INT nCmdShow)
2376{
2377 extern int __argc;
2378 extern char **__argv;
2379 char *basename;
2380
2381 GetModuleFileName(NULL, modulename, sizeof(modulename));
2382
2383 /* Map the executable file to memory */
2384 arc_data = MapExistingFile(modulename, &arc_size);
2385 if (!arc_data) {
2386 SystemError(GetLastError(), "Could not open archive");
2387 return 1;
2388 }
2389
2390 /* OK. So this program can act as installer (self-extracting
2391 * zip-file, or as uninstaller when started with '-u logfile'
2392 * command line flags.
2393 *
2394 * The installer is usually started without command line flags,
2395 * and the uninstaller is usually started with the '-u logfile'
2396 * flag. What to do if some innocent user double-clicks the
2397 * exe-file?
2398 * The following implements a defensive strategy...
2399 */
2400
2401 /* Try to extract the configuration data into a temporary file */
Thomas Hellera19cdad2004-02-20 14:43:21 +00002402 if (ExtractInstallData(arc_data, arc_size, &exe_size,
2403 &ini_file, &pre_install_script))
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00002404 return DoInstall();
2405
2406 if (!ini_file && __argc > 1) {
2407 return DoUninstall(__argc, __argv);
2408 }
2409
2410
2411 basename = strrchr(modulename, '\\');
2412 if (basename)
2413 ++basename;
2414
2415 /* Last guess about the purpose of this program */
2416 if (basename && (0 == strncmp(basename, "Remove", 6)))
2417 SystemError(0, "This program is normally started by windows");
2418 else
2419 SystemError(0, "Setup program invalid or damaged");
2420 return 1;
2421}