1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::num::NonZeroUsize;
use crate::{Color, IntRect};
use crate::color::PremultipliedColorU8;
use crate::geom::{IntSize, ScreenIntRect};
#[cfg(feature = "png-format")]
use crate::color::{premultiply_u8, ALPHA_U8_OPAQUE};
pub const BYTES_PER_PIXEL: usize = 4;
#[derive(Clone, PartialEq)]
pub struct Pixmap {
data: Vec<u8>,
size: IntSize,
}
impl Pixmap {
pub fn new(width: u32, height: u32) -> Option<Self> {
let size = IntSize::from_wh(width, height)?;
let data_len = data_len_for_size(size)?;
Some(Pixmap {
data: vec![0; data_len],
size,
})
}
#[cfg(feature = "png-format")]
pub(crate) fn from_vec(data: Vec<u8>, size: IntSize) -> Option<Self> {
let data_len = data_len_for_size(size)?;
if data.len() != data_len {
return None;
}
Some(Pixmap {
data,
size,
})
}
#[cfg(feature = "png-format")]
pub fn decode_png(data: &[u8]) -> Result<Self, png::DecodingError> {
fn make_custom_png_error(msg: &str) -> png::DecodingError {
std::io::Error::new(std::io::ErrorKind::Other, msg).into()
}
let mut decoder = png::Decoder::new(data);
decoder.set_transformations(png::Transformations::normalize_to_color8());
let mut reader = decoder.read_info()?;
let mut img_data = vec![0; reader.output_buffer_size()];
let info = reader.next_frame(&mut img_data)?;
if info.bit_depth != png::BitDepth::Eight {
return Err(make_custom_png_error("unsupported bit depth"));
}
let size = IntSize::from_wh(info.width, info.height)
.ok_or_else(|| make_custom_png_error("invalid image size"))?;
let data_len = data_len_for_size(size)
.ok_or_else(|| make_custom_png_error("image is too big"))?;
img_data = match info.color_type {
png::ColorType::Rgb => {
let mut rgba_data = Vec::with_capacity(data_len);
for rgb in img_data.chunks(3) {
rgba_data.push(rgb[0]);
rgba_data.push(rgb[1]);
rgba_data.push(rgb[2]);
rgba_data.push(ALPHA_U8_OPAQUE);
}
rgba_data
}
png::ColorType::Rgba => {
img_data
}
png::ColorType::Grayscale => {
let mut rgba_data = Vec::with_capacity(data_len);
for gray in img_data {
rgba_data.push(gray);
rgba_data.push(gray);
rgba_data.push(gray);
rgba_data.push(ALPHA_U8_OPAQUE);
}
rgba_data
}
png::ColorType::GrayscaleAlpha => {
let mut rgba_data = Vec::with_capacity(data_len);
for slice in img_data.chunks(2) {
let gray = slice[0];
let alpha = slice[1];
rgba_data.push(gray);
rgba_data.push(gray);
rgba_data.push(gray);
rgba_data.push(alpha);
}
rgba_data
}
png::ColorType::Indexed => {
return Err(make_custom_png_error("indexed PNG is not supported"));
}
};
for pixel in img_data.as_mut_slice().chunks_mut(BYTES_PER_PIXEL) {
let a = pixel[3];
pixel[0] = premultiply_u8(pixel[0], a);
pixel[1] = premultiply_u8(pixel[1], a);
pixel[2] = premultiply_u8(pixel[2], a);
}
Pixmap::from_vec(img_data, size)
.ok_or_else(|| make_custom_png_error("failed to create a pixmap"))
}
#[cfg(feature = "png-format")]
pub fn load_png<P: AsRef<std::path::Path>>(path: P) -> Result<Self, png::DecodingError> {
let data = std::fs::read(path)?;
Self::decode_png(&data)
}
#[cfg(feature = "png-format")]
pub fn encode_png(&self) -> Result<Vec<u8>, png::EncodingError> {
self.as_ref().encode_png()
}
#[cfg(feature = "png-format")]
pub fn save_png<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), png::EncodingError> {
self.as_ref().save_png(path)
}
pub fn as_ref(&self) -> PixmapRef {
PixmapRef {
data: &self.data,
size: self.size,
}
}
pub fn as_mut(&mut self) -> PixmapMut {
PixmapMut {
data: &mut self.data,
size: self.size,
}
}
#[inline]
pub fn width(&self) -> u32 {
self.size.width()
}
#[inline]
pub fn height(&self) -> u32 {
self.size.height()
}
#[allow(dead_code)]
pub(crate) fn size(&self) -> IntSize {
self.size
}
pub fn fill(&mut self, color: Color) {
let c = color.premultiply().to_color_u8();
for p in self.as_mut().pixels_mut() {
*p = c;
}
}
pub fn data(&self) -> &[u8] {
self.data.as_slice()
}
pub fn data_mut(&mut self) -> &mut [u8] {
self.data.as_mut_slice()
}
pub fn pixel(&self, x: u32, y: u32) -> Option<PremultipliedColorU8> {
let idx = self.width().checked_mul(y)?.checked_add(x)?;
self.pixels().get(idx as usize).cloned()
}
pub fn pixels_mut(&mut self) -> &mut [PremultipliedColorU8] {
bytemuck::cast_slice_mut(self.data_mut())
}
pub fn pixels(&self) -> &[PremultipliedColorU8] {
bytemuck::cast_slice(self.data())
}
pub fn take(self) -> Vec<u8> {
self.data
}
pub fn clone_rect(&self, rect: IntRect) -> Option<Pixmap> {
self.as_ref().clone_rect(rect)
}
}
impl core::fmt::Debug for Pixmap {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Pixmap")
.field("data", &"...")
.field("width", &self.size.width())
.field("height", &self.size.height())
.finish()
}
}
#[derive(Clone, Copy, PartialEq)]
pub struct PixmapRef<'a> {
data: &'a [u8],
size: IntSize,
}
impl<'a> PixmapRef<'a> {
pub fn from_bytes(data: &'a [u8], width: u32, height: u32) -> Option<Self> {
let size = IntSize::from_wh(width, height)?;
let data_len = data_len_for_size(size)?;
if data.len() < data_len {
return None;
}
Some(PixmapRef {
data,
size,
})
}
pub fn to_owned(&self) -> Pixmap {
Pixmap {
data: self.data.to_vec(),
size: self.size,
}
}
#[inline]
pub fn width(&self) -> u32 {
self.size.width()
}
#[inline]
pub fn height(&self) -> u32 {
self.size.height()
}
pub(crate) fn size(&self) -> IntSize {
self.size
}
pub(crate) fn rect(&self) -> ScreenIntRect {
self.size.to_screen_int_rect(0, 0)
}
pub fn data(&self) -> &'a [u8] {
self.data
}
pub fn pixel(&self, x: u32, y: u32) -> Option<PremultipliedColorU8> {
let idx = self.width().checked_mul(y)?.checked_add(x)?;
self.pixels().get(idx as usize).cloned()
}
pub fn pixels(&self) -> &'a [PremultipliedColorU8] {
bytemuck::cast_slice(self.data())
}
pub fn clone_rect(&self, rect: IntRect) -> Option<Pixmap> {
let rect = self.rect().to_int_rect().intersect(&rect)?;
let mut new = Pixmap::new(rect.width(), rect.height())?;
{
let old_pixels = self.pixels();
let mut new_mut = new.as_mut();
let new_pixels = new_mut.pixels_mut();
for y in 0..rect.height() {
for x in 0..rect.width() {
let old_idx = (y + rect.y() as u32) * self.width() + (x + rect.x() as u32);
let new_idx = y * rect.width() + x;
new_pixels[new_idx as usize] = old_pixels[old_idx as usize];
}
}
}
Some(new)
}
#[cfg(feature = "png-format")]
pub fn encode_png(&self) -> Result<Vec<u8>, png::EncodingError> {
let mut tmp_pixmap = self.to_owned();
for pixel in tmp_pixmap.pixels_mut() {
let c = pixel.demultiply();
*pixel = PremultipliedColorU8::from_rgba_unchecked(
c.red(), c.green(), c.blue(), c.alpha());
}
let mut data = Vec::new();
{
let mut encoder = png::Encoder::new(&mut data, self.width(), self.height());
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header()?;
writer.write_image_data(&tmp_pixmap.data)?;
}
Ok(data)
}
#[cfg(feature = "png-format")]
pub fn save_png<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), png::EncodingError> {
let data = self.encode_png()?;
std::fs::write(path, data)?;
Ok(())
}
}
impl core::fmt::Debug for PixmapRef<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("PixmapRef")
.field("data", &"...")
.field("width", &self.size.width())
.field("height", &self.size.height())
.finish()
}
}
#[derive(PartialEq)]
pub struct PixmapMut<'a> {
data: &'a mut [u8],
size: IntSize,
}
impl<'a> PixmapMut<'a> {
pub fn from_bytes(data: &'a mut [u8], width: u32, height: u32) -> Option<Self> {
let size = IntSize::from_wh(width, height)?;
let data_len = data_len_for_size(size)?;
if data.len() < data_len {
return None;
}
Some(PixmapMut {
data,
size,
})
}
pub fn to_owned(&self) -> Pixmap {
Pixmap {
data: self.data.to_vec(),
size: self.size,
}
}
pub fn as_ref(&self) -> PixmapRef {
PixmapRef {
data: &self.data,
size: self.size,
}
}
#[inline]
pub fn width(&self) -> u32 {
self.size.width()
}
#[inline]
pub fn height(&self) -> u32 {
self.size.height()
}
pub(crate) fn size(&self) -> IntSize {
self.size
}
pub fn fill(&mut self, color: Color) {
let c = color.premultiply().to_color_u8();
for p in self.pixels_mut() {
*p = c;
}
}
pub fn data_mut(&mut self) -> &mut [u8] {
self.data
}
pub fn pixels_mut(&mut self) -> &mut [PremultipliedColorU8] {
bytemuck::cast_slice_mut(self.data_mut())
}
pub(crate) fn as_subpixmap(&mut self) -> SubPixmapMut {
SubPixmapMut {
size: self.size(),
real_width: self.width() as usize,
data: &mut self.data,
}
}
pub(crate) fn subpixmap<'b>(&'b mut self, rect: IntRect) -> Option<SubPixmapMut<'b>> {
let rect = self.size.to_int_rect(0, 0).intersect(&rect)?;
let row_bytes = self.width() as usize * BYTES_PER_PIXEL;
let offset = rect.top() as usize * row_bytes + rect.left() as usize * BYTES_PER_PIXEL;
Some(SubPixmapMut {
size: rect.size(),
real_width: self.width() as usize,
data: &mut self.data[offset..],
})
}
}
impl core::fmt::Debug for PixmapMut<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("PixmapMut")
.field("data", &"...")
.field("width", &self.size.width())
.field("height", &self.size.height())
.finish()
}
}
pub struct SubPixmapMut<'a> {
pub data: &'a mut [u8],
pub size: IntSize,
pub real_width: usize,
}
impl<'a> SubPixmapMut<'a> {
pub fn pixels_mut(&mut self) -> &mut [PremultipliedColorU8] {
bytemuck::cast_slice_mut(self.data)
}
}
fn min_row_bytes(size: IntSize) -> Option<NonZeroUsize> {
let w = i32::try_from(size.width()).ok()?;
let w = w.checked_mul(BYTES_PER_PIXEL as i32)?;
NonZeroUsize::new(w as usize)
}
fn compute_data_len(size: IntSize, row_bytes: usize) -> Option<usize> {
let h = size.height().checked_sub(1)?;
let h = (h as usize).checked_mul(row_bytes)?;
let w = (size.width() as usize).checked_mul(BYTES_PER_PIXEL)?;
h.checked_add(w)
}
fn data_len_for_size(size: IntSize) -> Option<usize> {
let row_bytes = min_row_bytes(size)?;
compute_data_len(size, row_bytes.get())
}