creadimage.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <draw.h>
  4. Image *
  5. creadimage(Display *d, int fd, int dolock)
  6. {
  7. char hdr[5*12+1];
  8. Rectangle r;
  9. int m, nb, miny, maxy, new, ldepth, ncblock;
  10. uchar *buf, *a;
  11. Image *i;
  12. ulong chan;
  13. if(readn(fd, hdr, 5*12) != 5*12)
  14. return nil;
  15. /*
  16. * distinguish new channel descriptor from old ldepth.
  17. * channel descriptors have letters as well as numbers,
  18. * while ldepths are a single digit formatted as %-11d.
  19. */
  20. new = 0;
  21. for(m=0; m<10; m++){
  22. if(hdr[m] != ' '){
  23. new = 1;
  24. break;
  25. }
  26. }
  27. if(hdr[11] != ' '){
  28. werrstr("creadimage: bad format");
  29. return nil;
  30. }
  31. if(new){
  32. hdr[11] = '\0';
  33. if((chan = strtochan(hdr)) == 0){
  34. werrstr("creadimage: bad channel string %s", hdr);
  35. return nil;
  36. }
  37. }else{
  38. ldepth = ((int)hdr[10])-'0';
  39. if(ldepth<0 || ldepth>3){
  40. werrstr("creadimage: bad ldepth %d", ldepth);
  41. return nil;
  42. }
  43. chan = drawld2chan[ldepth];
  44. }
  45. r.min.x=atoi(hdr+1*12);
  46. r.min.y=atoi(hdr+2*12);
  47. r.max.x=atoi(hdr+3*12);
  48. r.max.y=atoi(hdr+4*12);
  49. if(r.min.x>r.max.x || r.min.y>r.max.y){
  50. werrstr("creadimage: bad rectangle");
  51. return nil;
  52. }
  53. if(dolock)
  54. lockdisplay(d);
  55. i = allocimage(d, r, chan, 0, 0);
  56. if(dolock)
  57. unlockdisplay(d);
  58. if(i == nil)
  59. return nil;
  60. ncblock = _compblocksize(r, i->depth);
  61. buf = malloc(ncblock);
  62. if(buf == nil)
  63. goto Errout;
  64. miny = r.min.y;
  65. while(miny != r.max.y){
  66. if(readn(fd, hdr, 2*12) != 2*12){
  67. Errout:
  68. if(dolock)
  69. lockdisplay(d);
  70. Erroutlock:
  71. freeimage(i);
  72. if(dolock)
  73. unlockdisplay(d);
  74. free(buf);
  75. return nil;
  76. }
  77. maxy = atoi(hdr+0*12);
  78. nb = atoi(hdr+1*12);
  79. if(maxy<=miny || r.max.y<maxy){
  80. werrstr("creadimage: bad maxy %d", maxy);
  81. goto Errout;
  82. }
  83. if(nb<=0 || ncblock<nb){
  84. werrstr("creadimage: bad count %d", nb);
  85. goto Errout;
  86. }
  87. if(readn(fd, buf, nb)!=nb)
  88. goto Errout;
  89. if(dolock)
  90. lockdisplay(d);
  91. a = bufimage(i->display, 21+nb);
  92. if(a == nil)
  93. goto Erroutlock;
  94. a[0] = 'Y';
  95. BPLONG(a+1, i->id);
  96. BPLONG(a+5, r.min.x);
  97. BPLONG(a+9, miny);
  98. BPLONG(a+13, r.max.x);
  99. BPLONG(a+17, maxy);
  100. if(!new) /* old image: flip the data bits */
  101. _twiddlecompressed(buf, nb);
  102. memmove(a+21, buf, nb);
  103. if(dolock)
  104. unlockdisplay(d);
  105. miny = maxy;
  106. }
  107. free(buf);
  108. return i;
  109. }