read.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <draw.h>
  4. #include <memdraw.h>
  5. Memimage*
  6. readmemimage(int fd)
  7. {
  8. char hdr[5*12+1];
  9. int dy;
  10. ulong chan;
  11. uint l, n;
  12. int m, j;
  13. int new, miny, maxy;
  14. Rectangle r;
  15. uchar *tmp;
  16. int ldepth, chunk;
  17. Memimage *i;
  18. if(readn(fd, hdr, 11) != 11){
  19. werrstr("readimage: short header");
  20. return nil;
  21. }
  22. if(memcmp(hdr, "compressed\n", 11) == 0)
  23. return creadmemimage(fd);
  24. if(readn(fd, hdr+11, 5*12-11) != 5*12-11){
  25. werrstr("readimage: short header (2)");
  26. return nil;
  27. }
  28. /*
  29. * distinguish new channel descriptor from old ldepth.
  30. * channel descriptors have letters as well as numbers,
  31. * while ldepths are a single digit formatted as %-11d.
  32. */
  33. new = 0;
  34. for(m=0; m<10; m++){
  35. if(hdr[m] != ' '){
  36. new = 1;
  37. break;
  38. }
  39. }
  40. if(hdr[11] != ' '){
  41. werrstr("readimage: bad format");
  42. return nil;
  43. }
  44. if(new){
  45. hdr[11] = '\0';
  46. if((chan = strtochan(hdr)) == 0){
  47. werrstr("readimage: bad channel string %s", hdr);
  48. return nil;
  49. }
  50. }else{
  51. ldepth = ((int)hdr[10])-'0';
  52. if(ldepth<0 || ldepth>3){
  53. werrstr("readimage: bad ldepth %d", ldepth);
  54. return nil;
  55. }
  56. chan = drawld2chan[ldepth];
  57. }
  58. r.min.x = atoi(hdr+1*12);
  59. r.min.y = atoi(hdr+2*12);
  60. r.max.x = atoi(hdr+3*12);
  61. r.max.y = atoi(hdr+4*12);
  62. if(r.min.x>r.max.x || r.min.y>r.max.y){
  63. werrstr("readimage: bad rectangle");
  64. return nil;
  65. }
  66. miny = r.min.y;
  67. maxy = r.max.y;
  68. l = bytesperline(r, chantodepth(chan));
  69. i = allocmemimage(r, chan);
  70. if(i == nil)
  71. return nil;
  72. chunk = 32*1024;
  73. if(chunk < l)
  74. chunk = l;
  75. tmp = malloc(chunk);
  76. if(tmp == nil)
  77. goto Err;
  78. while(maxy > miny){
  79. dy = maxy - miny;
  80. if(dy*l > chunk)
  81. dy = chunk/l;
  82. if(dy <= 0){
  83. werrstr("readmemimage: image too wide for buffer");
  84. goto Err;
  85. }
  86. n = dy*l;
  87. m = readn(fd, tmp, n);
  88. if(m != n){
  89. werrstr("readmemimage: read count %d not %d: %r", m, n);
  90. Err:
  91. freememimage(i);
  92. free(tmp);
  93. return nil;
  94. }
  95. if(!new) /* an old image: must flip all the bits */
  96. for(j=0; j<chunk; j++)
  97. tmp[j] ^= 0xFF;
  98. if(loadmemimage(i, Rect(r.min.x, miny, r.max.x, miny+dy), tmp, chunk) <= 0)
  99. goto Err;
  100. miny += dy;
  101. }
  102. free(tmp);
  103. return i;
  104. }