blob: a715528f9ad77c80170ad85f2366df1028524b4c [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 Heller48340392004-06-18 17:03:38 +0000593static HINSTANCE LoadPythonDll(char *fname)
594{
595 char fullpath[_MAX_PATH];
596 LONG size = sizeof(fullpath);
597 HINSTANCE h = LoadLibrary(fname);
598 if (h)
599 return h;
600 if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER,
601 "SOFTWARE\\Python\\PythonCore\\2.3\\InstallPath",
602 fullpath, &size))
603 return NULL;
604 strcat(fullpath, "\\");
605 strcat(fullpath, fname);
606 return LoadLibrary(fullpath);
607}
608
Thomas Hellera19cdad2004-02-20 14:43:21 +0000609static int prepare_script_environment(HINSTANCE hPython)
610{
611 PyObject *mod;
612 DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *));
613 DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *));
614 DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *));
615 DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *));
616 DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...));
617 DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...));
618 DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *));
619 if (!PyImport_ImportModule || !PyObject_GetAttrString ||
620 !PyObject_SetAttrString || !PyCFunction_New)
621 return 1;
622 if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format)
623 return 1;
624
625 mod = PyImport_ImportModule("__builtin__");
626 if (mod) {
627 int i;
628 g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError");
629 g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError");
630 for (i = 0; i < DIM(meth); ++i) {
631 PyObject_SetAttrString(mod, meth[i].ml_name,
632 PyCFunction_New(&meth[i], NULL));
633 }
634 }
635 g_Py_BuildValue = Py_BuildValue;
636 g_PyArg_ParseTuple = PyArg_ParseTuple;
637 g_PyErr_Format = PyErr_Format;
638
639 return 0;
640}
641
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000642/*
643 * This function returns one of the following error codes:
644 * 1 if the Python-dll does not export the functions we need
645 * 2 if no install-script is specified in pathname
646 * 3 if the install-script file could not be opened
647 * the return value of PyRun_SimpleFile() otherwise,
648 * which is 0 if everything is ok, -1 if an exception had occurred
649 * in the install-script.
650 */
651
652static int
653run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv)
654{
655 DECLPROC(hPython, void, Py_Initialize, (void));
656 DECLPROC(hPython, int, PySys_SetArgv, (int, char **));
657 DECLPROC(hPython, int, PyRun_SimpleFile, (FILE *, char *));
658 DECLPROC(hPython, void, Py_Finalize, (void));
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000659 DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...));
660 DECLPROC(hPython, PyObject *, PyCFunction_New,
661 (PyMethodDef *, PyObject *));
662 DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...));
663 DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *));
664
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000665 int result = 0;
666 FILE *fp;
667
668 if (!Py_Initialize || !PySys_SetArgv
669 || !PyRun_SimpleFile || !Py_Finalize)
670 return 1;
671
Thomas Hellera19cdad2004-02-20 14:43:21 +0000672 if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format)
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000673 return 1;
674
675 if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format)
676 return 1;
677
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000678 if (pathname == NULL || pathname[0] == '\0')
679 return 2;
680
681 fp = fopen(pathname, "r");
682 if (!fp) {
683 fprintf(stderr, "Could not open postinstall-script %s\n",
684 pathname);
685 return 3;
686 }
687
688 SetDlgItemText(hDialog, IDC_INFO, "Running Script...");
689
690 Py_Initialize();
691
Thomas Hellera19cdad2004-02-20 14:43:21 +0000692 prepare_script_environment(hPython);
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000693 PySys_SetArgv(argc, argv);
694 result = PyRun_SimpleFile(fp, pathname);
695 Py_Finalize();
696
697 fclose(fp);
698
699 return result;
700}
701
Thomas Hellera19cdad2004-02-20 14:43:21 +0000702static int do_run_simple_script(HINSTANCE hPython, char *script)
703{
704 int rc;
705 DECLPROC(hPython, void, Py_Initialize, (void));
706 DECLPROC(hPython, void, Py_SetProgramName, (char *));
707 DECLPROC(hPython, void, Py_Finalize, (void));
708 DECLPROC(hPython, int, PyRun_SimpleString, (char *));
709 DECLPROC(hPython, void, PyErr_Print, (void));
710
711 if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize ||
712 !PyRun_SimpleString || !PyErr_Print)
713 return -1;
714
715 Py_SetProgramName(modulename);
716 Py_Initialize();
717 prepare_script_environment(hPython);
718 rc = PyRun_SimpleString(script);
719 if (rc)
720 PyErr_Print();
721 Py_Finalize();
722 return rc;
723}
724
725static int run_simple_script(char *script)
726{
727 int rc;
728 char *tempname;
729 HINSTANCE hPython;
730 tempname = tmpnam(NULL);
731 freopen(tempname, "a", stderr);
732 freopen(tempname, "a", stdout);
733
Thomas Heller48340392004-06-18 17:03:38 +0000734 hPython = LoadPythonDll(pythondll);
Thomas Hellera19cdad2004-02-20 14:43:21 +0000735 if (!hPython) {
736 set_failure_reason("Can't load Python for pre-install script");
737 return -1;
738 }
739 rc = do_run_simple_script(hPython, script);
740 FreeLibrary(hPython);
741 fflush(stderr);
742 fflush(stdout);
743 /* We only care about the output when we fail. If the script works
744 OK, then we discard it
745 */
746 if (rc) {
747 int err_buf_size;
748 char *err_buf;
749 const char *prefix = "Running the pre-installation script failed\r\n";
750 int prefix_len = strlen(prefix);
751 FILE *fp = fopen(tempname, "rb");
752 fseek(fp, 0, SEEK_END);
753 err_buf_size = ftell(fp);
754 fseek(fp, 0, SEEK_SET);
755 err_buf = malloc(prefix_len + err_buf_size + 1);
756 if (err_buf) {
757 int n;
758 strcpy(err_buf, prefix);
759 n = fread(err_buf+prefix_len, 1, err_buf_size, fp);
760 err_buf[prefix_len+n] = '\0';
761 fclose(fp);
762 set_failure_reason(err_buf);
763 free(err_buf);
764 } else {
765 set_failure_reason("Out of memory!");
766 }
767 }
768 remove(tempname);
769 return rc;
770}
771
772
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000773static BOOL SystemError(int error, char *msg)
774{
775 char Buffer[1024];
776 int n;
777
778 if (error) {
779 LPVOID lpMsgBuf;
780 FormatMessage(
781 FORMAT_MESSAGE_ALLOCATE_BUFFER |
782 FORMAT_MESSAGE_FROM_SYSTEM,
783 NULL,
784 error,
785 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
786 (LPSTR)&lpMsgBuf,
787 0,
788 NULL
789 );
790 strncpy(Buffer, lpMsgBuf, sizeof(Buffer));
791 LocalFree(lpMsgBuf);
792 } else
793 Buffer[0] = '\0';
794 n = lstrlen(Buffer);
795 _snprintf(Buffer+n, sizeof(Buffer)-n, msg);
796 MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP);
797 return FALSE;
798}
799
800static BOOL AskOverwrite(char *filename)
801{
802 int result;
803 again:
804 if (allow_overwrite == ALWAYS)
805 return TRUE;
806 if (allow_overwrite == NEVER)
807 return FALSE;
808 result = MessageBox(hDialog,
809 "Overwrite existing files?\n"
810 "\n"
811 "Press YES to ALWAYS overwrite existing files,\n"
812 "press NO to NEVER overwrite existing files.",
813 "Overwrite options",
814 MB_YESNO | MB_ICONQUESTION);
815 if (result == IDYES)
816 allow_overwrite = ALWAYS;
817 else if (result == IDNO)
818 allow_overwrite = NEVER;
819 goto again;
820}
821
822static BOOL notify (int code, char *fmt, ...)
823{
824 char Buffer[1024];
825 va_list marker;
826 BOOL result = TRUE;
827 int a, b;
828 char *cp;
829
830 va_start(marker, fmt);
831 _vsnprintf(Buffer, sizeof(Buffer), fmt, marker);
832
833 switch (code) {
834/* Questions */
835 case CAN_OVERWRITE:
836 result = AskOverwrite(Buffer);
837 break;
838
839/* Information notification */
840 case DIR_CREATED:
841 if (logfile)
842 fprintf(logfile, "100 Made Dir: %s\n", fmt);
843 break;
844
845 case FILE_CREATED:
846 if (logfile)
847 fprintf(logfile, "200 File Copy: %s\n", fmt);
848 goto add_to_filelist_label;
849 break;
850
851 case FILE_OVERWRITTEN:
852 if (logfile)
853 fprintf(logfile, "200 File Overwrite: %s\n", fmt);
854 add_to_filelist_label:
855 if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py")))
856 add_to_filelist(fmt);
857 break;
858
859/* Error Messages */
860 case ZLIB_ERROR:
861 MessageBox(GetFocus(), Buffer, "Error",
862 MB_OK | MB_ICONWARNING);
863 break;
864
865 case SYSTEM_ERROR:
866 SystemError(GetLastError(), Buffer);
867 break;
868
869 case NUM_FILES:
870 a = va_arg(marker, int);
871 b = va_arg(marker, int);
872 SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a));
873 SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt);
874 }
875 va_end(marker);
876
877 return result;
878}
879
880static char *MapExistingFile(char *pathname, DWORD *psize)
881{
882 HANDLE hFile, hFileMapping;
883 DWORD nSizeLow, nSizeHigh;
884 char *data;
885
886 hFile = CreateFile(pathname,
887 GENERIC_READ, FILE_SHARE_READ, NULL,
888 OPEN_EXISTING,
889 FILE_ATTRIBUTE_NORMAL, NULL);
890 if (hFile == INVALID_HANDLE_VALUE)
891 return NULL;
892 nSizeLow = GetFileSize(hFile, &nSizeHigh);
893 hFileMapping = CreateFileMapping(hFile,
894 NULL, PAGE_READONLY, 0, 0, NULL);
895 CloseHandle(hFile);
896
897 if (hFileMapping == INVALID_HANDLE_VALUE)
898 return NULL;
899
900 data = MapViewOfFile(hFileMapping,
901 FILE_MAP_READ, 0, 0, 0);
902
903 CloseHandle(hFileMapping);
904 *psize = nSizeLow;
905 return data;
906}
907
908
909static void create_bitmap(HWND hwnd)
910{
911 BITMAPFILEHEADER *bfh;
912 BITMAPINFO *bi;
913 HDC hdc;
914
915 if (!bitmap_bytes)
916 return;
917
918 if (hBitmap)
919 return;
920
921 hdc = GetDC(hwnd);
922
923 bfh = (BITMAPFILEHEADER *)bitmap_bytes;
924 bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER));
925
926 hBitmap = CreateDIBitmap(hdc,
927 &bi->bmiHeader,
928 CBM_INIT,
929 bitmap_bytes + bfh->bfOffBits,
930 bi,
931 DIB_RGB_COLORS);
932 ReleaseDC(hwnd, hdc);
933}
934
Thomas Hellera19cdad2004-02-20 14:43:21 +0000935/* Extract everything we need to begin the installation. Currently this
936 is the INI filename with install data, and the raw pre-install script
937*/
938static BOOL ExtractInstallData(char *data, DWORD size, int *pexe_size,
939 char **out_ini_file, char **out_preinstall_script)
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000940{
941 /* read the end of central directory record */
942 struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof
943 (struct eof_cdir)];
944
945 int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir -
946 pe->ofsCDir;
947
948 int ofs = arc_start - sizeof (struct meta_data_hdr);
949
950 /* read meta_data info */
951 struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs];
952 char *src, *dst;
953 char *ini_file;
954 char tempdir[MAX_PATH];
955
Thomas Hellera19cdad2004-02-20 14:43:21 +0000956 /* ensure that if we fail, we don't have garbage out pointers */
957 *out_ini_file = *out_preinstall_script = NULL;
958
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000959 if (pe->tag != 0x06054b50) {
Thomas Hellera19cdad2004-02-20 14:43:21 +0000960 return FALSE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000961 }
962
963 if (pmd->tag != 0x1234567A || ofs < 0) {
Thomas Hellera19cdad2004-02-20 14:43:21 +0000964 return FALSE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000965 }
966
967 if (pmd->bitmap_size) {
968 /* Store pointer to bitmap bytes */
969 bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size;
970 }
971
972 *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size;
973
974 src = ((char *)pmd) - pmd->uncomp_size;
975 ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */
976 if (!ini_file)
Thomas Hellera19cdad2004-02-20 14:43:21 +0000977 return FALSE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000978 if (!GetTempPath(sizeof(tempdir), tempdir)
979 || !GetTempFileName(tempdir, "~du", 0, ini_file)) {
980 SystemError(GetLastError(),
981 "Could not create temporary file");
Thomas Hellera19cdad2004-02-20 14:43:21 +0000982 return FALSE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000983 }
984
985 dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size,
986 0, 0, NULL/*notify*/);
987 if (!dst)
Thomas Hellera19cdad2004-02-20 14:43:21 +0000988 return FALSE;
989 /* Up to the first \0 is the INI file data. */
990 strncpy(dst, src, pmd->uncomp_size);
991 src += strlen(dst) + 1;
992 /* Up to next \0 is the pre-install script */
993 *out_preinstall_script = strdup(src);
994 *out_ini_file = ini_file;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000995 UnmapViewOfFile(dst);
Thomas Hellera19cdad2004-02-20 14:43:21 +0000996 return TRUE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +0000997}
998
999static void PumpMessages(void)
1000{
1001 MSG msg;
1002 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
1003 TranslateMessage(&msg);
1004 DispatchMessage(&msg);
1005 }
1006}
1007
1008LRESULT CALLBACK
1009WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1010{
1011 HDC hdc;
1012 HFONT hFont;
1013 int h;
1014 PAINTSTRUCT ps;
1015 switch (msg) {
1016 case WM_PAINT:
1017 hdc = BeginPaint(hwnd, &ps);
1018 h = GetSystemMetrics(SM_CYSCREEN) / 10;
1019 hFont = CreateFont(h, 0, 0, 0, 700, TRUE,
1020 0, 0, 0, 0, 0, 0, 0, "Times Roman");
1021 hFont = SelectObject(hdc, hFont);
1022 SetBkMode(hdc, TRANSPARENT);
1023 TextOut(hdc, 15, 15, title, strlen(title));
1024 SetTextColor(hdc, RGB(255, 255, 255));
1025 TextOut(hdc, 10, 10, title, strlen(title));
1026 DeleteObject(SelectObject(hdc, hFont));
1027 EndPaint(hwnd, &ps);
1028 return 0;
1029 }
1030 return DefWindowProc(hwnd, msg, wParam, lParam);
1031}
1032
1033static HWND CreateBackground(char *title)
1034{
1035 WNDCLASS wc;
1036 HWND hwnd;
1037 char buffer[4096];
1038
1039 wc.style = CS_VREDRAW | CS_HREDRAW;
1040 wc.lpfnWndProc = WindowProc;
1041 wc.cbWndExtra = 0;
1042 wc.cbClsExtra = 0;
1043 wc.hInstance = GetModuleHandle(NULL);
1044 wc.hIcon = NULL;
1045 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
1046 wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128));
1047 wc.lpszMenuName = NULL;
1048 wc.lpszClassName = "SetupWindowClass";
1049
1050 if (!RegisterClass(&wc))
1051 MessageBox(hwndMain,
1052 "Could not register window class",
1053 "Setup.exe", MB_OK);
1054
1055 wsprintf(buffer, "Setup %s", title);
1056 hwnd = CreateWindow("SetupWindowClass",
1057 buffer,
1058 0,
1059 0, 0,
1060 GetSystemMetrics(SM_CXFULLSCREEN),
1061 GetSystemMetrics(SM_CYFULLSCREEN),
1062 NULL,
1063 NULL,
1064 GetModuleHandle(NULL),
1065 NULL);
1066 ShowWindow(hwnd, SW_SHOWMAXIMIZED);
1067 UpdateWindow(hwnd);
1068 return hwnd;
1069}
1070
1071/*
1072 * Center a window on the screen
1073 */
1074static void CenterWindow(HWND hwnd)
1075{
1076 RECT rc;
1077 int w, h;
1078
1079 GetWindowRect(hwnd, &rc);
1080 w = GetSystemMetrics(SM_CXSCREEN);
1081 h = GetSystemMetrics(SM_CYSCREEN);
1082 MoveWindow(hwnd,
1083 (w - (rc.right-rc.left))/2,
1084 (h - (rc.bottom-rc.top))/2,
1085 rc.right-rc.left, rc.bottom-rc.top, FALSE);
1086}
1087
1088#include <prsht.h>
1089
1090BOOL CALLBACK
1091IntroDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1092{
1093 LPNMHDR lpnm;
1094 char Buffer[4096];
1095
1096 switch (msg) {
1097 case WM_INITDIALOG:
1098 create_bitmap(hwnd);
1099 if(hBitmap)
1100 SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
1101 IMAGE_BITMAP, (LPARAM)hBitmap);
1102 CenterWindow(GetParent(hwnd));
1103 wsprintf(Buffer,
1104 "This Wizard will install %s on your computer. "
1105 "Click Next to continue "
1106 "or Cancel to exit the Setup Wizard.",
1107 meta_name);
1108 SetDlgItemText(hwnd, IDC_TITLE, Buffer);
1109 SetDlgItemText(hwnd, IDC_INTRO_TEXT, info);
1110 SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info);
1111 return FALSE;
1112
1113 case WM_NOTIFY:
1114 lpnm = (LPNMHDR) lParam;
1115
1116 switch (lpnm->code) {
1117 case PSN_SETACTIVE:
1118 PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT);
1119 break;
1120
1121 case PSN_WIZNEXT:
1122 break;
1123
1124 case PSN_RESET:
1125 break;
1126
1127 default:
1128 break;
1129 }
1130 }
1131 return FALSE;
1132}
1133
1134#ifdef USE_OTHER_PYTHON_VERSIONS
1135/* These are really private variables used to communicate
1136 * between StatusRoutine and CheckPythonExe
1137 */
1138char bound_image_dll[_MAX_PATH];
1139int bound_image_major;
1140int bound_image_minor;
1141
1142static BOOL __stdcall StatusRoutine(IMAGEHLP_STATUS_REASON reason,
1143 PSTR ImageName,
1144 PSTR DllName,
1145 ULONG Va,
1146 ULONG Parameter)
1147{
1148 char fname[_MAX_PATH];
1149 int int_version;
1150
1151 switch(reason) {
1152 case BindOutOfMemory:
1153 case BindRvaToVaFailed:
1154 case BindNoRoomInImage:
1155 case BindImportProcedureFailed:
1156 break;
1157
1158 case BindImportProcedure:
1159 case BindForwarder:
1160 case BindForwarderNOT:
1161 case BindImageModified:
1162 case BindExpandFileHeaders:
1163 case BindImageComplete:
1164 case BindSymbolsNotUpdated:
1165 case BindMismatchedSymbols:
1166 case BindImportModuleFailed:
1167 break;
1168
1169 case BindImportModule:
1170 if (1 == sscanf(DllName, "python%d", &int_version)) {
1171 SearchPath(NULL, DllName, NULL, sizeof(fname),
1172 fname, NULL);
1173 strcpy(bound_image_dll, fname);
1174 bound_image_major = int_version / 10;
1175 bound_image_minor = int_version % 10;
1176 OutputDebugString("BOUND ");
1177 OutputDebugString(fname);
1178 OutputDebugString("\n");
1179 }
1180 break;
1181 }
1182 return TRUE;
1183}
1184
1185/*
1186 */
1187static LPSTR get_sys_prefix(LPSTR exe, LPSTR dll)
1188{
1189 void (__cdecl * Py_Initialize)(void);
1190 void (__cdecl * Py_SetProgramName)(char *);
1191 void (__cdecl * Py_Finalize)(void);
1192 void* (__cdecl * PySys_GetObject)(char *);
1193 void (__cdecl * PySys_SetArgv)(int, char **);
1194 char* (__cdecl * Py_GetPrefix)(void);
1195 char* (__cdecl * Py_GetPath)(void);
1196 HINSTANCE hPython;
1197 LPSTR prefix = NULL;
1198 int (__cdecl * PyRun_SimpleString)(char *);
1199
1200 {
1201 char Buffer[256];
1202 wsprintf(Buffer, "PYTHONHOME=%s", exe);
1203 *strrchr(Buffer, '\\') = '\0';
1204// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK);
1205 _putenv(Buffer);
1206 _putenv("PYTHONPATH=");
1207 }
1208
1209 hPython = LoadLibrary(dll);
1210 if (!hPython)
1211 return NULL;
1212 Py_Initialize = (void (*)(void))GetProcAddress
1213 (hPython,"Py_Initialize");
1214
1215 PySys_SetArgv = (void (*)(int, char **))GetProcAddress
1216 (hPython,"PySys_SetArgv");
1217
1218 PyRun_SimpleString = (int (*)(char *))GetProcAddress
1219 (hPython,"PyRun_SimpleString");
1220
1221 Py_SetProgramName = (void (*)(char *))GetProcAddress
1222 (hPython,"Py_SetProgramName");
1223
1224 PySys_GetObject = (void* (*)(char *))GetProcAddress
1225 (hPython,"PySys_GetObject");
1226
1227 Py_GetPrefix = (char * (*)(void))GetProcAddress
1228 (hPython,"Py_GetPrefix");
1229
1230 Py_GetPath = (char * (*)(void))GetProcAddress
1231 (hPython,"Py_GetPath");
1232
1233 Py_Finalize = (void (*)(void))GetProcAddress(hPython,
1234 "Py_Finalize");
1235 Py_SetProgramName(exe);
1236 Py_Initialize();
1237 PySys_SetArgv(1, &exe);
1238
1239 MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK);
1240 MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK);
1241
1242 Py_Finalize();
1243 FreeLibrary(hPython);
1244
1245 return prefix;
1246}
1247
1248static BOOL
1249CheckPythonExe(LPSTR pathname, LPSTR version, int *pmajor, int *pminor)
1250{
1251 bound_image_dll[0] = '\0';
1252 if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES,
1253 pathname,
1254 NULL,
1255 NULL,
1256 StatusRoutine))
1257 return SystemError(0, "Could not bind image");
1258 if (bound_image_dll[0] == '\0')
1259 return SystemError(0, "Does not seem to be a python executable");
1260 *pmajor = bound_image_major;
1261 *pminor = bound_image_minor;
1262 if (version && *version) {
1263 char core_version[12];
1264 wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor);
1265 if (strcmp(version, core_version))
1266 return SystemError(0, "Wrong Python version");
1267 }
1268 get_sys_prefix(pathname, bound_image_dll);
1269 return TRUE;
1270}
1271
1272/*
1273 * Browse for other python versions. Insert it into the listbox specified
1274 * by hwnd. version, if not NULL or empty, is the version required.
1275 */
1276static BOOL GetOtherPythonVersion(HWND hwnd, LPSTR version)
1277{
1278 char vers_name[_MAX_PATH + 80];
1279 DWORD itemindex;
1280 OPENFILENAME of;
1281 char pathname[_MAX_PATH];
1282 DWORD result;
1283
1284 strcpy(pathname, "python.exe");
1285
1286 memset(&of, 0, sizeof(of));
1287 of.lStructSize = sizeof(OPENFILENAME);
1288 of.hwndOwner = GetParent(hwnd);
1289 of.hInstance = NULL;
1290 of.lpstrFilter = "python.exe\0python.exe\0";
1291 of.lpstrCustomFilter = NULL;
1292 of.nMaxCustFilter = 0;
1293 of.nFilterIndex = 1;
1294 of.lpstrFile = pathname;
1295 of.nMaxFile = sizeof(pathname);
1296 of.lpstrFileTitle = NULL;
1297 of.nMaxFileTitle = 0;
1298 of.lpstrInitialDir = NULL;
1299 of.lpstrTitle = "Python executable";
1300 of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
1301 of.lpstrDefExt = "exe";
1302
1303 result = GetOpenFileName(&of);
1304 if (result) {
1305 int major, minor;
1306 if (!CheckPythonExe(pathname, version, &major, &minor)) {
1307 return FALSE;
1308 }
1309 *strrchr(pathname, '\\') = '\0';
1310 wsprintf(vers_name, "Python Version %d.%d in %s",
1311 major, minor, pathname);
1312 itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1,
1313 (LPARAM)(LPSTR)vers_name);
1314 SendMessage(hwnd, LB_SETCURSEL, itemindex, 0);
1315 SendMessage(hwnd, LB_SETITEMDATA, itemindex,
1316 (LPARAM)(LPSTR)strdup(pathname));
1317 return TRUE;
1318 }
1319 return FALSE;
1320}
1321#endif /* USE_OTHER_PYTHON_VERSIONS */
1322
1323
1324/*
1325 * Fill the listbox specified by hwnd with all python versions found
1326 * in the registry. version, if not NULL or empty, is the version
1327 * required.
1328 */
1329static BOOL GetPythonVersions(HWND hwnd, HKEY hkRoot, LPSTR version)
1330{
1331 DWORD index = 0;
1332 char core_version[80];
1333 HKEY hKey;
1334 BOOL result = TRUE;
1335 DWORD bufsize;
1336
1337 if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot,
1338 "Software\\Python\\PythonCore",
1339 0, KEY_READ, &hKey))
1340 return FALSE;
1341 bufsize = sizeof(core_version);
1342 while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index,
1343 core_version, &bufsize, NULL,
1344 NULL, NULL, NULL)) {
1345 char subkey_name[80], vers_name[80], prefix_buf[MAX_PATH+1];
1346 int itemindex;
1347 DWORD value_size;
1348 HKEY hk;
1349
1350 bufsize = sizeof(core_version);
1351 ++index;
1352 if (version && *version && strcmp(version, core_version))
1353 continue;
1354
1355 wsprintf(vers_name, "Python Version %s (found in registry)",
1356 core_version);
1357 wsprintf(subkey_name,
1358 "Software\\Python\\PythonCore\\%s\\InstallPath",
1359 core_version);
1360 value_size = sizeof(subkey_name);
1361 if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) {
1362 if (ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL, prefix_buf,
1363 &value_size)) {
1364 itemindex = SendMessage(hwnd, LB_ADDSTRING, 0,
1365 (LPARAM)(LPSTR)vers_name);
1366 SendMessage(hwnd, LB_SETITEMDATA, itemindex,
1367 (LPARAM)(LPSTR)strdup(prefix_buf));
1368 }
1369 RegCloseKey(hk);
1370 }
1371 }
1372 RegCloseKey(hKey);
1373 return result;
1374}
1375
1376/* Return the installation scheme depending on Python version number */
1377SCHEME *GetScheme(int major, int minor)
1378{
1379 if (major > 2)
1380 return new_scheme;
1381 else if((major == 2) && (minor >= 2))
1382 return new_scheme;
1383 return old_scheme;
1384}
1385
1386BOOL CALLBACK
1387SelectPythonDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1388{
1389 LPNMHDR lpnm;
1390
1391 switch (msg) {
1392 case WM_INITDIALOG:
1393 if (hBitmap)
1394 SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
1395 IMAGE_BITMAP, (LPARAM)hBitmap);
1396 GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
1397 HKEY_LOCAL_MACHINE, target_version);
1398 GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
1399 HKEY_CURRENT_USER, target_version);
1400 { /* select the last entry which is the highest python
1401 version found */
1402 int count;
1403 count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1404 LB_GETCOUNT, 0, 0);
1405 if (count && count != LB_ERR)
1406 SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL,
1407 count-1, 0);
1408
1409 /* If a specific Python version is required,
1410 * display a prominent notice showing this fact.
1411 */
1412 if (target_version && target_version[0]) {
1413 char buffer[4096];
1414 wsprintf(buffer,
1415 "Python %s is required for this package. "
1416 "Select installation to use:",
1417 target_version);
1418 SetDlgItemText(hwnd, IDC_TITLE, buffer);
1419 }
1420
1421 if (count == 0) {
1422 char Buffer[4096];
1423 char *msg;
1424 if (target_version && target_version[0]) {
1425 wsprintf(Buffer,
1426 "Python version %s required, which was not found"
1427 " in the registry.", target_version);
1428 msg = Buffer;
1429 } else
1430 msg = "No Python installation found in the registry.";
1431 MessageBox(hwnd, msg, "Cannot install",
1432 MB_OK | MB_ICONSTOP);
1433 }
1434 }
1435 goto UpdateInstallDir;
1436 break;
1437
1438 case WM_COMMAND:
1439 switch (LOWORD(wParam)) {
1440/*
1441 case IDC_OTHERPYTHON:
1442 if (GetOtherPythonVersion(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
1443 target_version))
1444 goto UpdateInstallDir;
1445 break;
1446*/
1447 case IDC_VERSIONS_LIST:
1448 switch (HIWORD(wParam)) {
1449 int id;
1450 char *cp;
1451 case LBN_SELCHANGE:
1452 UpdateInstallDir:
1453 PropSheet_SetWizButtons(GetParent(hwnd),
1454 PSWIZB_BACK | PSWIZB_NEXT);
1455 id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1456 LB_GETCURSEL, 0, 0);
1457 if (id == LB_ERR) {
1458 PropSheet_SetWizButtons(GetParent(hwnd),
1459 PSWIZB_BACK);
1460 SetDlgItemText(hwnd, IDC_PATH, "");
1461 SetDlgItemText(hwnd, IDC_INSTALL_PATH, "");
1462 strcpy(python_dir, "");
1463 strcpy(pythondll, "");
1464 } else {
1465 char *pbuf;
1466 int result;
1467 PropSheet_SetWizButtons(GetParent(hwnd),
1468 PSWIZB_BACK | PSWIZB_NEXT);
1469 /* Get the python directory */
1470 cp = (LPSTR)SendDlgItemMessage(hwnd,
1471 IDC_VERSIONS_LIST,
1472 LB_GETITEMDATA,
1473 id,
1474 0);
1475 strcpy(python_dir, cp);
1476 SetDlgItemText(hwnd, IDC_PATH, python_dir);
1477 /* retrieve the python version and pythondll to use */
1478 result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1479 LB_GETTEXTLEN, (WPARAM)id, 0);
1480 pbuf = (char *)malloc(result + 1);
1481 if (pbuf) {
1482 /* guess the name of the python-dll */
1483 SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1484 LB_GETTEXT, (WPARAM)id,
1485 (LPARAM)pbuf);
1486 result = sscanf(pbuf, "Python Version %d.%d",
1487 &py_major, &py_minor);
Thomas Heller96142192004-04-15 18:19:02 +00001488 if (result == 2) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001489#ifdef _DEBUG
Thomas Hellera19cdad2004-02-20 14:43:21 +00001490 wsprintf(pythondll, "python%d%d_d.dll",
Thomas Heller96142192004-04-15 18:19:02 +00001491 py_major, py_minor);
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001492#else
Thomas Heller96142192004-04-15 18:19:02 +00001493 wsprintf(pythondll, "python%d%d.dll",
1494 py_major, py_minor);
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001495#endif
Thomas Heller96142192004-04-15 18:19:02 +00001496 }
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001497 free(pbuf);
1498 } else
1499 strcpy(pythondll, "");
1500 /* retrieve the scheme for this version */
1501 {
1502 char install_path[_MAX_PATH];
1503 SCHEME *scheme = GetScheme(py_major, py_minor);
1504 strcpy(install_path, python_dir);
1505 if (install_path[strlen(install_path)-1] != '\\')
1506 strcat(install_path, "\\");
1507 strcat(install_path, scheme[0].prefix);
1508 SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path);
1509 }
1510 }
1511 }
1512 break;
1513 }
1514 return 0;
1515
1516 case WM_NOTIFY:
1517 lpnm = (LPNMHDR) lParam;
1518
1519 switch (lpnm->code) {
1520 int id;
1521 case PSN_SETACTIVE:
1522 id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
1523 LB_GETCURSEL, 0, 0);
1524 if (id == LB_ERR)
1525 PropSheet_SetWizButtons(GetParent(hwnd),
1526 PSWIZB_BACK);
1527 else
1528 PropSheet_SetWizButtons(GetParent(hwnd),
1529 PSWIZB_BACK | PSWIZB_NEXT);
1530 break;
1531
1532 case PSN_WIZNEXT:
1533 break;
1534
1535 case PSN_WIZFINISH:
1536 break;
1537
1538 case PSN_RESET:
1539 break;
1540
1541 default:
1542 break;
1543 }
1544 }
1545 return 0;
1546}
1547
1548static BOOL OpenLogfile(char *dir)
1549{
1550 char buffer[_MAX_PATH+1];
1551 time_t ltime;
1552 struct tm *now;
1553 long result;
1554 HKEY hKey, hSubkey;
1555 char subkey_name[256];
1556 static char KeyName[] =
1557 "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
1558 DWORD disposition;
1559
1560 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
1561 KeyName,
1562 0,
1563 KEY_CREATE_SUB_KEY,
1564 &hKey);
1565 if (result != ERROR_SUCCESS) {
1566 if (result == ERROR_ACCESS_DENIED) {
1567 MessageBox(GetFocus(),
1568 "You do not seem to have sufficient access rights\n"
1569 "on this machine to install this software",
1570 NULL,
1571 MB_OK | MB_ICONSTOP);
1572 return FALSE;
1573 } else {
1574 MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK);
1575 }
1576 }
1577
1578 sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name);
1579 logfile = fopen(buffer, "a");
1580 time(&ltime);
1581 now = localtime(&ltime);
1582 strftime(buffer, sizeof(buffer),
1583 "*** Installation started %Y/%m/%d %H:%M ***\n",
1584 localtime(&ltime));
1585 fprintf(logfile, buffer);
1586 fprintf(logfile, "Source: %s\n", modulename);
1587
1588 sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor);
1589
1590 result = RegCreateKeyEx(hKey, subkey_name,
1591 0, NULL, 0,
1592 KEY_WRITE,
1593 NULL,
1594 &hSubkey,
1595 &disposition);
1596
1597 if (result != ERROR_SUCCESS)
1598 MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK);
1599
1600 RegCloseKey(hKey);
1601
1602 if (disposition == REG_CREATED_NEW_KEY)
1603 fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name);
1604
1605 sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title);
1606
1607 result = RegSetValueEx(hSubkey, "DisplayName",
1608 0,
1609 REG_SZ,
1610 buffer,
1611 strlen(buffer)+1);
1612
1613 if (result != ERROR_SUCCESS)
1614 MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK);
1615
1616 fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n",
1617 KeyName, subkey_name, "DisplayName", buffer);
1618
1619 {
1620 FILE *fp;
1621 sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name);
1622 fp = fopen(buffer, "wb");
1623 fwrite(arc_data, exe_size, 1, fp);
1624 fclose(fp);
1625
1626 sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"",
1627 dir, meta_name, dir, meta_name);
1628
1629 result = RegSetValueEx(hSubkey, "UninstallString",
1630 0,
1631 REG_SZ,
1632 buffer,
1633 strlen(buffer)+1);
1634
1635 if (result != ERROR_SUCCESS)
1636 MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK);
1637
1638 fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n",
1639 KeyName, subkey_name, "UninstallString", buffer);
1640 }
1641 return TRUE;
1642}
1643
1644static void CloseLogfile(void)
1645{
1646 char buffer[_MAX_PATH+1];
1647 time_t ltime;
1648 struct tm *now;
1649
1650 time(&ltime);
1651 now = localtime(&ltime);
1652 strftime(buffer, sizeof(buffer),
1653 "*** Installation finished %Y/%m/%d %H:%M ***\n",
1654 localtime(&ltime));
1655 fprintf(logfile, buffer);
1656 if (logfile)
1657 fclose(logfile);
1658}
1659
1660BOOL CALLBACK
1661InstallFilesDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1662{
1663 LPNMHDR lpnm;
1664 char Buffer[4096];
1665 SCHEME *scheme;
1666
1667 switch (msg) {
1668 case WM_INITDIALOG:
1669 if (hBitmap)
1670 SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
1671 IMAGE_BITMAP, (LPARAM)hBitmap);
1672 wsprintf(Buffer,
1673 "Click Next to begin the installation of %s. "
1674 "If you want to review or change any of your "
1675 " installation settings, click Back. "
1676 "Click Cancel to exit the wizard.",
1677 meta_name);
1678 SetDlgItemText(hwnd, IDC_TITLE, Buffer);
Thomas Hellera19cdad2004-02-20 14:43:21 +00001679 SetDlgItemText(hwnd, IDC_INFO, "Ready to install");
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001680 break;
1681
1682 case WM_NUMFILES:
1683 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam);
1684 PumpMessages();
1685 return TRUE;
1686
1687 case WM_NEXTFILE:
1688 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam,
1689 0);
1690 SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam);
1691 PumpMessages();
1692 return TRUE;
1693
1694 case WM_NOTIFY:
1695 lpnm = (LPNMHDR) lParam;
1696
1697 switch (lpnm->code) {
1698 case PSN_SETACTIVE:
1699 PropSheet_SetWizButtons(GetParent(hwnd),
1700 PSWIZB_BACK | PSWIZB_NEXT);
1701 break;
1702
1703 case PSN_WIZFINISH:
1704 break;
1705
1706 case PSN_WIZNEXT:
1707 /* Handle a Next button click here */
1708 hDialog = hwnd;
Thomas Hellera19cdad2004-02-20 14:43:21 +00001709 success = TRUE;
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001710
1711 /* Make sure the installation directory name ends in a */
1712 /* backslash */
1713 if (python_dir[strlen(python_dir)-1] != '\\')
1714 strcat(python_dir, "\\");
1715 /* Strip the trailing backslash again */
1716 python_dir[strlen(python_dir)-1] = '\0';
1717
1718 if (!OpenLogfile(python_dir))
1719 break;
1720
1721/*
1722 * The scheme we have to use depends on the Python version...
1723 if sys.version < "2.2":
1724 WINDOWS_SCHEME = {
1725 'purelib': '$base',
1726 'platlib': '$base',
1727 'headers': '$base/Include/$dist_name',
1728 'scripts': '$base/Scripts',
1729 'data' : '$base',
1730 }
1731 else:
1732 WINDOWS_SCHEME = {
1733 'purelib': '$base/Lib/site-packages',
1734 'platlib': '$base/Lib/site-packages',
1735 'headers': '$base/Include/$dist_name',
1736 'scripts': '$base/Scripts',
1737 'data' : '$base',
1738 }
1739*/
1740 scheme = GetScheme(py_major, py_minor);
Thomas Hellera19cdad2004-02-20 14:43:21 +00001741 /* Run the pre-install script. */
1742 if (pre_install_script && *pre_install_script) {
1743 SetDlgItemText (hwnd, IDC_TITLE,
1744 "Running pre-installation script");
1745 run_simple_script(pre_install_script);
1746 }
1747 if (!success) {
1748 break;
1749 }
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001750 /* Extract all files from the archive */
1751 SetDlgItemText(hwnd, IDC_TITLE, "Installing files...");
Thomas Hellera19cdad2004-02-20 14:43:21 +00001752 if (!unzip_archive (scheme,
1753 python_dir, arc_data,
1754 arc_size, notify))
1755 set_failure_reason("Failed to unzip installation files");
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001756 /* Compile the py-files */
Thomas Hellera19cdad2004-02-20 14:43:21 +00001757 if (success && pyc_compile) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001758 int errors;
1759 HINSTANCE hPython;
1760 SetDlgItemText(hwnd, IDC_TITLE,
1761 "Compiling files to .pyc...");
1762
1763 SetDlgItemText(hDialog, IDC_INFO, "Loading python...");
Thomas Heller48340392004-06-18 17:03:38 +00001764 hPython = LoadPythonDll(pythondll);
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001765 if (hPython) {
1766 errors = compile_filelist(hPython, FALSE);
1767 FreeLibrary(hPython);
1768 }
1769 /* Compilation errors are intentionally ignored:
1770 * Python2.0 contains a bug which will result
1771 * in sys.path containing garbage under certain
1772 * circumstances, and an error message will only
1773 * confuse the user.
1774 */
1775 }
Thomas Hellera19cdad2004-02-20 14:43:21 +00001776 if (success && pyo_compile) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001777 int errors;
1778 HINSTANCE hPython;
1779 SetDlgItemText(hwnd, IDC_TITLE,
1780 "Compiling files to .pyo...");
1781
1782 SetDlgItemText(hDialog, IDC_INFO, "Loading python...");
Thomas Heller48340392004-06-18 17:03:38 +00001783 hPython = LoadPythonDll(pythondll);
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001784 if (hPython) {
1785 errors = compile_filelist(hPython, TRUE);
1786 FreeLibrary(hPython);
1787 }
1788 /* Errors ignored: see above */
1789 }
1790
1791
1792 break;
1793
1794 case PSN_RESET:
1795 break;
1796
1797 default:
1798 break;
1799 }
1800 }
1801 return 0;
1802}
1803
1804
1805BOOL CALLBACK
1806FinishedDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1807{
1808 LPNMHDR lpnm;
1809
1810 switch (msg) {
1811 case WM_INITDIALOG:
1812 if (hBitmap)
1813 SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
1814 IMAGE_BITMAP, (LPARAM)hBitmap);
1815 if (!success)
Thomas Hellera19cdad2004-02-20 14:43:21 +00001816 SetDlgItemText(hwnd, IDC_INFO, get_failure_reason());
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001817
1818 /* async delay: will show the dialog box completely before
1819 the install_script is started */
1820 PostMessage(hwnd, WM_USER, 0, 0L);
1821 return TRUE;
1822
1823 case WM_USER:
1824
Thomas Hellera19cdad2004-02-20 14:43:21 +00001825 if (success && install_script && install_script[0]) {
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001826 char fname[MAX_PATH];
1827 char *tempname;
1828 FILE *fp;
1829 char buffer[4096];
1830 int n;
1831 HCURSOR hCursor;
1832 HINSTANCE hPython;
1833
1834 char *argv[3] = {NULL, "-install", NULL};
1835
1836 SetDlgItemText(hwnd, IDC_TITLE,
1837 "Please wait while running postinstall script...");
1838 strcpy(fname, python_dir);
1839 strcat(fname, "\\Scripts\\");
1840 strcat(fname, install_script);
1841
1842 if (logfile)
1843 fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname);
1844
1845 tempname = tmpnam(NULL);
1846
1847 if (!freopen(tempname, "a", stderr))
1848 MessageBox(GetFocus(), "freopen stderr", NULL, MB_OK);
1849 if (!freopen(tempname, "a", stdout))
1850 MessageBox(GetFocus(), "freopen stdout", NULL, MB_OK);
1851/*
1852 if (0 != setvbuf(stdout, NULL, _IONBF, 0))
1853 MessageBox(GetFocus(), "setvbuf stdout", NULL, MB_OK);
1854*/
1855 hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
1856
1857 argv[0] = fname;
1858
Thomas Heller48340392004-06-18 17:03:38 +00001859 hPython = LoadPythonDll(pythondll);
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00001860 if (hPython) {
1861 int result;
1862 result = run_installscript(hPython, fname, 2, argv);
1863 if (-1 == result) {
1864 fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result);
1865 }
1866 FreeLibrary(hPython);
1867 } else {
1868 fprintf(stderr, "*** Could not load Python ***");
1869 }
1870 fflush(stderr);
1871 fflush(stdout);
1872
1873 fp = fopen(tempname, "rb");
1874 n = fread(buffer, 1, sizeof(buffer), fp);
1875 fclose(fp);
1876 remove(tempname);
1877
1878 buffer[n] = '\0';
1879
1880 SetDlgItemText(hwnd, IDC_INFO, buffer);
1881 SetDlgItemText(hwnd, IDC_TITLE,
1882 "Postinstall script finished.\n"
1883 "Click the Finish button to exit the Setup wizard.");
1884
1885 SetCursor(hCursor);
1886 CloseLogfile();
1887 }
1888
1889 return TRUE;
1890
1891 case WM_NOTIFY:
1892 lpnm = (LPNMHDR) lParam;
1893
1894 switch (lpnm->code) {
1895 case PSN_SETACTIVE: /* Enable the Finish button */
1896 PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH);
1897 break;
1898
1899 case PSN_WIZNEXT:
1900 break;
1901
1902 case PSN_WIZFINISH:
1903 break;
1904
1905 case PSN_RESET:
1906 break;
1907
1908 default:
1909 break;
1910 }
1911 }
1912 return 0;
1913}
1914
1915void RunWizard(HWND hwnd)
1916{
1917 PROPSHEETPAGE psp = {0};
1918 HPROPSHEETPAGE ahpsp[4] = {0};
1919 PROPSHEETHEADER psh = {0};
1920
1921 /* Display module information */
1922 psp.dwSize = sizeof(psp);
1923 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1924 psp.hInstance = GetModuleHandle (NULL);
1925 psp.lParam = 0;
1926 psp.pfnDlgProc = IntroDlgProc;
1927 psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO);
1928
1929 ahpsp[0] = CreatePropertySheetPage(&psp);
1930
1931 /* Select python version to use */
1932 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1933 psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON);
1934 psp.pfnDlgProc = SelectPythonDlgProc;
1935
1936 ahpsp[1] = CreatePropertySheetPage(&psp);
1937
1938 /* Install the files */
1939 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1940 psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES);
1941 psp.pfnDlgProc = InstallFilesDlgProc;
1942
1943 ahpsp[2] = CreatePropertySheetPage(&psp);
1944
1945 /* Show success or failure */
1946 psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
1947 psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED);
1948 psp.pfnDlgProc = FinishedDlgProc;
1949
1950 ahpsp[3] = CreatePropertySheetPage(&psp);
1951
1952 /* Create the property sheet */
1953 psh.dwSize = sizeof(psh);
1954 psh.hInstance = GetModuleHandle(NULL);
1955 psh.hwndParent = hwnd;
1956 psh.phpage = ahpsp;
1957 psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/;
1958 psh.pszbmWatermark = NULL;
1959 psh.pszbmHeader = NULL;
1960 psh.nStartPage = 0;
1961 psh.nPages = 4;
1962
1963 PropertySheet(&psh);
1964}
1965
1966int DoInstall(void)
1967{
1968 char ini_buffer[4096];
1969
1970 /* Read installation information */
1971 GetPrivateProfileString("Setup", "title", "", ini_buffer,
1972 sizeof(ini_buffer), ini_file);
1973 unescape(title, ini_buffer, sizeof(title));
1974
1975 GetPrivateProfileString("Setup", "info", "", ini_buffer,
1976 sizeof(ini_buffer), ini_file);
1977 unescape(info, ini_buffer, sizeof(info));
1978
1979 GetPrivateProfileString("Setup", "build_info", "", build_info,
1980 sizeof(build_info), ini_file);
1981
1982 pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1,
1983 ini_file);
1984 pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1,
1985 ini_file);
1986
1987 GetPrivateProfileString("Setup", "target_version", "",
1988 target_version, sizeof(target_version),
1989 ini_file);
1990
1991 GetPrivateProfileString("metadata", "name", "",
1992 meta_name, sizeof(meta_name),
1993 ini_file);
1994
1995 GetPrivateProfileString("Setup", "install_script", "",
1996 install_script, sizeof(install_script),
1997 ini_file);
1998
1999
2000 hwndMain = CreateBackground(title);
2001
2002 RunWizard(hwndMain);
2003
2004 /* Clean up */
2005 UnmapViewOfFile(arc_data);
2006 if (ini_file)
2007 DeleteFile(ini_file);
2008
2009 if (hBitmap)
2010 DeleteObject(hBitmap);
2011
2012 return 0;
2013}
2014
2015/*********************** uninstall section ******************************/
2016
2017static int compare(const void *p1, const void *p2)
2018{
2019 return strcmp(*(char **)p2, *(char **)p1);
2020}
2021
2022/*
2023 * Commit suicide (remove the uninstaller itself).
2024 *
2025 * Create a batch file to first remove the uninstaller
2026 * (will succeed after it has finished), then the batch file itself.
2027 *
2028 * This technique has been demonstrated by Jeff Richter,
2029 * MSJ 1/1996
2030 */
2031void remove_exe(void)
2032{
2033 char exename[_MAX_PATH];
2034 char batname[_MAX_PATH];
2035 FILE *fp;
2036 STARTUPINFO si;
2037 PROCESS_INFORMATION pi;
2038
2039 GetModuleFileName(NULL, exename, sizeof(exename));
2040 sprintf(batname, "%s.bat", exename);
2041 fp = fopen(batname, "w");
2042 fprintf(fp, ":Repeat\n");
2043 fprintf(fp, "del \"%s\"\n", exename);
2044 fprintf(fp, "if exist \"%s\" goto Repeat\n", exename);
2045 fprintf(fp, "del \"%s\"\n", batname);
2046 fclose(fp);
2047
2048 ZeroMemory(&si, sizeof(si));
2049 si.cb = sizeof(si);
2050 si.dwFlags = STARTF_USESHOWWINDOW;
2051 si.wShowWindow = SW_HIDE;
2052 if (CreateProcess(NULL,
2053 batname,
2054 NULL,
2055 NULL,
2056 FALSE,
2057 CREATE_SUSPENDED | IDLE_PRIORITY_CLASS,
2058 NULL,
2059 "\\",
2060 &si,
2061 &pi)) {
2062 SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE);
2063 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
2064 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
2065 CloseHandle(pi.hProcess);
2066 ResumeThread(pi.hThread);
2067 CloseHandle(pi.hThread);
2068 }
2069}
2070
2071void DeleteRegistryKey(char *string)
2072{
2073 char *keyname;
2074 char *subkeyname;
2075 char *delim;
2076 HKEY hKey;
2077 long result;
2078 char *line;
2079
2080 line = strdup(string); /* so we can change it */
2081
2082 keyname = strchr(line, '[');
2083 if (!keyname)
2084 return;
2085 ++keyname;
2086
2087 subkeyname = strchr(keyname, ']');
2088 if (!subkeyname)
2089 return;
2090 *subkeyname++='\0';
2091 delim = strchr(subkeyname, '\n');
2092 if (delim)
2093 *delim = '\0';
2094
2095 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
2096 keyname,
2097 0,
2098 KEY_WRITE,
2099 &hKey);
2100
2101 if (result != ERROR_SUCCESS)
2102 MessageBox(GetFocus(), string, "Could not open key", MB_OK);
2103 else {
2104 result = RegDeleteKey(hKey, subkeyname);
2105 if (result != ERROR_SUCCESS)
2106 MessageBox(GetFocus(), string, "Could not delete key", MB_OK);
2107 RegCloseKey(hKey);
2108 }
2109 free(line);
2110}
2111
2112void DeleteRegistryValue(char *string)
2113{
2114 char *keyname;
2115 char *valuename;
2116 char *value;
2117 HKEY hKey;
2118 long result;
2119 char *line;
2120
2121 line = strdup(string); /* so we can change it */
2122
2123/* Format is 'Reg DB Value: [key]name=value' */
2124 keyname = strchr(line, '[');
2125 if (!keyname)
2126 return;
2127 ++keyname;
2128 valuename = strchr(keyname, ']');
2129 if (!valuename)
2130 return;
2131 *valuename++ = '\0';
2132 value = strchr(valuename, '=');
2133 if (!value)
2134 return;
2135
2136 *value++ = '\0';
2137
2138 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
2139 keyname,
2140 0,
2141 KEY_WRITE,
2142 &hKey);
2143 if (result != ERROR_SUCCESS)
2144 MessageBox(GetFocus(), string, "Could not open key", MB_OK);
2145 else {
2146 result = RegDeleteValue(hKey, valuename);
2147 if (result != ERROR_SUCCESS)
2148 MessageBox(GetFocus(), string, "Could not delete value", MB_OK);
2149 RegCloseKey(hKey);
2150 }
2151 free(line);
2152}
2153
2154BOOL MyDeleteFile(char *line)
2155{
2156 char *pathname = strchr(line, ':');
2157 if (!pathname)
2158 return FALSE;
2159 ++pathname;
2160 while (isspace(*pathname))
2161 ++pathname;
2162 return DeleteFile(pathname);
2163}
2164
2165BOOL MyRemoveDirectory(char *line)
2166{
2167 char *pathname = strchr(line, ':');
2168 if (!pathname)
2169 return FALSE;
2170 ++pathname;
2171 while (isspace(*pathname))
2172 ++pathname;
2173 return RemoveDirectory(pathname);
2174}
2175
2176BOOL Run_RemoveScript(char *line)
2177{
2178 char *dllname;
2179 char *scriptname;
2180 static char lastscript[MAX_PATH];
2181
2182/* Format is 'Run Scripts: [pythondll]scriptname' */
2183/* XXX Currently, pythondll carries no path!!! */
2184 dllname = strchr(line, '[');
2185 if (!dllname)
2186 return FALSE;
2187 ++dllname;
2188 scriptname = strchr(dllname, ']');
2189 if (!scriptname)
2190 return FALSE;
2191 *scriptname++ = '\0';
2192 /* this function may be called more than one time with the same
2193 script, only run it one time */
2194 if (strcmp(lastscript, scriptname)) {
2195 HINSTANCE hPython;
2196 char *argv[3] = {NULL, "-remove", NULL};
2197 char buffer[4096];
2198 FILE *fp;
2199 char *tempname;
2200 int n;
2201
2202 argv[0] = scriptname;
2203
2204 tempname = tmpnam(NULL);
2205
2206 if (!freopen(tempname, "a", stderr))
2207 MessageBox(GetFocus(), "freopen stderr", NULL, MB_OK);
2208 if (!freopen(tempname, "a", stdout))
2209 MessageBox(GetFocus(), "freopen stdout", NULL, MB_OK);
2210
2211 hPython = LoadLibrary(dllname);
2212 if (hPython) {
2213 if (0x80000000 == run_installscript(hPython, scriptname, 2, argv))
2214 fprintf(stderr, "*** Could not load Python ***");
2215 FreeLibrary(hPython);
2216 }
2217
2218 fflush(stderr);
2219 fflush(stdout);
2220
2221 fp = fopen(tempname, "rb");
2222 n = fread(buffer, 1, sizeof(buffer), fp);
2223 fclose(fp);
2224 remove(tempname);
2225
2226 buffer[n] = '\0';
2227 if (buffer[0])
2228 MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK);
2229
2230 strcpy(lastscript, scriptname);
2231 }
2232 return TRUE;
2233}
2234
2235int DoUninstall(int argc, char **argv)
2236{
2237 FILE *logfile;
2238 char buffer[4096];
2239 int nLines = 0;
2240 int i;
2241 char *cp;
2242 int nFiles = 0;
2243 int nDirs = 0;
2244 int nErrors = 0;
2245 char **lines;
2246 int lines_buffer_size = 10;
2247
2248 if (argc != 3) {
2249 MessageBox(NULL,
2250 "Wrong number of args",
2251 NULL,
2252 MB_OK);
2253 return 1; /* Error */
2254 }
2255 if (strcmp(argv[1], "-u")) {
2256 MessageBox(NULL,
2257 "2. arg is not -u",
2258 NULL,
2259 MB_OK);
2260 return 1; /* Error */
2261 }
2262
2263 {
2264 DWORD result;
2265 HKEY hKey;
2266 static char KeyName[] =
2267 "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
2268
2269 result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
2270 KeyName,
2271 0,
2272 KEY_CREATE_SUB_KEY,
2273 &hKey);
2274 if (result == ERROR_ACCESS_DENIED) {
2275 MessageBox(GetFocus(),
2276 "You do not seem to have sufficient access rights\n"
2277 "on this machine to uninstall this software",
2278 NULL,
2279 MB_OK | MB_ICONSTOP);
2280 return 1; /* Error */
2281 }
2282 RegCloseKey(hKey);
2283 }
2284
2285 logfile = fopen(argv[2], "r");
2286 if (!logfile) {
2287 MessageBox(NULL,
2288 "could not open logfile",
2289 NULL,
2290 MB_OK);
2291 return 1; /* Error */
2292 }
2293
2294 lines = (char **)malloc(sizeof(char *) * lines_buffer_size);
2295 if (!lines)
2296 return SystemError(0, "Out of memory");
2297
2298 /* Read the whole logfile, realloacting the buffer */
2299 while (fgets(buffer, sizeof(buffer), logfile)) {
2300 int len = strlen(buffer);
2301 /* remove trailing white space */
2302 while (isspace(buffer[len-1]))
2303 len -= 1;
2304 buffer[len] = '\0';
2305 lines[nLines++] = strdup(buffer);
2306 if (nLines >= lines_buffer_size) {
2307 lines_buffer_size += 10;
2308 lines = (char **)realloc(lines,
2309 sizeof(char *) * lines_buffer_size);
2310 if (!lines)
2311 return SystemError(0, "Out of memory");
2312 }
2313 }
2314 fclose(logfile);
2315
2316 /* Sort all the lines, so that highest 3-digit codes are first */
2317 qsort(&lines[0], nLines, sizeof(char *),
2318 compare);
2319
2320 if (IDYES != MessageBox(NULL,
2321 "Are you sure you want to remove\n"
2322 "this package from your computer?",
2323 "Please confirm",
2324 MB_YESNO | MB_ICONQUESTION))
2325 return 0;
2326
2327 cp = "";
2328 for (i = 0; i < nLines; ++i) {
2329 /* Ignore duplicate lines */
2330 if (strcmp(cp, lines[i])) {
2331 int ign;
2332 cp = lines[i];
2333 /* Parse the lines */
2334 if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) {
2335 if (MyRemoveDirectory(cp))
2336 ++nDirs;
2337 else {
2338 int code = GetLastError();
2339 if (code != 2 && code != 3) { /* file or path not found */
2340 ++nErrors;
2341 }
2342 }
2343 } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) {
2344 if (MyDeleteFile(cp))
2345 ++nFiles;
2346 else {
2347 int code = GetLastError();
2348 if (code != 2 && code != 3) { /* file or path not found */
2349 ++nErrors;
2350 }
2351 }
2352 } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) {
2353 if (MyDeleteFile(cp))
2354 ++nFiles;
2355 else {
2356 int code = GetLastError();
2357 if (code != 2 && code != 3) { /* file or path not found */
2358 ++nErrors;
2359 }
2360 }
2361 } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) {
2362 DeleteRegistryKey(cp);
2363 } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) {
2364 DeleteRegistryValue(cp);
2365 } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) {
2366 Run_RemoveScript(cp);
2367 }
2368 }
2369 }
2370
2371 if (DeleteFile(argv[2])) {
2372 ++nFiles;
2373 } else {
2374 ++nErrors;
2375 SystemError(GetLastError(), argv[2]);
2376 }
2377 if (nErrors)
2378 wsprintf(buffer,
2379 "%d files and %d directories removed\n"
2380 "%d files or directories could not be removed",
2381 nFiles, nDirs, nErrors);
2382 else
2383 wsprintf(buffer, "%d files and %d directories removed",
2384 nFiles, nDirs);
2385 MessageBox(NULL, buffer, "Uninstall Finished!",
2386 MB_OK | MB_ICONINFORMATION);
2387 remove_exe();
2388 return 0;
2389}
2390
2391int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst,
2392 LPSTR lpszCmdLine, INT nCmdShow)
2393{
2394 extern int __argc;
2395 extern char **__argv;
2396 char *basename;
2397
2398 GetModuleFileName(NULL, modulename, sizeof(modulename));
2399
2400 /* Map the executable file to memory */
2401 arc_data = MapExistingFile(modulename, &arc_size);
2402 if (!arc_data) {
2403 SystemError(GetLastError(), "Could not open archive");
2404 return 1;
2405 }
2406
2407 /* OK. So this program can act as installer (self-extracting
2408 * zip-file, or as uninstaller when started with '-u logfile'
2409 * command line flags.
2410 *
2411 * The installer is usually started without command line flags,
2412 * and the uninstaller is usually started with the '-u logfile'
2413 * flag. What to do if some innocent user double-clicks the
2414 * exe-file?
2415 * The following implements a defensive strategy...
2416 */
2417
2418 /* Try to extract the configuration data into a temporary file */
Thomas Hellera19cdad2004-02-20 14:43:21 +00002419 if (ExtractInstallData(arc_data, arc_size, &exe_size,
2420 &ini_file, &pre_install_script))
Thomas Hellerbb4b7d22002-11-22 20:39:33 +00002421 return DoInstall();
2422
2423 if (!ini_file && __argc > 1) {
2424 return DoUninstall(__argc, __argv);
2425 }
2426
2427
2428 basename = strrchr(modulename, '\\');
2429 if (basename)
2430 ++basename;
2431
2432 /* Last guess about the purpose of this program */
2433 if (basename && (0 == strncmp(basename, "Remove", 6)))
2434 SystemError(0, "This program is normally started by windows");
2435 else
2436 SystemError(0, "Setup program invalid or damaged");
2437 return 1;
2438}