File: wvwrap.cpp

package info (click to toggle)
vile 9.8za-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 10,644 kB
  • sloc: ansic: 120,894; lex: 14,981; sh: 4,478; perl: 3,511; cpp: 3,180; makefile: 1,425; awk: 271
file content (466 lines) | stat: -rw-r--r-- 10,938 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/*
 * vile:notabinsert sw=4:
 *
 * wvwrap.cpp:  A WinVile WRAPper .
 *
 * Originally written by Ed Henderson.
 *
 * This wrapper may be used to open one or more files via a right mouse
 * click in the Windows Explorer.  For more details, please read
 * doc/oleauto.doc .
 *
 * Note:  A great deal of the code included in this file is copied
 * (almost verbatim) from other vile modules.
 *
 * $Id: wvwrap.cpp,v 1.24 2022/08/21 23:38:55 tom Exp $
 */

#include "w32vile.h"

#include <objbase.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include <initguid.h>

#include "w32reg.h"
#include "w32ole.h"
#include "vl_alloc.h"
#include "makeargv.h"

#define DQUOTE '"'
#define SQUOTE '\''

static size_t olebuf_len;	/* scaled in wchar_t */
static OLECHAR *olebuf;

#ifdef OPT_TRACE
#define Trace MyTrace
static void
Trace(const char *fmt,...)
{
    FILE *fp = fopen("c:\\temp\\wvwrap.log", "a");
    if (fp != 0) {
	va_list ap;
	va_start(ap, fmt);
	vfprintf(fp, fmt, ap);
	va_end(ap);
	fclose(fp);
    }
}

#define TRACE(params) Trace params
#else
#define OPT_TRACE 0
#define TRACE(params)		/* nothing */
#endif

//--------------------------------------------------------------

/* WINVER >= _0x0500 */
#ifndef WC_NO_BEST_FIT_CHARS
#define WC_NO_BEST_FIT_CHARS 0
#endif

static char *
asc_charstring(const LPTSTR source)
{
    char *target = 0;

    if (source != 0) {
#if (defined(_UNICODE) || defined(UNICODE))
	ULONG len = WideCharToMultiByte(CP_ACP,
					WC_NO_BEST_FIT_CHARS,
					source,
					-1,
					0,
					0,
					NULL,
					NULL);
	if (len) {
	    target = typecallocn(char, len + 1);

	    (void) WideCharToMultiByte(CP_ACP,
				       WC_NO_BEST_FIT_CHARS,
				       source,
				       -1,
				       target,
				       len,
				       NULL,
				       NULL);
	}
#else
	size_t len = strlen(source) + 1;
	target = typecallocn(char, len + 1);
	if (target != 0)
	    memcpy(target, source, len);
#endif
    }

    return target;
}
static LPTSTR
w32_charstring(const char *source)
{
    TCHAR *target = 0;

    if (source != 0) {
#if (defined(_UNICODE) || defined(UNICODE))
	ULONG len = MultiByteToWideChar(CP_ACP,
					MB_USEGLYPHCHARS | MB_PRECOMPOSED,
					source,
					-1,
					0,
					0);
	if (len != 0) {
	    target = typecallocn(TCHAR, len + 1);

	    (void) MultiByteToWideChar(CP_ACP,
				       MB_USEGLYPHCHARS | MB_PRECOMPOSED,
				       source,
				       -1,
				       target,
				       len);
	}
#else
	size_t len = strlen(source) + 1;
	target = typecallocn(TCHAR, len + 1);
	if (target != 0)
	    memcpy(target, source, len);
#endif
    }

    return target;
}

/* from w32misc.c */
static LPTSTR
w32_prognam(void)
{
    return W32_STRING("wvwrap");
}

int
w32_message_box(HWND hwnd, const char *message, int code)
{
    int rc;
    LPTSTR buf = w32_charstring(message);

    rc = MessageBox(hwnd, buf, w32_prognam(), code);
    free((void *) buf);
    return (rc);
}

static char *
fmt_win32_error(ULONG errcode, char **buf, ULONG buflen)
{
    int flags = FORMAT_MESSAGE_FROM_SYSTEM;
    LPTSTR result = 0;

    if (*buf) {
	result = typeallocn(TCHAR, buflen + 1);
    } else {
	flags |= FORMAT_MESSAGE_ALLOCATE_BUFFER;
    }

    FormatMessage(flags,
		  NULL,
		  errcode,
		  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),	/* dflt language */
		  result,
		  buflen,
		  NULL);

    if (*buf != 0) {
	char *tmp = asc_charstring(result);
	strcpy(*buf, tmp);
	free(tmp);
    }
    return (*buf);
}

static int
nomem(void)
{
    char buf[512], *tmp;

    tmp = buf;
    fmt_win32_error((ULONG) E_OUTOFMEMORY, &tmp, 0);
    w32_message_box(NULL, buf, MB_OK | MB_ICONSTOP);
    return (1);
}

#if !(defined(_UNICODE) || defined(UNICODE))
/*
 * Quick & Dirty Unicode conversion routine.  Routine uses a
 * dynamic buffer to hold the converted string so it may be any arbitrary
 * size.  However, the same dynamic buffer is reused when the routine is
 * called a second time.  So make sure that the converted string is
 * used/copied before the conversion routine is called again.
 *
 * from w32ole.cpp
 */
static OLECHAR *
ConvertToUnicode(const char *szA)
{
    size_t len;

    len = strlen(szA) + 1;
    if (len > olebuf_len) {
	if (olebuf)
	    free(olebuf);
	olebuf_len = olebuf_len * 2 + len;
	if ((olebuf = typeallocn(OLECHAR, olebuf_len)) == NULL)
	    return (olebuf);	/* We're gonna' die */
    }
    mbstowcs(olebuf, szA, len);
    return (olebuf);
}
#endif

/*
 * vile's prompts for directory/filename do not expect to strip quotes; they
 * use the strings exactly as given.  At the same time, the initial "cd" and
 * "e" commands use the token parsing which stops on a blank.  That makes it
 * not simple to use OLE to send characters to the server to specify filenames
 * containing blanks.
 *
 * We work around the problem using the "eval" command, which forces a reparse
 * of the whole line.  That uses an extra level of interpretation, so we have
 * to double each single quote _twice_ to enter single quotes in the filename.
 *
 * We turn off globbing to prevent vile from expanding dollar-signs and square
 * brackets.
 *
 * Obscure, but it works.
 */
static char *
escape_quotes(const char *src)
{
    size_t len = 4 * strlen(src) + 1;
    char *result = typeallocn(char, len);

    if (result == 0)
	exit(nomem());

    char *dst = result;
    while (*src != '\0') {
	UCHAR ch = (UCHAR) * src;
	// only send ASCII, do not rely on the runtime to guess how to handle
	// non-ASCII characters.
	if (ch > 127) {
	    sprintf(dst, "\026x%02x", ch);
	    dst += 4;
	    src += 1;
	    continue;
	} else {
	    if (*src == SQUOTE) {
		*dst++ = SQUOTE;
		*dst++ = SQUOTE;
		*dst++ = SQUOTE;
	    }
	    *dst++ = *src++;
	}
    }
    *dst = '\0';

    return result;
}

static void
append(char *&buffer, size_t &length, char *value)
{
    size_t newsize = strlen(buffer) + strlen(value);
    if ((newsize + 1) > length) {
	length = (newsize + 1) * 2;
	buffer = (char *) realloc(buffer, length);
    }
    strcat(buffer, value);
}

#define MY_BUFSIZ 4096

int WINAPI
WinMain(HINSTANCE hInstance,	// handle to current instance
	HINSTANCE hPrevInstance,	// handle to previous instance
	LPSTR lpCmdLine,	// pointer to command line
	int nCmdShow)		// show state of window
{
    BSTR bstr;
    size_t dynbuf_len;
    HRESULT hr;
    HWND hwnd;
    VARIANT_BOOL insert_mode, glob_mode, minimized;
    char *lclbuf = NULL, tmp[512], *dynbuf;
    OLECHAR *olestr;
    LPUNKNOWN punk;
    IVileAuto *pVileAuto;
    char **argv;
    int argc;
    int argc1;

    if (make_argv(0, lpCmdLine, &argv, &argc, NULL) < 0)
	return (nomem());
    argc1 = after_options(0, argc, argv);

#if OPT_TRACE
    Trace("; cmdline:%s\n", lpCmdLine);
    for (int n = 0; n < argc; ++n)
	Trace("; %sargv%d:%s\n", (n >= argc1) ? "*" : "", n, argv[n]);
#endif

    olebuf_len = MY_BUFSIZ;
    dynbuf_len = MY_BUFSIZ;
    olebuf = typeallocn(OLECHAR, olebuf_len);
    dynbuf = typeallocn(char, dynbuf_len);
    if (!(olebuf && dynbuf))
	return (nomem());

    hr = CoInitialize(NULL);	// Fire up COM.
    if (FAILED(hr)) {
	fmt_win32_error(hr, &lclbuf, 0);
	sprintf(tmp,
		"ERROR: CoInitialize() failed, errcode: %#lx, desc: %s",
		hr,
		lclbuf);
	w32_message_box(NULL, tmp, MB_OK | MB_ICONSTOP);
	return (1);
    }
    hr = CoCreateInstance(CLSID_VileAuto,
			  NULL,
			  CLSCTX_LOCAL_SERVER,
			  IID_IUnknown,
			  (void **) &punk);
    if (FAILED(hr)) {
	fmt_win32_error(hr, &lclbuf, 0);
	sprintf(tmp,
		"ERROR: CoInitialize() failed, errcode: %#lx, desc: %s\n"
		"Try registering winvile via its -Or switch.",
		hr,
		lclbuf);
	w32_message_box(NULL, tmp, MB_OK | MB_ICONSTOP);
	return (1);
    }
    hr = punk->QueryInterface(IID_IVileAuto, (void **) &pVileAuto);
    punk->Release();
    if (FAILED(hr)) {
	fmt_win32_error(hr, &lclbuf, 0);
	sprintf(tmp,
		"ERROR: QueryInterface() failed, errcode: %#lx, desc: %s\n\n",
		hr,
		lclbuf);
	w32_message_box(NULL, tmp, MB_OK | MB_ICONSTOP);
	return (1);
    }
    pVileAuto->put_Visible(VARIANT_TRUE);	// May not be necessary
    pVileAuto->get_InsertMode(&insert_mode);
    pVileAuto->get_GlobMode(&glob_mode);
    if (argc > argc1) {
	char *cp;

	*dynbuf = '\0';

	if (insert_mode)
	    append(dynbuf, dynbuf_len, "\033");

#if OPT_TRACE
	/*
	 * Turn on tracing in the server, for debugging.
	 */
	append(dynbuf, dynbuf_len, ":setv $debug=true\n");
#endif
	/*
	 * Disable globbing to simplify quoting.
	 */
	append(dynbuf, dynbuf_len, ":set noglob\n");

	/*
	 * When wvwrap starts up (and subsequently launches winvile), the
	 * editor's CWD is set to a path deep within the bowels of Windows.
	 * Not very useful.  Change CWD to the directory of the first
	 * file on the commandline.
	 */
	cp = strrchr(*argv, '\\');
	if (cp) {
	    int add_delim;

	    *cp = '\0';
	    if (cp == *argv) {
		/* filename is of the form:  \<leaf> .  handle this. */
		append(dynbuf, dynbuf_len, ":cd \\\n");
	    } else {
		/*
		 * To add insult to injury, Windows Explorer has a habit of
		 * passing 8.3 filenames to wvwrap (noted on a win2K system and
		 * a FAT32 partition).  If the folder portion of the file's
		 * path happens to be in 8.3 format (i.e., a tilde included in
		 * the folder name), then 8.3 folder names appear in winvile's
		 * Recent Folders list.
		 *
		 * Needless to say, it's no fun trying to decipher 8.3 folder
		 * names.
		 */

		LPTSTR the_arg = w32_charstring(*argv);
		TCHAR folder[FILENAME_MAX];
		char *fp;

		if (GetLongPathName(the_arg, folder, sizeof(folder)) > 0)
		    fp = asc_charstring(folder);
		else
		    fp = asc_charstring(the_arg);

		add_delim = (isalpha(fp[0]) && fp[1] == ':' && fp[2] == '\0');

		/*
		 * With regard to the following code, note that the
		 * original file might be in the form "<drive>:\leaf", in
		 * which case *argv now points at "<drive>:" .  Recall that
		 * cd'ing to <drive>:  on a DOS/WIN32 host has special
		 * semantics (which we don't want).
		 */
		char temp[MY_BUFSIZ];
		sprintf(temp, ":eval cd '%s%s'\n",
			escape_quotes(fp),
			(add_delim) ? "\\" : "");

		append(dynbuf, dynbuf_len, temp);
		free(fp);
		free(the_arg);
	    }
	    *cp = '\\';
	}

	while (argc1 < argc) {
	    char temp[MY_BUFSIZ];
	    sprintf(temp, ":eval e '%s'\n", escape_quotes(argv[argc1++]));
	    append(dynbuf, dynbuf_len, temp);
	}
	if (glob_mode)
	    append(dynbuf, dynbuf_len, ":set glob\n");

	TRACE(("; dynbuf:\n%s\n", dynbuf));
	olestr = TO_OLE_STRING(dynbuf);
	bstr = SysAllocString(olestr);

	if (!(bstr && olestr))
	    return (nomem());
	pVileAuto->VileKeys(bstr);

	SysFreeString(bstr);
	free(olestr);
    }

    // Set foreground window using a method that's compatible with win2k
    pVileAuto->get_MainHwnd((LONG *) & hwnd);
    (void) SetForegroundWindow(hwnd);

    // If editor minimized, restore window
    hr = pVileAuto->get_IsMinimized(&minimized);
    if (SUCCEEDED(hr) && minimized)
	hr = pVileAuto->Restore();
    pVileAuto->Release();
    CoUninitialize();		// shut down COM
    return (0);
}