1/*
2 * Copyright 2005-2019, Haiku, Inc. All rights reserved.
3 * Copyright 2005, Ingo Weinhold, <bonefish@users.sf.net>
4 *
5 * Distributed under the terms of the MIT License.
6 *
7 * Authors:
8 *	Jeremiah Bailey, <jjbailey@gmail.com>
9 *	Ingo Weinhold, <bonefish@users.sf.net>
10 */
11
12
13#include "Arguments.h"
14
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18
19#include <Catalog.h>
20#include <Locale.h>
21
22
23#undef B_TRANSLATION_CONTEXT
24#define B_TRANSLATION_CONTEXT "Terminal arguments parsing"
25
26
27Arguments::Arguments(int defaultArgsNum, const char* const* defaultArgs)
28	: fUsageRequested(false),
29	  fBounds(50, 50, 630, 435),
30	  fStandardShell(true),
31	  fFullScreen(false),
32	  fShellArgumentCount(0),
33	  fShellArguments(NULL),
34	  fTitle(NULL),
35	  fWorkingDirectory(NULL)
36{
37	_SetShellArguments(defaultArgsNum, defaultArgs);
38}
39
40
41Arguments::~Arguments()
42{
43	_SetShellArguments(0, NULL);
44}
45
46
47void
48Arguments::Parse(int argc, const char* const* argv)
49{
50	int argi;
51	for (argi = 1; argi < argc; argi ++) {
52		const char* arg = argv[argi];
53
54		if (*arg == '-') {
55			if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0)
56				fUsageRequested = true;
57			else if (strcmp(arg, "-t") == 0 || strcmp(arg, "--title") == 0) {
58				// title
59				if (argi >= argc)
60					fUsageRequested = true;
61				else
62					fTitle = argv[++argi];
63			} else if (strcmp(arg, "-w") == 0
64					|| strcmp(arg, "--working-directory") == 0) {
65				if (argi >= argc)
66					fUsageRequested = true;
67				else
68					fWorkingDirectory = argv[++argi];
69			} else if (strcmp(arg, "-f") == 0
70					|| strcmp(arg, "--fullscreen") == 0)
71				fFullScreen = true;
72			else {
73				// illegal option
74				fprintf(stderr, B_TRANSLATE("Unrecognized option \"%s\"\n"),
75					arg);
76				fUsageRequested = true;
77			}
78		} else {
79			// no option, so the remainder is the shell program with arguments
80			_SetShellArguments(argc - argi, argv + argi);
81			argi = argc;
82			fStandardShell = false;
83		}
84	}
85}
86
87
88void
89Arguments::GetShellArguments(int& argc, const char* const*& argv) const
90{
91	argc = fShellArgumentCount;
92	argv = fShellArguments;
93}
94
95
96void
97Arguments::_SetShellArguments(int argc, const char* const* argv)
98{
99	// delete old arguments
100	for (int32 i = 0; i < fShellArgumentCount; i++)
101		free((void *)fShellArguments[i]);
102	delete[] fShellArguments;
103
104	fShellArguments = NULL;
105	fShellArgumentCount = 0;
106
107	// copy new ones
108	if (argc > 0 && argv) {
109		fShellArguments = new const char*[argc + 1];
110		for (int i = 0; i < argc; i++)
111			fShellArguments[i] = strdup(argv[i]);
112
113		fShellArguments[argc] = NULL;
114		fShellArgumentCount = argc;
115	}
116}
117
118