xref: /vim-8.2.3635/src/os_amiga.c (revision b420ac9d)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * os_amiga.c
12  *
13  * Amiga system-dependent routines.
14  */
15 
16 #include "vim.h"
17 #include "version.h"
18 
19 #ifdef Window
20 # undef Window	// Amiga has its own Window definition
21 #endif
22 
23 #undef TRUE		// will be redefined by exec/types.h
24 #undef FALSE
25 
26 // cproto fails on missing include files, skip them
27 #ifndef PROTO
28 
29 #ifndef LATTICE
30 # include <exec/types.h>
31 # include <exec/exec.h>
32 # include <libraries/dos.h>
33 # include <intuition/intuition.h>
34 #endif
35 
36 // XXX These are included from os_amiga.h
37 // #include <proto/exec.h>
38 // #include <proto/dos.h>
39 // #include <proto/intuition.h>
40 
41 #include <exec/memory.h>
42 #include <libraries/dosextens.h>
43 
44 #include <dos/dostags.h>	    // for 2.0 functions
45 #include <dos/dosasl.h>
46 
47 // From version 4 of AmigaOS, several system structures must be allocated
48 // and freed using system functions. "struct AnchorPath" is one.
49 #ifdef __amigaos4__
50 # include <dos/anchorpath.h>
51 # define	free_fib(x) FreeDosObject(DOS_FIB, x)
52 #else
53 # define	free_fib(x) vim_free(fib)
54 #endif
55 
56 #if defined(LATTICE) && !defined(SASC) && defined(FEAT_ARP)
57 # include <libraries/arp_pragmas.h>
58 #endif
59 
60 #endif // PROTO
61 
62 /*
63  * Set stack size to 1 MiB on NG systems. This should be enough even for
64  * hungry syntax HL / plugin combinations. Leave the stack alone on OS 3
65  * and below, those systems might be low on memory.
66  */
67 #if defined(__amigaos4__)
68 static const char* __attribute__((used)) stackcookie = "$STACK: 1048576";
69 #elif defined(__AROS__) || defined(__MORPHOS__)
70 unsigned long __stack = 1048576;
71 #endif
72 
73 /*
74  * At this point TRUE and FALSE are defined as 1L and 0L, but we want 1 and 0.
75  */
76 #undef	TRUE
77 #define TRUE (1)
78 #undef	FALSE
79 #define FALSE (0)
80 
81 #ifdef __amigaos4__
82 # define	dos_packet(a, b, c)   DoPkt(a, b, c, 0, 0, 0, 0)
83 #elif !defined(AZTEC_C) && !defined(__AROS__)
84 static long dos_packet(struct MsgPort *, long, long);
85 #endif
86 static int lock2name(BPTR lock, char_u *buf, long   len);
87 static void out_num(long n);
88 static struct FileInfoBlock *get_fib(char_u *);
89 static int sortcmp(const void *a, const void *b);
90 
91 static BPTR		raw_in = (BPTR)NULL;
92 static BPTR		raw_out = (BPTR)NULL;
93 static int		close_win = FALSE;  // set if Vim opened the window
94 
95 /* Use autoopen for AmigaOS4, AROS and MorphOS */
96 #if !defined(__amigaos4__) && !defined(__AROS__) && !defined(__MORPHOS__)
97 struct IntuitionBase	*IntuitionBase = NULL;
98 #endif
99 #ifdef FEAT_ARP
100 struct ArpBase		*ArpBase = NULL;
101 #endif
102 
103 static struct Window	*wb_window;
104 static char_u		*oldwindowtitle = NULL;
105 
106 #ifdef FEAT_ARP
107 int			dos2 = FALSE;	    // Amiga DOS 2.0x or higher
108 #endif
109 int			size_set = FALSE;   // set to TRUE if window size was set
110 
111 #ifdef __GNUC__
112 static char version[] __attribute__((used)) =
113     "\0$VER: Vim "
114     VIM_VERSION_MAJOR_STR "."
115     VIM_VERSION_MINOR_STR
116 # ifdef PATCHLEVEL
117     "." PATCHLEVEL
118 # endif
119 # ifdef BUILDDATE
120     " (" BUILDDATE ")"
121 # endif
122     ;
123 #endif
124 
125     void
win_resize_on(void)126 win_resize_on(void)
127 {
128     OUT_STR_NF("\033[12{");
129 }
130 
131     void
win_resize_off(void)132 win_resize_off(void)
133 {
134     OUT_STR_NF("\033[12}");
135 }
136 
137     void
mch_write(char_u * p,int len)138 mch_write(char_u *p, int len)
139 {
140     Write(raw_out, (char *)p, (long)len);
141 }
142 
143 /*
144  * mch_inchar(): low level input function.
145  * Get a characters from the keyboard.
146  * If time == 0 do not wait for characters.
147  * If time == n wait a short time for characters.
148  * If time == -1 wait forever for characters.
149  *
150  * Return number of characters read.
151  */
152     int
mch_inchar(char_u * buf,int maxlen,long time,int tb_change_cnt)153 mch_inchar(
154     char_u  *buf,
155     int	    maxlen,
156     long    time,		// milli seconds
157     int	    tb_change_cnt)
158 {
159     int	    len;
160     long    utime;
161 
162     if (time >= 0)
163     {
164 	if (time == 0)
165 	    utime = 100L;	    // time = 0 causes problems in DOS 1.2
166 	else
167 	    utime = time * 1000L;   // convert from milli to micro secs
168 	if (WaitForChar(raw_in, utime) == 0)	// no character available
169 	    return 0;
170     }
171     else    // time == -1
172     {
173 	/*
174 	 * If there is no character available within 2 seconds (default)
175 	 * write the autoscript file to disk.  Or cause the CursorHold event
176 	 * to be triggered.
177 	 */
178 	if (WaitForChar(raw_in, p_ut * 1000L) == 0)
179 	{
180 	    if (trigger_cursorhold() && maxlen >= 3)
181 	    {
182 		buf[0] = K_SPECIAL;
183 		buf[1] = KS_EXTRA;
184 		buf[2] = (int)KE_CURSORHOLD;
185 		return 3;
186 	    }
187 	    before_blocking();
188 	}
189     }
190 
191     for (;;)	    // repeat until we got a character
192     {
193 	len = Read(raw_in, (char *)buf, (long)maxlen / input_conv.vc_factor);
194 	if (len > 0)
195 	{
196 	    // Convert from 'termencoding' to 'encoding'.
197 	    if (input_conv.vc_type != CONV_NONE)
198 		len = convert_input(buf, len, maxlen);
199 	    return len;
200 	}
201     }
202 }
203 
204 /*
205  * return non-zero if a character is available
206  */
207     int
mch_char_avail(void)208 mch_char_avail(void)
209 {
210     return (WaitForChar(raw_in, 100L) != 0);
211 }
212 
213 /*
214  * Return amount of memory still available in Kbyte.
215  */
216     long_u
mch_avail_mem(int special)217 mch_avail_mem(int special)
218 {
219 #if defined(__amigaos4__) || defined(__AROS__) || defined(__MORPHOS__)
220     return (long_u)AvailMem(MEMF_ANY) >> 10;
221 #else
222     return (long_u)(AvailMem(special ? (long)MEMF_CHIP : (long)MEMF_ANY)) >> 10;
223 #endif
224 }
225 
226 /*
227  * Waits a specified amount of time, or until input arrives if
228  * flags does not have MCH_DELAY_IGNOREINPUT.
229  */
230     void
mch_delay(long msec,int flags)231 mch_delay(long msec, int flags)
232 {
233 #ifndef LATTICE		// SAS declares void Delay(ULONG)
234     void	    Delay(long);
235 #endif
236 
237     if (msec > 0)
238     {
239 	if (flags & MCH_DELAY_IGNOREINPUT)
240 	    Delay(msec / 20L);	    // Delay works with 20 msec intervals
241 	else
242 	    WaitForChar(raw_in, msec * 1000L);
243     }
244 }
245 
246 /*
247  * We have no job control, fake it by starting a new shell.
248  */
249     void
mch_suspend(void)250 mch_suspend(void)
251 {
252     suspend_shell();
253 }
254 
255 #ifndef DOS_LIBRARY
256 # define DOS_LIBRARY	((UBYTE *)"dos.library")
257 #endif
258 
259     void
mch_init(void)260 mch_init(void)
261 {
262 #if !defined(__amigaos4__) && !defined(__AROS__) && !defined(__MORPHOS__)
263     static char	    intlibname[] = "intuition.library";
264 #endif
265 
266 #ifdef AZTEC_C
267     Enable_Abort = 0;		// disallow vim to be aborted
268 #endif
269     Columns = 80;
270     Rows = 24;
271 
272     /*
273      * Set input and output channels, unless we have opened our own window
274      */
275     if (raw_in == (BPTR)NULL)
276     {
277 	raw_in = Input();
278 	raw_out = Output();
279 	/*
280 	 * If Input() is not interactive, then Output() will be (because of
281 	 * check in mch_check_win()).  Used for "Vim -".
282 	 * Also check the other way around, for "Vim -h | more".
283 	 */
284 	if (!IsInteractive(raw_in))
285 	    raw_in = raw_out;
286 	else if (!IsInteractive(raw_out))
287 	    raw_out = raw_in;
288     }
289 
290     out_flush();
291 
292     wb_window = NULL;
293 #if !defined(__amigaos4__) && !defined(__AROS__) && !defined(__MORPHOS__)
294     if ((IntuitionBase = (struct IntuitionBase *)
295 				OpenLibrary((UBYTE *)intlibname, 0L)) == NULL)
296     {
297 	mch_errmsg(_("cannot open "));
298 	mch_errmsg(intlibname);
299 	mch_errmsg("!?\n");
300 	mch_exit(3);
301     }
302 #endif
303 }
304 
305 #ifndef PROTO
306 # include <workbench/startup.h>
307 #endif
308 
309 /*
310  * Check_win checks whether we have an interactive window.
311  * If not, a new window is opened with the newcli command.
312  * If we would open a window ourselves, the :sh and :! commands would not
313  * work properly (Why? probably because we are then running in a background
314  * CLI). This also is the best way to assure proper working in a next
315  * Workbench release.
316  *
317  * For the -f option (foreground mode) we open our own window and disable :sh.
318  * Otherwise the calling program would never know when editing is finished.
319  */
320 #define BUF2SIZE 320	    // length of buffer for argument with complete path
321 
322     int
mch_check_win(int argc,char ** argv)323 mch_check_win(int argc, char **argv)
324 {
325     int		    i;
326     BPTR	    nilfh, fh;
327     char_u	    buf1[24];
328     char_u	    buf2[BUF2SIZE];
329     static char_u   *(constrings[3]) = {(char_u *)"con:0/0/662/210/",
330 					(char_u *)"con:0/0/640/200/",
331 					(char_u *)"con:0/0/320/200/"};
332     static char_u   *winerr = (char_u *)N_("VIM: Can't open window!\n");
333     struct WBArg    *argp;
334     int		    ac;
335     char	    *av;
336     char_u	    *device = NULL;
337     int		    exitval = 4;
338 #if !defined(__amigaos4__) && !defined(__AROS__) && !defined(__MORPHOS__)
339     struct Library  *DosBase;
340 #endif
341     int		    usewin = FALSE;
342 
343 /*
344  * check if we are running under DOS 2.0x or higher
345  */
346 #if !defined(__amigaos4__) && !defined(__AROS__) && !defined(__MORPHOS__)
347     DosBase = OpenLibrary(DOS_LIBRARY, 37L);
348     if (DosBase != NULL)
349     // if (((struct Library *)DOSBase)->lib_Version >= 37)
350     {
351 	CloseLibrary(DosBase);
352 # ifdef FEAT_ARP
353 	dos2 = TRUE;
354 # endif
355     }
356     else	    // without arp functions we NEED 2.0
357     {
358 # ifndef FEAT_ARP
359 	mch_errmsg(_("Need Amigados version 2.04 or later\n"));
360 	exit(3);
361 # else
362 		    // need arp functions for dos 1.x
363 	if (!(ArpBase = (struct ArpBase *) OpenLibrary((UBYTE *)ArpName, ArpVersion)))
364 	{
365 	    fprintf(stderr, _("Need %s version %ld\n"), ArpName, ArpVersion);
366 	    exit(3);
367 	}
368 # endif
369     }
370 #endif	/* __amigaos4__ __AROS__ __MORPHOS__ */
371 
372     /*
373      * scan argv[] for the "-f" and "-d" arguments
374      */
375     for (i = 1; i < argc; ++i)
376 	if (argv[i][0] == '-')
377 	{
378 	    switch (argv[i][1])
379 	    {
380 	    case 'f':
381 		usewin = TRUE;
382 		break;
383 
384 	    case 'd':
385 		if (i < argc - 1
386 #ifdef FEAT_DIFF
387 			// require using "-dev", "-d" means diff mode
388 			&& argv[i][2] == 'e' && argv[i][3] == 'v'
389 #endif
390 		   )
391 		    device = (char_u *)argv[i + 1];
392 		break;
393 	    }
394 	}
395 
396 /*
397  * If we were not started from workbench, do not have a "-d" or "-dev"
398  * argument and we have been started with an interactive window, use that
399  * window.
400  */
401     if (argc != 0
402 	    && device == NULL
403 	    && (IsInteractive(Input()) || IsInteractive(Output())))
404 	return OK;
405 
406 /*
407  * When given the "-f" argument, we open our own window. We can't use the
408  * newcli trick below, because the calling program (mail, rn, etc.) would not
409  * know when we are finished.
410  */
411     if (usewin)
412     {
413 	/*
414 	 * Try to open a window. First try the specified device.
415 	 * Then try a 24 line 80 column window.
416 	 * If that fails, try two smaller ones.
417 	 */
418 	for (i = -1; i < 3; ++i)
419 	{
420 	    if (i >= 0)
421 		device = constrings[i];
422 	    if (device != NULL && (raw_in = Open((UBYTE *)device,
423 					   (long)MODE_NEWFILE)) != (BPTR)NULL)
424 		break;
425 	}
426 	if (raw_in == (BPTR)NULL)	// all three failed
427 	{
428 	    mch_errmsg(_(winerr));
429 	    goto exit;
430 	}
431 	raw_out = raw_in;
432 	close_win = TRUE;
433 	return OK;
434     }
435 
436     if ((nilfh = Open((UBYTE *)"NIL:", (long)MODE_NEWFILE)) == (BPTR)NULL)
437     {
438 	mch_errmsg(_("Cannot open NIL:\n"));
439 	goto exit;
440     }
441 
442     /*
443      * Make a unique name for the temp file (which we will not delete!).
444      * Use a pointer on the stack (nobody else will be using it).
445      * Under AmigaOS4, this assumption might change in the future, so
446      * we use a pointer to the current task instead. This should be a
447      * shared structure and thus globally unique.
448      */
449 #if !defined(__amigaos4__) && !defined(__AROS__) && !defined(__MORPHOS__)
450     sprintf((char *)buf1, "t:nc%p", FindTask(0));
451 #else
452     sprintf((char *)buf1, "t:nc%ld", (long)buf1);
453 #endif
454     if ((fh = Open((UBYTE *)buf1, (long)MODE_NEWFILE)) == (BPTR)NULL)
455     {
456 	mch_errmsg(_("Cannot create "));
457 	mch_errmsg((char *)buf1);
458 	mch_errmsg("\n");
459 	goto exit;
460     }
461     /*
462      * Write the command into the file, put quotes around the arguments that
463      * have a space in them.
464      */
465     if (argc == 0)	// run from workbench
466 	ac = ((struct WBStartup *)argv)->sm_NumArgs;
467     else
468 	ac = argc;
469     for (i = 0; i < ac; ++i)
470     {
471 	if (argc == 0)
472 	{
473 	    *buf2 = NUL;
474 	    argp = &(((struct WBStartup *)argv)->sm_ArgList[i]);
475 	    if (argp->wa_Lock)
476 		(void)lock2name(argp->wa_Lock, buf2, (long)(BUF2SIZE - 1));
477 #ifdef FEAT_ARP
478 	    if (dos2)	    // use 2.0 function
479 #endif
480 		AddPart((UBYTE *)buf2, (UBYTE *)argp->wa_Name, (long)(BUF2SIZE - 1));
481 #ifdef FEAT_ARP
482 	    else	    // use arp function
483 		TackOn((char *)buf2, argp->wa_Name);
484 #endif
485 	    av = (char *)buf2;
486 	}
487 	else
488 	    av = argv[i];
489 
490 	// skip '-d' or "-dev" option
491 	if (av[0] == '-' && av[1] == 'd'
492 #ifdef FEAT_DIFF
493 		&& av[2] == 'e' && av[3] == 'v'
494 #endif
495 		)
496 	{
497 	    ++i;
498 	    continue;
499 	}
500 	if (vim_strchr((char_u *)av, ' '))
501 	    Write(fh, "\"", 1L);
502 	Write(fh, av, (long)strlen(av));
503 	if (vim_strchr((char_u *)av, ' '))
504 	    Write(fh, "\"", 1L);
505 	Write(fh, " ", 1L);
506     }
507     Write(fh, "\nendcli\n", 8L);
508     Close(fh);
509 
510 /*
511  * Try to open a new cli in a window. If "-d" or "-dev" argument was given try
512  * to open the specified device. Then try a 24 line 80 column window.  If that
513  * fails, try two smaller ones.
514  */
515     for (i = -1; i < 3; ++i)
516     {
517 	if (i >= 0)
518 	    device = constrings[i];
519 	else if (device == NULL)
520 	    continue;
521 	sprintf((char *)buf2, "newcli <nil: >nil: %s from %s", (char *)device, (char *)buf1);
522 #ifdef FEAT_ARP
523 	if (dos2)
524 	{
525 #endif
526 	    if (!SystemTags((UBYTE *)buf2, SYS_UserShell, TRUE, TAG_DONE))
527 		break;
528 #ifdef FEAT_ARP
529 	}
530 	else
531 	{
532 	    if (Execute((UBYTE *)buf2, nilfh, nilfh))
533 		break;
534 	}
535 #endif
536     }
537     if (i == 3)	    // all three failed
538     {
539 	DeleteFile((UBYTE *)buf1);
540 	mch_errmsg(_(winerr));
541 	goto exit;
542     }
543     exitval = 0;    // The Execute succeeded: exit this program
544 
545 exit:
546 #ifdef FEAT_ARP
547     if (ArpBase)
548 	CloseLibrary((struct Library *) ArpBase);
549 #endif
550     exit(exitval);
551     // NOTREACHED
552     return FAIL;
553 }
554 
555 /*
556  * Return TRUE if the input comes from a terminal, FALSE otherwise.
557  * We fake there is a window, because we can always open one!
558  */
559     int
mch_input_isatty(void)560 mch_input_isatty(void)
561 {
562     return TRUE;
563 }
564 
565 /*
566  * fname_case(): Set the case of the file name, if it already exists.
567  *		 This will cause the file name to remain exactly the same
568  *		 if the file system ignores, but preserves case.
569  */
570 //ARGSUSED
571     void
fname_case(char_u * name,int len)572 fname_case(
573     char_u	*name,
574     int		len)		// buffer size, ignored here
575 {
576     struct FileInfoBlock    *fib;
577     size_t		    flen;
578 
579     fib = get_fib(name);
580     if (fib != NULL)
581     {
582 	flen = STRLEN(name);
583 	// TODO: Check if this fix applies to AmigaOS < 4 too.
584 #ifdef __amigaos4__
585 	if (fib->fib_DirEntryType == ST_ROOT)
586 	    strcat(fib->fib_FileName, ":");
587 #endif
588 	if (flen == strlen(fib->fib_FileName))	// safety check
589 	    mch_memmove(name, fib->fib_FileName, flen);
590 	free_fib(fib);
591     }
592 }
593 
594 /*
595  * Get the FileInfoBlock for file "fname"
596  * The returned structure has to be free()d.
597  * Returns NULL on error.
598  */
599     static struct FileInfoBlock *
get_fib(char_u * fname)600 get_fib(char_u *fname)
601 {
602     BPTR		    flock;
603     struct FileInfoBlock    *fib;
604 
605     if (fname == NULL)	    // safety check
606 	return NULL;
607 #ifdef __amigaos4__
608     fib = AllocDosObject(DOS_FIB,0);
609 #else
610     fib = ALLOC_ONE(struct FileInfoBlock);
611 #endif
612     if (fib != NULL)
613     {
614 	flock = Lock((UBYTE *)fname, (long)ACCESS_READ);
615 	if (flock == (BPTR)NULL || !Examine(flock, fib))
616 	{
617 	    free_fib(fib);  // in case of an error the memory is freed here
618 	    fib = NULL;
619 	}
620 	if (flock)
621 	    UnLock(flock);
622     }
623     return fib;
624 }
625 
626 #ifdef FEAT_TITLE
627 /*
628  * set the title of our window
629  * icon name is not set
630  */
631     void
mch_settitle(char_u * title,char_u * icon)632 mch_settitle(char_u *title, char_u *icon)
633 {
634     if (wb_window != NULL && title != NULL)
635 	SetWindowTitles(wb_window, (UBYTE *)title, (UBYTE *)-1L);
636 }
637 
638 /*
639  * Restore the window/icon title.
640  * which is one of:
641  *  SAVE_RESTORE_TITLE  Just restore title
642  *  SAVE_RESTORE_ICON   Just restore icon (which we don't have)
643  *  SAVE_RESTORE_BOTH   Restore title and icon (which we don't have)
644  */
645     void
mch_restore_title(int which)646 mch_restore_title(int which)
647 {
648     if (which & SAVE_RESTORE_TITLE)
649 	mch_settitle(oldwindowtitle, NULL);
650 }
651 
652     int
mch_can_restore_title(void)653 mch_can_restore_title(void)
654 {
655     return (wb_window != NULL);
656 }
657 
658     int
mch_can_restore_icon(void)659 mch_can_restore_icon(void)
660 {
661     return FALSE;
662 }
663 #endif
664 
665     void
mch_setmouse(int on UNUSED)666 mch_setmouse(int on UNUSED)
667 {
668     // TODO: implement
669 }
670 
671 /*
672  * Insert user name in s[len].
673  */
674     int
mch_get_user_name(char_u * s,int len)675 mch_get_user_name(char_u *s, int len)
676 {
677 #if defined(__amigaos4__) || defined(__AROS__) || defined(__MORPHOS__)
678     struct passwd   *pwd = getpwuid(getuid());
679 
680     if (pwd != NULL && pwd->pw_name && len > 0)
681     {
682         vim_strncpy(s, (char_u *)pwd->pw_name, len - 1);
683         return OK;
684     }
685 #endif
686     *s = NUL;
687     return FAIL;
688 }
689 
690 /*
691  * Insert host name is s[len].
692  */
693     void
mch_get_host_name(char_u * s,int len)694 mch_get_host_name(char_u *s, int len)
695 {
696 #if defined(__amigaos4__) && defined(__CLIB2__)
697     gethostname(s, len);
698 #else
699     vim_strncpy(s, "Amiga", len - 1);
700 #endif
701 }
702 
703 /*
704  * return process ID
705  */
706     long
mch_get_pid(void)707 mch_get_pid(void)
708 {
709 #if defined(__amigaos4__) || defined(__AROS__) || defined(__MORPHOS__)
710     // This is as close to a pid as we can come. We could use CLI numbers also,
711     // but then we would have two different types of process identifiers.
712     return((long)FindTask(0));
713 #else
714     return (long)0;
715 #endif
716 }
717 
718 /*
719  * Get name of current directory into buffer 'buf' of length 'len' bytes.
720  * Return OK for success, FAIL for failure.
721  */
722     int
mch_dirname(char_u * buf,int len)723 mch_dirname(char_u *buf, int len)
724 {
725     return mch_FullName((char_u *)"", buf, len, FALSE);
726 }
727 
728 /*
729  * get absolute file name into buffer 'buf' of length 'len' bytes
730  *
731  * return FAIL for failure, OK otherwise
732  */
733     int
mch_FullName(char_u * fname,char_u * buf,int len,int force)734 mch_FullName(
735     char_u	*fname,
736     char_u	*buf,
737     int		len,
738     int		force)
739 {
740     BPTR	l;
741     int		retval = FAIL;
742     int		i;
743 
744     // Lock the file.  If it exists, we can get the exact name.
745     if ((l = Lock((UBYTE *)fname, (long)ACCESS_READ)) != (BPTR)0)
746     {
747 	retval = lock2name(l, buf, (long)len - 1);
748 	UnLock(l);
749     }
750     else if (force || !mch_isFullName(fname))	    // not a full path yet
751     {
752 	/*
753 	 * If the file cannot be locked (doesn't exist), try to lock the
754 	 * current directory and concatenate the file name.
755 	 */
756 	if ((l = Lock((UBYTE *)"", (long)ACCESS_READ)) != (BPTR)NULL)
757 	{
758 	    retval = lock2name(l, buf, (long)len);
759 	    UnLock(l);
760 	    if (retval == OK)
761 	    {
762 		i = STRLEN(buf);
763 		// Concatenate the fname to the directory.  Don't add a slash
764 		// if fname is empty, but do change "" to "/".
765 		if (i == 0 || *fname != NUL)
766 		{
767 		    if (i < len - 1 && (i == 0 || buf[i - 1] != ':'))
768 			buf[i++] = '/';
769 		    vim_strncpy(buf + i, fname, len - i - 1);
770 		}
771 	    }
772 	}
773     }
774     if (*buf == 0 || *buf == ':')
775 	retval = FAIL;	// something failed; use the file name
776     return retval;
777 }
778 
779 /*
780  * Return TRUE if "fname" does not depend on the current directory.
781  */
782     int
mch_isFullName(char_u * fname)783 mch_isFullName(char_u *fname)
784 {
785     return (vim_strchr(fname, ':') != NULL && *fname != ':');
786 }
787 
788 /*
789  * Get the full file name from a lock. Use 2.0 function if possible, because
790  * the arp function has more restrictions on the path length.
791  *
792  * return FAIL for failure, OK otherwise
793  */
794     static int
lock2name(BPTR lock,char_u * buf,long len)795 lock2name(BPTR lock, char_u *buf, long len)
796 {
797 #ifdef FEAT_ARP
798     if (dos2)		    // use 2.0 function
799 #endif
800 	return ((int)NameFromLock(lock, (UBYTE *)buf, len) ? OK : FAIL);
801 #ifdef FEAT_ARP
802     else		// use arp function
803 	return ((int)PathName(lock, (char *)buf, (long)(len/32)) ? OK : FAIL);
804 #endif
805 }
806 
807 /*
808  * get file permissions for 'name'
809  * Returns -1 when it doesn't exist.
810  */
811     long
mch_getperm(char_u * name)812 mch_getperm(char_u *name)
813 {
814     struct FileInfoBlock    *fib;
815     long		    retval = -1;
816 
817     fib = get_fib(name);
818     if (fib != NULL)
819     {
820 	retval = fib->fib_Protection;
821 	free_fib(fib);
822     }
823     return retval;
824 }
825 
826 /*
827  * set file permission for 'name' to 'perm'
828  *
829  * return FAIL for failure, OK otherwise
830  */
831     int
mch_setperm(char_u * name,long perm)832 mch_setperm(char_u *name, long perm)
833 {
834     perm &= ~FIBF_ARCHIVE;		// reset archived bit
835     return (SetProtection((UBYTE *)name, (long)perm) ? OK : FAIL);
836 }
837 
838 /*
839  * Set hidden flag for "name".
840  */
841     void
mch_hide(char_u * name)842 mch_hide(char_u *name)
843 {
844     // can't hide a file
845 }
846 
847 /*
848  * return FALSE if "name" is not a directory
849  * return TRUE if "name" is a directory.
850  * return FALSE for error.
851  */
852     int
mch_isdir(char_u * name)853 mch_isdir(char_u *name)
854 {
855     struct FileInfoBlock    *fib;
856     int			    retval = FALSE;
857 
858     fib = get_fib(name);
859     if (fib != NULL)
860     {
861 #ifdef __amigaos4__
862 	retval = (FIB_IS_DRAWER(fib)) ? TRUE : FALSE;
863 #else
864 	retval = ((fib->fib_DirEntryType >= 0) ? TRUE : FALSE);
865 #endif
866 	free_fib(fib);
867     }
868     return retval;
869 }
870 
871 /*
872  * Create directory "name".
873  */
874     int
mch_mkdir(char_u * name)875 mch_mkdir(char_u *name)
876 {
877     BPTR	lock;
878 
879     lock = CreateDir(name);
880     if (lock != NULL)
881     {
882 	UnLock(lock);
883 	return 0;
884     }
885     return -1;
886 }
887 
888 /*
889  * Return 1 if "name" can be executed, 0 if not.
890  * If "use_path" is FALSE only check if "name" is executable.
891  * Return -1 if unknown.
892  */
893     int
mch_can_exe(char_u * name,char_u ** path,int use_path)894 mch_can_exe(char_u *name, char_u **path, int use_path)
895 {
896     // TODO
897     return -1;
898 }
899 
900 /*
901  * Check what "name" is:
902  * NODE_NORMAL: file or directory (or doesn't exist)
903  * NODE_WRITABLE: writable device, socket, fifo, etc.
904  * NODE_OTHER: non-writable things
905  */
906     int
mch_nodetype(char_u * name)907 mch_nodetype(char_u *name)
908 {
909     // TODO
910     return NODE_NORMAL;
911 }
912 
913     void
mch_early_init(void)914 mch_early_init(void)
915 {
916 }
917 
918 /*
919  * Careful: mch_exit() may be called before mch_init()!
920  */
921     void
mch_exit(int r)922 mch_exit(int r)
923 {
924     exiting = TRUE;
925 
926     if (raw_in)			    // put terminal in 'normal' mode
927     {
928 	settmode(TMODE_COOK);
929 	stoptermcap();
930     }
931     out_char('\n');
932     if (raw_out)
933     {
934 	if (term_console)
935 	{
936 	    win_resize_off();	    // window resize events de-activated
937 	    if (size_set)
938 		OUT_STR("\233t\233u");	// reset window size (CSI t CSI u)
939 	}
940 	out_flush();
941     }
942 
943 #ifdef FEAT_TITLE
944     mch_restore_title(SAVE_RESTORE_BOTH);    // restore window title
945 #endif
946 
947     ml_close_all(TRUE);		    // remove all memfiles
948 
949 #ifdef FEAT_ARP
950     if (ArpBase)
951 	CloseLibrary((struct Library *) ArpBase);
952 #endif
953     if (close_win)
954 	Close(raw_in);
955     if (r)
956 	printf(_("Vim exiting with %d\n"), r); // somehow this makes :cq work!?
957     exit(r);
958 }
959 
960 /*
961  * This is a routine for setting a given stream to raw or cooked mode on the
962  * Amiga . This is useful when you are using Lattice C to produce programs
963  * that want to read single characters with the "getch()" or "fgetc" call.
964  *
965  * Written : 18-Jun-87 By Chuck McManis.
966  */
967 
968 #define MP(xx)	((struct MsgPort *)((struct FileHandle *) (BADDR(xx)))->fh_Type)
969 
970 /*
971  * Function mch_settmode() - Convert the specified file pointer to 'raw' or
972  * 'cooked' mode. This only works on TTY's.
973  *
974  * Raw: keeps DOS from translating keys for you, also (BIG WIN) it means
975  *	getch() will return immediately rather than wait for a return. You
976  *	lose editing features though.
977  *
978  * Cooked: This function returns the designate file pointer to its normal,
979  *	wait for a <CR> mode. This is exactly like raw() except that
980  *	it sends a 0 to the console to make it back into a CON: from a RAW:
981  */
982     void
mch_settmode(tmode_T tmode)983 mch_settmode(tmode_T tmode)
984 {
985 #if defined(__AROS__) || defined(__amigaos4__) || defined(__MORPHOS__)
986     if (!SetMode(raw_in, tmode == TMODE_RAW ? 1 : 0))
987 #else
988     if (dos_packet(MP(raw_in), (long)ACTION_SCREEN_MODE,
989 					  tmode == TMODE_RAW ? -1L : 0L) == 0)
990 #endif
991 	mch_errmsg(_("cannot change console mode ?!\n"));
992 }
993 
994 /*
995  * Code for this routine came from the following :
996  *
997  * ConPackets.c -  C. Scheppner, A. Finkel, P. Lindsay	CBM
998  *   DOS packet example
999  *   Requires 1.2
1000  *
1001  * Found on Fish Disk 56.
1002  *
1003  * Heavely modified by mool.
1004  */
1005 
1006 #ifndef PROTO
1007 # include <devices/conunit.h>
1008 #endif
1009 
1010 /*
1011  * Get console size in a system friendly way on AROS and MorphOS.
1012  * Return FAIL for failure, OK otherwise
1013  */
1014 #if defined(__AROS__) || defined(__MORPHOS__)
1015     int
mch_get_shellsize(void)1016 mch_get_shellsize(void)
1017 {
1018     if (!term_console)
1019         return FAIL;
1020 
1021     if (raw_in && raw_out)
1022     {
1023         // Save current console mode.
1024         int old_tmode = cur_tmode;
1025         char ctrl[] = "\x9b""0 q";
1026 
1027         // Set RAW mode.
1028         mch_settmode(TMODE_RAW);
1029 
1030         // Write control sequence to console.
1031         if (Write(raw_out, ctrl, sizeof(ctrl)) == sizeof(ctrl))
1032         {
1033             char scan[] = "\x9b""1;1;%d;%d r",
1034                  answ[sizeof(scan) + 8] = { '\0' };
1035 
1036             // Read return sequence from input.
1037             if (Read(raw_in, answ, sizeof(answ) - 1) > 0)
1038             {
1039                 // Parse result and set Vim globals.
1040                 if (sscanf(answ, scan, &Rows, &Columns) == 2)
1041                 {
1042                     // Restore console mode.
1043                     mch_settmode(old_tmode);
1044                     return OK;
1045                 }
1046             }
1047         }
1048 
1049         // Restore console mode.
1050         mch_settmode(old_tmode);
1051     }
1052 
1053     // I/O error. Default size fallback.
1054     term_console = FALSE;
1055     Columns = 80;
1056     Rows = 24;
1057 
1058     return FAIL;
1059 }
1060 #else
1061 /*
1062  * Try to get the real window size,
1063  * return FAIL for failure, OK otherwise
1064  */
1065     int
mch_get_shellsize(void)1066 mch_get_shellsize(void)
1067 {
1068     struct ConUnit  *conUnit;
1069 #ifndef __amigaos4__
1070     char	    id_a[sizeof(struct InfoData) + 3];
1071 #endif
1072     struct InfoData *id=0;
1073 
1074     if (!term_console)	// not an amiga window
1075 	goto out;
1076 
1077     // insure longword alignment
1078 #ifdef __amigaos4__
1079     if (!(id = AllocDosObject(DOS_INFODATA, 0)))
1080 	goto out;
1081 #else
1082     id = (struct InfoData *)(((long)id_a + 3L) & ~3L);
1083 #endif
1084 
1085     /*
1086      * Should make console aware of real window size, not the one we set.
1087      * Unfortunately, under DOS 2.0x this redraws the window and it
1088      * is rarely needed, so we skip it now, unless we changed the size.
1089      */
1090     if (size_set)
1091 	OUT_STR("\233t\233u");	// CSI t CSI u
1092     out_flush();
1093 
1094     if (dos_packet(MP(raw_out), (long)ACTION_DISK_INFO, ((ULONG) id) >> 2) == 0
1095 	    || (wb_window = (struct Window *)id->id_VolumeNode) == NULL)
1096     {
1097 	// it's not an amiga window, maybe aux device
1098 	// terminal type should be set
1099 	term_console = FALSE;
1100 	goto out;
1101     }
1102     if (oldwindowtitle == NULL)
1103 	oldwindowtitle = (char_u *)wb_window->Title;
1104     if (id->id_InUse == (BPTR)NULL)
1105     {
1106 	mch_errmsg(_("mch_get_shellsize: not a console??\n"));
1107 	return FAIL;
1108     }
1109     conUnit = (struct ConUnit *) ((struct IOStdReq *) id->id_InUse)->io_Unit;
1110 
1111     // get window size
1112     Rows = conUnit->cu_YMax + 1;
1113     Columns = conUnit->cu_XMax + 1;
1114     if (Rows < 0 || Rows > 200)	    // cannot be an amiga window
1115     {
1116 	Columns = 80;
1117 	Rows = 24;
1118 	term_console = FALSE;
1119 	return FAIL;
1120     }
1121 
1122     return OK;
1123 out:
1124 #ifdef __amigaos4__
1125     FreeDosObject(DOS_INFODATA, id); // Safe to pass NULL
1126 #endif
1127 
1128     return FAIL;
1129 }
1130 #endif
1131 
1132 /*
1133  * Try to set the real window size to Rows and Columns.
1134  */
1135     void
mch_set_shellsize(void)1136 mch_set_shellsize(void)
1137 {
1138     if (term_console)
1139     {
1140 	size_set = TRUE;
1141 	out_char(CSI);
1142 	out_num((long)Rows);
1143 	out_char('t');
1144 	out_char(CSI);
1145 	out_num((long)Columns);
1146 	out_char('u');
1147 	out_flush();
1148     }
1149 }
1150 
1151 /*
1152  * Rows and/or Columns has changed.
1153  */
1154     void
mch_new_shellsize(void)1155 mch_new_shellsize(void)
1156 {
1157     // Nothing to do.
1158 }
1159 
1160 /*
1161  * out_num - output a (big) number fast
1162  */
1163     static void
out_num(long n)1164 out_num(long n)
1165 {
1166     OUT_STR_NF(tltoa((unsigned long)n));
1167 }
1168 
1169 #if !defined(AZTEC_C) && !defined(__AROS__) && !defined(__amigaos4__)
1170 /*
1171  * Sendpacket.c
1172  *
1173  * An invaluable addition to your Amiga.lib file. This code sends a packet to
1174  * the given message port. This makes working around DOS lots easier.
1175  *
1176  * Note, I didn't write this, those wonderful folks at CBM did. I do suggest
1177  * however that you may wish to add it to Amiga.Lib, to do so, compile it and
1178  * say 'oml lib:amiga.lib -r sendpacket.o'
1179  */
1180 
1181 #ifndef PROTO
1182 // #include <proto/exec.h>
1183 // #include <proto/dos.h>
1184 # include <exec/memory.h>
1185 #endif
1186 
1187 /*
1188  * Function - dos_packet written by Phil Lindsay, Carolyn Scheppner, and Andy
1189  * Finkel. This function will send a packet of the given type to the Message
1190  * Port supplied.
1191  */
1192 
1193     static long
dos_packet(struct MsgPort * pid,long action,long arg)1194 dos_packet(
1195     struct MsgPort *pid,    // process identifier ... (handlers message port)
1196     long	    action, // packet type ... (what you want handler to do)
1197     long	    arg)    // single argument
1198 {
1199 # ifdef FEAT_ARP
1200     struct MsgPort	    *replyport;
1201     struct StandardPacket   *packet;
1202     long		    res1;
1203 
1204     if (dos2)
1205 # endif
1206 	return DoPkt(pid, action, arg, 0L, 0L, 0L, 0L);	// use 2.0 function
1207 # ifdef FEAT_ARP
1208 
1209     replyport = (struct MsgPort *) CreatePort(NULL, 0);	// use arp function
1210     if (!replyport)
1211 	return (0);
1212 
1213     // Allocate space for a packet, make it public and clear it
1214     packet = (struct StandardPacket *)
1215 	AllocMem((long) sizeof(struct StandardPacket), MEMF_PUBLIC | MEMF_CLEAR);
1216     if (!packet) {
1217 	DeletePort(replyport);
1218 	return (0);
1219     }
1220     packet->sp_Msg.mn_Node.ln_Name = (char *) &(packet->sp_Pkt);
1221     packet->sp_Pkt.dp_Link = &(packet->sp_Msg);
1222     packet->sp_Pkt.dp_Port = replyport;
1223     packet->sp_Pkt.dp_Type = action;
1224     packet->sp_Pkt.dp_Arg1 = arg;
1225 
1226     PutMsg(pid, (struct Message *)packet);	// send packet
1227 
1228     WaitPort(replyport);
1229     GetMsg(replyport);
1230 
1231     res1 = packet->sp_Pkt.dp_Res1;
1232 
1233     FreeMem(packet, (long) sizeof(struct StandardPacket));
1234     DeletePort(replyport);
1235 
1236     return (res1);
1237 # endif
1238 }
1239 #endif // !defined(AZTEC_C) && !defined(__AROS__)
1240 
1241 /*
1242  * Call shell.
1243  * Return error number for failure, 0 otherwise
1244  */
1245     int
mch_call_shell(char_u * cmd,int options)1246 mch_call_shell(
1247     char_u	*cmd,
1248     int		options)	// SHELL_*, see vim.h
1249 {
1250     BPTR	mydir;
1251     int		x;
1252     int		tmode = cur_tmode;
1253 #ifdef AZTEC_C
1254     int		use_execute;
1255     char_u	*shellcmd = NULL;
1256     char_u	*shellarg;
1257 #endif
1258     int		retval = 0;
1259 
1260     if (close_win)
1261     {
1262 	// if Vim opened a window: Executing a shell may cause crashes
1263 	emsg(_("E360: Cannot execute shell with -f option"));
1264 	return -1;
1265     }
1266 
1267     if (term_console)
1268 	win_resize_off();	    // window resize events de-activated
1269     out_flush();
1270 
1271     if (options & SHELL_COOKED)
1272 	settmode(TMODE_COOK);	    // set to normal mode
1273     mydir = Lock((UBYTE *)"", (long)ACCESS_READ);   // remember current dir
1274 
1275 #if !defined(AZTEC_C)		    // not tested very much
1276     if (cmd == NULL)
1277     {
1278 # ifdef FEAT_ARP
1279 	if (dos2)
1280 # endif
1281 	    x = SystemTags(p_sh, SYS_UserShell, TRUE, TAG_DONE);
1282 # ifdef FEAT_ARP
1283 	else
1284 	    x = Execute(p_sh, raw_in, raw_out);
1285 # endif
1286     }
1287     else
1288     {
1289 # ifdef FEAT_ARP
1290 	if (dos2)
1291 # endif
1292 	    x = SystemTags((char *)cmd, SYS_UserShell, TRUE, TAG_DONE);
1293 # ifdef FEAT_ARP
1294 	else
1295 	    x = Execute((char *)cmd, 0L, raw_out);
1296 # endif
1297     }
1298 # ifdef FEAT_ARP
1299     if ((dos2 && x < 0) || (!dos2 && !x))
1300 # else
1301     if (x < 0)
1302 # endif
1303     {
1304 	msg_puts(_("Cannot execute "));
1305 	if (cmd == NULL)
1306 	{
1307 	    msg_puts(_("shell "));
1308 	    msg_outtrans(p_sh);
1309 	}
1310 	else
1311 	    msg_outtrans(cmd);
1312 	msg_putchar('\n');
1313 	retval = -1;
1314     }
1315 # ifdef FEAT_ARP
1316     else if (!dos2 || x)
1317 # else
1318     else if (x)
1319 # endif
1320     {
1321 	if ((x = IoErr()) != 0)
1322 	{
1323 	    if (!(options & SHELL_SILENT))
1324 	    {
1325 		msg_putchar('\n');
1326 		msg_outnum((long)x);
1327 		msg_puts(_(" returned\n"));
1328 	    }
1329 	    retval = x;
1330 	}
1331     }
1332 #else	// else part is for AZTEC_C
1333     if (p_st >= 4 || (p_st >= 2 && !(options & SHELL_FILTER)))
1334 	use_execute = 1;
1335     else
1336 	use_execute = 0;
1337     if (!use_execute)
1338     {
1339 	/*
1340 	 * separate shell name from argument
1341 	 */
1342 	shellcmd = vim_strsave(p_sh);
1343 	if (shellcmd == NULL)	    // out of memory, use Execute
1344 	    use_execute = 1;
1345 	else
1346 	{
1347 	    shellarg = skiptowhite(shellcmd);	// find start of arguments
1348 	    if (*shellarg != NUL)
1349 	    {
1350 		*shellarg++ = NUL;
1351 		shellarg = skipwhite(shellarg);
1352 	    }
1353 	}
1354     }
1355     if (cmd == NULL)
1356     {
1357 	if (use_execute)
1358 	{
1359 # ifdef FEAT_ARP
1360 	    if (dos2)
1361 # endif
1362 		x = SystemTags((UBYTE *)p_sh, SYS_UserShell, TRUE, TAG_DONE);
1363 # ifdef FEAT_ARP
1364 	    else
1365 		x = !Execute((UBYTE *)p_sh, raw_in, raw_out);
1366 # endif
1367 	}
1368 	else
1369 	    x = fexecl((char *)shellcmd, (char *)shellcmd, (char *)shellarg, NULL);
1370     }
1371     else if (use_execute)
1372     {
1373 # ifdef FEAT_ARP
1374 	if (dos2)
1375 # endif
1376 	    x = SystemTags((UBYTE *)cmd, SYS_UserShell, TRUE, TAG_DONE);
1377 # ifdef FEAT_ARP
1378 	else
1379 	    x = !Execute((UBYTE *)cmd, 0L, raw_out);
1380 # endif
1381     }
1382     else if (p_st & 1)
1383 	x = fexecl((char *)shellcmd, (char *)shellcmd, (char *)shellarg,
1384 							   (char *)cmd, NULL);
1385     else
1386 	x = fexecl((char *)shellcmd, (char *)shellcmd, (char *)shellarg,
1387 					   (char *)p_shcf, (char *)cmd, NULL);
1388 # ifdef FEAT_ARP
1389     if ((dos2 && x < 0) || (!dos2 && x))
1390 # else
1391     if (x < 0)
1392 # endif
1393     {
1394 	msg_puts(_("Cannot execute "));
1395 	if (use_execute)
1396 	{
1397 	    if (cmd == NULL)
1398 		msg_outtrans(p_sh);
1399 	    else
1400 		msg_outtrans(cmd);
1401 	}
1402 	else
1403 	{
1404 	    msg_puts(_("shell "));
1405 	    msg_outtrans(shellcmd);
1406 	}
1407 	msg_putchar('\n');
1408 	retval = -1;
1409     }
1410     else
1411     {
1412 	if (use_execute)
1413 	{
1414 # ifdef FEAT_ARP
1415 	    if (!dos2 || x)
1416 # else
1417 	    if (x)
1418 # endif
1419 		x = IoErr();
1420 	}
1421 	else
1422 	    x = wait();
1423 	if (x)
1424 	{
1425 	    if (!(options & SHELL_SILENT) && !emsg_silent)
1426 	    {
1427 		msg_putchar('\n');
1428 		msg_outnum((long)x);
1429 		msg_puts(_(" returned\n"));
1430 	    }
1431 	    retval = x;
1432 	}
1433     }
1434     vim_free(shellcmd);
1435 #endif	// AZTEC_C
1436 
1437     if ((mydir = CurrentDir(mydir)) != 0) // make sure we stay in the same directory
1438 	UnLock(mydir);
1439     if (tmode == TMODE_RAW)
1440     {
1441 	// The shell may have messed with the mode, always set it.
1442 	cur_tmode = TMODE_UNKNOWN;
1443 	settmode(TMODE_RAW);		// set to raw mode
1444     }
1445 #ifdef FEAT_TITLE
1446     resettitle();
1447 #endif
1448     if (term_console)
1449 	win_resize_on();		// window resize events activated
1450     return retval;
1451 }
1452 
1453 /*
1454  * check for an "interrupt signal"
1455  * We only react to a CTRL-C, but also clear the other break signals to avoid
1456  * trouble with lattice-c programs.
1457  */
1458     void
mch_breakcheck(int force)1459 mch_breakcheck(int force)
1460 {
1461    if (SetSignal(0L, (long)(SIGBREAKF_CTRL_C|SIGBREAKF_CTRL_D|SIGBREAKF_CTRL_E|SIGBREAKF_CTRL_F)) & SIGBREAKF_CTRL_C)
1462 	got_int = TRUE;
1463 }
1464 
1465 // this routine causes manx to use this Chk_Abort() rather than its own
1466 // otherwise it resets our ^C when doing any I/O (even when Enable_Abort
1467 // is zero).  Since we want to check for our own ^C's
1468 
1469 #ifdef _DCC
1470 #define Chk_Abort chkabort
1471 #endif
1472 
1473 #ifdef LATTICE
1474 void __regargs __chkabort(void);
1475 
__chkabort(void)1476 void __regargs __chkabort(void)
1477 {}
1478 
1479 #else
1480     long
Chk_Abort(void)1481 Chk_Abort(void)
1482 {
1483     return(0L);
1484 }
1485 #endif
1486 
1487 /*
1488  * mch_expandpath() - this code does wild-card pattern matching using the arp
1489  *		      routines.
1490  *
1491  * "pat" has backslashes before chars that are not to be expanded.
1492  * Returns the number of matches found.
1493  *
1494  * This is based on WildDemo2.c (found in arp1.1 distribution).
1495  * That code's copyright follows:
1496  *	Copyright (c) 1987, Scott Ballantyne
1497  *	Use and abuse as you please.
1498  */
1499 
1500 #ifdef __amigaos4__
1501 # define	ANCHOR_BUF_SIZE	1024
1502 #else
1503 # define ANCHOR_BUF_SIZE (512)
1504 # define ANCHOR_SIZE (sizeof(struct AnchorPath) + ANCHOR_BUF_SIZE)
1505 #endif
1506 
1507     int
mch_expandpath(garray_T * gap,char_u * pat,int flags)1508 mch_expandpath(
1509     garray_T	*gap,
1510     char_u	*pat,
1511     int		flags)		// EW_* flags
1512 {
1513     struct AnchorPath	*Anchor;
1514     LONG		Result;
1515     char_u		*starbuf, *sp, *dp;
1516     int			start_len;
1517     int			matches;
1518 #ifdef __amigaos4__
1519     struct TagItem	AnchorTags[] = {
1520 	{ADO_Strlen, ANCHOR_BUF_SIZE},
1521 	{ADO_Flags, APF_DODOT|APF_DOWILD|APF_MultiAssigns},
1522 	{TAG_DONE, 0L}
1523     };
1524 #endif
1525 
1526     start_len = gap->ga_len;
1527 
1528     // Get our AnchorBase
1529 #ifdef __amigaos4__
1530     Anchor = AllocDosObject(DOS_ANCHORPATH, AnchorTags);
1531 #else
1532     Anchor = alloc_clear(ANCHOR_SIZE);
1533 #endif
1534     if (Anchor == NULL)
1535 	return 0;
1536 
1537 #ifndef __amigaos4__
1538     Anchor->ap_Strlen = ANCHOR_BUF_SIZE;  // ap_Length not supported anymore
1539 # ifdef APF_DODOT
1540     Anchor->ap_Flags = APF_DODOT | APF_DOWILD;	// allow '.' for current dir
1541 # else
1542     Anchor->ap_Flags = APF_DoDot | APF_DoWild;	// allow '.' for current dir
1543 # endif
1544 #endif
1545 
1546 #ifdef FEAT_ARP
1547     if (dos2)
1548     {
1549 #endif
1550 	// hack to replace '*' by '#?'
1551 	starbuf = alloc(2 * STRLEN(pat) + 1);
1552 	if (starbuf == NULL)
1553 	    goto Return;
1554 	for (sp = pat, dp = starbuf; *sp; ++sp)
1555 	{
1556 	    if (*sp == '*')
1557 	    {
1558 		*dp++ = '#';
1559 		*dp++ = '?';
1560 	    }
1561 	    else
1562 		*dp++ = *sp;
1563 	}
1564 	*dp = NUL;
1565 	Result = MatchFirst((UBYTE *)starbuf, Anchor);
1566 	vim_free(starbuf);
1567 #ifdef FEAT_ARP
1568     }
1569     else
1570 	Result = FindFirst((char *)pat, Anchor);
1571 #endif
1572 
1573     /*
1574      * Loop to get all matches.
1575      */
1576     while (Result == 0)
1577     {
1578 #ifdef __amigaos4__
1579 	addfile(gap, (char_u *)Anchor->ap_Buffer, flags);
1580 #else
1581 	addfile(gap, (char_u *)Anchor->ap_Buf, flags);
1582 #endif
1583 #ifdef FEAT_ARP
1584 	if (dos2)
1585 #endif
1586 	    Result = MatchNext(Anchor);
1587 #ifdef FEAT_ARP
1588 	else
1589 	    Result = FindNext(Anchor);
1590 #endif
1591     }
1592     matches = gap->ga_len - start_len;
1593 
1594     if (Result == ERROR_BUFFER_OVERFLOW)
1595 	emsg(_("ANCHOR_BUF_SIZE too small."));
1596     else if (matches == 0 && Result != ERROR_OBJECT_NOT_FOUND
1597 			  && Result != ERROR_DEVICE_NOT_MOUNTED
1598 			  && Result != ERROR_NO_MORE_ENTRIES)
1599 	emsg(_("I/O ERROR"));
1600 
1601     /*
1602      * Sort the files for this pattern.
1603      */
1604     if (matches)
1605 	qsort((void *)(((char_u **)gap->ga_data) + start_len),
1606 				  (size_t)matches, sizeof(char_u *), sortcmp);
1607 
1608     // Free the wildcard stuff
1609 #ifdef FEAT_ARP
1610     if (dos2)
1611 #endif
1612 	MatchEnd(Anchor);
1613 #ifdef FEAT_ARP
1614     else
1615 	FreeAnchorChain(Anchor);
1616 #endif
1617 
1618 Return:
1619 #ifdef __amigaos4__
1620     FreeDosObject(DOS_ANCHORPATH, Anchor);
1621 #else
1622     vim_free(Anchor);
1623 #endif
1624 
1625     return matches;
1626 }
1627 
1628     static int
sortcmp(const void * a,const void * b)1629 sortcmp(const void *a, const void *b)
1630 {
1631     char *s = *(char **)a;
1632     char *t = *(char **)b;
1633 
1634     return pathcmp(s, t, -1);
1635 }
1636 
1637 /*
1638  * Return TRUE if "p" has wildcards that can be expanded by mch_expandpath().
1639  */
1640     int
mch_has_exp_wildcard(char_u * p)1641 mch_has_exp_wildcard(char_u *p)
1642 {
1643     for ( ; *p; MB_PTR_ADV(p))
1644     {
1645 	if (*p == '\\' && p[1] != NUL)
1646 	    ++p;
1647 	else if (vim_strchr((char_u *)"*?[(#", *p) != NULL)
1648 	    return TRUE;
1649     }
1650     return FALSE;
1651 }
1652 
1653     int
mch_has_wildcard(char_u * p)1654 mch_has_wildcard(char_u *p)
1655 {
1656     for ( ; *p; MB_PTR_ADV(p))
1657     {
1658 	if (*p == '\\' && p[1] != NUL)
1659 	    ++p;
1660 	else
1661 	    if (vim_strchr((char_u *)
1662 #  ifdef VIM_BACKTICK
1663 				    "*?[(#$`"
1664 #  else
1665 				    "*?[(#$"
1666 #  endif
1667 						, *p) != NULL
1668 		    || (*p == '~' && p[1] != NUL))
1669 		return TRUE;
1670     }
1671     return FALSE;
1672 }
1673 
1674 /*
1675  * With AmigaDOS 2.0 support for reading local environment variables
1676  *
1677  * Two buffers are allocated:
1678  * - A big one to do the expansion into.  It is freed before returning.
1679  * - A small one to hold the return value.  It is kept until the next call.
1680  */
1681     char_u *
mch_getenv(char_u * var)1682 mch_getenv(char_u *var)
1683 {
1684     int		    len;
1685     UBYTE	    *buf;		// buffer to expand in
1686     char_u	    *retval;		// return value
1687     static char_u   *alloced = NULL;	// allocated memory
1688 
1689 #ifdef FEAT_ARP
1690     if (!dos2)
1691 	retval = (char_u *)getenv((char *)var);
1692     else
1693 #endif
1694     {
1695 	VIM_CLEAR(alloced);
1696 	retval = NULL;
1697 
1698 	buf = alloc(IOSIZE);
1699 	if (buf == NULL)
1700 	    return NULL;
1701 
1702 	len = GetVar((UBYTE *)var, buf, (long)(IOSIZE - 1), (long)0);
1703 	if (len >= 0)
1704 	{
1705 	    retval = vim_strsave((char_u *)buf);
1706 	    alloced = retval;
1707 	}
1708 
1709 	vim_free(buf);
1710     }
1711 
1712     // if $VIM is not defined, use "vim:" instead
1713     if (retval == NULL && STRCMP(var, "VIM") == 0)
1714 	retval = (char_u *)"vim:";
1715 
1716     return retval;
1717 }
1718 
1719 /*
1720  * Amiga version of setenv() with AmigaDOS 2.0 support.
1721  */
1722 // ARGSUSED
1723     int
mch_setenv(char * var,char * value,int x)1724 mch_setenv(char *var, char *value, int x)
1725 {
1726 #ifdef FEAT_ARP
1727     if (!dos2)
1728 	return setenv(var, value);
1729 #endif
1730 
1731     if (SetVar((UBYTE *)var, (UBYTE *)value, (LONG)-1, (ULONG)GVF_LOCAL_ONLY))
1732 	return 0;   // success
1733     return -1;	    // failure
1734 }
1735