diff options
| -rw-r--r-- | browser.c | 85 |
1 files changed, 63 insertions, 22 deletions
@@ -93,6 +93,59 @@ void renderPage(const sds page, const struct md_syntax* syntax, int* *matches, i sdsfree(toPrint); } +#define MAX_LEN_COMMAND 16 +#define COMMAND_FORMAT ": %16s" + +int handleCLI(sds authority, sds *address, const sds page, int* *anchorIndecies, int *anchorCount) { + // Get a line + char line[1024]; + fgets(line, 1024, stdin); + + // Nothing + if (line[0] == '\0') { + printf("Please enter a valid command!\n"); + return 0; + } + + // Number or URL + if (line[0] != ':') { + // Index of anchor + if (strchr(line, '/') == NULL) { + int gotoIndex = 0; + sscanf(line, "%d", &gotoIndex); + + if (gotoIndex < 0 || gotoIndex >= *anchorCount) { + printf("Invalid anchor index!\n"); + return 0; + } + + char* newplace = strchr(page + (*anchorIndecies)[gotoIndex], '(') + 1; + sdsfree(*address); + *address = sdscatlen(sdsdup(authority), newplace, strchr(newplace, ')') - newplace); + } + // New address + else { + sdsfree(*address); + *address = sdsnewlen(line, strlen(line)-1 /* skip newline */); + } + return 0; + } + + // Special command + + // Get command name and it's arguments + // Currently no command takes arguments + char name[MAX_LEN_COMMAND+1] = { '\0' }; + int argsAssigned = sscanf(line, COMMAND_FORMAT, name); + + if (streq(name, "quit") || streq(name, "exit")) { + return 1; + } + + printf("Invalid command %s!\n", name); + return 0; +} + int main(int argc, char* argv[]) { /* * Compile regexes used in rendering @@ -108,45 +161,33 @@ int main(int argc, char* argv[]) { */ sds page; - sds address = sdsnew(argv[1]); + sds authority = sdsnew(argv[1]); + sds address = sdsdup(authority); int* anchorIndecies = NULL; int anchorCount = 0; - int gotoIndex = 0; - int count = 0; - - while (count < 2) { + int stopProgram = 0; + while (!stopProgram) { /* * Get the page */ + printf("\033[30;107m%s\033[0m\n", address); page = get_page("127.0.0.1", "8080", address); renderPage(page, &md, &anchorIndecies, &anchorCount); /* * Handle user input */ - - scanf("%d", &gotoIndex); - - if (gotoIndex < anchorCount) { - char* newplace = strchr(page + anchorIndecies[gotoIndex], '(') + 1; - sdsfree(address); - address = sdscatlen(sdsnew(argv[1]), newplace, strchr(newplace, ')') - newplace); - - free(anchorIndecies); - anchorCount = 0; - } - else { - printf("error\n"); - } - + stopProgram = handleCLI(authority, &address, page, &anchorIndecies, &anchorCount); + free(anchorIndecies); + anchorIndecies = NULL; + anchorCount = 0; sdsfree(page); - count++; } regfree(&md.anchor); - free(anchorIndecies); sdsfree(address); + sdsfree(authority); } |
