AmendHub

Download

jcs

/

cat

/

util.c

 

(View History)

jcs   *: Initial import Latest amendment: 1 on 2026-09-30

1 /*
2 * Copyright (c) 2020-2022 joshua stein <jcs@jcs.org>
3 * Copyright (c) 1998, 2015 Todd C. Miller <millert@openbsd.org>
4 * Copyright (c) 1990, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20 /* THINK C Project must have a header of "#include <MacHeaders>" */
21
22 #pragma options(!profile)
23
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <GestaltEqu.h>
29 #include <Script.h>
30 #include <SetUpA4.h>
31 #include "util.h"
32
33 /* ALRT resources */
34 #define ASK_ALERT_ID 130
35
36 #define ERROR_STRING_SIZE 256
37 static char err_str[ERROR_STRING_SIZE];
38
39 /* basic DITL with an ok button (1), text area (2), and icon (3) */
40 #define ALERT_DITL_OK 1
41 #define ALERT_DITL_ICON 3
42 static const char alert_ditl[] = {
43 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4E,
44 0x00, 0xFA, 0x00, 0x64, 0x01, 0x34, 0x04, 0x02,
45 0x4F, 0x4B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D,
46 0x00, 0x4E, 0x00, 0x41, 0x01, 0x36, 0x08, 0x02,
47 0x5E, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D,
48 0x00, 0x17, 0x00, 0x2D, 0x00, 0x37, 0xA0, 0x02,
49 0x00, 0x01
50 };
51 static Handle alert_ditl_h = NULL;
52
53 /* ICN# to show for APPICON_ALERT */
54 #define APPICON_ICN_ID 128
55
56 /* DITL with a Yes button (1), No button (2), text (3), and icon (4) */
57 static const char ask_ditl[] = {
58 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46,
59 0x00, 0xE6, 0x00, 0x5A, 0x01, 0x20, 0x04, 0x03,
60 0x59, 0x65, 0x73, 0x21, 0x00, 0x00, 0x00, 0x00,
61 0x00, 0x46, 0x00, 0xA0, 0x00, 0x5A, 0x00, 0xDA,
62 0x04, 0x02, 0x4E, 0x6F, 0x00, 0x00, 0x00, 0x00,
63 0x00, 0x0A, 0x00, 0x32, 0x00, 0x41, 0x01, 0x22,
64 0x08, 0x02, 0x5E, 0x30, 0x00, 0x00, 0x00, 0x00,
65 0x00, 0x0A, 0x00, 0x0A, 0x00, 0x2A, 0x00, 0x2A,
66 0xA0, 0x02, 0x00, 0x01
67 };
68 static Handle ask_ditl_h = NULL;
69
70 /* DITL with just a text view */
71 static const char progress_ditl[] = {
72 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14,
73 0x00, 0x1E, 0x00, 0x32, 0x01, 0x3B, 0x08, 0x02,
74 0x5E, 0x30
75 };
76 static Handle progress_ditl_h = NULL;
77 static DialogPtr progress_dialog = NULL;
78
79 static TEHandle track_control_te = NULL;
80
81 enum {
82 STOP_ALERT,
83 CAUTION_ALERT,
84 NOTE_ALERT,
85 APPICON_ALERT
86 };
87
88 void vwarn(short alert_func, const char *format, va_list ap);
89
90 /*
91 * Util helper needed to be called at program startup, to pre-allocate
92 * some things that we can't do during errors.
93 */
94
95 void
96 util_init(void)
97 {
98 alert_ditl_h = xNewHandle(sizeof(alert_ditl));
99 if (alert_ditl_h == NULL)
100 ExitToShell();
101 HLock(alert_ditl_h);
102 memcpy(*alert_ditl_h, alert_ditl, sizeof(alert_ditl));
103 HUnlock(alert_ditl_h);
104 }
105
106 /*
107 * Memory functions
108 */
109
110 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
111
112 #ifdef MALLOC_DEBUG
113 /*
114 * malloc tracking, storing a stack trace of each xmalloc call and its
115 * size, which can be dumped with xalloc_print(). xfree also gains the
116 * ability to detect junk frees.
117 *
118 * Requires project options 'Always generate stack frames',
119 * 'Macsbug Names', and 'Long format' to be enabled.
120 */
121 #if !__option(force_frame) || !__option(long_macsbug_names)
122 #error
123 #endif
124
125 #define XALLOC_SYMBOL_SIZE 32
126 #define XALLOC_NSYMBOLS 64
127 #define XALLOC_MAX_STACK_DEPTH 10
128 static char *symbols = NULL;
129 struct xalloc {
130 char *stack[XALLOC_MAX_STACK_DEPTH];
131 unsigned long addr;
132 unsigned long size;
133 };
134 #define XALLOC_NXALLOCS 512
135 static struct xalloc *xallocs = NULL;
136 #endif
137
138 void *
139 xmalloc(size_t size)
140 {
141 void *ptr;
142 #ifdef MALLOC_DEBUG
143 static char cursym[XALLOC_SYMBOL_SIZE], *tsym, *sym;
144 struct xalloc *xa;
145 unsigned long _a6, ret;
146 unsigned char *code;
147 size_t n, cn, j;
148 short nframe;
149 #endif
150
151 if (size == 0)
152 panic("xmalloc: zero size");
153
154 ptr = NewPtr(size);
155 if (ptr == NULL)
156 return NULL;
157
158 #ifdef MALLOC_DEBUG
159 asm {
160 move.l a6,_a6
161 };
162
163 if (symbols == NULL) {
164 symbols = NewPtr(n = XALLOC_SYMBOL_SIZE * XALLOC_NSYMBOLS);
165 if (symbols == NULL)
166 panic("NewPtr failed for xalloc symbols");
167 memset(symbols, 0, n);
168 }
169 if (xallocs == NULL) {
170 xallocs = (struct xalloc *)NewPtr(n = (XALLOC_NXALLOCS *
171 sizeof(struct xalloc)));
172 if (xallocs == NULL)
173 panic("NewPtr failed for xallocs");
174 memset(xallocs, 0, n);
175 }
176
177 xa = NULL;
178 for (n = 0; n < XALLOC_NXALLOCS; n++) {
179 if (xallocs[n].addr == 0) {
180 xa = &xallocs[n];
181 break;
182 }
183 }
184 if (xa == NULL)
185 panic("out of xalloc space");
186
187 /*
188 * A6 register points to previous stack A6. Above A6 is our return
189 * address. Walk the code after the return address looking for an RTS
190 * instruction, then walk 3 bytes after that and we should have that
191 * function's symbol. Then jump to the previous A6 that our A6 points
192 * to and do it again to find the previous function symbol, repeating
193 * until we hit "main" or "uthread_begin".
194 */
195 for (nframe = 0; nframe < XALLOC_MAX_STACK_DEPTH; nframe++) {
196 ret = *(unsigned long *)(_a6 + 4);
197 code = (unsigned char *)ret;
198
199 cursym[0] = '\0';
200 for (; ; code += 2) {
201 if (code[0] == 0x4e && code[1] == 0x75) { /* RTS */
202 code += 3;
203 strlcpy(cursym, (char *)code, sizeof(cursym));
204 break;
205 }
206 }
207
208 if (!cursym[0])
209 break;
210
211 sym = NULL;
212 for (n = 0; n < XALLOC_NSYMBOLS; n++) {
213 tsym = symbols + (XALLOC_SYMBOL_SIZE * n);
214
215 if (tsym[0] == '\0')
216 break;
217 if (strcmp(tsym, cursym) == 0) {
218 sym = tsym;
219 break;
220 }
221 }
222 if (sym == NULL) {
223 for (n = 0; n < XALLOC_NSYMBOLS; n++) {
224 tsym = symbols + (XALLOC_SYMBOL_SIZE * n);
225 if (tsym[0] != '\0')
226 continue;
227
228 strlcpy(tsym, cursym, XALLOC_SYMBOL_SIZE);
229 sym = tsym;
230 break;
231 }
232 }
233 if (sym == NULL)
234 break;
235
236 xa->stack[nframe] = sym;
237
238 if (strcmp(sym, "main") == 0 || strcmp(sym, "uthread_begin") == 0)
239 break;
240
241 /* walk back up the chain */
242 _a6 = *(unsigned long *)_a6;
243 }
244
245 xa->addr = (unsigned long)ptr;
246 xa->size = size;
247 #endif
248
249 return ptr;
250 }
251
252 void
253 xfree(void *ptrptr)
254 {
255 unsigned long *addr = (unsigned long *)ptrptr;
256 void *ptr;
257 #ifdef MALLOC_DEBUG
258 size_t n;
259 #endif
260
261 if (ptrptr == NULL)
262 panic("xfree(NULL)");
263
264 ptr = (void *)*addr;
265 if (ptr == NULL)
266 panic("xfree(&NULL) likely a double-free");
267
268 #ifdef MALLOC_DEBUG
269 for (n = 0; n < XALLOC_NXALLOCS; n++) {
270 if (xallocs[n].addr == (unsigned long)ptr) {
271 memset(&xallocs[n], 0, sizeof(struct xalloc));
272 break;
273 }
274 }
275 if (n == XALLOC_NXALLOCS)
276 panic("xfree() without xalloc, possibly a junk free",
277 (unsigned long)ptr);
278 #endif
279
280 DisposePtr(ptr);
281 *addr = 0L;
282 }
283
284 void *
285 xmalloczero(size_t size)
286 {
287 void *ptr;
288
289 ptr = xmalloc(size);
290 if (ptr != NULL)
291 memset(ptr, 0, size);
292
293 return ptr;
294 }
295
296 void *
297 xcalloc(size_t nmemb, size_t size)
298 {
299 if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
300 nmemb > 0 && SIZE_MAX / nmemb < size)
301 panic("xcalloc(%lu, %lu) overflow", nmemb, size);
302
303 return xmalloczero(nmemb * size);
304 }
305
306 void *
307 xrealloc(void *src, size_t size)
308 {
309 void *ptr, *tsrc;
310
311 ptr = xmalloc(size);
312 if (ptr != NULL && src != NULL) {
313 memcpy(ptr, src, size);
314 tsrc = src;
315 xfree(&tsrc);
316 }
317
318 return ptr;
319 }
320
321 void *
322 xreallocarray(void *optr, size_t nmemb, size_t size)
323 {
324 if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
325 nmemb > 0 && SIZE_MAX / nmemb < size)
326 panic("xreallocarray(%lu, %lu) failed", nmemb, size);
327
328 return xrealloc(optr, size * nmemb);
329 }
330
331 char *
332 xstrdup(const char *str)
333 {
334 char *cp;
335 size_t len;
336
337 len = strlen(str);
338 cp = xmalloc(len + 1);
339 if (cp != NULL)
340 strlcpy(cp, str, len + 1);
341
342 return cp;
343 }
344
345 char *
346 xstrndup(const char *str, size_t maxlen)
347 {
348 char *copy;
349 const char *cp;
350 size_t len;
351
352 /* strnlen */
353 for (cp = str; maxlen != 0 && *cp != '\0'; cp++, maxlen--)
354 ;
355
356 len = (size_t)(cp - str);
357 copy = xmalloc(len + 1);
358 if (copy != NULL) {
359 (void)memcpy(copy, str, len);
360 copy[len] = '\0';
361 }
362
363 return copy;
364 }
365
366 #ifdef MALLOC_DEBUG
367 void
368 xalloc_print(size_t (*printer)(const char *, ...))
369 {
370 ssize_t n, j, len;
371 size_t total = 0, nallocs = 0;
372 char chain[128];
373
374 for (n = 0; n < XALLOC_NXALLOCS; n++) {
375 if (xallocs[n].addr == 0)
376 continue;
377
378 total += xallocs[n].size;
379 nallocs++;
380
381 chain[0] = '\0';
382 len = 0;
383 for (j = XALLOC_MAX_STACK_DEPTH - 1; j >= 0; j--) {
384 if (xallocs[n].stack[j] == 0)
385 continue;
386
387 if (chain[0] != '\0') {
388 if (len >= sizeof(chain) - 2)
389 break;
390 chain[len++] = ' ';
391 chain[len++] = ':';
392 chain[len++] = ' ';
393 chain[len++] = '\0';
394 }
395
396 len = strlcat(chain, xallocs[n].stack[j], sizeof(chain));
397 if (len >= sizeof(chain))
398 break;
399 }
400
401 printer("%ld @ %s", xallocs[n].size, chain);
402 }
403
404 printer("%ld bytes in %ld allocations in use", total, nallocs);
405 }
406 #endif
407
408 /* if var having used_size can't fit add, grow it by grow_amount */
409 bool
410 grow_to_fit(void *var, size_t *var_size, size_t used_size, size_t add,
411 size_t grow_amount)
412 {
413 char **p = var;
414 char *curp = *p;
415 char *newp;
416 size_t new_size;
417
418 if (used_size + add < *var_size)
419 return true;
420
421 new_size = *var_size;
422 while (new_size < used_size + add)
423 new_size += grow_amount;
424
425 newp = xrealloc(curp, new_size);
426 if (newp == NULL)
427 return false;
428
429 *var_size = new_size;
430 *p = newp;
431
432 return true;
433 }
434
435 /*
436 * String functions
437 */
438
439 short
440 getline(char *str, size_t len, char **ret)
441 {
442 short i;
443
444 for (i = 0; i < len; i++) {
445 if (str[i] == '\r' || i == len - 1) {
446 if (*ret == NULL) {
447 *ret = xmalloc(i + 1);
448 if (*ret == NULL)
449 return -1;
450 }
451 memcpy(*ret, str, i + 1);
452 (*ret)[i] = '\0';
453 return i + 1;
454 }
455 }
456
457 return 0;
458 }
459
460 const char *
461 ordinal(unsigned short n)
462 {
463 switch (n % 100) {
464 case 11:
465 case 12:
466 case 13:
467 return "th";
468 default:
469 switch (n % 10) {
470 case 1:
471 return "st";
472 case 2:
473 return "nd";
474 case 3:
475 return "rd";
476 default:
477 return "th";
478 }
479 }
480 }
481
482 size_t
483 rtrim(char *str, char *chars)
484 {
485 size_t len, rlen, n, j;
486
487 rlen = len = strlen(str);
488
489 for (n = len; n > 0; n--) {
490 for (j = 0; chars[j] != '\0'; j++) {
491 if (str[n - 1] == chars[j]) {
492 rlen--;
493 str[n - 1] = '\0';
494 goto next_in_str;
495 }
496 }
497
498 break;
499 next_in_str:
500 continue;
501 }
502
503 return rlen;
504 }
505
506 long
507 strpos_quoted(char *str, char c)
508 {
509 long pos;
510 unsigned char quot = 0;
511
512 for (pos = 0; str[pos] != '\0'; pos++) {
513 if (quot) {
514 if (str[pos] == '\\') {
515 pos++;
516 continue;
517 }
518 if (str[pos] == quot)
519 quot = 0;
520 continue;
521 } else {
522 if (str[pos] == '"') {
523 quot = str[pos];
524 continue;
525 }
526 if (str[pos] == c)
527 return pos;
528 }
529 }
530
531 return -1;
532 }
533
534 char *
535 OSTypeToString(OSType type)
536 {
537 static char ostype_s[5];
538
539 ostype_s[0] = (unsigned char)((type >> 24) & 0xff);
540 ostype_s[1] = (unsigned char)((type >> 16) & 0xff);
541 ostype_s[2] = (unsigned char)((type >> 8) & 0xff);
542 ostype_s[3] = (unsigned char)(type & 0xff);
543 ostype_s[4] = 0;
544
545 return ostype_s;
546 }
547
548 /*
549 * BSD err(3) and warn(3) functions
550 */
551
552 void
553 vwarn(short alert_func, const char *format, va_list ap)
554 {
555 Rect bounds;
556 short hit, itype;
557 WindowPtr win, dialog;
558 Handle ihandle;
559 Rect irect;
560
561 GetPort(&win);
562
563 vsnprintf(err_str, ERROR_STRING_SIZE, format, ap);
564
565 ParamText(CtoPstr(err_str), "\p", "\p", "\p");
566
567 center_in_screen(320, 110, false, &bounds);
568 dialog = NewDialog(nil, &bounds, "\p", false, dBoxProc,
569 (WindowPtr)-1L, false, 0, alert_ditl_h);
570
571 GetDItem(dialog, ALERT_DITL_ICON, &itype, &ihandle, &irect);
572 switch (alert_func) {
573 case CAUTION_ALERT:
574 ihandle = GetIcon(cautionIcon);
575 break;
576 case NOTE_ALERT:
577 ihandle = GetIcon(noteIcon);
578 break;
579 case APPICON_ALERT:
580 ihandle = GetResource('ICN#', APPICON_ICN_ID);
581 if (ihandle)
582 break;
583 default:
584 ihandle = GetIcon(stopIcon);
585 }
586 SetDItem(dialog, ALERT_DITL_ICON, itype, ihandle, &irect);
587
588 ShowWindow(dialog);
589
590 for (;;) {
591 ModalDialog(0, &hit);
592 if (hit == ok)
593 break;
594 }
595 ReleaseResource(ihandle);
596 DisposDialog(dialog);
597
598 /*
599 * Pre-allocate for the next one while we have memory. We can't use
600 * xNewHandle because we might already be alerting about an OOM
601 * condition.
602 */
603 DisposHandle(alert_ditl_h);
604 alert_ditl_h = NewHandle(sizeof(alert_ditl));
605 if (alert_ditl_h == NULL)
606 ExitToShell();
607 HLock(alert_ditl_h);
608 memcpy(*alert_ditl_h, alert_ditl, sizeof(alert_ditl));
609 HUnlock(alert_ditl_h);
610
611 SetPort(win);
612 }
613
614 void
615 panic(const char *format, ...)
616 {
617 va_list ap;
618
619 va_start(ap, format);
620 vwarn(STOP_ALERT, format, ap);
621 va_end(ap);
622
623 ExitToShell();
624 }
625
626 void
627 err(short ret, const char *format, ...)
628 {
629 va_list ap;
630
631 va_start(ap, format);
632 vwarn(STOP_ALERT, format, ap);
633 va_end(ap);
634
635 ExitToShell();
636 }
637
638 void
639 warn(const char *format, ...)
640 {
641 va_list ap;
642
643 va_start(ap, format);
644 vwarn(CAUTION_ALERT, format, ap);
645 va_end(ap);
646 }
647
648 void
649 warnx(const char *format, ...)
650 {
651 va_list ap;
652
653 va_start(ap, format);
654 vwarn(CAUTION_ALERT, format, ap);
655 va_end(ap);
656 }
657
658 void
659 note(const char *format, ...)
660 {
661 va_list ap;
662
663 va_start(ap, format);
664 vwarn(NOTE_ALERT, format, ap);
665 va_end(ap);
666 }
667
668 void
669 appicon_note(const char *format, ...)
670 {
671 va_list ap;
672
673 va_start(ap, format);
674 vwarn(APPICON_ALERT, format, ap);
675 va_end(ap);
676 }
677
678 short
679 ask(const char *format, ...)
680 {
681 Rect bounds;
682 short hit;
683 WindowPtr win, dialog;
684 va_list ap;
685
686 GetPort(&win);
687
688 va_start(ap, format);
689 vsnprintf(err_str, ERROR_STRING_SIZE, format, ap);
690 va_end(ap);
691
692 ParamText(CtoPstr(err_str), "\p", "\p", "\p");
693
694 ask_ditl_h = xNewHandle(sizeof(ask_ditl));
695 HLock(ask_ditl_h);
696 memcpy(*ask_ditl_h, ask_ditl, sizeof(ask_ditl));
697 HUnlock(ask_ditl_h);
698
699 center_in_screen(300, 100, false, &bounds);
700 dialog = NewDialog(nil, &bounds, "\p", false, dBoxProc,
701 (WindowPtr)-1L, false, 0, ask_ditl_h);
702
703 ShowWindow(dialog);
704 for (;;) {
705 ModalDialog(0, &hit);
706 if (hit == 1 || hit == 2)
707 break;
708 }
709 DisposDialog(dialog);
710 DisposHandle(ask_ditl_h);
711
712 SetPort(win);
713
714 return (hit == 1);
715 }
716
717 void
718 about(char *program_name)
719 {
720 VersRecHndl vers;
721 char vers_s[255];
722 char short_vers[255] = { 0 };
723 short vlen, n;
724
725 if ((vers = (VersRecHndl)GetResource('vers', 1))) {
726 /*
727 * vers "long version string" is a pascal string after the
728 * short version pascal string
729 */
730 HLock(vers);
731 vlen = (*vers)->shortVersion[0];
732 memcpy(short_vers, (*vers)->shortVersion + vlen + 1,
733 sizeof((*vers)->shortVersion) - vlen - 1);
734 PtoCstr(short_vers);
735 snprintf(vers_s, sizeof(vers_s), "%s %s", program_name,
736 short_vers);
737 for (n = 0; n < sizeof(vers_s); n++) {
738 if (vers_s[n] == '©') {
739 vers_s[n - 1] = '\r';
740 break;
741 }
742 }
743 ReleaseResource(vers);
744 appicon_note("%s", vers_s);
745 } else
746 warnx("Can't find version number!");
747 }
748
749 void
750 progress(char *format, ...)
751 {
752 static Str255 progress_s;
753 Handle thandle;
754 va_list argptr;
755 Rect bounds;
756 Rect trect;
757 short ttype;
758
759 if (format == NULL) {
760 if (progress_dialog != NULL) {
761 DisposDialog(progress_dialog);
762 DisposHandle(progress_ditl_h);
763 progress_dialog = NULL;
764 }
765 return;
766 }
767
768 va_start(argptr, format);
769 vsnprintf((char *)progress_s, 256, format, argptr);
770 va_end(argptr);
771 CtoPstr(progress_s);
772
773 if (progress_dialog == NULL) {
774 progress_ditl_h = xNewHandle(sizeof(progress_ditl));
775 HLock(progress_ditl_h);
776 memcpy(*progress_ditl_h, progress_ditl, sizeof(progress_ditl));
777 HUnlock(progress_ditl_h);
778
779 center_in_screen(330, 60, false, &bounds);
780 progress_dialog = NewDialog(nil, &bounds, "\p", false, dBoxProc,
781 (WindowPtr)-1L, false, 0, progress_ditl_h);
782 }
783
784 GetDItem(progress_dialog, 1, &ttype, &thandle, &trect);
785 SetIText(thandle, progress_s);
786 if (progress_s[0] > 30) {
787 trect.top -= 8;
788 trect.bottom += 16;
789 SetDItem(progress_dialog, 1, ttype, thandle, &trect);
790 }
791
792 ShowWindow(progress_dialog);
793 DrawDialog(progress_dialog);
794 }
795
796 void
797 window_rect(WindowPtr win, Rect *ret)
798 {
799 *ret = (*(((WindowPeek)win)->strucRgn))->rgnBBox;
800 ret->left += 1;
801 ret->right -= 2;
802 ret->top -= 1;
803 ret->bottom -= 1;
804 }
805
806 void
807 center_in_screen(short width, short height, bool titlebar, Rect *b)
808 {
809 b->left = ((screenBits.bounds.right - screenBits.bounds.left) / 2) -
810 (width / 2);
811 b->top = ((screenBits.bounds.bottom - screenBits.bounds.top) / 2) -
812 (height / 2) + (titlebar ? GetMBarHeight() : 0);
813 b->right = b->left + width;
814 b->bottom = b->top + height;
815 }
816
817 Point
818 centered_sfget_dialog(void)
819 {
820 Point p;
821 Rect r;
822
823 center_in_screen(364, 216, false, &r);
824 p.h = r.left;
825 p.v = r.top;
826
827 return p;
828 }
829
830 Point
831 centered_sfput_dialog(void)
832 {
833 Point p;
834 Rect r;
835
836 center_in_screen(320, 200, false, &r);
837 p.h = r.left;
838 p.v = r.top;
839
840 return p;
841 }
842
843 /*
844 * General Mac-specific non-GUI functions
845 */
846
847 static unsigned long _xorshift_state = 0;
848 unsigned long
849 xorshift32(void)
850 {
851 unsigned long x = _xorshift_state;
852 if (x == 0)
853 x = Ticks;
854 x ^= x << 13;
855 x ^= x >> 17;
856 x ^= x << 5;
857 return _xorshift_state = x;
858 }
859
860
861 /*
862 * Error checking wrappers for Mac toolkit functions
863 */
864
865 Handle
866 xNewHandle(size_t size)
867 {
868 Handle h;
869
870 if (size == 0)
871 panic("Zero xNewHandle size");
872
873 h = NewHandle(size);
874 if (h == NULL)
875 panic("Failed to NewHandle(%lu)", size);
876
877 return h;
878 }
879
880 Handle
881 xGetResource(ResType type, short id)
882 {
883 Handle h;
884
885 h = GetResource(type, id);
886 if (h == NULL)
887 panic("Failed to find resource %d", id);
888
889 return h;
890 }
891
892 StringHandle
893 xGetString(short id)
894 {
895 StringHandle h;
896
897 h = GetString(id);
898 if (h == NULL)
899 panic("Failed to find STR resource %d", id);
900
901 return h;
902 }
903
904 char *
905 xGetStringAsChar(short id)
906 {
907 StringHandle h;
908 char *out;
909 size_t l;
910
911 h = xGetString(id);
912 HLock(h);
913 l = (*h)[0];
914 out = xmalloc(l + 1);
915 if (out != NULL) {
916 memcpy((void *)out, (void *)(*h + 1), l);
917 out[l] = '\0';
918 }
919 ReleaseResource(h);
920
921 return out;
922 }
923
924 bool
925 xGetStringAsLong(short id, long *ret)
926 {
927 char *c;
928
929 c = xGetStringAsChar(id);
930 if (c == NULL)
931 return false;
932 *ret = atol(c);
933 xfree(&c);
934 return true;
935 }
936
937 bool
938 xSetHandleSize(Handle h, Size s)
939 {
940 SetHandleSize(h, s);
941 if (MemError()) {
942 warn("Failed to SetHandleSize to %ld", s);
943 return false;
944 }
945 return true;
946 }
947
948 /*
949 * Filesystem utilities
950 */
951
952 short
953 getpath(short vRefNum, Str255 fileName, Str255 ret, bool include_file)
954 {
955 WDPBRec wdir;
956 HVolumeParam wvol;
957 DirInfo wcinfo;
958 char *name = NULL;
959 size_t retlen = 0, len;
960 char *tmpret = NULL, *tmp = NULL;
961 char *lastcolon;
962
963 ret[0] = 0;
964
965 if (strchr((char *)fileName + 1, ':') != NULL) {
966 /* already a full path */
967 memcpy(ret, fileName, 256);
968 if (!include_file) {
969 PtoCstr(ret);
970 lastcolon = strrchr((char *)ret, ':');
971 lastcolon[0] = '\0';
972 CtoPstr(ret);
973 }
974 return 0;
975 }
976
977 name = xmalloc(FILENAME_MAX);
978 if (name == NULL)
979 return 1;
980
981 wdir.ioVRefNum = wdir.ioWDVRefNum = vRefNum;
982 wdir.ioWDIndex = 0;
983 wdir.ioWDProcID = 0;
984 wdir.ioNamePtr = (StringPtr)name;
985 if (PBGetWDInfo(&wdir, 0) != noErr) {
986 warn("Failed looking up directory");
987 xfree(&name);
988 return 1;
989 }
990
991 wvol.ioNamePtr = (StringPtr)name;
992 wvol.ioVRefNum = vRefNum;
993 wvol.ioVolIndex = 0;
994
995 if (PBHGetVInfoSync((HParmBlkPtr)&wvol) != noErr) {
996 warn("Failed getting volume info");
997 xfree(&name);
998 return 1;
999 }
1000
1001 if (wvol.ioVSigWord != 0x4244) {
1002 warn("Unknown filesystem type 0x%x", wvol.ioVSigWord);
1003 xfree(&name);
1004 return 1;
1005 }
1006
1007 wcinfo.ioVRefNum = vRefNum;
1008 wcinfo.ioNamePtr = (StringPtr)name;
1009 wcinfo.ioFDirIndex = -1;
1010 wcinfo.ioDrParID = wdir.ioWDDirID;
1011 wcinfo.ioDrDirID = wdir.ioWDDirID;
1012
1013 tmp = xmalloc(FILENAME_MAX);
1014 if (tmp == NULL) {
1015 xfree(&name);
1016 return 1;
1017 }
1018 tmpret = xmalloc(FILENAME_MAX);
1019 if (tmp == NULL) {
1020 xfree(&tmp);
1021 xfree(&name);
1022 return 1;
1023 }
1024
1025 /* go backwards, prepending each folder's parent */
1026 while (wcinfo.ioDrParID != 1) {
1027 wcinfo.ioDrDirID = wcinfo.ioDrParID; /* .. */
1028
1029 if (PBGetCatInfo((CInfoPBPtr)&wcinfo, 0) != noErr)
1030 break;
1031
1032 len = name[0];
1033 PtoCstr(name);
1034 if (retlen == 0) {
1035 retlen = len;
1036 strlcpy(tmpret, (char *)name, FILENAME_MAX);
1037 } else {
1038 strlcpy(tmp, tmpret, FILENAME_MAX);
1039 snprintf(tmpret, FILENAME_MAX, "%s:%s", name, tmp);
1040 }
1041 }
1042
1043 if (include_file) {
1044 /* append the original path */
1045 memcpy(name, fileName, FILENAME_MAX);
1046 PtoCstr(name);
1047 if (retlen == 0)
1048 strlcpy(tmpret, name, FILENAME_MAX);
1049 else {
1050 strlcat(tmpret, ":", FILENAME_MAX);
1051 strlcat(tmpret, name, FILENAME_MAX);
1052 }
1053 } else if (retlen == 0) {
1054 ret[0] = 0;
1055 xfree(&tmp);
1056 xfree(&tmpret);
1057 xfree(&name);
1058 return 0;
1059 }
1060
1061 CtoPstr(tmpret);
1062 memcpy(ret, tmpret, FILENAME_MAX);
1063 xfree(&tmp);
1064 xfree(&tmpret);
1065 xfree(&name);
1066
1067 return 0;
1068 }
1069
1070 short
1071 stat(char *path, struct stat *sb)
1072 {
1073 char *ppath;
1074 short ret;
1075
1076 ppath = xstrdup(path);
1077 if (ppath == NULL)
1078 return -1;
1079 CtoPstr(ppath);
1080 ret = FStat((unsigned char *)ppath, sb);
1081 xfree(&ppath);
1082
1083 return ret;
1084 }
1085
1086 short
1087 FStat(Str255 path, struct stat *sb)
1088 {
1089 CInfoPBRec catblock = { 0 };
1090 short ret;
1091
1092 catblock.hFileInfo.ioNamePtr = path;
1093 ret = PBGetCatInfo(&catblock, 0);
1094 if (ret != noErr)
1095 return -1;
1096
1097 /* data fork logical length, ignoring resource fork logical length */
1098 sb->st_size = catblock.hFileInfo.ioFlLgLen;
1099 sb->st_ctime = catblock.hFileInfo.ioFlCrDat;
1100 sb->st_mtime = catblock.hFileInfo.ioFlMdDat;
1101 sb->st_flags = catblock.hFileInfo.ioFlAttrib;
1102
1103 return 0;
1104 }
1105
1106 bool
1107 FIsDir(Str255 path)
1108 {
1109 struct stat st;
1110
1111 if (FStat(path, &st) != 0)
1112 return false;
1113
1114 /* bit 4 is set in ioFlAttrib if the item is a directory */
1115 if (st.st_flags & (1 << 4))
1116 return true;
1117
1118 return false;
1119 }
1120
1121 OSErr
1122 copy_file(Str255 source, Str255 dest, bool overwrite)
1123 {
1124 FInfo fi;
1125 IOParam pb;
1126 short error, source_ref, dest_ref;
1127
1128 /* copy data fork */
1129
1130 error = GetFInfo(source, 0, &fi);
1131 if (error)
1132 return error;
1133
1134 error = Create(dest, 0, fi.fdCreator, fi.fdType);
1135 if (error == dupFNErr && overwrite) {
1136 error = FSDelete(dest, 0);
1137 if (error)
1138 return error;
1139 error = Create(dest, 0, fi.fdCreator, fi.fdType);
1140 }
1141 if (error)
1142 return error;
1143
1144 memset(&pb, 0, sizeof(pb));
1145 pb.ioNamePtr = source;
1146 pb.ioPermssn = fsRdPerm;
1147 error = PBOpen(&pb, false);
1148 if (error)
1149 return error;
1150 source_ref = pb.ioRefNum;
1151
1152 error = FSOpen(dest, 0, &dest_ref);
1153 if (error) {
1154 FSClose(source_ref);
1155 return error;
1156 }
1157
1158 error = copy_file_contents(source_ref, dest_ref);
1159
1160 FSClose(source_ref);
1161 FSClose(dest_ref);
1162
1163 if (error)
1164 return error;
1165
1166 /*
1167 * Copy resource fork, open source as shared read/write in case it's
1168 * an open resource file.
1169 */
1170 source_ref = OpenRFPerm(source, 0, fsRdWrShPerm);
1171
1172 if (source_ref == -1 && ResError() == eofErr) {
1173 /* no resource fork */
1174 FSClose(source_ref);
1175 FSClose(dest_ref);
1176 return 0;
1177 }
1178
1179 if (source_ref == -1)
1180 return ResError();
1181
1182 CreateResFile(dest);
1183 if (ResError()) {
1184 FSClose(source_ref);
1185 return ResError();
1186 }
1187 error = OpenRF(dest, 0, &dest_ref);
1188 if (error) {
1189 FSClose(source_ref);
1190 return error;
1191 }
1192
1193 error = copy_file_contents(source_ref, dest_ref);
1194
1195 FSClose(source_ref);
1196 FSClose(dest_ref);
1197
1198 return error;
1199 }
1200
1201 OSErr
1202 copy_file_contents(short source_ref, short dest_ref)
1203 {
1204 char *buf;
1205 short error;
1206 long source_size, count;
1207
1208 GetEOF(source_ref, &source_size);
1209 error = SetFPos(source_ref, fsFromStart, 0);
1210 if (error)
1211 return error;
1212 error = SetEOF(dest_ref, source_size);
1213 if (error)
1214 return error;
1215 error = SetFPos(dest_ref, fsFromStart, 0);
1216 if (error)
1217 return error;
1218
1219 buf = xmalloc(1024);
1220 if (buf == NULL)
1221 return -1;
1222
1223 while (source_size > 0) {
1224 count = 1024;
1225 if (count > source_size)
1226 count = source_size;
1227 error = FSRead(source_ref, &count, buf);
1228 if (error && error != eofErr)
1229 break;
1230 source_size -= count;
1231 error = FSWrite(dest_ref, &count, buf);
1232 if (error && error != eofErr)
1233 break;
1234 }
1235
1236 xfree(&buf);
1237
1238 if (error && error != eofErr)
1239 return error;
1240
1241 return 0;
1242 }
1243
1244 /* read a \r-terminated line or the final non-line bytes of an open file */
1245 OSErr
1246 FSReadLine(short frefnum, char *buf, size_t buflen)
1247 {
1248 char tbuf;
1249 size_t pos, fsize, rlen = 1, total_read = 0;
1250 short error;
1251
1252 GetFPos(frefnum, &pos);
1253 GetEOF(frefnum, &fsize);
1254
1255 for (; pos <= fsize; pos++) {
1256 if (total_read > buflen)
1257 return -1;
1258
1259 error = FSRead(frefnum, &rlen, &tbuf);
1260 if (error)
1261 return -1;
1262
1263 if (tbuf == '\r')
1264 return total_read;
1265
1266 buf[total_read++] = tbuf;
1267 }
1268
1269 /* nothing found until the end of the file */
1270 return total_read;
1271 }
1272
1273
1274 /*
1275 * Gestalt functions
1276 */
1277 char *
1278 gestalt_machine_type(void)
1279 {
1280 short error;
1281 long resp;
1282
1283 error = Gestalt(gestaltMachineType, &resp);
1284 if (error)
1285 return NULL;
1286 switch (resp) {
1287 case gestaltClassic:
1288 return "Macintosh 128K";
1289 case gestaltMacXL:
1290 return "Macintosh XL";
1291 case gestaltMac512KE:
1292 return "Macintosh 512Ke";
1293 case gestaltMacPlus:
1294 return "Macintosh Plus";
1295 case gestaltMacSE:
1296 return "Macintosh SE";
1297 case gestaltMacII:
1298 return "Macintosh II";
1299 case gestaltMacIIx:
1300 return "Macintosh IIx";
1301 case gestaltMacIIcx:
1302 return "Macintosh IIcx";
1303 case gestaltMacSE030:
1304 return "Macintosh SE/30";
1305 case gestaltPortable:
1306 return "Macintosh Portable";
1307 case gestaltMacIIci:
1308 return "Macintosh IIci";
1309 case gestaltMacIIfx:
1310 return "Macintosh IIfx";
1311 case gestaltMacClassic:
1312 return "Macintosh Classic";
1313 case gestaltMacIIsi:
1314 return "Macintosh IIsi";
1315 case gestaltMacLC:
1316 return "Macintosh LC";
1317 }
1318
1319 return NULL;
1320 }
1321
1322 char *
1323 get_version(bool long_version)
1324 {
1325 static char vers_s[256] = { 0 };
1326 char *v;
1327 VersRecHndl vers;
1328 short len;
1329
1330 vers = (VersRecHndl)GetResource('vers', 1);
1331 if (!vers)
1332 return "?.?";
1333
1334 HLock(vers);
1335 v = (char *)&(*vers)->shortVersion;
1336 len = v[0];
1337 if (long_version) {
1338 v += len + 1;
1339 len = v[0];
1340 }
1341 memcpy(vers_s, v, len + 1);
1342 ReleaseResource(vers);
1343
1344 PtoCstr(vers_s);
1345 return vers_s;
1346 }
1347
1348 /*
1349 * General Mac-specific GUI functions
1350 */
1351
1352 short
1353 FontHeight(short font_id, short size)
1354 {
1355 FMInput f_in;
1356 FMOutput *f_out;
1357
1358 if (font_id == -1)
1359 font_id = thePort->txFont;
1360 if (size == -1)
1361 size = thePort->txSize;
1362
1363 f_in.family = font_id;
1364 f_in.size = size;
1365 f_in.face = 0;
1366 f_in.needBits = false;
1367 f_in.device = 0;
1368 f_in.numer.h = f_in.numer.v = 1;
1369 f_in.denom.h = f_in.denom.v = 1;
1370
1371 f_out = FMSwapFont(&f_in);
1372
1373 return (((f_out->leading + f_out->ascent + f_out->descent) *
1374 f_out->numer.v) / f_out->denom.v);
1375 }
1376
1377 void
1378 DrawGrowIconOnly(WindowPtr win)
1379 {
1380 Rect r;
1381 RgnHandle tmp;
1382
1383 GetClip(tmp = NewRgn());
1384 if (tmp == NULL) {
1385 warn("NewRgn() failed");
1386 return;
1387 }
1388 r = win->portRect;
1389 r.top = r.bottom - SCROLLBAR_WIDTH;
1390 r.left = r.right - SCROLLBAR_WIDTH + 1;
1391 ClipRect(&r);
1392 DrawGrowIcon(win);
1393 SetClip(tmp);
1394 DisposeRgn(tmp);
1395 }
1396
1397 /* assumes a fixed-width style */
1398 short
1399 TEGetWidth(short off, TEHandle te)
1400 {
1401 TextStyle style;
1402 short fheight, fwidth, ascent, old_font, old_size;
1403
1404 TEGetStyle(off, &style, &fheight, &ascent, te);
1405
1406 old_font = thePort->txFace;
1407 old_size = thePort->txSize;
1408 thePort->txFace = style.tsFont;
1409 thePort->txSize = style.tsSize;
1410 fwidth = CharWidth('m');
1411 thePort->txFace = old_font;
1412 thePort->txSize = old_size;
1413
1414 return fwidth;
1415 }
1416
1417 #define ceildiv(a,b) ((a / b) + (!!(a % b)))
1418
1419 void
1420 UpdateScrollbarForTE(GrafPtr win, ControlHandle control, TEHandle te, bool reset)
1421 {
1422 size_t vlines, telines;
1423 TERec *ter;
1424 RgnHandle rgn;
1425 short fheight, fwidth, max, val, per_line, horiz, max_chars, n;
1426
1427 HLock(control);
1428 HLock(te);
1429 ter = *te;
1430
1431 horiz = (((*control)->contrlRect.bottom - (*control)->contrlRect.top) <
1432 ((*control)->contrlRect.right - (*control)->contrlRect.left));
1433
1434 if (horiz) {
1435 fwidth = TEGetWidth(0, te);
1436 per_line = ((ter->viewRect.right - ter->viewRect.left) /
1437 fwidth) - 1;
1438 for (max_chars = 0, n = 1; n < ter->nLines; n++) {
1439 if (ter->lineStarts[n] - ter->lineStarts[n - 1] > max_chars)
1440 max_chars = ter->lineStarts[n] - ter->lineStarts[n - 1];
1441 }
1442
1443 if (max_chars <= per_line)
1444 /* don't enable the scrollbar */
1445 max = 1;
1446 else
1447 max = max_chars - per_line + 1;
1448
1449 if (reset) {
1450 val = 1;
1451 TESetSelect(0, 0, te);
1452 } else {
1453 val = (ter->viewRect.left - ter->destRect.left);
1454
1455 if (val < 0)
1456 val = 1;
1457 else {
1458 val = ceildiv(val, fwidth) + 1;
1459 if (val > max)
1460 max = val;
1461 }
1462 }
1463 } else {
1464 fheight = TEGetHeight(0, 0, te);
1465 vlines = (ter->viewRect.bottom - ter->viewRect.top) / fheight;
1466 telines = ter->nLines;
1467 /* telines is inaccurate if the last line doesn't have any chars */
1468 //if (telines >= vlines)
1469 // telines++;
1470 max = telines - vlines + 1;
1471 if (max < 1)
1472 max = 1;
1473
1474 if (reset) {
1475 val = 1;
1476 TESetSelect(0, 0, te);
1477 } else {
1478 val = (ter->viewRect.top - ter->destRect.top);
1479 if (val < 0)
1480 val = 1;
1481 else {
1482 val = ceildiv(val, fheight) + 1;
1483 if (val > max)
1484 max = val;
1485 }
1486 }
1487 }
1488
1489 /*
1490 * Avoid SetCtlMax because it will redraw and then SetCtlValue will
1491 * redraw again, which can cause a jump if we're trying to keep the
1492 * scrollbar position in the same place (like at the bottom).
1493 */
1494 (*control)->contrlMax = max;
1495 SetCtlValue(control, val);
1496
1497 rgn = NewRgn();
1498 RectRgn(rgn, &(*control)->contrlRect);
1499 UpdtControl(win, rgn);
1500 CloseRgn(rgn);
1501
1502 HUnlock(te);
1503 HUnlock(control);
1504 }
1505
1506 void
1507 SetTrackControlTE(TEHandle te)
1508 {
1509 track_control_te = te;
1510 }
1511
1512 pascal void
1513 TrackMouseDownInControl(ControlHandle control, short part)
1514 {
1515 TERec *ter;
1516 short page, val, adj, fheight, fwidth, horiz, per_line;
1517
1518 if (track_control_te == NULL)
1519 panic("TrackMouseDownInControl without SetTrackControlTE");
1520
1521 HLock(track_control_te);
1522 ter = *track_control_te;
1523
1524 horiz = (((*control)->contrlRect.bottom - (*control)->contrlRect.top) <
1525 ((*control)->contrlRect.right - (*control)->contrlRect.left));
1526
1527 if (horiz) {
1528 fwidth = TEGetWidth(0, track_control_te);
1529 per_line = ((ter->viewRect.right - ter->viewRect.left) /
1530 fwidth) - 1;
1531 page = ceildiv(GetCtlMax(control) + per_line,
1532 ((per_line * 75) / 100)) + 1;
1533 } else {
1534 /* keep 1 line of context between pages */
1535 fheight = TEGetHeight(0, 0, track_control_te);
1536 page = ((ter->viewRect.bottom - ter->viewRect.top) / fheight) - 1;
1537 }
1538
1539 adj = 0;
1540 switch (part) {
1541 case inUpButton:
1542 adj = -1;
1543 break;
1544 case inPageUp:
1545 adj = -page;
1546 break;
1547 case inDownButton:
1548 adj = 1;
1549 break;
1550 case inPageDown:
1551 adj = page;
1552 break;
1553 }
1554
1555 val = GetCtlValue(control);
1556 if (val + adj < GetCtlMin(control))
1557 adj = -(val - GetCtlMin(control));
1558 if (val + adj > GetCtlMax(control))
1559 adj = (GetCtlMax(control) - val);
1560 if (adj == 0)
1561 return;
1562
1563 if (horiz)
1564 TEScroll(-adj * fwidth, 0, track_control_te);
1565 else
1566 TEScroll(0, -adj * fheight, track_control_te);
1567
1568 SetCtlValue(control, val + adj);
1569
1570 HUnlock(track_control_te);
1571 }
1572
1573 pascal bool
1574 ModalDialogFilter(DialogPtr dlg, EventRecord *event, short *hit)
1575 {
1576 WindowPtr event_win;
1577 short event_in;
1578 char key;
1579
1580 switch (event->what) {
1581 case mouseDown:
1582 event_in = FindWindow(event->where, &event_win);
1583
1584 switch (event_in) {
1585 case inGoAway:
1586 if (TrackGoAway(dlg, event->where)) {
1587 *hit = -1;
1588 return true;
1589 }
1590 }
1591 break;
1592 case keyDown:
1593 key = event->message & charCodeMask;
1594
1595 if (event->modifiers & cmdKey) {
1596 switch (key) {
1597 case 'x':
1598 ZeroScrap();
1599 DlgCut(dlg);
1600 break;
1601 case 'c':
1602 ZeroScrap();
1603 DlgCopy(dlg);
1604 break;
1605 case 'v':
1606 if (TEFromScrap() == noErr)
1607 DlgPaste(dlg);
1608 break;
1609 }
1610 event->what = nullEvent;
1611 return false;
1612 } else if (key == 13 || key == 3) {
1613 /* OK button */
1614 *hit = OK;
1615 return true;
1616 }
1617
1618 break;
1619 }
1620
1621 return false;
1622 }
1623
1624 static short _password_dialog_ditl_id = -1;
1625 static char *_password_dialog_storage = NULL;
1626 static size_t _password_dialog_storage_len = 0;
1627
1628 void
1629 PasswordDialogFieldFilterSetup(short ditl_id, char *storage, size_t len)
1630 {
1631 _password_dialog_ditl_id = ditl_id;
1632 _password_dialog_storage = storage;
1633 _password_dialog_storage_len = len;
1634
1635 memset(_password_dialog_storage, 0, len);
1636 }
1637
1638 pascal bool
1639 PasswordDialogFieldFilter(DialogPtr dlg, EventRecord *event, short *hit)
1640 {
1641 DialogPeek dlgp;
1642 short sel_start, sel_end;
1643 char key;
1644
1645 dlgp = (DialogPeek)dlg;
1646 if (dlgp->editField == _password_dialog_ditl_id - 1) {
1647 sel_start = (*(dlgp->textH))->selStart;
1648 sel_end = (*(dlgp->textH))->selEnd;
1649
1650 switch (event->what) {
1651 case keyDown:
1652 case autoKey:
1653 key = event->message & charCodeMask;
1654 if (event->modifiers & cmdKey) {
1655 /* TODO: implement DlgPaste for cmd+v? */
1656 event->what = nullEvent;
1657 return false;
1658 }
1659
1660 if (key == 8) {
1661 /* backspace */
1662 if (sel_start == sel_end && sel_start > 0)
1663 memmove(_password_dialog_storage + sel_start - 1,
1664 _password_dialog_storage + sel_start,
1665 _password_dialog_storage_len - sel_start - 1);
1666 else if (sel_start != sel_end)
1667 memmove(_password_dialog_storage + sel_start,
1668 _password_dialog_storage + sel_end,
1669 _password_dialog_storage_len - sel_end - 1);
1670 } else if (sel_start >= _password_dialog_storage_len) {
1671 event->what = nullEvent;
1672 return false;
1673 } else if (key >= ' ' && key <= '~') {
1674 if (sel_start != sel_end)
1675 /* delete selection before making space for new char */
1676 memmove(_password_dialog_storage + sel_start,
1677 _password_dialog_storage + sel_end,
1678 _password_dialog_storage_len - sel_end - 1);
1679 memmove(_password_dialog_storage + sel_start + 1,
1680 _password_dialog_storage + sel_start,
1681 _password_dialog_storage_len - sel_start - 1);
1682 _password_dialog_storage[sel_start] = key;
1683 event->message = '•';
1684 }
1685 _password_dialog_storage[(*(dlgp->textH))->teLength + 1] = '\0';
1686 sel_start = 0;
1687 break;
1688 }
1689 }
1690
1691 return ModalDialogFilter(dlg, event, hit);
1692 }
1693
1694 void
1695 PasswordDialogFieldFinish(void)
1696 {
1697 _password_dialog_ditl_id = -1;
1698 _password_dialog_storage = NULL;
1699 _password_dialog_storage_len = 0;
1700 }
1701
1702 /* (*(some_te))->caretHook = NullCaretHook; */
1703 pascal void
1704 NullCaretHook(void)
1705 {
1706 asm {
1707 move.l (a7)+,d0
1708 rts
1709 }
1710 }
1711
1712 static bool menu_bar_hidden = false;
1713 static short old_mbar_height;
1714 static Rect mbar_rect;
1715 static RgnHandle mbar_save_region;
1716
1717 void
1718 HideMenuBar(void)
1719 {
1720 RgnHandle mbar_region;
1721 WindowPeek win;
1722
1723 old_mbar_height = GetMBarHeight();
1724 SetRect(&mbar_rect, screenBits.bounds.left, screenBits.bounds.top,
1725 screenBits.bounds.right, screenBits.bounds.top + old_mbar_height);
1726
1727 mbar_save_region = NewRgn();
1728 mbar_region = NewRgn();
1729
1730 MBarHeight = 0;
1731 CopyRgn(GetGrayRgn(), mbar_save_region);
1732 RectRgn(mbar_region, &mbar_rect);
1733 UnionRgn(GetGrayRgn(), mbar_region, GetGrayRgn());
1734
1735 win = (WindowPeek)FrontWindow();
1736 PaintOne(win, mbar_region);
1737 PaintBehind(win, mbar_region);
1738 CalcVis(win);
1739 CalcVisBehind(win, mbar_region);
1740 DisposeRgn(mbar_region);
1741
1742 menu_bar_hidden = true;
1743 }
1744
1745 void
1746 RestoreHiddenMenuBar(void)
1747 {
1748 WindowPeek win;
1749
1750 if (!menu_bar_hidden)
1751 return;
1752
1753 CopyRgn(mbar_save_region, GetGrayRgn());
1754 MBarHeight = old_mbar_height;
1755
1756 RectRgn(mbar_save_region, &mbar_rect);
1757 win = (WindowPeek)FrontWindow();
1758 CalcVis(win);
1759 CalcVisBehind(win, mbar_save_region);
1760 DisposeRgn(mbar_save_region);
1761
1762 menu_bar_hidden = false;
1763
1764 HiliteMenu(0);
1765 DrawMenuBar();
1766 }
1767
1768 /* C Extensions */
1769
1770 /*
1771 * Appends src to string dst of size dsize (unlike strncat, dsize is the
1772 * full size of dst, not space left). At most dsize-1 characters
1773 * will be copied. Always NUL terminates (unless dsize <= strlen(dst)).
1774 * Returns strlen(src) + MIN(dsize, strlen(initial dst)).
1775 * If retval >= dsize, truncation occurred.
1776 */
1777 size_t
1778 strlcat(char *dst, const char *src, size_t dsize)
1779 {
1780 const char *odst = dst;
1781 const char *osrc = src;
1782 size_t n = dsize;
1783 size_t dlen;
1784
1785 /* Find the end of dst and adjust bytes left but don't go past end. */
1786 while (n-- != 0 && *dst != '\0')
1787 dst++;
1788 dlen = dst - odst;
1789 n = dsize - dlen;
1790
1791 if (n-- == 0)
1792 return(dlen + strlen(src));
1793 while (*src != '\0') {
1794 if (n != 0) {
1795 *dst++ = *src;
1796 n--;
1797 }
1798 src++;
1799 }
1800 *dst = '\0';
1801
1802 return(dlen + (src - osrc)); /* count does not include NUL */
1803 }
1804
1805 /*
1806 * Copy string src to buffer dst of size dsize. At most dsize-1
1807 * chars will be copied. Always NUL terminates (unless dsize == 0).
1808 * Returns strlen(src); if retval >= dsize, truncation occurred.
1809 */
1810 size_t
1811 strlcpy(char *dst, const char *src, size_t dsize)
1812 {
1813 const char *osrc = src;
1814 size_t nleft = dsize;
1815
1816 /* Copy as many bytes as will fit. */
1817 if (nleft != 0) {
1818 while (--nleft != 0) {
1819 if ((*dst++ = *src++) == '\0')
1820 break;
1821 }
1822 }
1823
1824 /* Not enough room in dst, add NUL and traverse rest of src. */
1825 if (nleft == 0) {
1826 if (dsize != 0)
1827 *dst = '\0'; /* NUL-terminate dst */
1828 while (*src++)
1829 ;
1830 }
1831
1832 return(src - osrc - 1); /* count does not include NUL */
1833 }
1834
1835 char *
1836 strndup(const char *str, size_t maxlen)
1837 {
1838 char *copy;
1839 const char *cp;
1840 size_t len;
1841
1842 /* strnlen */
1843 for (cp = str; maxlen != 0 && *cp != '\0'; cp++, maxlen--)
1844 ;
1845
1846 len = (size_t)(cp - str);
1847 copy = malloc(len + 1);
1848 if (copy != NULL) {
1849 (void)memcpy(copy, str, len);
1850 copy[len] = '\0';
1851 }
1852
1853 return copy;
1854 }
1855
1856 /*
1857 * Get next token from string *stringp, where tokens are possibly-empty
1858 * strings separated by characters from delim.
1859 *
1860 * Writes NULs into the string at *stringp to end tokens.
1861 * delim need not remain constant from call to call.
1862 * On return, *stringp points past the last NUL written (if there might
1863 * be further tokens), or is NULL (if there are definitely no more tokens).
1864 *
1865 * If *stringp is NULL, strsep returns NULL.
1866 */
1867 char *
1868 strsep(char **stringp, const char *delim)
1869 {
1870 char *s;
1871 const char *spanp;
1872 int c, sc;
1873 char *tok;
1874
1875 if ((s = *stringp) == NULL)
1876 return (NULL);
1877 for (tok = s;;) {
1878 c = *s++;
1879 spanp = delim;
1880 do {
1881 if ((sc = *spanp++) == c) {
1882 if (c == 0)
1883 s = NULL;
1884 else
1885 s[-1] = 0;
1886 *stringp = s;
1887 return (tok);
1888 }
1889 } while (sc != 0);
1890 }
1891 return (NULL);
1892 }
1893
1894 static struct format {
1895 unsigned leftJustify : 1;
1896 unsigned forceSign : 1;
1897 unsigned altForm : 1;
1898 unsigned zeroPad : 1;
1899 unsigned havePrecision : 1;
1900 unsigned hSize : 1;
1901 unsigned lSize : 1;
1902 unsigned LSize : 1;
1903 char sign;
1904 char exponent;
1905 int fieldWidth;
1906 int precision;
1907 } default_format;
1908
1909 short bounded_vfprintf(FILE *fp, const char *fmt, va_list arg);
1910 static int nullio(FILE *fp, int i);
1911
1912 short
1913 bounded_vfprintf(FILE *fp, const char *fmt, va_list arg)
1914 {
1915 register int c, i, nwritten = 0;
1916 register unsigned long n;
1917 register char *s;
1918 #define VFPRINTF_BUFLEN 512
1919 static char buf[VFPRINTF_BUFLEN], *digits, *t;
1920 struct format F;
1921
1922 for (c = *fmt; c; c = *++fmt) {
1923 if (c != '%')
1924 goto copy1;
1925 F = default_format;
1926
1927 /* decode flags */
1928
1929 for (;;) {
1930 c = *++fmt;
1931 if (c == '-')
1932 F.leftJustify = TRUE;
1933 else if (c == '+')
1934 F.forceSign = TRUE;
1935 else if (c == ' ')
1936 F.sign = ' ';
1937 else if (c == '#')
1938 F.altForm = TRUE;
1939 else if (c == '0')
1940 F.zeroPad = TRUE;
1941 else
1942 break;
1943 }
1944
1945 /* decode field width */
1946
1947 if (c == '*') {
1948 if ((F.fieldWidth = va_arg(arg, int)) < 0) {
1949 F.leftJustify = TRUE;
1950 F.fieldWidth = -F.fieldWidth;
1951 }
1952 c = *++fmt;
1953 }
1954 else {
1955 for (; c >= '0' && c <= '9'; c = *++fmt)
1956 F.fieldWidth = (10 * F.fieldWidth) + (c - '0');
1957 }
1958
1959 /* decode precision */
1960
1961 if (c == '.') {
1962 if ((c = *++fmt) == '*') {
1963 F.precision = va_arg(arg, int);
1964 c = *++fmt;
1965 }
1966 else {
1967 for (; c >= '0' && c <= '9'; c = *++fmt)
1968 F.precision = (10 * F.precision) + (c - '0');
1969 }
1970 if (F.precision >= 0)
1971 F.havePrecision = TRUE;
1972 }
1973
1974 /* perform appropriate conversion */
1975
1976 s = &buf[VFPRINTF_BUFLEN];
1977 if (F.leftJustify)
1978 F.zeroPad = FALSE;
1979 conv: switch (c) {
1980
1981 /* 'h' size modifier */
1982
1983 case 'h':
1984 F.hSize = TRUE;
1985 c = *++fmt;
1986 goto conv;
1987
1988 /* 'l' size modifier */
1989
1990 case 'l':
1991 F.lSize = TRUE;
1992 c = *++fmt;
1993 goto conv;
1994
1995 /* 'L' size modifier */
1996
1997 case 'L':
1998 F.LSize = TRUE;
1999 c = *++fmt;
2000 goto conv;
2001
2002 /* decimal (signed) */
2003
2004 case 'd':
2005 case 'i':
2006 if (F.lSize)
2007 n = va_arg(arg, long);
2008 else
2009 n = va_arg(arg, int);
2010 if (F.hSize)
2011 n = (short) n;
2012 if ((long) n < 0) {
2013 n = -n;
2014 F.sign = '-';
2015 }
2016 else if (F.forceSign)
2017 F.sign = '+';
2018 goto decimal;
2019
2020 /* decimal (unsigned) */
2021
2022 case 'u':
2023 if (F.lSize)
2024 n = va_arg(arg, unsigned long);
2025 else
2026 n = va_arg(arg, unsigned int);
2027 if (F.hSize)
2028 n = (unsigned short) n;
2029 F.sign = 0;
2030 goto decimal;
2031
2032 /* decimal (common code) */
2033
2034 decimal:
2035 if (!F.havePrecision) {
2036 if (F.zeroPad) {
2037 F.precision = F.fieldWidth;
2038 if (F.sign)
2039 --F.precision;
2040 }
2041 if (F.precision < 1)
2042 F.precision = 1;
2043 }
2044 for (i = 0; n; n /= 10, i++)
2045 *--s = n % 10 + '0';
2046 for (; i < F.precision; i++)
2047 *--s = '0';
2048 if (F.sign) {
2049 *--s = F.sign;
2050 i++;
2051 }
2052 break;
2053
2054 /* octal (unsigned) */
2055
2056 case 'o':
2057 if (F.lSize)
2058 n = va_arg(arg, unsigned long);
2059 else
2060 n = va_arg(arg, unsigned int);
2061 if (F.hSize)
2062 n = (unsigned short) n;
2063 if (!F.havePrecision) {
2064 if (F.zeroPad)
2065 F.precision = F.fieldWidth;
2066 if (F.precision < 1)
2067 F.precision = 1;
2068 }
2069 for (i = 0; n; n /= 8, i++)
2070 *--s = n % 8 + '0';
2071 if (F.altForm && i && *s != '0') {
2072 *--s = '0';
2073 i++;
2074 }
2075 for (; i < F.precision; i++)
2076 *--s = '0';
2077 break;
2078
2079 /* hexadecimal (unsigned) */
2080
2081 case 'p':
2082 F.havePrecision = F.lSize = TRUE;
2083 F.precision = 8;
2084 /* ... */
2085 case 'X':
2086 digits = "0123456789ABCDEF";
2087 goto hexadecimal;
2088 case 'x':
2089 digits = "0123456789abcdef";
2090 /* ... */
2091 hexadecimal:
2092 if (F.lSize)
2093 n = va_arg(arg, unsigned long);
2094 else
2095 n = va_arg(arg, unsigned int);
2096 if (F.hSize)
2097 n = (unsigned short) n;
2098 if (!F.havePrecision) {
2099 if (F.zeroPad) {
2100 F.precision = F.fieldWidth;
2101 if (F.altForm)
2102 F.precision -= 2;
2103 }
2104 if (F.precision < 1)
2105 F.precision = 1;
2106 }
2107 for (i = 0; n; n /= 16, i++)
2108 *--s = digits[n % 16];
2109 for (; i < F.precision; i++)
2110 *--s = '0';
2111 if (F.altForm) {
2112 *--s = c;
2113 *--s = '0';
2114 i += 2;
2115 }
2116 break;
2117
2118 /* character */
2119
2120 case 'c':
2121 *--s = va_arg(arg, int);
2122 i = 1;
2123 break;
2124
2125 /* string */
2126
2127 case 's':
2128 s = va_arg(arg, char *);
2129 if (F.altForm) {
2130 i = (unsigned char) *s++;
2131 if (F.havePrecision && i > F.precision)
2132 i = F.precision;
2133 }
2134 else {
2135 if (!F.havePrecision)
2136 i = strlen(s);
2137 else if ((t = memchr(s, '\0', F.precision)) != NULL)
2138 i = t - s;
2139 else
2140 i = F.precision;
2141 }
2142 break;
2143
2144 /* store # bytes written so far */
2145
2146 case 'n':
2147 s = va_arg(arg, void *);
2148 if (F.hSize)
2149 * (short *) s = nwritten;
2150 else if (F.lSize)
2151 * (long *) s = nwritten;
2152 else
2153 * (int *) s = nwritten;
2154 continue;
2155
2156 /* oops - unknown conversion, abort */
2157
2158 default:
2159 if (c != '%')
2160 goto done;
2161 copy1:
2162 putc(c, fp); /* disregard EOF */
2163 ++nwritten;
2164 continue;
2165 }
2166
2167 /* pad on the left */
2168
2169 if (i < F.fieldWidth && !F.leftJustify) {
2170 do {
2171 putc(' ', fp); /* disregard EOF */
2172 ++nwritten;
2173 } while (i < --F.fieldWidth);
2174 }
2175
2176 /* write the converted result */
2177
2178 fwrite(s, 1, i, fp); /* disregard EOF */
2179 nwritten += i;
2180
2181 /* pad on the right */
2182
2183 for (; i < F.fieldWidth; i++) {
2184 putc(' ', fp); /* disregard EOF */
2185 ++nwritten;
2186 }
2187 }
2188
2189 /* all done! */
2190
2191 done:
2192 return(nwritten);
2193 }
2194
2195 short
2196 snprintf(char *s, size_t size, const char *fmt, ...)
2197 {
2198 return(vsnprintf(s, size, fmt, __va(fmt)));
2199 }
2200
2201 static int
2202 nullio(FILE *fp, int i)
2203 {
2204 return(EOF);
2205 }
2206
2207 short
2208 vsnprintf(char *s, size_t size, const char *fmt, void *p)
2209 {
2210 FILE f;
2211 int n;
2212 unsigned char zb;
2213
2214 memset(&f, 0, sizeof(f));
2215 f.refnum = -1;
2216 f.ptr = (unsigned char *)s;
2217 f.cnt = size;
2218 f.proc = nullio;
2219 f.dirty = 1;
2220
2221 if (size == 0)
2222 zb = s[0];
2223
2224 if ((n = bounded_vfprintf(&f, fmt, p)) >= 0) {
2225 if (n < size)
2226 s[n] = 0;
2227 else
2228 s[size - 1] = 0;
2229 }
2230
2231 if (size == 0)
2232 s[0] = zb;
2233
2234 return(n);
2235 }