blob: 64e213ec58bf11f467993ba10d1b1edaf13ee72a [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);
Thomas Heller96142192004-04-15 18:19:02 +00001472 if (result == 2) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001473#ifdef _DEBUG
Thomas Hellera19cdad2004-02-20 14:43:21 +00001474 wsprintf(pythondll, "python%d%d_d.dll",
Thomas Heller96142192004-04-15 18:19:02 +00001475 py_major, py_minor);
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001476#else
Thomas Heller96142192004-04-15 18:19:02 +00001477 wsprintf(pythondll, "python%d%d.dll",
1478 py_major, py_minor);
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001479#endif
Thomas Heller96142192004-04-15 18:19:02 +00001480 }
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001481 free(pbuf);
1482 } else
1483 strcpy(pythondll, "");
1484 /* retrieve the scheme for this version */
1485 {
1486 char install_path[_MAX_PATH];
1487 SCHEME *scheme = GetScheme(py_major, py_minor);
1488 strcpy(install_path, python_dir);
1489 if (install_path[strlen(install_path)-1] != '\\')
1490 strcat(install_path, "\\");
1491 strcat(install_path, scheme[0].prefix);
1492 SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path);
1493 }
1494 }
1495 }
1496 break;
1497 }
1498 return 0;
1499
1500 case WM_NOTIFY:
1501 lpnm = (LPNMHDR) lParam;
1502
1503 switch (lpnm->code) {
1504 int id;
1505 case PSN_SETACTIVE:
1506 id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1507 LB_GETCURSEL, 0, 0);
1508 if (id == LB_ERR)
1509 PropSheet_SetWizButtons(GetParent(hwnd),
1510 PSWIZB_BACK);
1511 else
1512 PropSheet_SetWizButtons(GetParent(hwnd),
1513 PSWIZB_BACK | PSWIZB_NEXT);
1514 break;
1515
1516 case PSN_WIZNEXT:
1517 break;
1518
1519 case PSN_WIZFINISH:
1520 break;
1521
1522 case PSN_RESET:
1523 break;
1524
1525 default:
1526 break;
1527 }
1528 }
1529 return 0;
1530}
1531
1532static BOOL OpenLogfile(char *dir)
1533{
1534 char buffer[_MAX_PATH+1];
1535 time_t ltime;
1536 struct tm *now;
1537 long result;
1538 HKEY hKey, hSubkey;
1539 char subkey_name[256];
1540 static char KeyName[] =
1541 "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
1542 DWORD disposition;
1543
1544 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
1545 KeyName,
1546 0,
1547 KEY_CREATE_SUB_KEY,
1548 &hKey);
1549 if (result != ERROR_SUCCESS) {
1550 if (result == ERROR_ACCESS_DENIED) {
1551 MessageBox(GetFocus(),
1552 "You do not seem to have sufficient access rights\n"
1553 "on this machine to install this software",
1554 NULL,
1555 MB_OK | MB_ICONSTOP);
1556 return FALSE;
1557 } else {
1558 MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK);
1559 }
1560 }
1561
1562 sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name);
1563 logfile = fopen(buffer, "a");
1564 time(&ltime);
1565 now = localtime(&ltime);
1566 strftime(buffer, sizeof(buffer),
1567 "*** Installation started %Y/%m/%d %H:%M ***\n",
1568 localtime(&ltime));
1569 fprintf(logfile, buffer);
1570 fprintf(logfile, "Source: %s\n", modulename);
1571
1572 sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor);
1573
1574 result = RegCreateKeyEx(hKey, subkey_name,
1575 0, NULL, 0,
1576 KEY_WRITE,
1577 NULL,
1578 &hSubkey,
1579 &disposition);
1580
1581 if (result != ERROR_SUCCESS)
1582 MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK);
1583
1584 RegCloseKey(hKey);
1585
1586 if (disposition == REG_CREATED_NEW_KEY)
1587 fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name);
1588
1589 sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title);
1590
1591 result = RegSetValueEx(hSubkey, "DisplayName",
1592 0,
1593 REG_SZ,
1594 buffer,
1595 strlen(buffer)+1);
1596
1597 if (result != ERROR_SUCCESS)
1598 MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK);
1599
1600 fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n",
1601 KeyName, subkey_name, "DisplayName", buffer);
1602
1603 {
1604 FILE *fp;
1605 sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name);
1606 fp = fopen(buffer, "wb");
1607 fwrite(arc_data, exe_size, 1, fp);
1608 fclose(fp);
1609
1610 sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"",
1611 dir, meta_name, dir, meta_name);
1612
1613 result = RegSetValueEx(hSubkey, "UninstallString",
1614 0,
1615 REG_SZ,
1616 buffer,
1617 strlen(buffer)+1);
1618
1619 if (result != ERROR_SUCCESS)
1620 MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK);
1621
1622 fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n",
1623 KeyName, subkey_name, "UninstallString", buffer);
1624 }
1625 return TRUE;
1626}
1627
1628static void CloseLogfile(void)
1629{
1630 char buffer[_MAX_PATH+1];
1631 time_t ltime;
1632 struct tm *now;
1633
1634 time(&ltime);
1635 now = localtime(&ltime);
1636 strftime(buffer, sizeof(buffer),
1637 "*** Installation finished %Y/%m/%d %H:%M ***\n",
1638 localtime(&ltime));
1639 fprintf(logfile, buffer);
1640 if (logfile)
1641 fclose(logfile);
1642}
1643
1644BOOL CALLBACK
1645InstallFilesDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1646{
1647 LPNMHDR lpnm;
1648 char Buffer[4096];
1649 SCHEME *scheme;
1650
1651 switch (msg) {
1652 case WM_INITDIALOG:
1653 if (hBitmap)
1654 SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
1655 IMAGE_BITMAP, (LPARAM)hBitmap);
1656 wsprintf(Buffer,
1657 "Click Next to begin the installation of %s. "
1658 "If you want to review or change any of your "
1659 " installation settings, click Back. "
1660 "Click Cancel to exit the wizard.",
1661 meta_name);
1662 SetDlgItemText(hwnd, IDC_TITLE, Buffer);
Thomas Hellera19cdad2004-02-20 14:43:21 +00001663 SetDlgItemText(hwnd, IDC_INFO, "Ready to install");
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001664 break;
1665
1666 case WM_NUMFILES:
1667 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam);
1668 PumpMessages();
1669 return TRUE;
1670
1671 case WM_NEXTFILE:
1672 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam,
1673 0);
1674 SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam);
1675 PumpMessages();
1676 return TRUE;
1677
1678 case WM_NOTIFY:
1679 lpnm = (LPNMHDR) lParam;
1680
1681 switch (lpnm->code) {
1682 case PSN_SETACTIVE:
1683 PropSheet_SetWizButtons(GetParent(hwnd),
1684 PSWIZB_BACK | PSWIZB_NEXT);
1685 break;
1686
1687 case PSN_WIZFINISH:
1688 break;
1689
1690 case PSN_WIZNEXT:
1691 /* Handle a Next button click here */
1692 hDialog = hwnd;
Thomas Hellera19cdad2004-02-20 14:43:21 +00001693 success = TRUE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001694
1695 /* Make sure the installation directory name ends in a */
1696 /* backslash */
1697 if (python_dir[strlen(python_dir)-1] != '\\')
1698 strcat(python_dir, "\\");
1699 /* Strip the trailing backslash again */
1700 python_dir[strlen(python_dir)-1] = '\0';
1701
1702 if (!OpenLogfile(python_dir))
1703 break;
1704
1705/*
1706 * The scheme we have to use depends on the Python version...
1707 if sys.version < "2.2":
1708 WINDOWS_SCHEME = {
1709 'purelib': '$base',
1710 'platlib': '$base',
1711 'headers': '$base/Include/$dist_name',
1712 'scripts': '$base/Scripts',
1713 'data' : '$base',
1714 }
1715 else:
1716 WINDOWS_SCHEME = {
1717 'purelib': '$base/Lib/site-packages',
1718 'platlib': '$base/Lib/site-packages',
1719 'headers': '$base/Include/$dist_name',
1720 'scripts': '$base/Scripts',
1721 'data' : '$base',
1722 }
1723*/
1724 scheme = GetScheme(py_major, py_minor);
Thomas Hellera19cdad2004-02-20 14:43:21 +00001725 /* Run the pre-install script. */
1726 if (pre_install_script && *pre_install_script) {
1727 SetDlgItemText (hwnd, IDC_TITLE,
1728 "Running pre-installation script");
1729 run_simple_script(pre_install_script);
1730 }
1731 if (!success) {
1732 break;
1733 }
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001734 /* Extract all files from the archive */
1735 SetDlgItemText(hwnd, IDC_TITLE, "Installing files...");
Thomas Hellera19cdad2004-02-20 14:43:21 +00001736 if (!unzip_archive (scheme,
1737 python_dir, arc_data,
1738 arc_size, notify))
1739 set_failure_reason("Failed to unzip installation files");
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001740 /* Compile the py-files */
Thomas Hellera19cdad2004-02-20 14:43:21 +00001741 if (success && pyc_compile) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001742 int errors;
1743 HINSTANCE hPython;
1744 SetDlgItemText(hwnd, IDC_TITLE,
1745 "Compiling files to .pyc...");
1746
1747 SetDlgItemText(hDialog, IDC_INFO, "Loading python...");
1748 hPython = LoadLibrary(pythondll);
1749 if (hPython) {
1750 errors = compile_filelist(hPython, FALSE);
1751 FreeLibrary(hPython);
1752 }
1753 /* Compilation errors are intentionally ignored:
1754 * Python2.0 contains a bug which will result
1755 * in sys.path containing garbage under certain
1756 * circumstances, and an error message will only
1757 * confuse the user.
1758 */
1759 }
Thomas Hellera19cdad2004-02-20 14:43:21 +00001760 if (success && pyo_compile) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001761 int errors;
1762 HINSTANCE hPython;
1763 SetDlgItemText(hwnd, IDC_TITLE,
1764 "Compiling files to .pyo...");
1765
1766 SetDlgItemText(hDialog, IDC_INFO, "Loading python...");
1767 hPython = LoadLibrary(pythondll);
1768 if (hPython) {
1769 errors = compile_filelist(hPython, TRUE);
1770 FreeLibrary(hPython);
1771 }
1772 /* Errors ignored: see above */
1773 }
1774
1775
1776 break;
1777
1778 case PSN_RESET:
1779 break;
1780
1781 default:
1782 break;
1783 }
1784 }
1785 return 0;
1786}
1787
1788
1789BOOL CALLBACK
1790FinishedDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1791{
1792 LPNMHDR lpnm;
1793
1794 switch (msg) {
1795 case WM_INITDIALOG:
1796 if (hBitmap)
1797 SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
1798 IMAGE_BITMAP, (LPARAM)hBitmap);
1799 if (!success)
Thomas Hellera19cdad2004-02-20 14:43:21 +00001800 SetDlgItemText(hwnd, IDC_INFO, get_failure_reason());
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001801
1802 /* async delay: will show the dialog box completely before
1803 the install_script is started */
1804 PostMessage(hwnd, WM_USER, 0, 0L);
1805 return TRUE;
1806
1807 case WM_USER:
1808
Thomas Hellera19cdad2004-02-20 14:43:21 +00001809 if (success && install_script && install_script[0]) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001810 char fname[MAX_PATH];
1811 char *tempname;
1812 FILE *fp;
1813 char buffer[4096];
1814 int n;
1815 HCURSOR hCursor;
1816 HINSTANCE hPython;
1817
1818 char *argv[3] = {NULL, "-install", NULL};
1819
1820 SetDlgItemText(hwnd, IDC_TITLE,
1821 "Please wait while running postinstall script...");
1822 strcpy(fname, python_dir);
1823 strcat(fname, "\\Scripts\\");
1824 strcat(fname, install_script);
1825
1826 if (logfile)
1827 fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname);
1828
1829 tempname = tmpnam(NULL);
1830
1831 if (!freopen(tempname, "a", stderr))
1832 MessageBox(GetFocus(), "freopen stderr", NULL, MB_OK);
1833 if (!freopen(tempname, "a", stdout))
1834 MessageBox(GetFocus(), "freopen stdout", NULL, MB_OK);
1835/*
1836 if (0 != setvbuf(stdout, NULL, _IONBF, 0))
1837 MessageBox(GetFocus(), "setvbuf stdout", NULL, MB_OK);
1838*/
1839 hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
1840
1841 argv[0] = fname;
1842
1843 hPython = LoadLibrary(pythondll);
1844 if (hPython) {
1845 int result;
1846 result = run_installscript(hPython, fname, 2, argv);
1847 if (-1 == result) {
1848 fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result);
1849 }
1850 FreeLibrary(hPython);
1851 } else {
1852 fprintf(stderr, "*** Could not load Python ***");
1853 }
1854 fflush(stderr);
1855 fflush(stdout);
1856
1857 fp = fopen(tempname, "rb");
1858 n = fread(buffer, 1, sizeof(buffer), fp);
1859 fclose(fp);
1860 remove(tempname);
1861
1862 buffer[n] = '\0';
1863
1864 SetDlgItemText(hwnd, IDC_INFO, buffer);
1865 SetDlgItemText(hwnd, IDC_TITLE,
1866 "Postinstall script finished.\n"
1867 "Click the Finish button to exit the Setup wizard.");
1868
1869 SetCursor(hCursor);
1870 CloseLogfile();
1871 }
1872
1873 return TRUE;
1874
1875 case WM_NOTIFY:
1876 lpnm = (LPNMHDR) lParam;
1877
1878 switch (lpnm->code) {
1879 case PSN_SETACTIVE: /* Enable the Finish button */
1880 PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH);
1881 break;
1882
1883 case PSN_WIZNEXT:
1884 break;
1885
1886 case PSN_WIZFINISH:
1887 break;
1888
1889 case PSN_RESET:
1890 break;
1891
1892 default:
1893 break;
1894 }
1895 }
1896 return 0;
1897}
1898
1899void RunWizard(HWND hwnd)
1900{
1901 PROPSHEETPAGE psp = {0};
1902 HPROPSHEETPAGE ahpsp[4] = {0};
1903 PROPSHEETHEADER psh = {0};
1904
1905 /* Display module information */
1906 psp.dwSize = sizeof(psp);
1907 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1908 psp.hInstance = GetModuleHandle (NULL);
1909 psp.lParam = 0;
1910 psp.pfnDlgProc = IntroDlgProc;
1911 psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO);
1912
1913 ahpsp[0] = CreatePropertySheetPage(&psp);
1914
1915 /* Select python version to use */
1916 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1917 psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON);
1918 psp.pfnDlgProc = SelectPythonDlgProc;
1919
1920 ahpsp[1] = CreatePropertySheetPage(&psp);
1921
1922 /* Install the files */
1923 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1924 psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES);
1925 psp.pfnDlgProc = InstallFilesDlgProc;
1926
1927 ahpsp[2] = CreatePropertySheetPage(&psp);
1928
1929 /* Show success or failure */
1930 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1931 psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED);
1932 psp.pfnDlgProc = FinishedDlgProc;
1933
1934 ahpsp[3] = CreatePropertySheetPage(&psp);
1935
1936 /* Create the property sheet */
1937 psh.dwSize = sizeof(psh);
1938 psh.hInstance = GetModuleHandle(NULL);
1939 psh.hwndParent = hwnd;
1940 psh.phpage = ahpsp;
1941 psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/;
1942 psh.pszbmWatermark = NULL;
1943 psh.pszbmHeader = NULL;
1944 psh.nStartPage = 0;
1945 psh.nPages = 4;
1946
1947 PropertySheet(&psh);
1948}
1949
1950int DoInstall(void)
1951{
1952 char ini_buffer[4096];
1953
1954 /* Read installation information */
1955 GetPrivateProfileString("Setup", "title", "", ini_buffer,
1956 sizeof(ini_buffer), ini_file);
1957 unescape(title, ini_buffer, sizeof(title));
1958
1959 GetPrivateProfileString("Setup", "info", "", ini_buffer,
1960 sizeof(ini_buffer), ini_file);
1961 unescape(info, ini_buffer, sizeof(info));
1962
1963 GetPrivateProfileString("Setup", "build_info", "", build_info,
1964 sizeof(build_info), ini_file);
1965
1966 pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1,
1967 ini_file);
1968 pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1,
1969 ini_file);
1970
1971 GetPrivateProfileString("Setup", "target_version", "",
1972 target_version, sizeof(target_version),
1973 ini_file);
1974
1975 GetPrivateProfileString("metadata", "name", "",
1976 meta_name, sizeof(meta_name),
1977 ini_file);
1978
1979 GetPrivateProfileString("Setup", "install_script", "",
1980 install_script, sizeof(install_script),
1981 ini_file);
1982
1983
1984 hwndMain = CreateBackground(title);
1985
1986 RunWizard(hwndMain);
1987
1988 /* Clean up */
1989 UnmapViewOfFile(arc_data);
1990 if (ini_file)
1991 DeleteFile(ini_file);
1992
1993 if (hBitmap)
1994 DeleteObject(hBitmap);
1995
1996 return 0;
1997}
1998
1999/*********************** uninstall section ******************************/
2000
2001static int compare(const void *p1, const void *p2)
2002{
2003 return strcmp(*(char **)p2, *(char **)p1);
2004}
2005
2006/*
2007 * Commit suicide (remove the uninstaller itself).
2008 *
2009 * Create a batch file to first remove the uninstaller
2010 * (will succeed after it has finished), then the batch file itself.
2011 *
2012 * This technique has been demonstrated by Jeff Richter,
2013 * MSJ 1/1996
2014 */
2015void remove_exe(void)
2016{
2017 char exename[_MAX_PATH];
2018 char batname[_MAX_PATH];
2019 FILE *fp;
2020 STARTUPINFO si;
2021 PROCESS_INFORMATION pi;
2022
2023 GetModuleFileName(NULL, exename, sizeof(exename));
2024 sprintf(batname, "%s.bat", exename);
2025 fp = fopen(batname, "w");
2026 fprintf(fp, ":Repeat\n");
2027 fprintf(fp, "del \"%s\"\n", exename);
2028 fprintf(fp, "if exist \"%s\" goto Repeat\n", exename);
2029 fprintf(fp, "del \"%s\"\n", batname);
2030 fclose(fp);
2031
2032 ZeroMemory(&si, sizeof(si));
2033 si.cb = sizeof(si);
2034 si.dwFlags = STARTF_USESHOWWINDOW;
2035 si.wShowWindow = SW_HIDE;
2036 if (CreateProcess(NULL,
2037 batname,
2038 NULL,
2039 NULL,
2040 FALSE,
2041 CREATE_SUSPENDED | IDLE_PRIORITY_CLASS,
2042 NULL,
2043 "\\",
2044 &si,
2045 &pi)) {
2046 SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE);
2047 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
2048 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
2049 CloseHandle(pi.hProcess);
2050 ResumeThread(pi.hThread);
2051 CloseHandle(pi.hThread);
2052 }
2053}
2054
2055void DeleteRegistryKey(char *string)
2056{
2057 char *keyname;
2058 char *subkeyname;
2059 char *delim;
2060 HKEY hKey;
2061 long result;
2062 char *line;
2063
2064 line = strdup(string); /* so we can change it */
2065
2066 keyname = strchr(line, '[');
2067 if (!keyname)
2068 return;
2069 ++keyname;
2070
2071 subkeyname = strchr(keyname, ']');
2072 if (!subkeyname)
2073 return;
2074 *subkeyname++='\0';
2075 delim = strchr(subkeyname, '\n');
2076 if (delim)
2077 *delim = '\0';
2078
2079 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
2080 keyname,
2081 0,
2082 KEY_WRITE,
2083 &hKey);
2084
2085 if (result != ERROR_SUCCESS)
2086 MessageBox(GetFocus(), string, "Could not open key", MB_OK);
2087 else {
2088 result = RegDeleteKey(hKey, subkeyname);
2089 if (result != ERROR_SUCCESS)
2090 MessageBox(GetFocus(), string, "Could not delete key", MB_OK);
2091 RegCloseKey(hKey);
2092 }
2093 free(line);
2094}
2095
2096void DeleteRegistryValue(char *string)
2097{
2098 char *keyname;
2099 char *valuename;
2100 char *value;
2101 HKEY hKey;
2102 long result;
2103 char *line;
2104
2105 line = strdup(string); /* so we can change it */
2106
2107/* Format is 'Reg DB Value: [key]name=value' */
2108 keyname = strchr(line, '[');
2109 if (!keyname)
2110 return;
2111 ++keyname;
2112 valuename = strchr(keyname, ']');
2113 if (!valuename)
2114 return;
2115 *valuename++ = '\0';
2116 value = strchr(valuename, '=');
2117 if (!value)
2118 return;
2119
2120 *value++ = '\0';
2121
2122 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
2123 keyname,
2124 0,
2125 KEY_WRITE,
2126 &hKey);
2127 if (result != ERROR_SUCCESS)
2128 MessageBox(GetFocus(), string, "Could not open key", MB_OK);
2129 else {
2130 result = RegDeleteValue(hKey, valuename);
2131 if (result != ERROR_SUCCESS)
2132 MessageBox(GetFocus(), string, "Could not delete value", MB_OK);
2133 RegCloseKey(hKey);
2134 }
2135 free(line);
2136}
2137
2138BOOL MyDeleteFile(char *line)
2139{
2140 char *pathname = strchr(line, ':');
2141 if (!pathname)
2142 return FALSE;
2143 ++pathname;
2144 while (isspace(*pathname))
2145 ++pathname;
2146 return DeleteFile(pathname);
2147}
2148
2149BOOL MyRemoveDirectory(char *line)
2150{
2151 char *pathname = strchr(line, ':');
2152 if (!pathname)
2153 return FALSE;
2154 ++pathname;
2155 while (isspace(*pathname))
2156 ++pathname;
2157 return RemoveDirectory(pathname);
2158}
2159
2160BOOL Run_RemoveScript(char *line)
2161{
2162 char *dllname;
2163 char *scriptname;
2164 static char lastscript[MAX_PATH];
2165
2166/* Format is 'Run Scripts: [pythondll]scriptname' */
2167/* XXX Currently, pythondll carries no path!!! */
2168 dllname = strchr(line, '[');
2169 if (!dllname)
2170 return FALSE;
2171 ++dllname;
2172 scriptname = strchr(dllname, ']');
2173 if (!scriptname)
2174 return FALSE;
2175 *scriptname++ = '\0';
2176 /* this function may be called more than one time with the same
2177 script, only run it one time */
2178 if (strcmp(lastscript, scriptname)) {
2179 HINSTANCE hPython;
2180 char *argv[3] = {NULL, "-remove", NULL};
2181 char buffer[4096];
2182 FILE *fp;
2183 char *tempname;
2184 int n;
2185
2186 argv[0] = scriptname;
2187
2188 tempname = tmpnam(NULL);
2189
2190 if (!freopen(tempname, "a", stderr))
2191 MessageBox(GetFocus(), "freopen stderr", NULL, MB_OK);
2192 if (!freopen(tempname, "a", stdout))
2193 MessageBox(GetFocus(), "freopen stdout", NULL, MB_OK);
2194
2195 hPython = LoadLibrary(dllname);
2196 if (hPython) {
2197 if (0x80000000 == run_installscript(hPython, scriptname, 2, argv))
2198 fprintf(stderr, "*** Could not load Python ***");
2199 FreeLibrary(hPython);
2200 }
2201
2202 fflush(stderr);
2203 fflush(stdout);
2204
2205 fp = fopen(tempname, "rb");
2206 n = fread(buffer, 1, sizeof(buffer), fp);
2207 fclose(fp);
2208 remove(tempname);
2209
2210 buffer[n] = '\0';
2211 if (buffer[0])
2212 MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK);
2213
2214 strcpy(lastscript, scriptname);
2215 }
2216 return TRUE;
2217}
2218
2219int DoUninstall(int argc, char **argv)
2220{
2221 FILE *logfile;
2222 char buffer[4096];
2223 int nLines = 0;
2224 int i;
2225 char *cp;
2226 int nFiles = 0;
2227 int nDirs = 0;
2228 int nErrors = 0;
2229 char **lines;
2230 int lines_buffer_size = 10;
2231
2232 if (argc != 3) {
2233 MessageBox(NULL,
2234 "Wrong number of args",
2235 NULL,
2236 MB_OK);
2237 return 1; /* Error */
2238 }
2239 if (strcmp(argv[1], "-u")) {
2240 MessageBox(NULL,
2241 "2. arg is not -u",
2242 NULL,
2243 MB_OK);
2244 return 1; /* Error */
2245 }
2246
2247 {
2248 DWORD result;
2249 HKEY hKey;
2250 static char KeyName[] =
2251 "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
2252
2253 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
2254 KeyName,
2255 0,
2256 KEY_CREATE_SUB_KEY,
2257 &hKey);
2258 if (result == ERROR_ACCESS_DENIED) {
2259 MessageBox(GetFocus(),
2260 "You do not seem to have sufficient access rights\n"
2261 "on this machine to uninstall this software",
2262 NULL,
2263 MB_OK | MB_ICONSTOP);
2264 return 1; /* Error */
2265 }
2266 RegCloseKey(hKey);
2267 }
2268
2269 logfile = fopen(argv[2], "r");
2270 if (!logfile) {
2271 MessageBox(NULL,
2272 "could not open logfile",
2273 NULL,
2274 MB_OK);
2275 return 1; /* Error */
2276 }
2277
2278 lines = (char **)malloc(sizeof(char *) * lines_buffer_size);
2279 if (!lines)
2280 return SystemError(0, "Out of memory");
2281
2282 /* Read the whole logfile, realloacting the buffer */
2283 while (fgets(buffer, sizeof(buffer), logfile)) {
2284 int len = strlen(buffer);
2285 /* remove trailing white space */
2286 while (isspace(buffer[len-1]))
2287 len -= 1;
2288 buffer[len] = '\0';
2289 lines[nLines++] = strdup(buffer);
2290 if (nLines >= lines_buffer_size) {
2291 lines_buffer_size += 10;
2292 lines = (char **)realloc(lines,
2293 sizeof(char *) * lines_buffer_size);
2294 if (!lines)
2295 return SystemError(0, "Out of memory");
2296 }
2297 }
2298 fclose(logfile);
2299
2300 /* Sort all the lines, so that highest 3-digit codes are first */
2301 qsort(&lines[0], nLines, sizeof(char *),
2302 compare);
2303
2304 if (IDYES != MessageBox(NULL,
2305 "Are you sure you want to remove\n"
2306 "this package from your computer?",
2307 "Please confirm",
2308 MB_YESNO | MB_ICONQUESTION))
2309 return 0;
2310
2311 cp = "";
2312 for (i = 0; i < nLines; ++i) {
2313 /* Ignore duplicate lines */
2314 if (strcmp(cp, lines[i])) {
2315 int ign;
2316 cp = lines[i];
2317 /* Parse the lines */
2318 if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) {
2319 if (MyRemoveDirectory(cp))
2320 ++nDirs;
2321 else {
2322 int code = GetLastError();
2323 if (code != 2 && code != 3) { /* file or path not found */
2324 ++nErrors;
2325 }
2326 }
2327 } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) {
2328 if (MyDeleteFile(cp))
2329 ++nFiles;
2330 else {
2331 int code = GetLastError();
2332 if (code != 2 && code != 3) { /* file or path not found */
2333 ++nErrors;
2334 }
2335 }
2336 } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) {
2337 if (MyDeleteFile(cp))
2338 ++nFiles;
2339 else {
2340 int code = GetLastError();
2341 if (code != 2 && code != 3) { /* file or path not found */
2342 ++nErrors;
2343 }
2344 }
2345 } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) {
2346 DeleteRegistryKey(cp);
2347 } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) {
2348 DeleteRegistryValue(cp);
2349 } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) {
2350 Run_RemoveScript(cp);
2351 }
2352 }
2353 }
2354
2355 if (DeleteFile(argv[2])) {
2356 ++nFiles;
2357 } else {
2358 ++nErrors;
2359 SystemError(GetLastError(), argv[2]);
2360 }
2361 if (nErrors)
2362 wsprintf(buffer,
2363 "%d files and %d directories removed\n"
2364 "%d files or directories could not be removed",
2365 nFiles, nDirs, nErrors);
2366 else
2367 wsprintf(buffer, "%d files and %d directories removed",
2368 nFiles, nDirs);
2369 MessageBox(NULL, buffer, "Uninstall Finished!",
2370 MB_OK | MB_ICONINFORMATION);
2371 remove_exe();
2372 return 0;
2373}
2374
2375int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst,
2376 LPSTR lpszCmdLine, INT nCmdShow)
2377{
2378 extern int __argc;
2379 extern char **__argv;
2380 char *basename;
2381
2382 GetModuleFileName(NULL, modulename, sizeof(modulename));
2383
2384 /* Map the executable file to memory */
2385 arc_data = MapExistingFile(modulename, &arc_size);
2386 if (!arc_data) {
2387 SystemError(GetLastError(), "Could not open archive");
2388 return 1;
2389 }
2390
2391 /* OK. So this program can act as installer (self-extracting
2392 * zip-file, or as uninstaller when started with '-u logfile'
2393 * command line flags.
2394 *
2395 * The installer is usually started without command line flags,
2396 * and the uninstaller is usually started with the '-u logfile'
2397 * flag. What to do if some innocent user double-clicks the
2398 * exe-file?
2399 * The following implements a defensive strategy...
2400 */
2401
2402 /* Try to extract the configuration data into a temporary file */
Thomas Hellera19cdad2004-02-20 14:43:21 +00002403 if (ExtractInstallData(arc_data, arc_size, &exe_size,
2404 &ini_file, &pre_install_script))
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00002405 return DoInstall();
2406
2407 if (!ini_file && __argc > 1) {
2408 return DoUninstall(__argc, __argv);
2409 }
2410
2411
2412 basename = strrchr(modulename, '\\');
2413 if (basename)
2414 ++basename;
2415
2416 /* Last guess about the purpose of this program */
2417 if (basename && (0 == strncmp(basename, "Remove", 6)))
2418 SystemError(0, "This program is normally started by windows");
2419 else
2420 SystemError(0, "Setup program invalid or damaged");
2421 return 1;
2422}