summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/cli/fds/FDS.java
blob: d94aae05721a228001108f2bf13f5a6602b0c910 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package bjc.utils.cli.fds;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import bjc.utils.cli.CommandHelp;
import bjc.utils.cli.GenericHelp;
import bjc.utils.cli.fds.FDSState.InputMode;
import bjc.utils.funcutils.StringUtils;
import bjc.utils.ioutils.Block;
import bjc.utils.ioutils.BlockReader;
import bjc.utils.ioutils.PushbackBlockReader;

import com.ibm.icu.text.BreakIterator;

import static bjc.utils.ioutils.BlockReaders.*;

/**
 * Runs a FDS (FDiskScript) interface.
 * 
 * This is a rudimentary console interface inspired heavily by FDisk's interface
 * style.
 * 
 * Commands are denoted by a single character, but can invoke submodes.
 * 
 * @author bjculkin
 *
 */
public class FDS {
	private static SimpleFDSMode<?> miscMode;

	static {
		miscMode = new SimpleFDSMode<>("MSC");
		configureMiscMode();
	}

	private static void configureMiscMode() {
		GenericHelp loadScriptHelp = new GenericHelp("load-script\tLoad a script from a file", "");
		miscMode.addCommand("X", FDS::loadScript, loadScriptHelp);

		GenericHelp quitProgramHelp = new GenericHelp("quit-program\tQuit the program", "");
		miscMode.addCommand("Q", (state) -> state.modes.drop(state.modes.size()), quitProgramHelp);

		GenericHelp inlineInputHelp = new GenericHelp("inline-input\tProvide data input inline with commands",
				"");
		miscMode.addCommand("I", (state) -> {
			if(state.mode == InputMode.CHORD) {
				state.mode = InputMode.INLINE;
			} else if(state.mode == InputMode.INLINE) {
				state.mode = InputMode.CHORD;
			} else {
				state.printer.printf("? MNV\n");
			}
		}, inlineInputHelp);

		GenericHelp dataMacroHelp = new GenericHelp("input-macro\tDefine a macro for providing data", "");
		miscMode.addCommand("i", (state) -> createMacro(state, state.dataMacros), dataMacroHelp);

		GenericHelp comMacroHelp = new GenericHelp("command-macro\tDefine a macro for providing commands", "");
		miscMode.addCommand("c", (state) -> createMacro(state, state.commandMacros), comMacroHelp);
	}

	private static void createMacro(FDSState<?> state, Map<String, List<Block>> macroStore) {
		PushbackBlockReader source = state.datain;

		String macroName;
		List<Block> macroBody = new LinkedList<>();

		state.dataPrompter.accept("Enter macro name: ");
		Block blk = source.next();

		String blkContents = blk.contents.trim();

		BreakIterator charBreaker = BreakIterator.getCharacterInstance();
		charBreaker.setText(blkContents);

		macroName = blkContents.substring(0, charBreaker.next());

		state.dataPrompter.accept("Enter macro body (. to end body)");
		while(source.hasNext()) {
			blk = source.next();

			blkContents = blk.contents.trim();

			if(blkContents.equals(".")) break;

			macroBody.add(new Block(blk.blockNo, blkContents, blk.startLine, blk.endLine));
		}

		macroStore.put(macroName, macroBody);

		state.dataPrompter.accept(state.defaultPrompt);
	}

	/**
	 * Run a provided FDS mode until it is exited or there is no more input.
	 * 
	 * @param state
	 *                The initial state for the mode.
	 * 
	 * @return The final state of the mode.
	 * 
	 * @throws FDSException
	 *                 If something went wrong during mode execution.
	 */
	public static <S> S runFDS(FDSState<S> state) throws FDSException {
		BlockReader blockSource = state.comin;

		while(blockSource.hasNext() && !state.modes.empty()) {
			Block comBlock = blockSource.next();

			handleCommandString(comBlock, state);
		}

		return state.state;
	}

	private static <S> void handleCommandString(Block comBlock, FDSState<S> state) throws FDSException {
		String comString = comBlock.contents.trim();
		BreakIterator charBreaker = BreakIterator.getCharacterInstance();
		charBreaker.setText(comString);

		switch(state.mode) {
		case INLINE:
			if(comString.contains(" ")) {
				handleInlineCommand(comString.split(" "), state, comBlock);
				break;
			}
		case CHORD:
			if(StringUtils.graphemeCount(comString) > 1) {
				chordCommand(comBlock, state, comString);
				break;
			}
		case NORMAL:
			handleCommand(comString.substring(0, charBreaker.next()), state);
			break;
		default:
			throw new FDSException(String.format("Unknown input mode '%s'", state.mode));
		}
	}

	private static <S> void handleInlineCommand(String[] commands, FDSState<S> state, Block comBlock)
			throws FDSException {
		boolean dataInput = false;

		for(int i = 0; i < commands.length; i++) {
			String strang = commands[i].trim();

			if(dataInput) {
				if(strang.equals(";")) {
					dataInput = false;
				} else {
					Block dataBlock = new Block(comBlock.blockNo + i, strang, comBlock.startLine,
							comBlock.endLine);

					state.datain.addBlock(dataBlock);
				}
			} else {
				chordCommand(comBlock, state, strang);

				dataInput = true;
			}
		}
	}

	private static <S> void chordCommand(Block comBlock, FDSState<S> state, String comString) throws FDSException {
		PushbackBlockReader source = state.comin;

		BreakIterator charBreaker = BreakIterator.getCharacterInstance();
		charBreaker.setText(comString);

		int lastPos = charBreaker.first();

		while(charBreaker.next() != BreakIterator.DONE && lastPos < comString.length()) {
			String c = comString.substring(lastPos, charBreaker.current());

			Block newCom = new Block(comBlock.blockNo + 1, c, comBlock.startLine, comBlock.startLine);

			source.addBlock(newCom);

			lastPos = charBreaker.current();
		}
	}

	@SuppressWarnings("unchecked")
	private static <S> void handleCommand(String com, FDSState<S> state) throws FDSException {
		if(state.modes.empty()) return;

		PrintStream printer = state.printer;

		/*
		 * Handle built-in commands over user commands.
		 */
		switch(com) {
		case "x":
			if(state.mode == InputMode.CHORD) {
				state.mode = InputMode.NORMAL;
			} else if(state.mode == InputMode.NORMAL) {
				state.mode = InputMode.CHORD;
			} else {
				printer.println("? MNV\n");
			}
			break;
		case "q":
			FDSMode<S> md = state.modes.pop();
			printer.printf("!< %s\n", md.getName());
			break;
		case "m":
			helpSummary(printer, state);
			break;
		case "M":
			/*
			 * We'll see if this cast actually causes any issues.
			 * 
			 * None of the commands in misc. mode should depend on
			 * the state type, so it shouldn't matter.
			 */
			state.modes.push((FDSMode<S>) miscMode);
			printer.printf("!> MSC\n");
			break;
		case "@":
			state.modes.push(state.dataMacroMode);
			printer.printf("!> IDM\n");
			break;
		case "#":
			state.modes.push(state.comMacroMode);
			printer.printf("!> ICM\n");
			break;
		default:
			FDSMode<S> curMode = state.modes.top();

			if(curMode.hasSubmode(com)) {
				FDSMode<S> mode = curMode.getSubmode(com);

				state.modes.push(mode);
				printer.printf("!> %s\n", mode.getName());
			} else if(curMode.hasCommand(com)) {
				curMode.getCommand(com).run(state);
			} else {
				printer.printf("? UBC '%s'\n", com);
			}
		}
	}

	private static <S> void loadScript(FDSState<S> state) {
		state.dataPrompter.accept("Enter a filename: ");

		String fileName = state.datain.next().contents.split(" ")[0];

		PrintStream printer = state.printer;

		try {
			FileInputStream fis = new FileInputStream(fileName);

			BlockReader reader = simple("\\R", new InputStreamReader(fis));

			state.comin = pushback(serial(reader, state.comin));
			state.datain = pushback(serial(reader, state.datain));
		} catch(FileNotFoundException fnfex) {
			printer.printf("? FNF '%s'\n", fileName);
		}

		state.dataPrompter.accept(state.defaultPrompt);
	}

	private static <S> void helpSummary(PrintStream printer, FDSState<S> state) {
		FDSMode<S> mode = state.modes.top();

		printer.printf("Help for mode %s:\n", mode.getName());

		for(String bound : mode.registeredChars()) {
			Collection<CommandHelp> help = mode.getHelp(bound);

			if(help.size() > 1) {
				for(CommandHelp hlp : help) {
					printer.printf("\t%s\t- %s\n", bound, hlp.getSummary());
				}

				printer.println();
			} else {
				CommandHelp hlp = help.iterator().next();

				printer.printf("\t%s\t- %s\n", bound, hlp.getSummary());
			}
		}

		printer.printf("\nHelp for global commands:\n");
		printer.printf("\tx\t- chord mode\tread each character as a seperate command\n");
		printer.printf("\tq\t- exit mode\texit the current submode\n");
		printer.printf("\tm\t- show help\tshow this help message\n");
		printer.printf("\tM\t- misc. mode\tsubmode with misc. commands\n");
		printer.printf("\t@\t- invoke data macro\tinvoke bound data macros\n");
		printer.printf("\t#\t- invoke command macro\tinvoke bound command macros\n\n");
	}
}