summaryrefslogtreecommitdiff
path: root/Build/source/texk/contrib/pdfdde.c
blob: b6736e7fd2841480fe6ace909a6fabc7f0cf3020 (plain)
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
/* pdfdde.c -- control Adobe Acrobat under Windows.  Written by Fabrice
   Popineau many years ago, based on Adobe documentation.  Public
   domain.  */
   
// #include <afx.h>
#include <win32lib.h>
#include <ddeml.h>
#include <dde.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <shellapi.h>

#include <getopt.h>

#define ACROBAT_EXE	"acrobat.exe"
#define ACROBAT		"acroview"
#define EVAL_TOPIC	"control"
#define RESULT_ITEM	"Result"
#define ERROR_ITEM	"Error"

/* Timeouts & delays */
#define CONNECT_DELAY		500		/* ms */
#define TRANSACTION_TIMEOUT	5000		/* ms */
#define MAX_INPUT_IDLE_WAIT     INFINITE	/* ms */

static DWORD DDEsession;
static HCONV DDEconversation;

/* The raw base name */
static char *argv0 = NULL;
static int nPage = 0;
static char *sFileName = NULL;
static int bAll = 0;
static int bServer = 0;
static int iDebug = 0;
static char *sGoto = NULL;
static char sLongFileName[MAXPATHLEN];

const char *pdfdde_version_string = "0.2";

/* Test whether getopt found an option ``A''.
   Assumes the option index is in the variable `option_index', and the
   option table in a variable `long_options'.  */
#define ARGUMENT_IS(a) (_stricmp(long_options[option_index].name, a) == 0)
#define PROGRAM_IS(a) (_stricmp(a, argv0) == 0)

static struct option long_options [] = {
    { "debug",               0, 0, 0},
    { "help",                0, 0, 0},
    { "version",             0, 0, 0},
    { "file",                1, 0, 0},
    { "page",                1, 0, 0},
    { "goto",                1, 0, 0},
    { "all",                 0, 0, 0},
    {0, 0, 0, 0}
};


char *FindAcrobatModule()
{
    char buf[260];
    char path[260];
    char *program;
    HANDLE hFile;
    HINSTANCE hInst;
 
    program = (char *)malloc(MAX_PATH*sizeof(char));
    if (program == NULL) goto exit_1;

    buf[0] = path[0] = program[0] = '\0';
    
    if (GetTempPath(sizeof(path), path) != 0) {
	strcpy(buf, path);
    }


    strcat(buf, "dummy.pdf");
    
    hFile = CreateFile(buf, 
		       GENERIC_READ|GENERIC_WRITE, 
		       FILE_SHARE_READ | FILE_SHARE_WRITE, 
		       NULL,
		       OPEN_ALWAYS, 
		       FILE_ATTRIBUTE_NORMAL, 
		       NULL);
    
    CloseHandle(hFile);
    
    hInst = FindExecutable("dummy.pdf", path, program);
    
    DeleteFile(buf);
    
#if 0
    switch ((int)hInst) {
    case SE_ERR_FNF:
	fprintf(stdout, "File not found: %s\n", argv[1]);
	break;
    case SE_ERR_NOASSOC:
	fprintf(stdout, "No association for %s\n", argv[1]);
	break;
    default:
	fprintf(stdout, "File .pdf is opened by %s\n", program);
	break;
    }
#endif

    if (*program == '\0' || (GetFileAttributes(program) == 0xFFFFFFFF)) {
	program = NULL;
    }

exit_1:
    return program;

}

void CloseConversation (void)
{
    if (DDEconversation)
	DdeDisconnect(DDEconversation);
    if (DDEsession)
	DdeUninitialize(DDEsession);
}

void error(LPCTSTR fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    fputc('\n', stderr);

    /* Tidy up */
    CloseConversation();
    exit(1);
}

void *emalloc(size_t len)
{
    void *p = malloc(len);

    if (p == NULL)
	error("Out of memory - cannot allocate %d bytes", len);

    return p;
}

int outstanding_requests;

HDDEDATA CALLBACK
Callback (UINT uType, UINT uFmt, HCONV hconv, HSZ hsz1, HSZ hsz2,
	  HDDEDATA hdata, DWORD dwData1, DWORD dwData2)
{
    if (uType == XTYP_ADVDATA) {
	DWORD len = DdeGetData(hdata, NULL, 0, 0);
	char *buf = _alloca(len + 1);
	DdeGetData(hdata, (LPBYTE)buf, len + 1, 0);
	
	if (--outstanding_requests == 0)
	    PostQuitMessage(0);
	
	return (HDDEDATA) DDE_FACK;
    }
    
    return (HDDEDATA) NULL;
}

int StartServer(LPCTSTR prog)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    
    /* To be sure ... */
    if (! prog) 
	return 1;

    ZeroMemory (&si, sizeof (si));
    si.cb = sizeof (si);
    if (!CreateProcess (NULL, (LPTSTR)prog, NULL, NULL, FALSE, 0,
			NULL, NULL, &si, &pi))
    {
	error("Could not start process %s", prog);
	return 1;
    }

    /* Wait for the process to enter an idle state */
    WaitForInputIdle (pi.hProcess, MAX_INPUT_IDLE_WAIT);

    /* Close the handles */
    CloseHandle (pi.hThread);
    CloseHandle (pi.hProcess);
    return 0;
}

HSZ DDEString(LPCTSTR str)
{
    HSZ hsz = DdeCreateStringHandle(DDEsession, str, CP_WINANSI);
    if (hsz == 0)
	error("Cannot create string for %s", str);
    return hsz;
}

FreeString(HSZ hsz)
{
    DdeFreeStringHandle(DDEsession, hsz);
}

void OpenConversation(LPCTSTR topic_name)
{
    UINT ret;
    HSZ service;
    HSZ topic;
    int n;
    
    ret = DdeInitialize(&DDEsession, Callback, APPCMD_CLIENTONLY, 0);
    if (ret != DMLERR_NO_ERROR)
	error("Cannot start DDE");

    service = DDEString(ACROBAT);
    topic = DDEString(topic_name);
    DDEconversation = DdeConnect(DDEsession, service, topic, 0);

    if (DDEconversation == 0)
    {
	if (StartServer(FindAcrobatModule()) == 0)
	{
	    /* Try to connect */
	    for (n = 0; n < 5; n++)
	    {
		Sleep (CONNECT_DELAY);
		DDEconversation = DdeConnect(DDEsession, service, topic, 0);
		if (DDEconversation)
		    break;
	    }
	    if (DDEconversation == 0)
		error("Cannot contact server %s", ACROBAT);
	}
    }
    FreeString(service);
    FreeString(topic);
}

void __cdecl ExecuteCommand(LPCTSTR command, ...)
{
    HDDEDATA ret;
    va_list args;
    int len;
    char *buffer;
    
    va_start( args, command );
    len = _vscprintf(command, args) // _vscprintf doesn't count
	+ 1;			// terminating '\0'
    buffer = malloc( len * sizeof(char) );
    vsprintf( buffer, command, args );
    
    ret = DdeClientTransaction((LPBYTE)buffer, strlen(buffer) + 1,
			       DDEconversation, 0, 0, XTYP_EXECUTE,
			       TRANSACTION_TIMEOUT, 0);
    if (ret == 0)
	error("Cannot execute command \"%s\" (error %ld)", command, DdeGetLastError(DDEsession));
}

void StartHotLink(LPCTSTR item_name)
{
    HSZ item = DDEString(item_name);
    DdeClientTransaction(0, 0, DDEconversation, item, CF_TEXT, XTYP_ADVSTART,
			 TRANSACTION_TIMEOUT, 0);
    FreeString(item);
}

LPTSTR RequestData (LPCTSTR item_name)
{
    HSZ item = DDEString(item_name);
    DWORD len;
    char *buf;
    HDDEDATA result;
    result = DdeClientTransaction (NULL, 0, DDEconversation, item, CF_TEXT,
				   XTYP_REQUEST, TRANSACTION_TIMEOUT, 0);
    FreeString(item);
    if (result == 0)
	error("Cannot request item %s\n", item_name);

    len = DdeGetData(result, NULL, 0, 0);
    buf = emalloc(len + 1);
    DdeGetData(result, (LPBYTE)buf, len + 1, 0);
    return buf;
}

void usage()
{
  fprintf(stderr, "Usage:\n");
  fprintf(stderr, "\tpdfopen  --file <filename> [--page <page>]\n");
  fprintf(stderr, "\t\t       Opens <filename> (at page <page> if available)\n");
  fprintf(stderr, "\t\t             in Acrobat or Acrobat Reader.\n");
  fprintf(stderr, "\tpdfclose --file <filename>\n");
  fprintf(stderr, "\t         Closes <filename> in Acrobat or Acrobat Reader.\n");
  fprintf(stderr, "\tpdfclose --all\n");
  fprintf(stderr, "\t         Closes all documents in Acrobat or Acrobat Reader.\n");
  fprintf(stderr, "\tpdfdde\n");
  fprintf(stderr, "\t\t       Read commands on stdin\n");
  fprintf(stderr, "Beware: only documents opened by `pdfopen' can be closed\n");
  fprintf(stderr, "        by `pdfclose'.\n");
  exit(0);
}

char *CheckFileName(char *p)
{
  char sTmp[MAXPATHLEN];
  char *fp;

  sLongFileName[0] = '\0';

  if (GetFileAttributes(p) == -1) {
    fprintf(stderr, "%s: non existent file %s\n", argv0, p);
    return NULL;
  }
  if (GetFullPathName(p, sizeof(sTmp), sTmp, &fp) == 0) {
    fprintf(stderr, "%s: failed to get full path name for %s (Error %d)\n", argv0, p, GetLastError());
    return NULL;
  }
  if (GetLongPathName(sTmp, sLongFileName, sizeof(sLongFileName)) == 0) {
    fprintf(stderr, "%s: failed to get long path name for %s (Error %d)\n", argv0, sTmp, GetLastError());
    return NULL;
  }
  return sLongFileName;
}

int pdfopen()
{
  if (sLongFileName[0] == '\0') {
    fprintf(stderr, "%s: mandatory `--file' argument not found.\n", argv0);
    return EXIT_FAILURE;
  }

  OpenConversation(EVAL_TOPIC);
  
  ExecuteCommand("[DocOpen(\"%s\")]", sLongFileName); 
  ExecuteCommand("[FileOpen(\"%s\")]", sLongFileName); 

  if (nPage > 0) {
    ExecuteCommand("[DocGoTo(\"%s\", %d)]", sLongFileName, nPage); 
  }

  if (sGoto != NULL) {
    ExecuteCommand("[DocGoToNameDest(\"%s\", %s)]", sLongFileName, sGoto); 
  }

  CloseConversation();
#if 0
  /* Problem : it seems that these calls can put AR into a strange state.
     It would have been simpler if Adobe had simply iconified their application. */
  if (stricmp(argv0, "pdfclose") == 0) {
    sprintf(buf, "[AppHide()]");
  }
  else if (stricmp(argv0, "pdfopen") == 0) {
    sprintf(buf, "[AppShow()]");
  }
  bRetVal = DdeClientTransaction((unsigned char *)buf, (DWORD)strlen(buf),
				 (HCONV)hConversation, NULL,
				 (UINT)CF_TEXT, (UINT)XTYP_EXECUTE, (DWORD)1000, &dwResult);
#endif
  
  return EXIT_SUCCESS;
}

int pdfclose()
{
    OpenConversation(EVAL_TOPIC);

    if (bAll) {
	ExecuteCommand("[CloseAllDocs()]");
    }
    else if (sLongFileName[0] != '\0') {
	ExecuteCommand("[DocClose(\"%s\")]", sLongFileName);
    }
    
#if 0
    fprintf(stderr, "cmd : %s\n", buf);
#endif
    
    CloseConversation();
    
    return EXIT_SUCCESS;
}

int pdfserver()
{
  char line[1024];

  OpenConversation(EVAL_TOPIC);
  
  fprintf(stdout, "Type Ctrl-Z to quit.\n");

  while (fgets(line, sizeof(line), stdin)) {
#define WHITE_DELIM " \t\n"
    char *p = strtok(line, WHITE_DELIM);
    if (stricmp(p, "open") == 0) {
      p = strtok(NULL, WHITE_DELIM);
      if (CheckFileName(p) == NULL) goto next;
  
      ExecuteCommand("[DocOpen(\"%s\")]", sLongFileName); 
    }
    else if (stricmp(p, "close") == 0) {
      p = strtok(NULL, WHITE_DELIM);
      if (CheckFileName(p) == NULL) goto next;
      ExecuteCommand("[DocClose(\"%s\")]", sLongFileName);
    }
    else if (stricmp(p, "closeall") == 0) {
      ExecuteCommand("[CloseAllDocs()]");
    }
    else if (stricmp(p, "goto") == 0) {
      p = strtok(NULL, WHITE_DELIM);
      if (p == NULL) goto next;
      if (CheckFileName(p) == NULL) goto next;
      p = strtok(NULL, WHITE_DELIM);
      if (p == NULL) goto next;
      nPage = atoi(p) - 1;
      ExecuteCommand("[DocGoTo(\"%s\", %d)]", sLongFileName, nPage); 
    }
    else if (stricmp(p, "gotoname") == 0) {
      p = strtok(NULL, WHITE_DELIM);
      if (p == NULL) goto next;
      if (CheckFileName(p) == NULL) goto next;
      p = strtok(NULL, WHITE_DELIM);
      if (p == NULL) goto next;
      sGoto = p;
      ExecuteCommand("[DocGoToNameDest(\"%s\", %s)]", sLongFileName, sGoto); 
    }
    else if (stricmp(p, "show") == 0) {
      ExecuteCommand("[AppShow()]");

    }
    else if (stricmp(p, "hide") == 0) {
      ExecuteCommand("[AppHide()]");

    }
    else if (stricmp(p, "exit") == 0) {
      ExecuteCommand("[AppExit()]");
      goto exit;
    }
    else if (stricmp(p, "list") == 0) {
      fprintf(stdout, "open <file>		open the file\n");
      fprintf(stdout, "close <file>		close the file\n");
      fprintf(stdout, "closeall		close all files\n");
      fprintf(stdout, "goto <file> <page>	goto the given <page> in <file>\n");
      fprintf(stdout, "gotoname <file> <dest>	goto the <dest> named destination in <file>\n");
      fprintf(stdout, "show			show acroview\n");
      fprintf(stdout, "hide			hide acroview\n");
      fprintf(stdout, "exit			exit acroview and %s\n", argv0);
    }
  next: ;   
  }

#if 0
  fprintf(stderr, "cmd : %s\n", buf);
#endif
exit:
  CloseConversation();

  return EXIT_SUCCESS;
}

int main (int argc, char *argv[])
{
  BOOL bRet = FALSE;
  char *p;
  int argv0len = 0;
  int g; /* getopt return code */
  int option_index;

  /* Make argv0 to point to the raw base name */
  argv0 = argv[0];
  if ((p = strrchr(argv0, '/'))
      || (p = strrchr(argv0, '\\'))) {
    argv0 = _strdup(p+1);
  }
  if ((argv0len = strlen(argv0)) > 4 
      && _strnicmp(argv0 + argv0len - 4, ".exe", 4) == 0)
    argv0[argv0len - 4] = '\0';

  for(;;) {
    g = getopt_long_only (argc, argv, "", long_options, &option_index);
    
    if (g == EOF)
      break;

    if (g == '?') {
      usage();			/* Unknown option.  */
      exit(EXIT_FAILURE);
    }

    /* assert (g == 0); */ /* We have no short option names.  */
    /*
      FIXME : try 'mktexpk --mfmode --bdpi 600 ...'
    */

    if (ARGUMENT_IS ("debug")) {
#if 0
      if (! isalnum(*optarg)) {
	fprintf(stderr, "%s: warning, `%s' bad debug argument.\n", argv0, optarg);
      }
      iDebug |= atoi (optarg);
#endif
      iDebug = TRUE;
    }
    else if (ARGUMENT_IS ("help")) {
      usage();
      exit(EXIT_SUCCESS);
    }
    else if (ARGUMENT_IS ("version")) {
      fprintf(stderr, "%s of %s.\n", argv0, pdfdde_version_string);
      exit(EXIT_SUCCESS);
    }
    else if (PROGRAM_IS("pdfopen")) {
      if (ARGUMENT_IS("file")) {
	CheckFileName(optarg);
      }
      else if (ARGUMENT_IS("page")) {
	nPage = atoi(optarg) - 1;
      }
      else if (ARGUMENT_IS("goto")) {
	sGoto = optarg;
      }
    }
    else if (PROGRAM_IS("pdfclose")) {
      if (ARGUMENT_IS("file")) {
	CheckFileName(optarg);
      }
      else if (ARGUMENT_IS("all")) {
	bAll = TRUE;
      }
    }
  }

#if 0
  /* shifting options from argv[] list */
  for (i = 0; i < argc - optind; i++)
    argv[i] = argv[optind+i];
  argv[i] = NULL;

  argc = i;
#endif

  if (PROGRAM_IS("pdfopen")) {
    bRet = pdfopen();
  }
  else if (PROGRAM_IS("pdfclose")) {
    bRet = pdfclose();
  }
  else if (PROGRAM_IS("pdfdde")) {
    bRet = pdfserver();
  }
  else {
    fprintf(stderr, "This program has been incorrectly copied to the name %s.\n", argv[0]);
    bRet = EXIT_FAILURE;
  }
  return bRet;
}