Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.1.098.9 KB2026-09-14
Version
0.1.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-09-14
Size
98.9 KB
Downloads
1
Checksum
bdac84a1e4fe4dd3505b93c2781b1f15833b5189c2e4ee976225fa3c512885cc
Dependencies
None

slide.rs

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
//! スライド 1 枚
//!
//! スライドは図形の並びである。文字は図形の中に入っていて、図形の外に文字は置けない。
//! 図形には差し込み口 (`<p:ph>`) の種類が付いていることがあり、題名や本文はそれで見分ける。
//!
//! # 段落は docx と別の型にしてある
//!
//! docx の段落は書式の名前を持ち、pptx の段落は箇条書きの深さを持つ。持ち物が違うので分けてある。
//! 中の [`Run`] は同じものを使う。

use crate::error::Error;
use crate::paragraph::{Align, Run};
use crate::xml::{self, Event, Reader};


/// 1 インチあたりの長さ。pptx の位置と大きさはこの単位で入っている
pub const INCH: i64 = 914400;


/// スライドの段落
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Paragraph {
    /// 箇条書きの深さ。0 がいちばん浅い
    pub level: u32,
    /// 行のそろえ方
    pub align: Align,
    /// 中身
    pub run: Vec<Run>,
}


impl Paragraph {
    /// 飾りのない 1 行
    pub fn new(text: &str) -> Paragraph {
        Paragraph {run: vec![Run::new(text)], ..Paragraph::default()}
    }

    /// 深さを指定した 1 行
    pub fn nested(text: &str, level: u32) -> Paragraph {
        Paragraph {level, run: vec![Run::new(text)], ..Paragraph::default()}
    }

    /// 中の続きをつないだ文字
    pub fn text(&self) -> String {
        let mut result = String::new();

        for one in &self.run {
            result.push_str(&one.text);
        }

        result
    }
}


/// スライドに置かれたもの
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Shape {
    /// 図形の名前
    pub name: String,
    /// 差し込み口の種類 (title、body、subTitle など)。ないときは空
    pub place: String,
    /// 左上の位置。[`INCH`] 単位。分からないときは 0
    pub x: i64,
    pub y: i64,
    /// 大きさ。[`INCH`] 単位。分からないときは 0
    pub width: i64,
    pub height: i64,
    /// 中の段落
    pub paragraph: Vec<Paragraph>,
}


impl Shape {
    /// 位置と大きさを決めた、文字だけの図形
    pub fn text(name: &str, x: i64, y: i64, width: i64, height: i64, line: &[&str]) -> Shape {
        Shape {
            name: name.to_string(),
            place: String::new(),
            x,
            y,
            width,
            height,
            paragraph: line.iter().map(|one| Paragraph::new(one)).collect(),
        }
    }

    /// 中の文字を、段落ごとに改行でつないで返す
    pub fn body(&self) -> String {
        let mut result = String::new();

        for one in &self.paragraph {
            if !result.is_empty() {
                result.push('\n');
            }

            result.push_str(&one.text());
        }

        result
    }
}


/// スライド 1 枚
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Slide {
    pub shape: Vec<Shape>,
}


impl Slide {
    /// 図形を並べたスライド
    pub fn new(shape: Vec<Shape>) -> Slide {
        Slide {shape}
    }

    /// 中の文字を、図形ごとに改行でつないで返す
    pub fn text(&self) -> String {
        let mut result = String::new();

        for one in &self.shape {
            let body = one.body();

            if body.is_empty() {
                continue;
            }

            if !result.is_empty() {
                result.push('\n');
            }

            result.push_str(&body);
        }

        result
    }
}


/// スライドのパートを読む
///
/// 組にまとめられた図形 (`<p:grpSp>`) の中身も、同じ並びに入れて返す。
pub fn read(source: &mut Reader) -> Result<Slide, Error> {
    let mut result = Slide::default();

    while let Some(event) = source.next()? {
        if event != Event::Open {
            continue;
        }

        match source.name() {
            "sp" => result.shape.push(read_shape(source, "sp")?),
            "pic" => result.shape.push(read_shape(source, "pic")?),
            "graphicFrame" => result.shape.push(read_shape(source, "graphicFrame")?),
            _ => {}
        }
    }

    Ok(result)
}


/// 図形 1 つを、閉じる印まで読む
fn read_shape(source: &mut Reader, close: &str) -> Result<Shape, Error> {
    let mut result = Shape::default();
    let mut named = false;
    let mut placed = false;
    let mut sized = false;

    while let Some(event) = source.next()? {
        if event == Event::Close {
            if source.name() == close {
                return Ok(result);
            }

            continue;
        }

        if event == Event::Text {
            continue;
        }

        match source.name() {
            // 図形の名前は最初の cNvPr に入っている。中の図の名前ではない
            "cNvPr" if !named => {
                result.name = source.attribute("name").unwrap_or("").to_string();
                named = true;
            }

            "ph" if !placed => {
                result.place = source.attribute("type").unwrap_or("body").to_string();
                placed = true;
            }

            "off" if !sized => {
                result.x = number(source.attribute("x"));
                result.y = number(source.attribute("y"));
            }

            "ext" if !sized => {
                result.width = number(source.attribute("cx"));
                result.height = number(source.attribute("cy"));
                sized = true;
            }

            "p" if event == Event::Open => result.paragraph.push(read_paragraph(source)?),
            _ => {}
        }
    }

    Ok(result)
}


/// `<a:p>` を読んだ直後から `</a:p>` まで読む
fn read_paragraph(source: &mut Reader) -> Result<Paragraph, Error> {
    let mut result = Paragraph::default();
    let mut decorating = false;
    let mut reading = false;
    let mut coloring = false;
    let mut run: Option<Run> = None;

    while let Some(event) = source.next()? {
        if event == Event::Text {
            if reading {
                if let Some(one) = run.as_mut() {
                    one.text.push_str(source.text());
                }
            }

            continue;
        }

        if event == Event::Close {
            match source.name() {
                "p" => {
                    if let Some(one) = run.take() {
                        result.run.push(one);
                    }

                    return Ok(result);
                }

                "rPr" | "defRPr" => decorating = false,
                "solidFill" => coloring = false,
                "t" => reading = false,

                "r" | "fld" => {
                    if let Some(one) = run.take() {
                        result.run.push(one);
                    }
                }

                _ => {}
            }

            continue;
        }

        let empty = event == Event::Empty;

        match source.name() {
            "pPr" => {
                result.level = number(source.attribute("lvl")) as u32;
                result.align = align(source.attribute("algn"));
            }

            "r" | "fld" => run = Some(Run::default()),

            "rPr" => {
                if let Some(one) = run.as_mut() {
                    decorate(one, source);
                }

                decorating = !empty && run.is_some();
            }

            "t" if run.is_some() => reading = !empty,
            "solidFill" if decorating => coloring = true,

            "srgbClr" if coloring => {
                if let Some(one) = run.as_mut() {
                    one.color = source.attribute("val").unwrap_or("").to_string();
                }
            }

            "latin" if decorating => {
                if let Some(one) = run.as_mut() {
                    one.font = source.attribute("typeface").unwrap_or("").to_string();
                }
            }

            "br" => {
                match result.run.last_mut() {
                    Some(one) => one.text.push('\n'),
                    None => result.run.push(Run::new("\n")),
                }
            }

            _ => {}
        }
    }

    Ok(result)
}


/// `<a:rPr>` の属性を読む
fn decorate(run: &mut Run, source: &Reader) {
    run.bold = flag(source.attribute("b"));
    run.italic = flag(source.attribute("i"));
    run.strike = matches!(source.attribute("strike"), Some("sngStrike") | Some("dblStrike"));
    run.underline = !matches!(source.attribute("u"), None | Some("none"));

    // 大きさは 100 分の 1 ポイントで入っている
    run.size = number(source.attribute("sz")) as f64 / 100.0;
}


/// `b="1"` のような印を読む
fn flag(value: Option<&str>) -> bool {
    matches!(value, Some("1") | Some("true"))
}


/// 数として読む。読めなければ 0
fn number(value: Option<&str>) -> i64 {
    match value {
        Some(text) => text.trim().parse().unwrap_or(0),
        None => 0,
    }
}


/// `algn="ctr"` を読む
fn align(value: Option<&str>) -> Align {
    match value {
        Some("l") => Align::Left,
        Some("ctr") => Align::Center,
        Some("r") => Align::Right,
        Some("just") | Some("dist") => Align::Justify,
        _ => Align::None,
    }
}


/// `algn` に書く形
fn align_name(value: Align) -> Option<&'static str> {
    match value {
        Align::None => None,
        Align::Left => Some("l"),
        Align::Center => Some("ctr"),
        Align::Right => Some("r"),
        Align::Justify => Some("just"),
    }
}


/// 図形の並びを XML にして足す
pub fn shape_into(result: &mut String, shape: &[Shape]) {
    for (index, one) in shape.iter().enumerate() {
        // 1 番は図形をまとめる入れ物が使うので、2 番から振る
        let id = index + 2;
        result.push_str(&format!("<p:sp><p:nvSpPr><p:cNvPr id=\"{id}\" name=\""));
        xml::escape_into(&one.name, result);
        result.push_str("\"/><p:cNvSpPr><a:spLocks noGrp=\"1\"/></p:cNvSpPr><p:nvPr>");

        if !one.place.is_empty() {
            result.push_str("<p:ph type=\"");
            xml::escape_into(&one.place, result);
            result.push_str("\"/>");
        }

        result.push_str("</p:nvPr></p:nvSpPr><p:spPr><a:xfrm>");
        result.push_str(&format!("<a:off x=\"{}\" y=\"{}\"/>", one.x, one.y));
        result.push_str(&format!("<a:ext cx=\"{}\" cy=\"{}\"/>", one.width, one.height));
        result.push_str("</a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></p:spPr>");
        result.push_str("<p:txBody><a:bodyPr wrap=\"square\"><a:normAutofit/></a:bodyPr><a:lstStyle/>");

        // 文字の入れ物には段落が 1 つ以上必要である
        if one.paragraph.is_empty() {
            result.push_str("<a:p/>");
        }

        for line in &one.paragraph {
            paragraph_into(result, line);
        }

        result.push_str("</p:txBody></p:sp>");
    }
}


/// 段落を XML にして足す
fn paragraph_into(result: &mut String, one: &Paragraph) {
    result.push_str("<a:p>");
    let align = align_name(one.align);

    if one.level > 0 || align.is_some() {
        result.push_str("<a:pPr");

        if one.level > 0 {
            result.push_str(&format!(" lvl=\"{}\"", one.level));
        }

        if let Some(name) = align {
            result.push_str(&format!(" algn=\"{name}\""));
        }

        result.push_str("/>");
    }

    for run in &one.run {
        run_into(result, run);
    }

    result.push_str("</a:p>");
}


/// 続きの文字を XML にして足す
fn run_into(result: &mut String, run: &Run) {
    // 改行は文字ではなく印として置く
    let mut first = true;

    for piece in run.text.split('\n') {
        if !first {
            result.push_str("<a:br/>");
        }

        first = false;

        if piece.is_empty() {
            continue;
        }

        result.push_str("<a:r><a:rPr lang=\"ja-JP\"");

        if run.bold {
            result.push_str(" b=\"1\"");
        }

        if run.italic {
            result.push_str(" i=\"1\"");
        }

        if run.underline {
            result.push_str(" u=\"sng\"");
        }

        if run.strike {
            result.push_str(" strike=\"sngStrike\"");
        }

        if run.size > 0.0 {
            result.push_str(&format!(" sz=\"{}\"", (run.size * 100.0).round() as i64));
        }

        let detailed = !run.color.is_empty() || !run.font.is_empty();

        if !detailed {
            result.push_str("/>");
        } else {
            result.push('>');

            if !run.color.is_empty() {
                result.push_str("<a:solidFill><a:srgbClr val=\"");
                xml::escape_into(&run.color, result);
                result.push_str("\"/></a:solidFill>");
            }

            if !run.font.is_empty() {
                result.push_str("<a:latin typeface=\"");
                xml::escape_into(&run.font, result);
                result.push_str("\"/><a:ea typeface=\"");
                xml::escape_into(&run.font, result);
                result.push_str("\"/>");
            }

            result.push_str("</a:rPr>");
        }

        result.push_str("<a:t>");
        xml::escape_into(piece, result);
        result.push_str("</a:t></a:r>");
    }
}