79 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			C
		
	
	
			
		
		
	
	
			79 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			C
		
	
	
| #include "console.h"
 | |
| #include <string.h>
 | |
| #include <stdlib.h>
 | |
| #include "main.h" // shouldn't be here
 | |
| 
 | |
| void consoleLog(const char *string) {
 | |
|   struct ConsoleEntry *new_entry;
 | |
|   new_entry = malloc(sizeof(struct ConsoleEntry));
 | |
|   int bytes = strlen(string);
 | |
|   new_entry->string = malloc(bytes);
 | |
|   new_entry->size = bytes;
 | |
|   memcpy(new_entry->string, string, bytes+1);
 | |
|   if (console_last_entry) {
 | |
|     console_last_entry->next = new_entry;
 | |
|     new_entry->prev = console_last_entry;
 | |
|     new_entry->next = NULL;
 | |
|   } else {
 | |
|     console_first_entry = new_entry;
 | |
|     new_entry->next = NULL;
 | |
|     new_entry->prev = NULL;
 | |
|   }
 | |
|   console_last_entry = new_entry;
 | |
| }
 | |
| 
 | |
| const char *consoleGetEntryString(const struct ConsoleEntry *entry) {
 | |
|   if (entry->string) {
 | |
|     return entry->string;
 | |
|   }
 | |
|   return "";
 | |
| }
 | |
| 
 | |
| int consoleGenerateHash(const char* string) {
 | |
|   int i, sum;
 | |
|   size_t string_length = strlen(string);
 | |
|   for (sum=0, i=0; i < string_length; i++) {
 | |
|     sum += string[i];
 | |
|   }
 | |
|   return sum % COMMAND_HASH_SIZE;
 | |
| }
 | |
| 
 | |
| void consoleAddCommand(const char *command_string, void(*function)) {
 | |
|   int string_hash = consoleGenerateHash(command_string);
 | |
|   consoleLog("command added!"); // TODO: consoleLogF(formatted log)
 | |
|   console_commands_table[string_hash] = function;
 | |
| }
 | |
| 
 | |
| char **consoleGetCommand(const char *string) {
 | |
|   int i = 0;
 | |
|   char** command_array;
 | |
|   command_array = malloc(2 * sizeof(char*));
 | |
|   while(string[i] != ' ' && string[i] != '\0') {
 | |
|     i++;
 | |
|   }
 | |
|   command_array[0] = malloc(i+1); // our command
 | |
|   command_array[1] = malloc(console_cmd_size-i+1); // our argument string
 | |
|   memcpy(command_array[0], string, i);
 | |
|   memcpy(command_array[1], string+i+1, console_cmd_size-i);
 | |
|   command_array[0][i] = '\0';
 | |
|   command_array[1][console_cmd_size-i] = '\0';
 | |
|   return command_array;
 | |
| }
 | |
| 
 | |
| void consoleFreeCommand(char **command_array) {
 | |
|   free(command_array[0]);
 | |
|   free(command_array[1]);
 | |
|   free(command_array);
 | |
| }
 | |
| 
 | |
| void consoleProcessCommand(const char *command_string) {
 | |
|   char **command = consoleGetCommand(command_string);
 | |
|   int command_hash = consoleGenerateHash(command[0]);
 | |
|   if (console_commands_table[command_hash]) {
 | |
|     (*console_commands_table[command_hash])(command[1]);
 | |
|   } else {
 | |
|     consoleLog("Command not found!");
 | |
|   }
 | |
|   consoleFreeCommand(command);
 | |
| }
 |