1 /* 2 ** Copyright 2003-2004, Axel Dörfler, axeld@pinc-software.de. All rights reserved. 3 ** Distributed under the terms of the OpenBeOS License. 4 */ 5 6 7 #include <SupportDefs.h> 8 #include <string.h> 9 #include <util/kernel_cpp.h> 10 11 #include "Handle.h" 12 #include "console.h" 13 #include "openfirmware.h" 14 15 16 class ConsoleHandle : public Handle { 17 public: 18 ConsoleHandle(); 19 20 virtual ssize_t ReadAt(void *cookie, off_t pos, void *buffer, size_t bufferSize); 21 virtual ssize_t WriteAt(void *cookie, off_t pos, const void *buffer, size_t bufferSize); 22 }; 23 24 static ConsoleHandle sInput, sOutput; 25 FILE *stdin, *stdout, *stderr; 26 27 28 ConsoleHandle::ConsoleHandle() 29 : Handle() 30 { 31 } 32 33 34 ssize_t 35 ConsoleHandle::ReadAt(void */*cookie*/, off_t /*pos*/, void *buffer, size_t bufferSize) 36 { 37 // don't seek in character devices 38 return of_read(fHandle, buffer, bufferSize); 39 } 40 41 42 ssize_t 43 ConsoleHandle::WriteAt(void */*cookie*/, off_t /*pos*/, const void *buffer, size_t bufferSize) 44 { 45 const char *string = (const char *)buffer; 46 47 // be nice to our audience and replace single "\n" with "\r\n" 48 49 while (bufferSize > 0) { 50 bool newLine = false; 51 size_t length = 0; 52 53 for (; length < bufferSize; length++) { 54 if (string[length] == '\r') 55 length += 2; 56 else if (string[length] == '\n') 57 break; 58 } 59 60 if (length > bufferSize) 61 length = bufferSize; 62 63 of_write(fHandle, string, length); 64 65 if (newLine) { 66 of_write(fHandle, "\r\n", 2); 67 string++; 68 bufferSize--; 69 } 70 71 string += length; 72 bufferSize -= length; 73 } 74 75 return string - (char *)buffer; 76 } 77 78 79 // #pragma mark - 80 81 82 status_t 83 console_init(void) 84 { 85 int input, output; 86 if (of_getprop(gChosen, "stdin", &input, sizeof(int)) == OF_FAILED) 87 return B_ERROR; 88 if (of_getprop(gChosen, "stdout", &output, sizeof(int)) == OF_FAILED) 89 return B_ERROR; 90 91 sInput.SetHandle(input); 92 sOutput.SetHandle(output); 93 94 // now that we're initialized, enable stdio functionality 95 stdin = (FILE *)&sInput; 96 stdout = stderr = (FILE *)&sOutput; 97 98 return B_OK; 99 } 100 101 102