keyboard.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <draw.h>
  12. #include <thread.h>
  13. #include <keyboard.h>
  14. void
  15. closekeyboard(Keyboardctl *kc)
  16. {
  17. if(kc == nil)
  18. return;
  19. postnote(PNPROC, kc->pid, "kill");
  20. #ifdef BUG
  21. /* Drain the channel */
  22. while(?kc->c)
  23. <-kc->c;
  24. #endif
  25. close(kc->ctlfd);
  26. close(kc->consfd);
  27. free(kc->file);
  28. free(kc->c);
  29. free(kc);
  30. }
  31. static
  32. void
  33. _ioproc(void *arg)
  34. {
  35. int m, n;
  36. char buf[20];
  37. Rune r;
  38. Keyboardctl *kc;
  39. kc = arg;
  40. threadsetname("kbdproc");
  41. kc->pid = getpid();
  42. n = 0;
  43. for(;;){
  44. while(n>0 && fullrune(buf, n)){
  45. m = chartorune(&r, buf);
  46. n -= m;
  47. memmove(buf, buf+m, n);
  48. send(kc->c, &r);
  49. }
  50. m = read(kc->consfd, buf+n, sizeof buf-n);
  51. if(m <= 0){
  52. yield(); /* if error is due to exiting, we'll exit here */
  53. fprint(2, "keyboard read error: %r\n");
  54. threadexits("error");
  55. }
  56. n += m;
  57. }
  58. }
  59. Keyboardctl*
  60. initkeyboard(char *file)
  61. {
  62. Keyboardctl *kc;
  63. char *t;
  64. kc = mallocz(sizeof(Keyboardctl), 1);
  65. if(kc == nil)
  66. return nil;
  67. if(file == nil)
  68. file = "/dev/cons";
  69. kc->file = strdup(file);
  70. kc->consfd = open(file, ORDWR|OCEXEC);
  71. t = malloc(strlen(file)+16);
  72. if(kc->consfd<0 || t==nil){
  73. Error1:
  74. free(kc);
  75. return nil;
  76. }
  77. sprint(t, "%sctl", file);
  78. kc->ctlfd = open(t, OWRITE|OCEXEC);
  79. if(kc->ctlfd < 0){
  80. fprint(2, "initkeyboard: can't open %s: %r\n", t);
  81. Error2:
  82. close(kc->consfd);
  83. free(t);
  84. goto Error1;
  85. }
  86. if(ctlkeyboard(kc, "rawon") < 0){
  87. fprint(2, "initkeyboard: can't turn on raw mode on %s: %r\n", t);
  88. close(kc->ctlfd);
  89. goto Error2;
  90. }
  91. free(t);
  92. kc->c = chancreate(sizeof(Rune), 20);
  93. proccreate(_ioproc, kc, 4096);
  94. return kc;
  95. }
  96. int
  97. ctlkeyboard(Keyboardctl *kc, char *m)
  98. {
  99. return write(kc->ctlfd, m, strlen(m));
  100. }