diff --git a/.gitattributes b/.gitattributes index 4306525457d25cc6ad0134b9715f7dcd2ea2f8be..90bc658405bd505e47c0669510d24687d876450e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -88,3 +88,6 @@ tasks/tasksmith-74f059424102/environment/source/spec/ISO-IEC-29500-1/ISO-IEC-295 tasks/tasksmith-74f059424102/environment/source/spec/ISO-IEC-29500-2/ISO-IEC-29500-2.pdf filter=lfs diff=lfs merge=lfs -text tasks/tasksmith-74f059424102/environment/source/spec/ISO-IEC-29500-3/ISO-IEC-29500-3.pdf filter=lfs diff=lfs merge=lfs -text tasks/tasksmith-74f059424102/environment/source/spec/ISO-IEC-29500-4/ISO-IEC-29500-4.pdf filter=lfs diff=lfs merge=lfs -text +tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/docx-icon.emf filter=lfs diff=lfs merge=lfs -text +tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/xlsx-icon.emf filter=lfs diff=lfs merge=lfs -text +tasks/tasksmith-74f059424102/environment/source/tests/test_files/calibriz.ttf filter=lfs diff=lfs merge=lfs -text diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/slide.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/slide.py new file mode 100644 index 0000000000000000000000000000000000000000..37a9780f6d5f60e1364b0d1c2d130d113a0711d1 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/slide.py @@ -0,0 +1,347 @@ +"""Slide-related custom element classes, including those for masters.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Callable, cast + +from pptx.oxml import parse_from_template, parse_xml +from pptx.oxml.dml.fill import CT_GradientFillProperties +from pptx.oxml.ns import nsdecls +from pptx.oxml.simpletypes import XsdString +from pptx.oxml.xmlchemy import ( + BaseOxmlElement, + Choice, + OneAndOnlyOne, + OptionalAttribute, + RequiredAttribute, + ZeroOrMore, + ZeroOrOne, + ZeroOrOneChoice, +) + +if TYPE_CHECKING: + from pptx.oxml.shapes.groupshape import CT_GroupShape + + +class _BaseSlideElement(BaseOxmlElement): + """Base class for the six slide types, providing common methods.""" + + cSld: CT_CommonSlideData + + @property + def spTree(self) -> CT_GroupShape: + """Return required `p:cSld/p:spTree` grandchild.""" + return self.cSld.spTree + + +class CT_Background(BaseOxmlElement): + """`p:bg` element.""" + + _insert_bgPr: Callable[[CT_BackgroundProperties], None] + + # ---these two are actually a choice, not a sequence, but simpler for + # ---present purposes this way. + _tag_seq = ("p:bgPr", "p:bgRef") + bgPr: CT_BackgroundProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "p:bgPr", successors=() + ) + bgRef = ZeroOrOne("p:bgRef", successors=()) + del _tag_seq + + def add_noFill_bgPr(self): + """Return a new `p:bgPr` element with noFill properties.""" + xml = "\n" " \n" " \n" "" % nsdecls("a", "p") + bgPr = cast(CT_BackgroundProperties, parse_xml(xml)) + self._insert_bgPr(bgPr) + return bgPr + + +class CT_BackgroundProperties(BaseOxmlElement): + """`p:bgPr` element.""" + + _tag_seq = ( + "a:noFill", + "a:solidFill", + "a:gradFill", + "a:blipFill", + "a:pattFill", + "a:grpFill", + "a:effectLst", + "a:effectDag", + "a:extLst", + ) + eg_fillProperties = ZeroOrOneChoice( + ( + Choice("a:noFill"), + Choice("a:solidFill"), + Choice("a:gradFill"), + Choice("a:blipFill"), + Choice("a:pattFill"), + Choice("a:grpFill"), + ), + successors=_tag_seq[6:], + ) + del _tag_seq + + def _new_gradFill(self): + """Override default to add default gradient subtree.""" + return CT_GradientFillProperties.new_gradFill() + + +class CT_CommonSlideData(BaseOxmlElement): + """`p:cSld` element.""" + + _remove_bg: Callable[[], None] + get_or_add_bg: Callable[[], CT_Background] + + _tag_seq = ("p:bg", "p:spTree", "p:custDataLst", "p:controls", "p:extLst") + bg: CT_Background | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "p:bg", successors=_tag_seq[1:] + ) + spTree: CT_GroupShape = OneAndOnlyOne("p:spTree") # pyright: ignore[reportAssignmentType] + del _tag_seq + name: str = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "name", XsdString, default="" + ) + + def get_or_add_bgPr(self) -> CT_BackgroundProperties: + """Return `p:bg/p:bgPr` grandchild. + + If no such grandchild is present, any existing `p:bg` child is first removed and a new + default `p:bg` with noFill settings is added. + """ + bg = self.bg + if bg is None or bg.bgPr is None: + bg = self._change_to_noFill_bg() + return cast(CT_BackgroundProperties, bg.bgPr) + + def _change_to_noFill_bg(self) -> CT_Background: + """Establish a `p:bg` child with no-fill settings. + + Any existing `p:bg` child is first removed. + """ + self._remove_bg() + bg = self.get_or_add_bg() + bg.add_noFill_bgPr() + return bg + + +class CT_NotesMaster(_BaseSlideElement): + """`p:notesMaster` element, root of a notes master part.""" + + _tag_seq = ("p:cSld", "p:clrMap", "p:hf", "p:notesStyle", "p:extLst") + cSld: CT_CommonSlideData = OneAndOnlyOne("p:cSld") # pyright: ignore[reportAssignmentType] + del _tag_seq + + @classmethod + def new_default(cls) -> CT_NotesMaster: + """Return a new `p:notesMaster` element based on the built-in default template.""" + return cast(CT_NotesMaster, parse_from_template("notesMaster")) + + +class CT_NotesSlide(_BaseSlideElement): + """`p:notes` element, root of a notes slide part.""" + + _tag_seq = ("p:cSld", "p:clrMapOvr", "p:extLst") + cSld: CT_CommonSlideData = OneAndOnlyOne("p:cSld") # pyright: ignore[reportAssignmentType] + del _tag_seq + + @classmethod + def new(cls) -> CT_NotesSlide: + """Return a new ```` element based on the default template. + + Note that the template does not include placeholders, which must be subsequently cloned + from the notes master. + """ + return cast(CT_NotesSlide, parse_from_template("notes")) + + +class CT_Slide(_BaseSlideElement): + """`p:sld` element, root element of a slide part (XML document).""" + + _tag_seq = ("p:cSld", "p:clrMapOvr", "p:transition", "p:timing", "p:extLst") + cSld: CT_CommonSlideData = OneAndOnlyOne("p:cSld") # pyright: ignore[reportAssignmentType] + clrMapOvr = ZeroOrOne("p:clrMapOvr", successors=_tag_seq[2:]) + timing = ZeroOrOne("p:timing", successors=_tag_seq[4:]) + del _tag_seq + + @classmethod + def new(cls) -> CT_Slide: + """Return new `p:sld` element configured as base slide shape.""" + return cast(CT_Slide, parse_xml(cls._sld_xml())) + + @property + def bg(self): + """Return `p:bg` grandchild or None if not present.""" + return self.cSld.bg + + def get_or_add_childTnLst(self): + """Return parent element for a new `p:video` child element. + + The `p:video` element causes play controls to appear under a video + shape (pic shape containing video). There can be more than one video + shape on a slide, which causes the precondition to vary. It needs to + handle the case when there is no `p:sld/p:timing` element and when + that element already exists. If the case isn't simple, it just nukes + what's there and adds a fresh one. This could theoretically remove + desired existing timing information, but there isn't any evidence + available to me one way or the other, so I've taken the simple + approach. + """ + childTnLst = self._childTnLst + if childTnLst is None: + childTnLst = self._add_childTnLst() + return childTnLst + + def _add_childTnLst(self): + """Add `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant. + + Any existing `p:timing` child element is ruthlessly removed and + replaced. + """ + self.remove(self.get_or_add_timing()) + timing = parse_xml(self._childTnLst_timing_xml()) + self._insert_timing(timing) + return timing.xpath("./p:tnLst/p:par/p:cTn/p:childTnLst")[0] + + @property + def _childTnLst(self): + """Return `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant. + + Return None if that element is not present. + """ + childTnLsts = self.xpath("./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst") + if not childTnLsts: + return None + return childTnLsts[0] + + @staticmethod + def _childTnLst_timing_xml(): + return ( + "\n" + " \n" + " \n" + ' \n' + " \n" + " \n" + " \n" + " \n" + "" % nsdecls("p") + ) + + @staticmethod + def _sld_xml(): + return ( + "\n" + " \n" + " \n" + " \n" + ' \n' + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "" % nsdecls("a", "p", "r") + ) + + +class CT_SlideLayout(_BaseSlideElement): + """`p:sldLayout` element, root of a slide layout part.""" + + _tag_seq = ("p:cSld", "p:clrMapOvr", "p:transition", "p:timing", "p:hf", "p:extLst") + cSld: CT_CommonSlideData = OneAndOnlyOne("p:cSld") # pyright: ignore[reportAssignmentType] + del _tag_seq + + +class CT_SlideLayoutIdList(BaseOxmlElement): + """`p:sldLayoutIdLst` element, child of `p:sldMaster`. + + Contains references to the slide layouts that inherit from the slide master. + """ + + sldLayoutId_lst: list[CT_SlideLayoutIdListEntry] + + sldLayoutId = ZeroOrMore("p:sldLayoutId") + + +class CT_SlideLayoutIdListEntry(BaseOxmlElement): + """`p:sldLayoutId` element, child of `p:sldLayoutIdLst`. + + Contains a reference to a slide layout. + """ + + rId: str = RequiredAttribute("r:id", XsdString) # pyright: ignore[reportAssignmentType] + + +class CT_SlideMaster(_BaseSlideElement): + """`p:sldMaster` element, root of a slide master part.""" + + get_or_add_sldLayoutIdLst: Callable[[], CT_SlideLayoutIdList] + + _tag_seq = ( + "p:cSld", + "p:clrMap", + "p:sldLayoutIdLst", + "p:transition", + "p:timing", + "p:hf", + "p:txStyles", + "p:extLst", + ) + cSld: CT_CommonSlideData = OneAndOnlyOne("p:cSld") # pyright: ignore[reportAssignmentType] + sldLayoutIdLst: CT_SlideLayoutIdList = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "p:sldLayoutIdLst", successors=_tag_seq[3:] + ) + del _tag_seq + + +class CT_SlideTiming(BaseOxmlElement): + """`p:timing` element, specifying animations and timed behaviors.""" + + _tag_seq = ("p:tnLst", "p:bldLst", "p:extLst") + tnLst = ZeroOrOne("p:tnLst", successors=_tag_seq[1:]) + del _tag_seq + + +class CT_TimeNodeList(BaseOxmlElement): + """`p:tnLst` or `p:childTnList` element.""" + + def add_video(self, shape_id): + """Add a new `p:video` child element for movie having *shape_id*.""" + video_xml = ( + "\n" + ' \n' + ' \n' + " \n" + ' \n' + " \n" + " \n" + " \n" + ' \n' + " \n" + " \n" + "\n" % (nsdecls("p"), self._next_cTn_id, shape_id) + ) + video = parse_xml(video_xml) + self.append(video) + + @property + def _next_cTn_id(self): + """Return the next available unique ID (int) for p:cTn element.""" + cTn_id_strs = self.xpath("/p:sld/p:timing//p:cTn/@id") + ids = [int(id_str) for id_str in cTn_id_strs] + return max(ids) + 1 + + +class CT_TLMediaNodeVideo(BaseOxmlElement): + """`p:video` element, specifying video media details.""" + + _tag_seq = ("p:cMediaNode",) + cMediaNode = OneAndOnlyOne("p:cMediaNode") + del _tag_seq diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/table.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/table.py new file mode 100644 index 0000000000000000000000000000000000000000..cd3e9ebc389d7ffec03dc85b2f73e46e319a72e9 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/table.py @@ -0,0 +1,588 @@ +"""Custom element classes for table-related XML elements""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Callable, Iterator, cast + +from pptx.enum.text import MSO_VERTICAL_ANCHOR +from pptx.oxml import parse_xml +from pptx.oxml.dml.fill import CT_GradientFillProperties +from pptx.oxml.ns import nsdecls +from pptx.oxml.simpletypes import ST_Coordinate, ST_Coordinate32, XsdBoolean, XsdInt +from pptx.oxml.text import CT_TextBody +from pptx.oxml.xmlchemy import ( + BaseOxmlElement, + Choice, + OneAndOnlyOne, + OptionalAttribute, + RequiredAttribute, + ZeroOrMore, + ZeroOrOne, + ZeroOrOneChoice, +) +from pptx.util import Emu, lazyproperty + +if TYPE_CHECKING: + from pptx.util import Length + + +class CT_Table(BaseOxmlElement): + """`a:tbl` custom element class""" + + get_or_add_tblPr: Callable[[], CT_TableProperties] + tr_lst: list[CT_TableRow] + _add_tr: Callable[..., CT_TableRow] + + _tag_seq = ("a:tblPr", "a:tblGrid", "a:tr") + tblPr: CT_TableProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:tblPr", successors=_tag_seq[1:] + ) + tblGrid: CT_TableGrid = OneAndOnlyOne("a:tblGrid") # pyright: ignore[reportAssignmentType] + tr = ZeroOrMore("a:tr", successors=_tag_seq[3:]) + del _tag_seq + + def add_tr(self, height: Length) -> CT_TableRow: + """Return a newly created `a:tr` child element having its `h` attribute set to `height`.""" + return self._add_tr(h=height) + + @property + def bandCol(self) -> bool: + return self._get_boolean_property("bandCol") + + @bandCol.setter + def bandCol(self, value: bool): + self._set_boolean_property("bandCol", value) + + @property + def bandRow(self) -> bool: + return self._get_boolean_property("bandRow") + + @bandRow.setter + def bandRow(self, value: bool): + self._set_boolean_property("bandRow", value) + + @property + def firstCol(self) -> bool: + return self._get_boolean_property("firstCol") + + @firstCol.setter + def firstCol(self, value: bool): + self._set_boolean_property("firstCol", value) + + @property + def firstRow(self) -> bool: + return self._get_boolean_property("firstRow") + + @firstRow.setter + def firstRow(self, value: bool): + self._set_boolean_property("firstRow", value) + + def iter_tcs(self) -> Iterator[CT_TableCell]: + """Generate each `a:tc` element in this tbl. + + `a:tc` elements are generated left-to-right, top-to-bottom. + """ + return (tc for tr in self.tr_lst for tc in tr.tc_lst) + + @property + def lastCol(self) -> bool: + return self._get_boolean_property("lastCol") + + @lastCol.setter + def lastCol(self, value: bool): + self._set_boolean_property("lastCol", value) + + @property + def lastRow(self) -> bool: + return self._get_boolean_property("lastRow") + + @lastRow.setter + def lastRow(self, value: bool): + self._set_boolean_property("lastRow", value) + + @classmethod + def new_tbl( + cls, rows: int, cols: int, width: int, height: int, tableStyleId: str | None = None + ) -> CT_Table: + """Return a new `p:tbl` element tree.""" + # working hypothesis is this is the default table style GUID + if tableStyleId is None: + tableStyleId = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}" + + xml = cls._tbl_tmpl() % (tableStyleId) + tbl = cast(CT_Table, parse_xml(xml)) + + # add specified number of rows and columns + rowheight = height // rows + colwidth = width // cols + + for col in range(cols): + # adjust width of last col to absorb any div error + if col == cols - 1: + colwidth = width - ((cols - 1) * colwidth) + tbl.tblGrid.add_gridCol(width=Emu(colwidth)) + + for row in range(rows): + # adjust height of last row to absorb any div error + if row == rows - 1: + rowheight = height - ((rows - 1) * rowheight) + tr = tbl.add_tr(height=Emu(rowheight)) + for col in range(cols): + tr.add_tc() + + return tbl + + def tc(self, row_idx: int, col_idx: int) -> CT_TableCell: + """Return `a:tc` element at `row_idx`, `col_idx`.""" + return self.tr_lst[row_idx].tc_lst[col_idx] + + def _get_boolean_property(self, propname: str) -> bool: + """Generalized getter for the boolean properties on the `a:tblPr` child element. + + Defaults to False if `propname` attribute is missing or `a:tblPr` element itself is not + present. + """ + tblPr = self.tblPr + if tblPr is None: + return False + propval = getattr(tblPr, propname) + return {True: True, False: False, None: False}[propval] + + def _set_boolean_property(self, propname: str, value: bool) -> None: + """Generalized setter for boolean properties on the `a:tblPr` child element. + + Sets `propname` attribute appropriately based on `value`. If `value` is True, the + attribute is set to "1"; a tblPr child element is added if necessary. If `value` is False, + the `propname` attribute is removed if present, allowing its default value of False to be + its effective value. + """ + if value not in (True, False): + raise ValueError("assigned value must be either True or False, got %s" % value) + tblPr = self.get_or_add_tblPr() + setattr(tblPr, propname, value) + + @classmethod + def _tbl_tmpl(cls): + return ( + "\n" + ' \n' + " %s\n" + " \n" + " \n" + "" % (nsdecls("a"), "%s") + ) + + +class CT_TableCell(BaseOxmlElement): + """`a:tc` custom element class""" + + get_or_add_tcPr: Callable[[], CT_TableCellProperties] + get_or_add_txBody: Callable[[], CT_TextBody] + + _tag_seq = ("a:txBody", "a:tcPr", "a:extLst") + txBody: CT_TextBody | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:txBody", successors=_tag_seq[1:] + ) + tcPr: CT_TableCellProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:tcPr", successors=_tag_seq[2:] + ) + del _tag_seq + + gridSpan: int = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "gridSpan", XsdInt, default=1 + ) + rowSpan: int = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "rowSpan", XsdInt, default=1 + ) + hMerge: bool = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "hMerge", XsdBoolean, default=False + ) + vMerge: bool = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "vMerge", XsdBoolean, default=False + ) + + @property + def anchor(self) -> MSO_VERTICAL_ANCHOR | None: + """String held in `anchor` attribute of `a:tcPr` child element of this `a:tc` element.""" + if self.tcPr is None: + return None + return self.tcPr.anchor + + @anchor.setter + def anchor(self, anchor_enum_idx: MSO_VERTICAL_ANCHOR | None): + """Set value of anchor attribute on `a:tcPr` child element.""" + if anchor_enum_idx is None and self.tcPr is None: + return + tcPr = self.get_or_add_tcPr() + tcPr.anchor = anchor_enum_idx + + def append_ps_from(self, spanned_tc: CT_TableCell): + """Append `a:p` elements taken from `spanned_tc`. + + Any non-empty paragraph elements in `spanned_tc` are removed and appended to the + text-frame of this cell. If `spanned_tc` is left with no content after this process, a + single empty `a:p` element is added to ensure the cell is compliant with the spec. + """ + source_txBody = spanned_tc.get_or_add_txBody() + target_txBody = self.get_or_add_txBody() + + # ---if source is empty, there's nothing to do--- + if source_txBody.is_empty: + return + + # ---a single empty paragraph in target is overwritten--- + if target_txBody.is_empty: + target_txBody.clear_content() + + for p in source_txBody.p_lst: + target_txBody.append(p) + + # ---neither source nor target can be left without ps--- + source_txBody.unclear_content() + target_txBody.unclear_content() + + @property + def col_idx(self) -> int: + """Offset of this cell's column in its table.""" + # ---tc elements come before any others in `a:tr` element--- + return cast(CT_TableRow, self.getparent()).index(self) + + @property + def is_merge_origin(self) -> bool: + """True if cell is top-left in merged cell range.""" + if self.gridSpan > 1 and not self.vMerge: + return True + return self.rowSpan > 1 and not self.hMerge + + @property + def is_spanned(self) -> bool: + """True if cell is in merged cell range but not merge origin cell.""" + return self.hMerge or self.vMerge + + @property + def marT(self) -> Length: + """Top margin for this cell. + + This value is stored in the `marT` attribute of the `a:tcPr` child element of this `a:tc`. + + Read/write. If the attribute is not present, the default value `45720` (0.05 inches) is + returned for top and bottom; `91440` (0.10 inches) is the default for left and right. + Assigning |None| to any `marX` property clears that attribute from the element, + effectively setting it to the default value. + """ + return self._get_marX("marT", Emu(45720)) + + @marT.setter + def marT(self, value: Length | None): + self._set_marX("marT", value) + + @property + def marR(self) -> Length: + """Right margin value represented in `marR` attribute.""" + return self._get_marX("marR", Emu(91440)) + + @marR.setter + def marR(self, value: Length | None): + self._set_marX("marR", value) + + @property + def marB(self) -> Length: + """Bottom margin value represented in `marB` attribute.""" + return self._get_marX("marB", Emu(45720)) + + @marB.setter + def marB(self, value: Length | None): + self._set_marX("marB", value) + + @property + def marL(self) -> Length: + """Left margin value represented in `marL` attribute.""" + return self._get_marX("marL", Emu(91440)) + + @marL.setter + def marL(self, value: Length | None): + self._set_marX("marL", value) + + @classmethod + def new(cls) -> CT_TableCell: + """Return a new `a:tc` element subtree.""" + return cast( + CT_TableCell, + parse_xml( + f"\n" + f" \n" + f" \n" + f" \n" + f" \n" + f" \n" + f" \n" + f"" + ), + ) + + @property + def row_idx(self) -> int: + """Offset of this cell's row in its table.""" + return cast(CT_TableRow, self.getparent()).row_idx + + @property + def tbl(self) -> CT_Table: + """Table element this cell belongs to.""" + return cast(CT_Table, self.xpath("ancestor::a:tbl")[0]) + + @property + def text(self) -> str: # pyright: ignore[reportIncompatibleMethodOverride] + """str text contained in cell""" + # ---note this shadows lxml _Element.text--- + txBody = self.txBody + if txBody is None: + return "" + return "\n".join([p.text for p in txBody.p_lst]) + + def _get_marX(self, attr_name: str, default: Length) -> Length: + """Generalized method to get margin values.""" + if self.tcPr is None: + return Emu(default) + return Emu(int(self.tcPr.get(attr_name, default))) + + def _new_txBody(self) -> CT_TextBody: + return CT_TextBody.new_a_txBody() + + def _set_marX(self, marX: str, value: Length | None) -> None: + """Set value of marX attribute on `a:tcPr` child element. + + If `marX` is |None|, the marX attribute is removed. `marX` is a string, one of `('marL', + 'marR', 'marT', 'marB')`. + """ + if value is None and self.tcPr is None: + return + tcPr = self.get_or_add_tcPr() + setattr(tcPr, marX, value) + + +class CT_TableCellProperties(BaseOxmlElement): + """`a:tcPr` custom element class""" + + eg_fillProperties = ZeroOrOneChoice( + ( + Choice("a:noFill"), + Choice("a:solidFill"), + Choice("a:gradFill"), + Choice("a:blipFill"), + Choice("a:pattFill"), + Choice("a:grpFill"), + ), + successors=("a:headers", "a:extLst"), + ) + anchor: MSO_VERTICAL_ANCHOR | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "anchor", MSO_VERTICAL_ANCHOR + ) + marL: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "marL", ST_Coordinate32 + ) + marR: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "marR", ST_Coordinate32 + ) + marT: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "marT", ST_Coordinate32 + ) + marB: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "marB", ST_Coordinate32 + ) + + def _new_gradFill(self): + return CT_GradientFillProperties.new_gradFill() + + +class CT_TableCol(BaseOxmlElement): + """`a:gridCol` custom element class.""" + + w: Length = RequiredAttribute("w", ST_Coordinate) # pyright: ignore[reportAssignmentType] + + +class CT_TableGrid(BaseOxmlElement): + """`a:tblGrid` custom element class.""" + + gridCol_lst: list[CT_TableCol] + _add_gridCol: Callable[..., CT_TableCol] + + gridCol = ZeroOrMore("a:gridCol") + + def add_gridCol(self, width: Length) -> CT_TableCol: + """A newly appended `a:gridCol` child element having its `w` attribute set to `width`.""" + return self._add_gridCol(w=width) + + +class CT_TableProperties(BaseOxmlElement): + """`a:tblPr` custom element class.""" + + bandRow = OptionalAttribute("bandRow", XsdBoolean, default=False) + bandCol = OptionalAttribute("bandCol", XsdBoolean, default=False) + firstRow = OptionalAttribute("firstRow", XsdBoolean, default=False) + firstCol = OptionalAttribute("firstCol", XsdBoolean, default=False) + lastRow = OptionalAttribute("lastRow", XsdBoolean, default=False) + lastCol = OptionalAttribute("lastCol", XsdBoolean, default=False) + + +class CT_TableRow(BaseOxmlElement): + """`a:tr` custom element class.""" + + tc_lst: list[CT_TableCell] + _add_tc: Callable[[], CT_TableCell] + + tc = ZeroOrMore("a:tc", successors=("a:extLst",)) + h: Length = RequiredAttribute("h", ST_Coordinate) # pyright: ignore[reportAssignmentType] + + def add_tc(self) -> CT_TableCell: + """A newly added minimal valid `a:tc` child element.""" + return self._add_tc() + + @property + def row_idx(self) -> int: + """Offset of this row in its table.""" + return cast(CT_Table, self.getparent()).tr_lst.index(self) + + def _new_tc(self): + return CT_TableCell.new() + + +class TcRange(object): + """A 2D block of `a:tc` cell elements in a table. + + This object assumes the structure of the underlying table does not change during its lifetime. + Structural changes in this context would be insertion or removal of rows or columns. + + The client is expected to create, use, and then abandon an instance in the context of a single + user operation that is known to have no structural side-effects of this type. + """ + + def __init__(self, tc: CT_TableCell, other_tc: CT_TableCell): + self._tc = tc + self._other_tc = other_tc + + @classmethod + def from_merge_origin(cls, tc: CT_TableCell): + """Return instance created from merge-origin tc element.""" + other_tc = tc.tbl.tc( + tc.row_idx + tc.rowSpan - 1, # ---other_row_idx + tc.col_idx + tc.gridSpan - 1, # ---other_col_idx + ) + return cls(tc, other_tc) + + @lazyproperty + def contains_merged_cell(self) -> bool: + """True if one or more cells in range are part of a merged cell.""" + for tc in self.iter_tcs(): + if tc.gridSpan > 1: + return True + if tc.rowSpan > 1: + return True + if tc.hMerge: + return True + if tc.vMerge: + return True + return False + + @lazyproperty + def dimensions(self) -> tuple[int, int]: + """(row_count, col_count) pair describing size of range.""" + _, _, width, height = self._extents + return height, width + + @lazyproperty + def in_same_table(self): + """True if both cells provided to constructor are in same table.""" + if self._tc.tbl is self._other_tc.tbl: + return True + return False + + def iter_except_left_col_tcs(self): + """Generate each `a:tc` element not in leftmost column of range.""" + for tr in self._tbl.tr_lst[self._top : self._bottom]: + for tc in tr.tc_lst[self._left + 1 : self._right]: + yield tc + + def iter_except_top_row_tcs(self): + """Generate each `a:tc` element in non-first rows of range.""" + for tr in self._tbl.tr_lst[self._top + 1 : self._bottom]: + for tc in tr.tc_lst[self._left : self._right]: + yield tc + + def iter_left_col_tcs(self): + """Generate each `a:tc` element in leftmost column of range.""" + col_idx = self._left + for tr in self._tbl.tr_lst[self._top : self._bottom]: + yield tr.tc_lst[col_idx] + + def iter_tcs(self): + """Generate each `a:tc` element in this range. + + Cell elements are generated left-to-right, top-to-bottom. + """ + return ( + tc + for tr in self._tbl.tr_lst[self._top : self._bottom] + for tc in tr.tc_lst[self._left : self._right] + ) + + def iter_top_row_tcs(self): + """Generate each `a:tc` element in topmost row of range.""" + tr = self._tbl.tr_lst[self._top] + for tc in tr.tc_lst[self._left : self._right]: + yield tc + + def move_content_to_origin(self): + """Move all paragraphs in range to origin cell.""" + tcs = list(self.iter_tcs()) + origin_tc = tcs[0] + for spanned_tc in tcs[1:]: + origin_tc.append_ps_from(spanned_tc) + + @lazyproperty + def _bottom(self): + """Index of row following last row of range""" + _, top, _, height = self._extents + return top + height + + @lazyproperty + def _extents(self) -> tuple[int, int, int, int]: + """A (left, top, width, height) tuple describing range extents. + + Note this is normalized to accommodate the various orderings of the corner cells provided + on construction, which may be in any of four configurations such as (top-left, + bottom-right), (bottom-left, top-right), etc. + """ + + def start_and_size(idx: int, other_idx: int) -> tuple[int, int]: + """Return beginning and length of range based on two indexes.""" + return min(idx, other_idx), abs(idx - other_idx) + 1 + + tc, other_tc = self._tc, self._other_tc + + left, width = start_and_size(tc.col_idx, other_tc.col_idx) + top, height = start_and_size(tc.row_idx, other_tc.row_idx) + + return left, top, width, height + + @lazyproperty + def _left(self): + """Index of leftmost column in range.""" + left, _, _, _ = self._extents + return left + + @lazyproperty + def _right(self): + """Index of column following the last column in range.""" + left, _, width, _ = self._extents + return left + width + + @lazyproperty + def _tbl(self): + """`a:tbl` element containing this cell range.""" + return self._tc.tbl + + @lazyproperty + def _top(self): + """Index of topmost row in range.""" + _, top, _, _ = self._extents + return top diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/text.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/text.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9ecc1523c2c522a68612d140849488e73130de --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/text.py @@ -0,0 +1,618 @@ +"""Custom element classes for text-related XML elements""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, Callable, cast + +from pptx.enum.lang import MSO_LANGUAGE_ID +from pptx.enum.text import ( + MSO_AUTO_SIZE, + MSO_TEXT_UNDERLINE_TYPE, + MSO_VERTICAL_ANCHOR, + PP_PARAGRAPH_ALIGNMENT, +) +from pptx.exc import InvalidXmlError +from pptx.oxml import parse_xml +from pptx.oxml.dml.fill import CT_GradientFillProperties +from pptx.oxml.ns import nsdecls +from pptx.oxml.simpletypes import ( + ST_Coordinate32, + ST_TextFontScalePercentOrPercentString, + ST_TextFontSize, + ST_TextIndentLevelType, + ST_TextSpacingPercentOrPercentString, + ST_TextSpacingPoint, + ST_TextTypeface, + ST_TextWrappingType, + XsdBoolean, +) +from pptx.oxml.xmlchemy import ( + BaseOxmlElement, + Choice, + OneAndOnlyOne, + OneOrMore, + OptionalAttribute, + RequiredAttribute, + ZeroOrMore, + ZeroOrOne, + ZeroOrOneChoice, +) +from pptx.util import Emu, Length + +if TYPE_CHECKING: + from pptx.oxml.action import CT_Hyperlink + + +class CT_RegularTextRun(BaseOxmlElement): + """`a:r` custom element class""" + + get_or_add_rPr: Callable[[], CT_TextCharacterProperties] + + rPr: CT_TextCharacterProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:rPr", successors=("a:t",) + ) + t: BaseOxmlElement = OneAndOnlyOne("a:t") # pyright: ignore[reportAssignmentType] + + @property + def text(self) -> str: + """All text of (required) `a:t` child.""" + text = self.t.text + # -- t.text is None when t element is empty, e.g. '' -- + return text or "" + + @text.setter + def text(self, value: str): # pyright: ignore[reportIncompatibleMethodOverride] + self.t.text = self._escape_ctrl_chars(value) + + @staticmethod + def _escape_ctrl_chars(s: str) -> str: + """Return str after replacing each control character with a plain-text escape. + + For example, a BEL character (x07) would appear as "_x0007_". Horizontal-tab + (x09) and line-feed (x0A) are not escaped. All other characters in the range + x00-x1F are escaped. + """ + return re.sub(r"([\x00-\x08\x0B-\x1F])", lambda match: "_x%04X_" % ord(match.group(1)), s) + + +class CT_TextBody(BaseOxmlElement): + """`p:txBody` custom element class. + + Also used for `c:txPr` in charts and perhaps other elements. + """ + + add_p: Callable[[], CT_TextParagraph] + p_lst: list[CT_TextParagraph] + + bodyPr: CT_TextBodyProperties = OneAndOnlyOne( # pyright: ignore[reportAssignmentType] + "a:bodyPr" + ) + p: CT_TextParagraph = OneOrMore("a:p") # pyright: ignore[reportAssignmentType] + + def clear_content(self): + """Remove all `a:p` children, but leave any others. + + cf. lxml `_Element.clear()` method which removes all children. + """ + for p in self.p_lst: + self.remove(p) + + @property + def defRPr(self) -> CT_TextCharacterProperties: + """`a:defRPr` element of required first `p` child, added with its ancestors if not present. + + Used when element is a ``c:txPr`` in a chart and the `p` element is used only to specify + formatting, not content. + """ + p = self.p_lst[0] + pPr = p.get_or_add_pPr() + defRPr = pPr.get_or_add_defRPr() + return defRPr + + @property + def is_empty(self) -> bool: + """True if only a single empty `a:p` element is present.""" + ps = self.p_lst + if len(ps) > 1: + return False + + if not ps: + raise InvalidXmlError("p:txBody must have at least one a:p") + + if ps[0].text != "": + return False + return True + + @classmethod + def new(cls): + """Return a new `p:txBody` element tree.""" + xml = cls._txBody_tmpl() + txBody = parse_xml(xml) + return txBody + + @classmethod + def new_a_txBody(cls) -> CT_TextBody: + """Return a new `a:txBody` element tree. + + Suitable for use in a table cell and possibly other situations. + """ + xml = cls._a_txBody_tmpl() + txBody = cast(CT_TextBody, parse_xml(xml)) + return txBody + + @classmethod + def new_p_txBody(cls): + """Return a new `p:txBody` element tree, suitable for use in an `p:sp` element.""" + xml = cls._p_txBody_tmpl() + return parse_xml(xml) + + @classmethod + def new_txPr(cls): + """Return a `c:txPr` element tree. + + Suitable for use in a chart object like data labels or tick labels. + """ + xml = ( + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "\n" + ) % nsdecls("c", "a") + txPr = parse_xml(xml) + return txPr + + def unclear_content(self): + """Ensure p:txBody has at least one a:p child. + + Intuitively, reverse a ".clear_content()" operation to minimum conformance with spec + (single empty paragraph). + """ + if len(self.p_lst) > 0: + return + self.add_p() + + @classmethod + def _a_txBody_tmpl(cls): + return "\n" " \n" " \n" "\n" % (nsdecls("a")) + + @classmethod + def _p_txBody_tmpl(cls): + return ( + "\n" " \n" " \n" "\n" % (nsdecls("p", "a")) + ) + + @classmethod + def _txBody_tmpl(cls): + return ( + "\n" + " \n" + " \n" + " \n" + "\n" % (nsdecls("a", "p")) + ) + + +class CT_TextBodyProperties(BaseOxmlElement): + """`a:bodyPr` custom element class.""" + + _add_noAutofit: Callable[[], BaseOxmlElement] + _add_normAutofit: Callable[[], CT_TextNormalAutofit] + _add_spAutoFit: Callable[[], BaseOxmlElement] + _remove_eg_textAutoFit: Callable[[], None] + + noAutofit: BaseOxmlElement | None + normAutofit: CT_TextNormalAutofit | None + spAutoFit: BaseOxmlElement | None + + eg_textAutoFit = ZeroOrOneChoice( + (Choice("a:noAutofit"), Choice("a:normAutofit"), Choice("a:spAutoFit")), + successors=("a:scene3d", "a:sp3d", "a:flatTx", "a:extLst"), + ) + lIns: Length = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "lIns", ST_Coordinate32, default=Emu(91440) + ) + tIns: Length = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "tIns", ST_Coordinate32, default=Emu(45720) + ) + rIns: Length = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "rIns", ST_Coordinate32, default=Emu(91440) + ) + bIns: Length = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "bIns", ST_Coordinate32, default=Emu(45720) + ) + anchor: MSO_VERTICAL_ANCHOR | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "anchor", MSO_VERTICAL_ANCHOR + ) + wrap: str | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "wrap", ST_TextWrappingType + ) + + @property + def autofit(self): + """The autofit setting for the text frame, a member of the `MSO_AUTO_SIZE` enumeration.""" + if self.noAutofit is not None: + return MSO_AUTO_SIZE.NONE + if self.normAutofit is not None: + return MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE + if self.spAutoFit is not None: + return MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT + return None + + @autofit.setter + def autofit(self, value: MSO_AUTO_SIZE | None): + if value is not None and value not in MSO_AUTO_SIZE: + raise ValueError( + f"only None or a member of the MSO_AUTO_SIZE enumeration can be assigned to" + f" CT_TextBodyProperties.autofit, got {value}" + ) + self._remove_eg_textAutoFit() + if value == MSO_AUTO_SIZE.NONE: + self._add_noAutofit() + elif value == MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE: + self._add_normAutofit() + elif value == MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT: + self._add_spAutoFit() + + +class CT_TextCharacterProperties(BaseOxmlElement): + """Custom element class for `a:rPr`, `a:defRPr`, and `a:endParaRPr`. + + 'rPr' is short for 'run properties', and it corresponds to the |Font| proxy class. + """ + + get_or_add_hlinkClick: Callable[[], CT_Hyperlink] + get_or_add_latin: Callable[[], CT_TextFont] + _remove_latin: Callable[[], None] + _remove_hlinkClick: Callable[[], None] + + eg_fillProperties = ZeroOrOneChoice( + ( + Choice("a:noFill"), + Choice("a:solidFill"), + Choice("a:gradFill"), + Choice("a:blipFill"), + Choice("a:pattFill"), + Choice("a:grpFill"), + ), + successors=( + "a:effectLst", + "a:effectDag", + "a:highlight", + "a:uLnTx", + "a:uLn", + "a:uFillTx", + "a:uFill", + "a:latin", + "a:ea", + "a:cs", + "a:sym", + "a:hlinkClick", + "a:hlinkMouseOver", + "a:rtl", + "a:extLst", + ), + ) + latin: CT_TextFont | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:latin", + successors=( + "a:ea", + "a:cs", + "a:sym", + "a:hlinkClick", + "a:hlinkMouseOver", + "a:rtl", + "a:extLst", + ), + ) + hlinkClick: CT_Hyperlink | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:hlinkClick", successors=("a:hlinkMouseOver", "a:rtl", "a:extLst") + ) + + lang: MSO_LANGUAGE_ID | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "lang", MSO_LANGUAGE_ID + ) + sz: int | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "sz", ST_TextFontSize + ) + b: bool | None = OptionalAttribute("b", XsdBoolean) # pyright: ignore[reportAssignmentType] + i: bool | None = OptionalAttribute("i", XsdBoolean) # pyright: ignore[reportAssignmentType] + u: MSO_TEXT_UNDERLINE_TYPE | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "u", MSO_TEXT_UNDERLINE_TYPE + ) + + def _new_gradFill(self): + return CT_GradientFillProperties.new_gradFill() + + def add_hlinkClick(self, rId: str) -> CT_Hyperlink: + """Add an `a:hlinkClick` child element with r:id attribute set to `rId`.""" + hlinkClick = self.get_or_add_hlinkClick() + hlinkClick.rId = rId + return hlinkClick + + +class CT_TextField(BaseOxmlElement): + """`a:fld` field element, for either a slide number or date field.""" + + get_or_add_rPr: Callable[[], CT_TextCharacterProperties] + + rPr: CT_TextCharacterProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:rPr", successors=("a:pPr", "a:t") + ) + t: BaseOxmlElement | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:t", successors=() + ) + + @property + def text(self) -> str: # pyright: ignore[reportIncompatibleMethodOverride] + """The text of the `a:t` child element.""" + t = self.t + if t is None: + return "" + return t.text or "" + + +class CT_TextFont(BaseOxmlElement): + """Custom element class for `a:latin`, `a:ea`, `a:cs`, and `a:sym`. + + These occur as child elements of CT_TextCharacterProperties, e.g. `a:rPr`. + """ + + typeface: str = RequiredAttribute( # pyright: ignore[reportAssignmentType] + "typeface", ST_TextTypeface + ) + + +class CT_TextLineBreak(BaseOxmlElement): + """`a:br` line break element""" + + get_or_add_rPr: Callable[[], CT_TextCharacterProperties] + + rPr = ZeroOrOne("a:rPr", successors=()) + + @property + def text(self): # pyright: ignore[reportIncompatibleMethodOverride] + """Unconditionally a single vertical-tab character. + + A line break element can contain no text other than the implicit line feed it + represents. + """ + return "\v" + + +class CT_TextNormalAutofit(BaseOxmlElement): + """`a:normAutofit` element specifying fit text to shape font reduction, etc.""" + + fontScale = OptionalAttribute( + "fontScale", ST_TextFontScalePercentOrPercentString, default=100.0 + ) + + +class CT_TextParagraph(BaseOxmlElement): + """`a:p` custom element class""" + + get_or_add_endParaRPr: Callable[[], CT_TextCharacterProperties] + get_or_add_pPr: Callable[[], CT_TextParagraphProperties] + r_lst: list[CT_RegularTextRun] + _add_br: Callable[[], CT_TextLineBreak] + _add_r: Callable[[], CT_RegularTextRun] + + pPr: CT_TextParagraphProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:pPr", successors=("a:r", "a:br", "a:fld", "a:endParaRPr") + ) + r = ZeroOrMore("a:r", successors=("a:endParaRPr",)) + br = ZeroOrMore("a:br", successors=("a:endParaRPr",)) + endParaRPr: CT_TextCharacterProperties | None = ZeroOrOne( + "a:endParaRPr", successors=() + ) # pyright: ignore[reportAssignmentType] + + def add_br(self) -> CT_TextLineBreak: + """Return a newly appended `a:br` element.""" + return self._add_br() + + def add_r(self, text: str | None = None) -> CT_RegularTextRun: + """Return a newly appended `a:r` element.""" + r = self._add_r() + if text: + r.text = text + return r + + def append_text(self, text: str): + """Append `a:r` and `a:br` elements to `p` based on `text`. + + Any `\n` or `\v` (vertical-tab) characters in `text` delimit `a:r` (run) elements and + themselves are translated to `a:br` (line-break) elements. The vertical-tab character + appears in clipboard text from PowerPoint at "soft" line-breaks (new-line, but not new + paragraph). + """ + for idx, r_str in enumerate(re.split("\n|\v", text)): + # ---breaks are only added _between_ items, not at start--- + if idx > 0: + self.add_br() + # ---runs that would be empty are not added--- + if r_str: + self.add_r(r_str) + + @property + def content_children(self) -> tuple[CT_RegularTextRun | CT_TextLineBreak | CT_TextField, ...]: + """Sequence containing text-container child elements of this `a:p` element. + + These include `a:r`, `a:br`, and `a:fld`. + """ + return tuple( + e for e in self if isinstance(e, (CT_RegularTextRun, CT_TextLineBreak, CT_TextField)) + ) + + @property + def text(self) -> str: # pyright: ignore[reportIncompatibleMethodOverride] + """str text contained in this paragraph.""" + # ---note this shadows the lxml _Element.text--- + return "".join([child.text for child in self.content_children]) + + def _new_r(self): + r_xml = "" % nsdecls("a") + return parse_xml(r_xml) + + +class CT_TextParagraphProperties(BaseOxmlElement): + """`a:pPr` custom element class.""" + + get_or_add_defRPr: Callable[[], CT_TextCharacterProperties] + _add_lnSpc: Callable[[], CT_TextSpacing] + _add_spcAft: Callable[[], CT_TextSpacing] + _add_spcBef: Callable[[], CT_TextSpacing] + _remove_lnSpc: Callable[[], None] + _remove_spcAft: Callable[[], None] + _remove_spcBef: Callable[[], None] + + _tag_seq = ( + "a:lnSpc", + "a:spcBef", + "a:spcAft", + "a:buClrTx", + "a:buClr", + "a:buSzTx", + "a:buSzPct", + "a:buSzPts", + "a:buFontTx", + "a:buFont", + "a:buNone", + "a:buAutoNum", + "a:buChar", + "a:buBlip", + "a:tabLst", + "a:defRPr", + "a:extLst", + ) + lnSpc: CT_TextSpacing | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:lnSpc", successors=_tag_seq[1:] + ) + spcBef: CT_TextSpacing | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:spcBef", successors=_tag_seq[2:] + ) + spcAft: CT_TextSpacing | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:spcAft", successors=_tag_seq[3:] + ) + defRPr: CT_TextCharacterProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:defRPr", successors=_tag_seq[16:] + ) + lvl: int = OptionalAttribute( # pyright: ignore[reportAssignmentType] + "lvl", ST_TextIndentLevelType, default=0 + ) + algn: PP_PARAGRAPH_ALIGNMENT | None = OptionalAttribute( + "algn", PP_PARAGRAPH_ALIGNMENT + ) # pyright: ignore[reportAssignmentType] + del _tag_seq + + @property + def line_spacing(self) -> float | Length | None: + """The spacing between baselines of successive lines in this paragraph. + + A float value indicates a number of lines. A |Length| value indicates a fixed spacing. + Value is contained in `./a:lnSpc/a:spcPts/@val` or `./a:lnSpc/a:spcPct/@val`. Value is + |None| if no element is present. + """ + lnSpc = self.lnSpc + if lnSpc is None: + return None + if lnSpc.spcPts is not None: + return lnSpc.spcPts.val + return cast(CT_TextSpacingPercent, lnSpc.spcPct).val + + @line_spacing.setter + def line_spacing(self, value: float | Length | None): + self._remove_lnSpc() + if value is None: + return + if isinstance(value, Length): + self._add_lnSpc().set_spcPts(value) + else: + self._add_lnSpc().set_spcPct(value) + + @property + def space_after(self) -> Length | None: + """The EMU equivalent of the centipoints value in `./a:spcAft/a:spcPts/@val`.""" + spcAft = self.spcAft + if spcAft is None: + return None + spcPts = spcAft.spcPts + if spcPts is None: + return None + return spcPts.val + + @space_after.setter + def space_after(self, value: Length | None): + self._remove_spcAft() + if value is not None: + self._add_spcAft().set_spcPts(value) + + @property + def space_before(self): + """The EMU equivalent of the centipoints value in `./a:spcBef/a:spcPts/@val`.""" + spcBef = self.spcBef + if spcBef is None: + return None + spcPts = spcBef.spcPts + if spcPts is None: + return None + return spcPts.val + + @space_before.setter + def space_before(self, value: Length | None): + self._remove_spcBef() + if value is not None: + self._add_spcBef().set_spcPts(value) + + +class CT_TextSpacing(BaseOxmlElement): + """Used for `a:lnSpc`, `a:spcBef`, and `a:spcAft` elements.""" + + get_or_add_spcPct: Callable[[], CT_TextSpacingPercent] + get_or_add_spcPts: Callable[[], CT_TextSpacingPoint] + _remove_spcPct: Callable[[], None] + _remove_spcPts: Callable[[], None] + + # this should actually be a OneAndOnlyOneChoice, but that's not + # implemented yet. + spcPct: CT_TextSpacingPercent | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:spcPct" + ) + spcPts: CT_TextSpacingPoint | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "a:spcPts" + ) + + def set_spcPct(self, value: float): + """Set spacing to `value` lines, e.g. 1.75 lines. + + A ./a:spcPts child is removed if present. + """ + self._remove_spcPts() + spcPct = self.get_or_add_spcPct() + spcPct.val = value + + def set_spcPts(self, value: Length): + """Set spacing to `value` points. A ./a:spcPct child is removed if present.""" + self._remove_spcPct() + spcPts = self.get_or_add_spcPts() + spcPts.val = value + + +class CT_TextSpacingPercent(BaseOxmlElement): + """`a:spcPct` element, specifying spacing in thousandths of a percent in its `val` attribute.""" + + val: float = RequiredAttribute( # pyright: ignore[reportAssignmentType] + "val", ST_TextSpacingPercentOrPercentString + ) + + +class CT_TextSpacingPoint(BaseOxmlElement): + """`a:spcPts` element, specifying spacing in centipoints in its `val` attribute.""" + + val: Length = RequiredAttribute( # pyright: ignore[reportAssignmentType] + "val", ST_TextSpacingPoint + ) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/theme.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/theme.py new file mode 100644 index 0000000000000000000000000000000000000000..19ac8dea63b5cf4fe6cfa4c294b1c6e229089e54 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/theme.py @@ -0,0 +1,29 @@ +"""lxml custom element classes for theme-related XML elements.""" + +from __future__ import annotations + +from . import parse_from_template +from .xmlchemy import BaseOxmlElement + + +class CT_OfficeStyleSheet(BaseOxmlElement): + """ + ```` element, root of a theme part + """ + + _tag_seq = ( + "a:themeElements", + "a:objectDefaults", + "a:extraClrSchemeLst", + "a:custClrLst", + "a:extLst", + ) + del _tag_seq + + @classmethod + def new_default(cls): + """ + Return a new ```` element containing default settings + suitable for use with a notes master. + """ + return parse_from_template("theme") diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/xmlchemy.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/xmlchemy.py new file mode 100644 index 0000000000000000000000000000000000000000..41fb2e17102dad3af81d3bf74710745c1a0537cc --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/xmlchemy.py @@ -0,0 +1,717 @@ +"""Base and meta classes enabling declarative definition of custom element classes.""" + +from __future__ import annotations + +import re +from typing import Any, Callable, Iterable, Protocol, Sequence, Type, cast + +from lxml import etree +from lxml.etree import ElementBase, _Element # pyright: ignore[reportPrivateUsage] + +from pptx.exc import InvalidXmlError +from pptx.oxml import oxml_parser +from pptx.oxml.ns import NamespacePrefixedTag, _nsmap, qn # pyright: ignore[reportPrivateUsage] +from pptx.util import lazyproperty + + +class AttributeType(Protocol): + """Interface for an object that can act as an attribute type. + + An attribute-type specifies how values are transformed to and from the XML "string" value of the + attribute. + """ + + @classmethod + def from_xml(cls, xml_value: str) -> Any: + """Transform an attribute value to a Python value.""" + ... + + @classmethod + def to_xml(cls, value: Any) -> str: + """Transform a Python value to a str value suitable to this XML attribute.""" + ... + + +def OxmlElement(nsptag_str: str, nsmap: dict[str, str] | None = None) -> BaseOxmlElement: + """Return a "loose" lxml element having the tag specified by `nsptag_str`. + + `nsptag_str` must contain the standard namespace prefix, e.g. 'a:tbl'. The resulting element is + an instance of the custom element class for this tag name if one is defined. + """ + nsptag = NamespacePrefixedTag(nsptag_str) + nsmap = nsmap if nsmap is not None else nsptag.nsmap + return oxml_parser.makeelement(nsptag.clark_name, nsmap=nsmap) + + +def serialize_for_reading(element: ElementBase): + """ + Serialize *element* to human-readable XML suitable for tests. No XML + declaration. + """ + xml = etree.tostring(element, encoding="unicode", pretty_print=True) + return XmlString(xml) + + +class XmlString(str): + """Provides string comparison override suitable for serialized XML; useful for tests.""" + + # ' text' + # | | || | + # +----------+------------------------------------------++-----------+ + # front attrs | text + # close + + _xml_elm_line_patt = re.compile(r"( *)([^<]*)?") + + def __eq__(self, other: object) -> bool: + if not isinstance(other, str): + return False + lines = self.splitlines() + lines_other = other.splitlines() + if len(lines) != len(lines_other): + return False + for line, line_other in zip(lines, lines_other): + if not self._eq_elm_strs(line, line_other): + return False + return True + + def __ne__(self, other: object) -> bool: + return not self.__eq__(other) + + def _attr_seq(self, attrs: str) -> list[str]: + """Return a sequence of attribute strings parsed from *attrs*. + + Each attribute string is stripped of whitespace on both ends. + """ + attrs = attrs.strip() + attr_lst = attrs.split() + return sorted(attr_lst) + + def _eq_elm_strs(self, line: str, line_2: str) -> bool: + """True if the element in `line_2` is XML-equivalent to the element in `line`. + + In particular, the order of attributes in XML is not significant. + """ + front, attrs, close, text = self._parse_line(line) + front_2, attrs_2, close_2, text_2 = self._parse_line(line_2) + if front != front_2: + return False + if self._attr_seq(attrs) != self._attr_seq(attrs_2): + return False + if close != close_2: + return False + if text != text_2: + return False + return True + + def _parse_line(self, line: str): + """Return front, attrs, close, text 4-tuple result of parsing XML element string `line`.""" + match = self._xml_elm_line_patt.match(line) + if match is None: + raise ValueError("`line` does not match pattern for an XML element") + front, attrs, close, text = [match.group(n) for n in range(1, 5)] + return front, attrs, close, text + + +class MetaOxmlElement(type): + """Metaclass for BaseOxmlElement.""" + + def __init__(cls, clsname: str, bases: tuple[type, ...], clsdict: dict[str, Any]): + dispatchable = ( + OneAndOnlyOne, + OneOrMore, + OptionalAttribute, + RequiredAttribute, + ZeroOrMore, + ZeroOrOne, + ZeroOrOneChoice, + ) + for key, value in clsdict.items(): + if isinstance(value, dispatchable): + value.populate_class_members(cls, key) + + +class BaseAttribute: + """Base class for OptionalAttribute and RequiredAttribute, providing common methods.""" + + def __init__(self, attr_name: str, simple_type: type[AttributeType]): + self._attr_name = attr_name + self._simple_type = simple_type + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """ + Add the appropriate methods to *element_cls*. + """ + self._element_cls = element_cls + self._prop_name = prop_name + + self._add_attr_property() + + def _add_attr_property(self): + """Add a read/write `{prop_name}` property to the element class. + + The property returns the interpreted value of this attribute on access and changes the + attribute value to its ST_* counterpart on assignment. + """ + property_ = property(self._getter, self._setter, None) + # assign unconditionally to overwrite element name definition + setattr(self._element_cls, self._prop_name, property_) + + @property + def _clark_name(self): + if ":" in self._attr_name: + return qn(self._attr_name) + return self._attr_name + + @property + def _getter(self) -> Callable[[BaseOxmlElement], Any]: + """Callable suitable for the "get" side of the attribute property descriptor.""" + raise NotImplementedError("must be implemented by each subclass") + + @property + def _setter(self) -> Callable[[BaseOxmlElement, Any], None]: + """Callable suitable for the "set" side of the attribute property descriptor.""" + raise NotImplementedError("must be implemented by each subclass") + + +class OptionalAttribute(BaseAttribute): + """Defines an optional attribute on a custom element class. + + An optional attribute returns a default value when not present for reading. When assigned + |None|, the attribute is removed. + """ + + def __init__(self, attr_name: str, simple_type: type[AttributeType], default: Any = None): + super(OptionalAttribute, self).__init__(attr_name, simple_type) + self._default = default + + @property + def _docstring(self): + """ + Return the string to use as the ``__doc__`` attribute of the property + for this attribute. + """ + return ( + "%s type-converted value of ``%s`` attribute, or |None| (or spec" + "ified default value) if not present. Assigning the default valu" + "e causes the attribute to be removed from the element." + % (self._simple_type.__name__, self._attr_name) + ) + + @property + def _getter(self) -> Callable[[BaseOxmlElement], Any]: + """Callable suitable for the "get" side of the attribute property descriptor.""" + + def get_attr_value(obj: BaseOxmlElement) -> Any: + attr_str_value = obj.get(self._clark_name) + if attr_str_value is None: + return self._default + return self._simple_type.from_xml(attr_str_value) + + get_attr_value.__doc__ = self._docstring + return get_attr_value + + @property + def _setter(self) -> Callable[[BaseOxmlElement, Any], None]: + """Callable suitable for the "set" side of the attribute property descriptor.""" + + def set_attr_value(obj: BaseOxmlElement, value: Any) -> None: + # -- when an XML attribute has a default value, setting it to that default removes the + # -- attribute from the element (when it is present) + if value == self._default: + if self._clark_name in obj.attrib: + del obj.attrib[self._clark_name] + return + str_value = self._simple_type.to_xml(value) + obj.set(self._clark_name, str_value) + + return set_attr_value + + +class RequiredAttribute(BaseAttribute): + """Defines a required attribute on a custom element class. + + A required attribute is assumed to be present for reading, so does not have a default value; + its actual value is always used. If missing on read, an |InvalidXmlError| is raised. It also + does not remove the attribute if |None| is assigned. Assigning |None| raises |TypeError| or + |ValueError|, depending on the simple type of the attribute. + """ + + @property + def _getter(self) -> Callable[[BaseOxmlElement], Any]: + """Callable suitable for the "get" side of the attribute property descriptor.""" + + def get_attr_value(obj: BaseOxmlElement) -> Any: + attr_str_value = obj.get(self._clark_name) + if attr_str_value is None: + raise InvalidXmlError( + "required '%s' attribute not present on element %s" % (self._attr_name, obj.tag) + ) + return self._simple_type.from_xml(attr_str_value) + + get_attr_value.__doc__ = self._docstring + return get_attr_value + + @property + def _docstring(self): + """ + Return the string to use as the ``__doc__`` attribute of the property + for this attribute. + """ + return "%s type-converted value of ``%s`` attribute." % ( + self._simple_type.__name__, + self._attr_name, + ) + + @property + def _setter(self) -> Callable[[BaseOxmlElement, Any], None]: + """Callable suitable for the "set" side of the attribute property descriptor.""" + + def set_attr_value(obj: BaseOxmlElement, value: Any) -> None: + str_value = self._simple_type.to_xml(value) + obj.set(self._clark_name, str_value) + + return set_attr_value + + +class _BaseChildElement: + """Base class for the child element classes corresponding to varying cardinalities. + + Subclasses include ZeroOrOne and ZeroOrMore. + """ + + def __init__(self, nsptagname: str, successors: Sequence[str] = ()): + super(_BaseChildElement, self).__init__() + self._nsptagname = nsptagname + self._successors = successors + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """Baseline behavior for adding the appropriate methods to `element_cls`.""" + self._element_cls = element_cls + self._prop_name = prop_name + + def _add_adder(self): + """Add an ``_add_x()`` method to the element class for this child element.""" + + def _add_child(obj: BaseOxmlElement, **attrs: Any): + new_method = getattr(obj, self._new_method_name) + child = new_method() + for key, value in attrs.items(): + setattr(child, key, value) + insert_method = getattr(obj, self._insert_method_name) + insert_method(child) + return child + + _add_child.__doc__ = ( + "Add a new ``<%s>`` child element unconditionally, inserted in t" + "he correct sequence." % self._nsptagname + ) + self._add_to_class(self._add_method_name, _add_child) + + def _add_creator(self): + """Add a `_new_{prop_name}()` method to the element class. + + This method creates a new, empty element of the correct type, having no attributes. + """ + creator = self._creator + creator.__doc__ = ( + 'Return a "loose", newly created ``<%s>`` element having no attri' + "butes, text, or children." % self._nsptagname + ) + self._add_to_class(self._new_method_name, creator) + + def _add_getter(self): + """Add a read-only `{prop_name}` property to the parent element class. + + The property locates and returns this child element or `None` if not present. + """ + property_ = property(self._getter, None, None) + # assign unconditionally to overwrite element name definition + setattr(self._element_cls, self._prop_name, property_) + + def _add_inserter(self): + """Add an ``_insert_x()`` method to the element class for this child element.""" + + def _insert_child(obj: BaseOxmlElement, child: BaseOxmlElement): + obj.insert_element_before(child, *self._successors) + return child + + _insert_child.__doc__ = ( + "Return the passed ``<%s>`` element after inserting it as a chil" + "d in the correct sequence." % self._nsptagname + ) + self._add_to_class(self._insert_method_name, _insert_child) + + def _add_list_getter(self): + """ + Add a read-only ``{prop_name}_lst`` property to the element class to + retrieve a list of child elements matching this type. + """ + prop_name = f"{self._prop_name}_lst" + property_ = property(self._list_getter, None, None) + setattr(self._element_cls, prop_name, property_) + + @lazyproperty + def _add_method_name(self): + return "_add_%s" % self._prop_name + + def _add_to_class(self, name: str, method: Callable[..., Any]): + """Add `method` to the target class as `name`, unless `name` is already defined there.""" + if hasattr(self._element_cls, name): + return + setattr(self._element_cls, name, method) + + @property + def _creator(self) -> Callable[[BaseOxmlElement], BaseOxmlElement]: + """Callable that creates a new, empty element of the child type, having no attributes.""" + + def new_child_element(obj: BaseOxmlElement): + return OxmlElement(self._nsptagname) + + return new_child_element + + @property + def _getter(self) -> Callable[[BaseOxmlElement], BaseOxmlElement | None]: + """Callable suitable for the "get" side of the property descriptor. + + This default getter returns the child element with matching tag name or |None| if not + present. + """ + + def get_child_element(obj: BaseOxmlElement) -> BaseOxmlElement | None: + return obj.find(qn(self._nsptagname)) + + get_child_element.__doc__ = ( + "``<%s>`` child element or |None| if not present." % self._nsptagname + ) + return get_child_element + + @lazyproperty + def _insert_method_name(self): + return "_insert_%s" % self._prop_name + + @property + def _list_getter(self) -> Callable[[BaseOxmlElement], list[BaseOxmlElement]]: + """Callable suitable for the "get" side of a list property descriptor.""" + + def get_child_element_list(obj: BaseOxmlElement) -> list[BaseOxmlElement]: + return cast("list[BaseOxmlElement]", obj.findall(qn(self._nsptagname))) + + get_child_element_list.__doc__ = ( + "A list containing each of the ``<%s>`` child elements, in the o" + "rder they appear." % self._nsptagname + ) + return get_child_element_list + + @lazyproperty + def _remove_method_name(self): + return "_remove_%s" % self._prop_name + + @lazyproperty + def _new_method_name(self): + return "_new_%s" % self._prop_name + + +class Choice(_BaseChildElement): + """Defines a child element belonging to a group, only one of which may appear as a child.""" + + @property + def nsptagname(self): + return self._nsptagname + + def populate_class_members( # pyright: ignore[reportIncompatibleMethodOverride] + self, element_cls: Type[BaseOxmlElement], group_prop_name: str, successors: Sequence[str] + ): + """Add the appropriate methods to `element_cls`.""" + self._element_cls = element_cls + self._group_prop_name = group_prop_name + self._successors = successors + + self._add_getter() + self._add_creator() + self._add_inserter() + self._add_adder() + self._add_get_or_change_to_method() + + def _add_get_or_change_to_method(self) -> None: + """Add a `get_or_change_to_x()` method to the element class for this child element.""" + + def get_or_change_to_child(obj: BaseOxmlElement): + child = getattr(obj, self._prop_name) + if child is not None: + return child + remove_group_method = getattr(obj, self._remove_group_method_name) + remove_group_method() + add_method = getattr(obj, self._add_method_name) + child = add_method() + return child + + get_or_change_to_child.__doc__ = ( + "Return the ``<%s>`` child, replacing any other group element if" " found." + ) % self._nsptagname + self._add_to_class(self._get_or_change_to_method_name, get_or_change_to_child) + + @property + def _prop_name(self): + """ + Calculate property name from tag name, e.g. a:schemeClr -> schemeClr. + """ + if ":" in self._nsptagname: + start = self._nsptagname.index(":") + 1 + else: + start = 0 + return self._nsptagname[start:] + + @lazyproperty + def _get_or_change_to_method_name(self): + return "get_or_change_to_%s" % self._prop_name + + @lazyproperty + def _remove_group_method_name(self): + return "_remove_%s" % self._group_prop_name + + +class OneAndOnlyOne(_BaseChildElement): + """Defines a required child element for MetaOxmlElement.""" + + def __init__(self, nsptagname: str): + super(OneAndOnlyOne, self).__init__(nsptagname, ()) + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """ + Add the appropriate methods to *element_cls*. + """ + super(OneAndOnlyOne, self).populate_class_members(element_cls, prop_name) + self._add_getter() + + @property + def _getter(self) -> Callable[[BaseOxmlElement], BaseOxmlElement]: + """Callable suitable for the "get" side of the property descriptor.""" + + def get_child_element(obj: BaseOxmlElement) -> BaseOxmlElement: + child = obj.find(qn(self._nsptagname)) + if child is None: + raise InvalidXmlError( + "required ``<%s>`` child element not present" % self._nsptagname + ) + return child + + get_child_element.__doc__ = "Required ``<%s>`` child element." % self._nsptagname + return get_child_element + + +class OneOrMore(_BaseChildElement): + """Defines a repeating child element for MetaOxmlElement that must appear at least once.""" + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """Add the appropriate methods to *element_cls*.""" + super(OneOrMore, self).populate_class_members(element_cls, prop_name) + self._add_list_getter() + self._add_creator() + self._add_inserter() + self._add_adder() + self._add_public_adder() + delattr(element_cls, prop_name) + + def _add_public_adder(self) -> None: + """Add a public `.add_x()` method to the parent element class.""" + + def add_child(obj: BaseOxmlElement) -> BaseOxmlElement: + private_add_method = getattr(obj, self._add_method_name) + child = private_add_method() + return child + + add_child.__doc__ = ( + "Add a new ``<%s>`` child element unconditionally, inserted in t" + "he correct sequence." % self._nsptagname + ) + self._add_to_class(self._public_add_method_name, add_child) + + @lazyproperty + def _public_add_method_name(self): + """ + add_childElement() is public API for a repeating element, allowing + new elements to be added to the sequence. May be overridden to + provide a friendlier API to clients having domain appropriate + parameter names for required attributes. + """ + return "add_%s" % self._prop_name + + +class ZeroOrMore(_BaseChildElement): + """ + Defines an optional repeating child element for MetaOxmlElement. + """ + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """ + Add the appropriate methods to *element_cls*. + """ + super(ZeroOrMore, self).populate_class_members(element_cls, prop_name) + self._add_list_getter() + self._add_creator() + self._add_inserter() + self._add_adder() + delattr(element_cls, prop_name) + + +class ZeroOrOne(_BaseChildElement): + """Defines an optional child element for MetaOxmlElement.""" + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """Add the appropriate methods to `element_cls`.""" + super(ZeroOrOne, self).populate_class_members(element_cls, prop_name) + self._add_getter() + self._add_creator() + self._add_inserter() + self._add_adder() + self._add_get_or_adder() + self._add_remover() + + def _add_get_or_adder(self): + """Add a `.get_or_add_x()` method to the element class for this child element.""" + + def get_or_add_child(obj: BaseOxmlElement) -> BaseOxmlElement: + child = getattr(obj, self._prop_name) + if child is None: + add_method = getattr(obj, self._add_method_name) + child = add_method() + return child + + get_or_add_child.__doc__ = ( + "Return the ``<%s>`` child element, newly added if not present." + ) % self._nsptagname + self._add_to_class(self._get_or_add_method_name, get_or_add_child) + + def _add_remover(self): + """Add a `._remove_x()` method to the element class for this child element.""" + + def _remove_child(obj: BaseOxmlElement) -> None: + obj.remove_all(self._nsptagname) + + _remove_child.__doc__ = f"Remove all `{self._nsptagname}` child elements." + self._add_to_class(self._remove_method_name, _remove_child) + + @lazyproperty + def _get_or_add_method_name(self): + return "get_or_add_%s" % self._prop_name + + +class ZeroOrOneChoice(_BaseChildElement): + """An `EG_*` element group where at most one of its members may appear as a child.""" + + def __init__(self, choices: Iterable[Choice], successors: Iterable[str] = ()): + self._choices = tuple(choices) + self._successors = tuple(successors) + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """Add the appropriate methods to `element_cls`.""" + super(ZeroOrOneChoice, self).populate_class_members(element_cls, prop_name) + self._add_choice_getter() + for choice in self._choices: + choice.populate_class_members(element_cls, self._prop_name, self._successors) + self._add_group_remover() + + def _add_choice_getter(self): + """Add a read-only `.{prop_name}` property to the element class. + + The property returns the present member of this group, or |None| if none are present. + """ + property_ = property(self._choice_getter, None, None) + # assign unconditionally to overwrite element name definition + setattr(self._element_cls, self._prop_name, property_) + + def _add_group_remover(self): + """Add a `._remove_eg_x()` method to the element class for this choice group.""" + + def _remove_choice_group(obj: BaseOxmlElement) -> None: + for tagname in self._member_nsptagnames: + obj.remove_all(tagname) + + _remove_choice_group.__doc__ = "Remove the current choice group child element if present." + self._add_to_class(self._remove_choice_group_method_name, _remove_choice_group) + + @property + def _choice_getter(self): + """ + Return a function object suitable for the "get" side of the property + descriptor. + """ + + def get_group_member_element(obj: BaseOxmlElement) -> BaseOxmlElement | None: + return cast( + "BaseOxmlElement | None", obj.first_child_found_in(*self._member_nsptagnames) + ) + + get_group_member_element.__doc__ = ( + "Return the child element belonging to this element group, or " + "|None| if no member child is present." + ) + return get_group_member_element + + @lazyproperty + def _member_nsptagnames(self) -> list[str]: + """Sequence of namespace-prefixed tagnames, one for each member element of choice group.""" + return [choice.nsptagname for choice in self._choices] + + @lazyproperty + def _remove_choice_group_method_name(self): + """Function-name for choice remover.""" + return f"_remove_{self._prop_name}" + + +# -- lxml typing isn't quite right here, just ignore this error on _Element -- +class BaseOxmlElement(etree.ElementBase, metaclass=MetaOxmlElement): + """Effective base class for all custom element classes. + + Adds standardized behavior to all classes in one place. + """ + + def __repr__(self): + return "<%s '<%s>' at 0x%0x>" % ( + self.__class__.__name__, + self._nsptag, + id(self), + ) + + def first_child_found_in(self, *tagnames: str) -> _Element | None: + """First child with tag in `tagnames`, or None if not found.""" + for tagname in tagnames: + child = self.find(qn(tagname)) + if child is not None: + return child + return None + + def insert_element_before(self, elm: ElementBase, *tagnames: str): + successor = self.first_child_found_in(*tagnames) + if successor is not None: + successor.addprevious(elm) + else: + self.append(elm) + return elm + + def remove_all(self, *tagnames: str) -> None: + """Remove child elements with tagname (e.g. "a:p") in `tagnames`.""" + for tagname in tagnames: + matching = self.findall(qn(tagname)) + for child in matching: + self.remove(child) + + @property + def xml(self) -> str: + """XML string for this element, suitable for testing purposes. + + Pretty printed for readability and without an XML declaration at the top. + """ + return serialize_for_reading(self) + + def xpath(self, xpath_str: str) -> Any: # pyright: ignore[reportIncompatibleMethodOverride] + """Override of `lxml` _Element.xpath() method. + + Provides standard Open XML namespace mapping (`nsmap`) in centralized location. + """ + return super().xpath(xpath_str, namespaces=_nsmap) + + @property + def _nsptag(self) -> str: + return NamespacePrefixedTag.from_clark_name(self.tag) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/package.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/package.py new file mode 100644 index 0000000000000000000000000000000000000000..79703cd6c04df62af2eecc8c75e82148f7665bd9 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/package.py @@ -0,0 +1,222 @@ +"""Overall .pptx package.""" + +from __future__ import annotations + +from typing import IO, Iterator + +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.package import OpcPackage +from pptx.opc.packuri import PackURI +from pptx.parts.coreprops import CorePropertiesPart +from pptx.parts.image import Image, ImagePart +from pptx.parts.media import MediaPart +from pptx.util import lazyproperty + + +class Package(OpcPackage): + """An overall .pptx package.""" + + @lazyproperty + def core_properties(self) -> CorePropertiesPart: + """Instance of |CoreProperties| holding read/write Dublin Core doc properties. + + Creates a default core properties part if one is not present (not common). + """ + try: + return self.part_related_by(RT.CORE_PROPERTIES) + except KeyError: + core_props = CorePropertiesPart.default(self) + self.relate_to(core_props, RT.CORE_PROPERTIES) + return core_props + + def get_or_add_image_part(self, image_file: str | IO[bytes]): + """ + Return an |ImagePart| object containing the image in *image_file*. If + the image part already exists in this package, it is reused, + otherwise a new one is created. + """ + return self._image_parts.get_or_add_image_part(image_file) + + def get_or_add_media_part(self, media): + """Return a |MediaPart| object containing the media in *media*. + + If a media part for this media bytestream ("file") is already present + in this package, it is reused, otherwise a new one is created. + """ + return self._media_parts.get_or_add_media_part(media) + + def next_image_partname(self, ext: str) -> PackURI: + """Return a |PackURI| instance representing the next available image partname. + + Partname uses the next available sequence number. *ext* is used as the extention on the + returned partname. + """ + + def first_available_image_idx(): + image_idxs = sorted( + [ + part.partname.idx + for part in self.iter_parts() + if ( + part.partname.startswith("/ppt/media/image") + and part.partname.idx is not None + ) + ] + ) + for i, image_idx in enumerate(image_idxs): + idx = i + 1 + if idx < image_idx: + return idx + return len(image_idxs) + 1 + + idx = first_available_image_idx() + return PackURI("/ppt/media/image%d.%s" % (idx, ext)) + + def next_media_partname(self, ext): + """Return |PackURI| instance for next available media partname. + + Partname is first available, starting at sequence number 1. Empty + sequence numbers are reused. *ext* is used as the extension on the + returned partname. + """ + + def first_available_media_idx(): + media_idxs = sorted( + [ + part.partname.idx + for part in self.iter_parts() + if part.partname.startswith("/ppt/media/media") + ] + ) + for i, media_idx in enumerate(media_idxs): + idx = i + 1 + if idx < media_idx: + return idx + return len(media_idxs) + 1 + + idx = first_available_media_idx() + return PackURI("/ppt/media/media%d.%s" % (idx, ext)) + + @property + def presentation_part(self): + """ + Reference to the |Presentation| instance contained in this package. + """ + return self.main_document_part + + @lazyproperty + def _image_parts(self): + """ + |_ImageParts| object providing access to the image parts in this + package. + """ + return _ImageParts(self) + + @lazyproperty + def _media_parts(self): + """Return |_MediaParts| object for this package. + + The media parts object provides access to all the media parts in this + package. + """ + return _MediaParts(self) + + +class _ImageParts(object): + """Provides access to the image parts in a package.""" + + def __init__(self, package): + super(_ImageParts, self).__init__() + self._package = package + + def __iter__(self) -> Iterator[ImagePart]: + """Generate a reference to each |ImagePart| object in the package.""" + image_parts = [] + for rel in self._package.iter_rels(): + if rel.is_external: + continue + if rel.reltype != RT.IMAGE: + continue + image_part = rel.target_part + if image_part in image_parts: + continue + image_parts.append(image_part) + yield image_part + + def get_or_add_image_part(self, image_file: str | IO[bytes]) -> ImagePart: + """Return |ImagePart| object containing the image in `image_file`. + + `image_file` can be either a path to an image file or a file-like object + containing an image. If an image part containing this same image already exists, + that instance is returned, otherwise a new image part is created. + """ + image = Image.from_file(image_file) + image_part = self._find_by_sha1(image.sha1) + return image_part if image_part else ImagePart.new(self._package, image) + + def _find_by_sha1(self, sha1: str) -> ImagePart | None: + """ + Return an |ImagePart| object belonging to this package or |None| if + no matching image part is found. The image part is identified by the + SHA1 hash digest of the image binary it contains. + """ + for image_part in self: + # ---skip unknown/unsupported image types, like SVG--- + if not hasattr(image_part, "sha1"): + continue + if image_part.sha1 == sha1: + return image_part + return None + + +class _MediaParts(object): + """Provides access to the media parts in a package. + + Supports iteration and :meth:`get()` using the media object SHA1 hash as + its key. + """ + + def __init__(self, package): + super(_MediaParts, self).__init__() + self._package = package + + def __iter__(self): + """Generate a reference to each |MediaPart| object in the package.""" + # A media part can appear in more than one relationship (and commonly + # does in the case of video). Use media_parts to keep track of those + # that have been "yielded"; they can be skipped if they occur again. + media_parts = [] + for rel in self._package.iter_rels(): + if rel.is_external: + continue + if rel.reltype not in (RT.MEDIA, RT.VIDEO): + continue + media_part = rel.target_part + if media_part in media_parts: + continue + media_parts.append(media_part) + yield media_part + + def get_or_add_media_part(self, media): + """Return a |MediaPart| object containing the media in *media*. + + If this package already contains a media part for the same + bytestream, that instance is returned, otherwise a new media part is + created. + """ + media_part = self._find_by_sha1(media.sha1) + if media_part is None: + media_part = MediaPart.new(self._package, media) + return media_part + + def _find_by_sha1(self, sha1): + """Return |MediaPart| object having *sha1* hash or None if not found. + + All media parts belonging to this package are considered. A media + part is identified by the SHA1 hash digest of its bytestream + ("file"). + """ + for media_part in self: + if media_part.sha1 == sha1: + return media_part + return None diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/__init__.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/chart.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/chart.py new file mode 100644 index 0000000000000000000000000000000000000000..7208071b4311b92dc5bc4690d162edcb4c51a567 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/chart.py @@ -0,0 +1,95 @@ +"""Chart part objects, including Chart and Charts.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pptx.chart.chart import Chart +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.package import XmlPart +from pptx.parts.embeddedpackage import EmbeddedXlsxPart +from pptx.util import lazyproperty + +if TYPE_CHECKING: + from pptx.chart.data import ChartData + from pptx.enum.chart import XL_CHART_TYPE + from pptx.package import Package + + +class ChartPart(XmlPart): + """A chart part. + + Corresponds to parts having partnames matching ppt/charts/chart[1-9][0-9]*.xml + """ + + partname_template = "/ppt/charts/chart%d.xml" + + @classmethod + def new(cls, chart_type: XL_CHART_TYPE, chart_data: ChartData, package: Package): + """Return new |ChartPart| instance added to `package`. + + Returned chart-part contains a chart of `chart_type` depicting `chart_data`. + """ + chart_part = cls.load( + package.next_partname(cls.partname_template), + CT.DML_CHART, + package, + chart_data.xml_bytes(chart_type), + ) + chart_part.chart_workbook.update_from_xlsx_blob(chart_data.xlsx_blob) + return chart_part + + @lazyproperty + def chart(self): + """|Chart| object representing the chart in this part.""" + return Chart(self._element, self) + + @lazyproperty + def chart_workbook(self): + """ + The |ChartWorkbook| object providing access to the external chart + data in a linked or embedded Excel workbook. + """ + return ChartWorkbook(self._element, self) + + +class ChartWorkbook(object): + """Provides access to external chart data in a linked or embedded Excel workbook.""" + + def __init__(self, chartSpace, chart_part): + super(ChartWorkbook, self).__init__() + self._chartSpace = chartSpace + self._chart_part = chart_part + + def update_from_xlsx_blob(self, xlsx_blob): + """ + Replace the Excel spreadsheet in the related |EmbeddedXlsxPart| with + the Excel binary in *xlsx_blob*, adding a new |EmbeddedXlsxPart| if + there isn't one. + """ + xlsx_part = self.xlsx_part + if xlsx_part is None: + self.xlsx_part = EmbeddedXlsxPart.new(xlsx_blob, self._chart_part.package) + return + xlsx_part.blob = xlsx_blob + + @property + def xlsx_part(self): + """Optional |EmbeddedXlsxPart| object containing data for this chart. + + This related part has its rId at `c:chartSpace/c:externalData/@rId`. This value + is |None| if there is no `` element. + """ + xlsx_part_rId = self._chartSpace.xlsx_part_rId + return None if xlsx_part_rId is None else self._chart_part.related_part(xlsx_part_rId) + + @xlsx_part.setter + def xlsx_part(self, xlsx_part): + """ + Set the related |EmbeddedXlsxPart| to *xlsx_part*. Assume one does + not already exist. + """ + rId = self._chart_part.relate_to(xlsx_part, RT.PACKAGE) + externalData = self._chartSpace.get_or_add_externalData() + externalData.rId = rId diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/coreprops.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/coreprops.py new file mode 100644 index 0000000000000000000000000000000000000000..8471cc8ef3910b75504509f74c86594638db1de9 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/coreprops.py @@ -0,0 +1,167 @@ +"""Core properties part, corresponds to ``/docProps/core.xml`` part in package.""" + +from __future__ import annotations + +import datetime as dt +from typing import TYPE_CHECKING + +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.opc.package import XmlPart +from pptx.opc.packuri import PackURI +from pptx.oxml.coreprops import CT_CoreProperties + +if TYPE_CHECKING: + from pptx.package import Package + + +class CorePropertiesPart(XmlPart): + """Corresponds to part named `/docProps/core.xml`. + + Contains the core document properties for this document package. + """ + + _element: CT_CoreProperties + + @classmethod + def default(cls, package: Package): + """Return default new |CorePropertiesPart| instance suitable as starting point. + + This provides a base for adding core-properties to a package that doesn't yet + have any. + """ + core_props = cls._new(package) + core_props.title = "PowerPoint Presentation" + core_props.last_modified_by = "python-pptx" + core_props.revision = 1 + core_props.modified = dt.datetime.now(dt.timezone.utc).replace(tzinfo=None) + return core_props + + @property + def author(self) -> str: + return self._element.author_text + + @author.setter + def author(self, value: str): + self._element.author_text = value + + @property + def category(self) -> str: + return self._element.category_text + + @category.setter + def category(self, value: str): + self._element.category_text = value + + @property + def comments(self) -> str: + return self._element.comments_text + + @comments.setter + def comments(self, value: str): + self._element.comments_text = value + + @property + def content_status(self) -> str: + return self._element.contentStatus_text + + @content_status.setter + def content_status(self, value: str): + self._element.contentStatus_text = value + + @property + def created(self): + return self._element.created_datetime + + @created.setter + def created(self, value: dt.datetime): + self._element.created_datetime = value + + @property + def identifier(self) -> str: + return self._element.identifier_text + + @identifier.setter + def identifier(self, value: str): + self._element.identifier_text = value + + @property + def keywords(self) -> str: + return self._element.keywords_text + + @keywords.setter + def keywords(self, value: str): + self._element.keywords_text = value + + @property + def language(self) -> str: + return self._element.language_text + + @language.setter + def language(self, value: str): + self._element.language_text = value + + @property + def last_modified_by(self) -> str: + return self._element.lastModifiedBy_text + + @last_modified_by.setter + def last_modified_by(self, value: str): + self._element.lastModifiedBy_text = value + + @property + def last_printed(self): + return self._element.lastPrinted_datetime + + @last_printed.setter + def last_printed(self, value: dt.datetime): + self._element.lastPrinted_datetime = value + + @property + def modified(self): + return self._element.modified_datetime + + @modified.setter + def modified(self, value: dt.datetime): + self._element.modified_datetime = value + + @property + def revision(self): + return self._element.revision_number + + @revision.setter + def revision(self, value: int): + self._element.revision_number = value + + @property + def subject(self) -> str: + return self._element.subject_text + + @subject.setter + def subject(self, value: str): + self._element.subject_text = value + + @property + def title(self) -> str: + return self._element.title_text + + @title.setter + def title(self, value: str): + self._element.title_text = value + + @property + def version(self) -> str: + return self._element.version_text + + @version.setter + def version(self, value: str): + self._element.version_text = value + + @classmethod + def _new(cls, package: Package) -> CorePropertiesPart: + """Return new empty |CorePropertiesPart| instance.""" + return CorePropertiesPart( + PackURI("/docProps/core.xml"), + CT.OPC_CORE_PROPERTIES, + package, + CT_CoreProperties.new_coreProperties(), + ) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/embeddedpackage.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/embeddedpackage.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa2cf40817f7eba335fa209da4b87aea033a4ae --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/embeddedpackage.py @@ -0,0 +1,93 @@ +"""Embedded Package part objects. + +"Package" in this context means another OPC package, i.e. a DOCX, PPTX, or XLSX "file". +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pptx.enum.shapes import PROG_ID +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.opc.package import Part + +if TYPE_CHECKING: + from pptx.package import Package + + +class EmbeddedPackagePart(Part): + """A distinct OPC package, e.g. an Excel file, embedded in this PPTX package. + + Has a partname like: `ppt/embeddings/Microsoft_Excel_Sheet1.xlsx`. + """ + + @classmethod + def factory(cls, prog_id: PROG_ID | str, object_blob: bytes, package: Package): + """Return a new |EmbeddedPackagePart| subclass instance added to *package*. + + The subclass is determined by `prog_id` which corresponds to the "application" + used to open the "file-type" of `object_blob`. The returned part contains the + bytes of `object_blob` and has the content-type also determined by `prog_id`. + """ + # --- a generic OLE object has no subclass --- + if not isinstance(prog_id, PROG_ID): + return cls( + package.next_partname("/ppt/embeddings/oleObject%d.bin"), + CT.OFC_OLE_OBJECT, + package, + object_blob, + ) + + # --- A Microsoft Office file-type is a distinguished package object --- + EmbeddedPartCls = { + PROG_ID.DOCX: EmbeddedDocxPart, + PROG_ID.PPTX: EmbeddedPptxPart, + PROG_ID.XLSX: EmbeddedXlsxPart, + }[prog_id] + + return EmbeddedPartCls.new(object_blob, package) + + @classmethod + def new(cls, blob: bytes, package: Package): + """Return new |EmbeddedPackagePart| subclass object. + + The returned part object contains `blob` and is added to `package`. + """ + return cls( + package.next_partname(cls.partname_template), + cls.content_type, + package, + blob, + ) + + +class EmbeddedDocxPart(EmbeddedPackagePart): + """A Word .docx file stored in a part. + + This part-type arises when a Word document appears as an embedded OLE-object shape. + """ + + partname_template = "/ppt/embeddings/Microsoft_Word_Document%d.docx" + content_type = CT.WML_DOCUMENT + + +class EmbeddedPptxPart(EmbeddedPackagePart): + """A PowerPoint file stored in a part. + + This part-type arises when a PowerPoint presentation (.pptx file) appears as an + embedded OLE-object shape. + """ + + partname_template = "/ppt/embeddings/Microsoft_PowerPoint_Presentation%d.pptx" + content_type = CT.PML_PRESENTATION + + +class EmbeddedXlsxPart(EmbeddedPackagePart): + """An Excel file stored in a part. + + This part-type arises as the data source for a chart, but may also be the OLE-object + for an embedded object shape. + """ + + partname_template = "/ppt/embeddings/Microsoft_Excel_Sheet%d.xlsx" + content_type = CT.SML_SHEET diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/image.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/image.py new file mode 100644 index 0000000000000000000000000000000000000000..9be5d02d642be1ff9086653f59f86fee38b6d43f --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/image.py @@ -0,0 +1,275 @@ +"""ImagePart and related objects.""" + +from __future__ import annotations + +import hashlib +import io +import os +from typing import IO, TYPE_CHECKING, Any, cast + +from PIL import Image as PIL_Image + +from pptx.opc.package import Part +from pptx.opc.spec import image_content_types +from pptx.util import Emu, lazyproperty + +if TYPE_CHECKING: + from pptx.opc.packuri import PackURI + from pptx.package import Package + from pptx.util import Length + + +class ImagePart(Part): + """An image part. + + An image part generally has a partname matching the regex `ppt/media/image[1-9][0-9]*.*`. + """ + + def __init__( + self, + partname: PackURI, + content_type: str, + package: Package, + blob: bytes, + filename: str | None = None, + ): + super(ImagePart, self).__init__(partname, content_type, package, blob) + self._blob = blob + self._filename = filename + + @classmethod + def new(cls, package: Package, image: Image) -> ImagePart: + """Return new |ImagePart| instance containing `image`. + + `image` is an |Image| object. + """ + return cls( + package.next_image_partname(image.ext), + image.content_type, + package, + image.blob, + image.filename, + ) + + @property + def desc(self) -> str: + """The filename associated with this image. + + Either the filename of the original image or a generic name of the form `image.ext` where + `ext` is appropriate to the image file format, e.g. `'jpg'`. An image created using a path + will have that filename; one created with a file-like object will have a generic name. + """ + # -- return generic filename if original filename is unknown -- + if self._filename is None: + return f"image.{self.ext}" + return self._filename + + @property + def ext(self) -> str: + """File-name extension for this image e.g. `'png'`.""" + return self.partname.ext + + @property + def image(self) -> Image: + """An |Image| object containing the image in this image part. + + Note this is a `pptx.image.Image` object, not a PIL Image. + """ + return Image(self._blob, self.desc) + + def scale(self, scaled_cx: int | None, scaled_cy: int | None) -> tuple[int, int]: + """Return scaled image dimensions in EMU based on the combination of parameters supplied. + + If `scaled_cx` and `scaled_cy` are both |None|, the native image size is returned. If + neither `scaled_cx` nor `scaled_cy` is |None|, their values are returned unchanged. If a + value is provided for either `scaled_cx` or `scaled_cy` and the other is |None|, the + missing value is calculated such that the image's aspect ratio is preserved. + """ + image_cx, image_cy = self._native_size + + if scaled_cx and scaled_cy: + return scaled_cx, scaled_cy + + if scaled_cx and not scaled_cy: + scaling_factor = float(scaled_cx) / float(image_cx) + scaled_cy = int(round(image_cy * scaling_factor)) + return scaled_cx, scaled_cy + + if not scaled_cx and scaled_cy: + scaling_factor = float(scaled_cy) / float(image_cy) + scaled_cx = int(round(image_cx * scaling_factor)) + return scaled_cx, scaled_cy + + # -- only remaining case is both `scaled_cx` and `scaled_cy` are `None` -- + return image_cx, image_cy + + @lazyproperty + def sha1(self) -> str: + """The 40-character SHA1 hash digest for the image binary of this image part. + + like: `"1be010ea47803b00e140b852765cdf84f491da47"`. + """ + return hashlib.sha1(self._blob).hexdigest() + + @property + def _dpi(self) -> tuple[int, int]: + """(horz_dpi, vert_dpi) pair representing the dots-per-inch resolution of this image.""" + image = Image.from_blob(self._blob) + return image.dpi + + @property + def _native_size(self) -> tuple[Length, Length]: + """A (width, height) 2-tuple representing the native dimensions of the image in EMU. + + Calculated based on the image DPI value, if present, assuming 72 dpi as a default. + """ + EMU_PER_INCH = 914400 + horz_dpi, vert_dpi = self._dpi + width_px, height_px = self._px_size + + width = EMU_PER_INCH * width_px / horz_dpi + height = EMU_PER_INCH * height_px / vert_dpi + + return Emu(int(width)), Emu(int(height)) + + @property + def _px_size(self) -> tuple[int, int]: + """A (width, height) 2-tuple representing the dimensions of this image in pixels.""" + image = Image.from_blob(self._blob) + return image.size + + +class Image(object): + """Immutable value object representing an image such as a JPEG, PNG, or GIF.""" + + def __init__(self, blob: bytes, filename: str | None): + super(Image, self).__init__() + self._blob = blob + self._filename = filename + + @classmethod + def from_blob(cls, blob: bytes, filename: str | None = None) -> Image: + """Return a new |Image| object loaded from the image binary in `blob`.""" + return cls(blob, filename) + + @classmethod + def from_file(cls, image_file: str | IO[bytes]) -> Image: + """Return a new |Image| object loaded from `image_file`. + + `image_file` can be either a path (str) or a file-like object. + """ + if isinstance(image_file, str): + # treat image_file as a path + with open(image_file, "rb") as f: + blob = f.read() + filename = os.path.basename(image_file) + else: + # assume image_file is a file-like object + # ---reposition file cursor if it has one--- + if callable(getattr(image_file, "seek")): + image_file.seek(0) + blob = image_file.read() + filename = None + + return cls.from_blob(blob, filename) + + @property + def blob(self) -> bytes: + """The binary image bytestream of this image.""" + return self._blob + + @lazyproperty + def content_type(self) -> str: + """MIME-type of this image, e.g. `"image/jpeg"`.""" + return image_content_types[self.ext] + + @lazyproperty + def dpi(self) -> tuple[int, int]: + """A (horz_dpi, vert_dpi) 2-tuple specifying the dots-per-inch resolution of this image. + + A default value of (72, 72) is used if the dpi is not specified in the image file. + """ + + def int_dpi(dpi: Any): + """Return an integer dots-per-inch value corresponding to `dpi`. + + If `dpi` is |None|, a non-numeric type, less than 1 or greater than 2048, 72 is + returned. + """ + try: + int_dpi = int(round(float(dpi))) + if int_dpi < 1 or int_dpi > 2048: + int_dpi = 72 + except (TypeError, ValueError): + int_dpi = 72 + return int_dpi + + def normalize_pil_dpi(pil_dpi: tuple[int, int] | None): + """Return a (horz_dpi, vert_dpi) 2-tuple corresponding to `pil_dpi`. + + The value for the 'dpi' key in the `info` dict of a PIL image. If the 'dpi' key is not + present or contains an invalid value, `(72, 72)` is returned. + """ + if isinstance(pil_dpi, tuple): + return (int_dpi(pil_dpi[0]), int_dpi(pil_dpi[1])) + return (72, 72) + + return normalize_pil_dpi(self._pil_props[2]) + + @lazyproperty + def ext(self) -> str: + """Canonical file extension for this image e.g. `'png'`. + + The returned extension is all lowercase and is the canonical extension for the content type + of this image, regardless of what extension may have been used in its filename, if any. + """ + ext_map = { + "BMP": "bmp", + "GIF": "gif", + "JPEG": "jpg", + "PNG": "png", + "TIFF": "tiff", + "WMF": "wmf", + } + format = self._format + if format not in ext_map: + tmpl = "unsupported image format, expected one of: %s, got '%s'" + raise ValueError(tmpl % (ext_map.keys(), format)) + return ext_map[format] + + @property + def filename(self) -> str | None: + """Filename from path used to load this image, if loaded from the filesystem. + + |None| if no filename was used in loading, such as when loaded from an in-memory stream. + """ + return self._filename + + @lazyproperty + def sha1(self) -> str: + """SHA1 hash digest of the image blob.""" + return hashlib.sha1(self._blob).hexdigest() + + @lazyproperty + def size(self) -> tuple[int, int]: + """A (width, height) 2-tuple specifying the dimensions of this image in pixels.""" + return self._pil_props[1] + + @property + def _format(self) -> str | None: + """The PIL Image format of this image, e.g. 'PNG'.""" + return self._pil_props[0] + + @lazyproperty + def _pil_props(self) -> tuple[str | None, tuple[int, int], tuple[int, int] | None]: + """tuple of image properties extracted from this image using Pillow.""" + stream = io.BytesIO(self._blob) + pil_image = PIL_Image.open(stream) # pyright: ignore[reportUnknownMemberType] + format = pil_image.format + width_px, height_px = pil_image.size + dpi = cast( + "tuple[int, int] | None", + pil_image.info.get("dpi"), # pyright: ignore[reportUnknownMemberType] + ) + stream.close() + return (format, (width_px, height_px), dpi) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/media.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/media.py new file mode 100644 index 0000000000000000000000000000000000000000..7e8bc2f21fc73b24fc47cb22516f4722827c36d9 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/media.py @@ -0,0 +1,37 @@ +"""MediaPart and related objects.""" + +from __future__ import annotations + +import hashlib + +from pptx.opc.package import Part +from pptx.util import lazyproperty + + +class MediaPart(Part): + """A media part, containing an audio or video resource. + + A media part generally has a partname matching the regex + `ppt/media/media[1-9][0-9]*.*`. + """ + + @classmethod + def new(cls, package, media): + """Return new |MediaPart| instance containing `media`. + + `media` must be a |Media| object. + """ + return cls( + package.next_media_partname(media.ext), + media.content_type, + package, + media.blob, + ) + + @lazyproperty + def sha1(self): + """The SHA1 hash digest for the media binary of this media part. + + Example: `'1be010ea47803b00e140b852765cdf84f491da47'` + """ + return hashlib.sha1(self._blob).hexdigest() diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/presentation.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/presentation.py new file mode 100644 index 0000000000000000000000000000000000000000..1413de457717fe33f61f794dd8bdb76cbd064044 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/presentation.py @@ -0,0 +1,126 @@ +"""Presentation part, the main part in a .pptx package.""" + +from __future__ import annotations + +from typing import IO, TYPE_CHECKING, Iterable + +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.package import XmlPart +from pptx.opc.packuri import PackURI +from pptx.parts.slide import NotesMasterPart, SlidePart +from pptx.presentation import Presentation +from pptx.util import lazyproperty + +if TYPE_CHECKING: + from pptx.parts.coreprops import CorePropertiesPart + from pptx.slide import NotesMaster, Slide, SlideLayout, SlideMaster + + +class PresentationPart(XmlPart): + """Top level class in object model. + + Represents the contents of the /ppt directory of a .pptx file. + """ + + def add_slide(self, slide_layout: SlideLayout): + """Return (rId, slide) pair of a newly created blank slide. + + New slide inherits appearance from `slide_layout`. + """ + partname = self._next_slide_partname + slide_layout_part = slide_layout.part + slide_part = SlidePart.new(partname, self.package, slide_layout_part) + rId = self.relate_to(slide_part, RT.SLIDE) + return rId, slide_part.slide + + @property + def core_properties(self) -> CorePropertiesPart: + """A |CoreProperties| object for the presentation. + + Provides read/write access to the Dublin Core properties of this presentation. + """ + return self.package.core_properties + + def get_slide(self, slide_id: int) -> Slide | None: + """Return optional related |Slide| object identified by `slide_id`. + + Returns |None| if no slide with `slide_id` is related to this presentation. + """ + for sldId in self._element.sldIdLst: + if sldId.id == slide_id: + return self.related_part(sldId.rId).slide + return None + + @lazyproperty + def notes_master(self) -> NotesMaster: + """ + Return the |NotesMaster| object for this presentation. If the + presentation does not have a notes master, one is created from + a default template. The same single instance is returned on each + call. + """ + return self.notes_master_part.notes_master + + @lazyproperty + def notes_master_part(self) -> NotesMasterPart: + """Return the |NotesMasterPart| object for this presentation. + + If the presentation does not have a notes master, one is created from a default template. + The same single instance is returned on each call. + """ + try: + return self.part_related_by(RT.NOTES_MASTER) + except KeyError: + notes_master_part = NotesMasterPart.create_default(self.package) + self.relate_to(notes_master_part, RT.NOTES_MASTER) + return notes_master_part + + @lazyproperty + def presentation(self): + """ + A |Presentation| object providing access to the content of this + presentation. + """ + return Presentation(self._element, self) + + def related_slide(self, rId: str) -> Slide: + """Return |Slide| object for related |SlidePart| related by `rId`.""" + return self.related_part(rId).slide + + def related_slide_master(self, rId: str) -> SlideMaster: + """Return |SlideMaster| object for |SlideMasterPart| related by `rId`.""" + return self.related_part(rId).slide_master + + def rename_slide_parts(self, rIds: Iterable[str]): + """Assign incrementing partnames to the slide parts identified by `rIds`. + + Partnames are like `/ppt/slides/slide9.xml` and are assigned in the order their id appears + in the `rIds` sequence. The name portion is always `slide`. The number part forms a + continuous sequence starting at 1 (e.g. 1, 2, ... 10, ...). The extension is always + `.xml`. + """ + for idx, rId in enumerate(rIds): + slide_part = self.related_part(rId) + slide_part.partname = PackURI("/ppt/slides/slide%d.xml" % (idx + 1)) + + def save(self, path_or_stream: str | IO[bytes]): + """Save this presentation package to `path_or_stream`. + + `path_or_stream` can be either a path to a filesystem location (a string) or a + file-like object. + """ + self.package.save(path_or_stream) + + def slide_id(self, slide_part): + """Return the slide-id associated with `slide_part`.""" + for sldId in self._element.sldIdLst: + if self.related_part(sldId.rId) is slide_part: + return sldId.id + raise ValueError("matching slide_part not found") + + @property + def _next_slide_partname(self): + """Return |PackURI| instance containing next available slide partname.""" + sldIdLst = self._element.get_or_add_sldIdLst() + partname_str = "/ppt/slides/slide%d.xml" % (len(sldIdLst) + 1) + return PackURI(partname_str) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/slide.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/slide.py new file mode 100644 index 0000000000000000000000000000000000000000..6650564a504f7dc2301cd301b75a2b29416469ee --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/slide.py @@ -0,0 +1,297 @@ +"""Slide and related objects.""" + +from __future__ import annotations + +from typing import IO, TYPE_CHECKING, cast + +from pptx.enum.shapes import PROG_ID +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.package import XmlPart +from pptx.opc.packuri import PackURI +from pptx.oxml.slide import CT_NotesMaster, CT_NotesSlide, CT_Slide +from pptx.oxml.theme import CT_OfficeStyleSheet +from pptx.parts.chart import ChartPart +from pptx.parts.embeddedpackage import EmbeddedPackagePart +from pptx.slide import NotesMaster, NotesSlide, Slide, SlideLayout, SlideMaster +from pptx.util import lazyproperty + +if TYPE_CHECKING: + from pptx.chart.data import ChartData + from pptx.enum.chart import XL_CHART_TYPE + from pptx.media import Video + from pptx.parts.image import Image, ImagePart + + +class BaseSlidePart(XmlPart): + """Base class for slide parts. + + This includes slide, slide-layout, and slide-master parts, but also notes-slide, + notes-master, and handout-master parts. + """ + + _element: CT_Slide + + def get_image(self, rId: str) -> Image: + """Return an |Image| object containing the image related to this slide by *rId*. + + Raises |KeyError| if no image is related by that id, which would generally indicate a + corrupted .pptx file. + """ + return cast("ImagePart", self.related_part(rId)).image + + def get_or_add_image_part(self, image_file: str | IO[bytes]): + """Return `(image_part, rId)` pair corresponding to `image_file`. + + The returned |ImagePart| object contains the image in `image_file` and is + related to this slide with the key `rId`. If either the image part or + relationship already exists, they are reused, otherwise they are newly created. + """ + image_part = self._package.get_or_add_image_part(image_file) + rId = self.relate_to(image_part, RT.IMAGE) + return image_part, rId + + @property + def name(self) -> str: + """Internal name of this slide.""" + return self._element.cSld.name + + +class NotesMasterPart(BaseSlidePart): + """Notes master part. + + Corresponds to package file `ppt/notesMasters/notesMaster1.xml`. + """ + + @classmethod + def create_default(cls, package): + """ + Create and return a default notes master part, including creating the + new theme it requires. + """ + notes_master_part = cls._new(package) + theme_part = cls._new_theme_part(package) + notes_master_part.relate_to(theme_part, RT.THEME) + return notes_master_part + + @lazyproperty + def notes_master(self): + """ + Return the |NotesMaster| object that proxies this notes master part. + """ + return NotesMaster(self._element, self) + + @classmethod + def _new(cls, package): + """ + Create and return a standalone, default notes master part based on + the built-in template (without any related parts, such as theme). + """ + return NotesMasterPart( + PackURI("/ppt/notesMasters/notesMaster1.xml"), + CT.PML_NOTES_MASTER, + package, + CT_NotesMaster.new_default(), + ) + + @classmethod + def _new_theme_part(cls, package): + """Return new default theme-part suitable for use with a notes master.""" + return XmlPart( + package.next_partname("/ppt/theme/theme%d.xml"), + CT.OFC_THEME, + package, + CT_OfficeStyleSheet.new_default(), + ) + + +class NotesSlidePart(BaseSlidePart): + """Notes slide part. + + Contains the slide notes content and the layout for the slide handout page. + Corresponds to package file `ppt/notesSlides/notesSlide[1-9][0-9]*.xml`. + """ + + @classmethod + def new(cls, package, slide_part): + """Return new |NotesSlidePart| for the slide in `slide_part`. + + The new notes-slide part is based on the (singleton) notes master and related to + both the notes-master part and `slide_part`. If no notes-master is present, + one is created based on the default template. + """ + notes_master_part = package.presentation_part.notes_master_part + notes_slide_part = cls._add_notes_slide_part(package, slide_part, notes_master_part) + notes_slide = notes_slide_part.notes_slide + notes_slide.clone_master_placeholders(notes_master_part.notes_master) + return notes_slide_part + + @lazyproperty + def notes_master(self): + """Return the |NotesMaster| object this notes slide inherits from.""" + notes_master_part = self.part_related_by(RT.NOTES_MASTER) + return notes_master_part.notes_master + + @lazyproperty + def notes_slide(self): + """Return the |NotesSlide| object that proxies this notes slide part.""" + return NotesSlide(self._element, self) + + @classmethod + def _add_notes_slide_part(cls, package, slide_part, notes_master_part): + """Create and return a new notes-slide part. + + The return part is fully related, but has no shape content (i.e. placeholders + not cloned). + """ + notes_slide_part = NotesSlidePart( + package.next_partname("/ppt/notesSlides/notesSlide%d.xml"), + CT.PML_NOTES_SLIDE, + package, + CT_NotesSlide.new(), + ) + notes_slide_part.relate_to(notes_master_part, RT.NOTES_MASTER) + notes_slide_part.relate_to(slide_part, RT.SLIDE) + return notes_slide_part + + +class SlidePart(BaseSlidePart): + """Slide part. Corresponds to package files ppt/slides/slide[1-9][0-9]*.xml.""" + + @classmethod + def new(cls, partname, package, slide_layout_part): + """Return newly-created blank slide part. + + The new slide-part has `partname` and a relationship to `slide_layout_part`. + """ + slide_part = cls(partname, CT.PML_SLIDE, package, CT_Slide.new()) + slide_part.relate_to(slide_layout_part, RT.SLIDE_LAYOUT) + return slide_part + + def add_chart_part(self, chart_type: XL_CHART_TYPE, chart_data: ChartData): + """Return str rId of new |ChartPart| object containing chart of `chart_type`. + + The chart depicts `chart_data` and is related to the slide contained in this + part by `rId`. + """ + return self.relate_to(ChartPart.new(chart_type, chart_data, self._package), RT.CHART) + + def add_embedded_ole_object_part( + self, prog_id: PROG_ID | str, ole_object_file: str | IO[bytes] + ): + """Return rId of newly-added OLE-object part formed from `ole_object_file`.""" + relationship_type = RT.PACKAGE if isinstance(prog_id, PROG_ID) else RT.OLE_OBJECT + return self.relate_to( + EmbeddedPackagePart.factory( + prog_id, self._blob_from_file(ole_object_file), self._package + ), + relationship_type, + ) + + def get_or_add_video_media_part(self, video: Video) -> tuple[str, str]: + """Return rIds for media and video relationships to media part. + + A new |MediaPart| object is created if it does not already exist + (such as would occur if the same video appeared more than once in + a presentation). Two relationships to the media part are created, + one each with MEDIA and VIDEO relationship types. The need for two + appears to be for legacy support for an earlier (pre-Office 2010) + PowerPoint media embedding strategy. + """ + media_part = self._package.get_or_add_media_part(video) + media_rId = self.relate_to(media_part, RT.MEDIA) + video_rId = self.relate_to(media_part, RT.VIDEO) + return media_rId, video_rId + + @property + def has_notes_slide(self): + """ + Return True if this slide has a notes slide, False otherwise. A notes + slide is created by the :attr:`notes_slide` property when one doesn't + exist; use this property to test for a notes slide without the + possible side-effect of creating one. + """ + try: + self.part_related_by(RT.NOTES_SLIDE) + except KeyError: + return False + return True + + @lazyproperty + def notes_slide(self) -> NotesSlide: + """The |NotesSlide| instance associated with this slide. + + If the slide does not have a notes slide, a new one is created. The same single instance + is returned on each call. + """ + try: + notes_slide_part = self.part_related_by(RT.NOTES_SLIDE) + except KeyError: + notes_slide_part = self._add_notes_slide_part() + return notes_slide_part.notes_slide + + @lazyproperty + def slide(self): + """ + The |Slide| object representing this slide part. + """ + return Slide(self._element, self) + + @property + def slide_id(self) -> int: + """Return the slide identifier stored in the presentation part for this slide part.""" + presentation_part = self.package.presentation_part + return presentation_part.slide_id(self) + + @property + def slide_layout(self) -> SlideLayout: + """|SlideLayout| object the slide in this part inherits appearance from.""" + slide_layout_part = self.part_related_by(RT.SLIDE_LAYOUT) + return slide_layout_part.slide_layout + + def _add_notes_slide_part(self): + """ + Return a newly created |NotesSlidePart| object related to this slide + part. Caller is responsible for ensuring this slide doesn't already + have a notes slide part. + """ + notes_slide_part = NotesSlidePart.new(self.package, self) + self.relate_to(notes_slide_part, RT.NOTES_SLIDE) + return notes_slide_part + + +class SlideLayoutPart(BaseSlidePart): + """Slide layout part. + + Corresponds to package files ``ppt/slideLayouts/slideLayout[1-9][0-9]*.xml``. + """ + + @lazyproperty + def slide_layout(self): + """ + The |SlideLayout| object representing this part. + """ + return SlideLayout(self._element, self) + + @property + def slide_master(self) -> SlideMaster: + """Slide master from which this slide layout inherits properties.""" + return self.part_related_by(RT.SLIDE_MASTER).slide_master + + +class SlideMasterPart(BaseSlidePart): + """Slide master part. + + Corresponds to package files ppt/slideMasters/slideMaster[1-9][0-9]*.xml. + """ + + def related_slide_layout(self, rId: str) -> SlideLayout: + """Return |SlideLayout| related to this slide-master by key `rId`.""" + return self.related_part(rId).slide_layout + + @lazyproperty + def slide_master(self): + """ + The |SlideMaster| object representing this part. + """ + return SlideMaster(self._element, self) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/presentation.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/presentation.py new file mode 100644 index 0000000000000000000000000000000000000000..a41bfd59a73e971ed83caeb4b3256b1f8d3f21e1 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/presentation.py @@ -0,0 +1,113 @@ +"""Main presentation object.""" + +from __future__ import annotations + +from typing import IO, TYPE_CHECKING, cast + +from pptx.shared import PartElementProxy +from pptx.slide import SlideMasters, Slides +from pptx.util import lazyproperty + +if TYPE_CHECKING: + from pptx.oxml.presentation import CT_Presentation, CT_SlideId + from pptx.parts.presentation import PresentationPart + from pptx.slide import NotesMaster, SlideLayouts + from pptx.util import Length + + +class Presentation(PartElementProxy): + """PresentationML (PML) presentation. + + Not intended to be constructed directly. Use :func:`pptx.Presentation` to open or + create a presentation. + """ + + _element: CT_Presentation + part: PresentationPart # pyright: ignore[reportIncompatibleMethodOverride] + + @property + def core_properties(self): + """|CoreProperties| instance for this presentation. + + Provides read/write access to the Dublin Core document properties for the presentation. + """ + return self.part.core_properties + + @property + def notes_master(self) -> NotesMaster: + """Instance of |NotesMaster| for this presentation. + + If the presentation does not have a notes master, one is created from a default template + and returned. The same single instance is returned on each call. + """ + return self.part.notes_master + + def save(self, file: str | IO[bytes]): + """Writes this presentation to `file`. + + `file` can be either a file-path or a file-like object open for writing bytes. + """ + self.part.save(file) + + @property + def slide_height(self) -> Length | None: + """Height of slides in this presentation, in English Metric Units (EMU). + + Returns |None| if no slide width is defined. Read/write. + """ + sldSz = self._element.sldSz + if sldSz is None: + return None + return sldSz.cy + + @slide_height.setter + def slide_height(self, height: Length): + sldSz = self._element.get_or_add_sldSz() + sldSz.cy = height + + @property + def slide_layouts(self) -> SlideLayouts: + """|SlideLayouts| collection belonging to the first |SlideMaster| of this presentation. + + A presentation can have more than one slide master and each master will have its own set + of layouts. This property is a convenience for the common case where the presentation has + only a single slide master. + """ + return self.slide_masters[0].slide_layouts + + @property + def slide_master(self): + """ + First |SlideMaster| object belonging to this presentation. Typically, + presentations have only a single slide master. This property provides + simpler access in that common case. + """ + return self.slide_masters[0] + + @lazyproperty + def slide_masters(self) -> SlideMasters: + """|SlideMasters| collection of slide-masters belonging to this presentation.""" + return SlideMasters(self._element.get_or_add_sldMasterIdLst(), self) + + @property + def slide_width(self): + """ + Width of slides in this presentation, in English Metric Units (EMU). + Returns |None| if no slide width is defined. Read/write. + """ + sldSz = self._element.sldSz + if sldSz is None: + return None + return sldSz.cx + + @slide_width.setter + def slide_width(self, width: Length): + sldSz = self._element.get_or_add_sldSz() + sldSz.cx = width + + @lazyproperty + def slides(self): + """|Slides| object containing the slides in this presentation.""" + sldIdLst = self._element.get_or_add_sldIdLst() + self.part.rename_slide_parts([cast("CT_SlideId", sldId).rId for sldId in sldIdLst]) + return Slides(sldIdLst, self) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/__init__.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..332109a31573cc7692ddefe1f94680054c744ab5 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/__init__.py @@ -0,0 +1,26 @@ +"""Objects used across sub-package.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from pptx.opc.package import XmlPart + from pptx.types import ProvidesPart + + +class Subshape(object): + """Provides access to the containing part for drawing elements that occur below a shape. + + Access to the part is required for example to add or drop a relationship. Provides + `self._parent` attribute to subclasses. + """ + + def __init__(self, parent: ProvidesPart): + super(Subshape, self).__init__() + self._parent = parent + + @property + def part(self) -> XmlPart: + """The package part containing this object.""" + return self._parent.part diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/autoshape.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/autoshape.py new file mode 100644 index 0000000000000000000000000000000000000000..c7f8cd93e2857927f4446abe6b4dc050bae00852 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/autoshape.py @@ -0,0 +1,355 @@ +"""Autoshape-related objects such as Shape and Adjustment.""" + +from __future__ import annotations + +from numbers import Number +from typing import TYPE_CHECKING, Iterable +from xml.sax import saxutils + +from pptx.dml.fill import FillFormat +from pptx.dml.line import LineFormat +from pptx.enum.shapes import MSO_AUTO_SHAPE_TYPE, MSO_SHAPE_TYPE +from pptx.shapes.base import BaseShape +from pptx.spec import autoshape_types +from pptx.text.text import TextFrame +from pptx.util import lazyproperty + +if TYPE_CHECKING: + from pptx.oxml.shapes.autoshape import CT_GeomGuide, CT_PresetGeometry2D, CT_Shape + from pptx.spec import AdjustmentValue + from pptx.types import ProvidesPart + + +class Adjustment: + """An adjustment value for an autoshape. + + An adjustment value corresponds to the position of an adjustment handle on an auto shape. + Adjustment handles are the small yellow diamond-shaped handles that appear on certain auto + shapes and allow the outline of the shape to be adjusted. For example, a rounded rectangle has + an adjustment handle that allows the radius of its corner rounding to be adjusted. + + Values are |float| and generally range from 0.0 to 1.0, although the value can be negative or + greater than 1.0 in certain circumstances. + """ + + def __init__(self, name: str, def_val: int, actual: int | None = None): + super(Adjustment, self).__init__() + self.name = name + self.def_val = def_val + self.actual = actual + + @property + def effective_value(self) -> float: + """Read/write |float| representing normalized adjustment value for this adjustment. + + Actual values are a large-ish integer expressed in shape coordinates, nominally between 0 + and 100,000. The effective value is normalized to a corresponding value nominally between + 0.0 and 1.0. Intuitively this represents the proportion of the width or height of the shape + at which the adjustment value is located from its starting point. For simple shapes such as + a rounded rectangle, this intuitive correspondence holds. For more complicated shapes and + at more extreme shape proportions (e.g. width is much greater than height), the value can + become negative or greater than 1.0. + """ + raw_value = self.actual if self.actual is not None else self.def_val + return self._normalize(raw_value) + + @effective_value.setter + def effective_value(self, value: float): + if not isinstance(value, Number): + raise ValueError(f"adjustment value must be numeric, got {repr(value)}") + self.actual = self._denormalize(value) + + @staticmethod + def _denormalize(value: float) -> int: + """Return integer corresponding to normalized `raw_value` on unit basis of 100,000. + + See Adjustment.normalize for additional details. + """ + return int(value * 100000.0) + + @staticmethod + def _normalize(raw_value: int) -> float: + """Return normalized value for `raw_value`. + + A normalized value is a |float| between 0.0 and 1.0 for nominal raw values between 0 and + 100,000. Raw values less than 0 and greater than 100,000 are valid and return values + calculated on the same unit basis of 100,000. + """ + return raw_value / 100000.0 + + @property + def val(self) -> int: + """Denormalized effective value. + + Expressed in shape coordinates, this is suitable for using in the XML. + """ + return self.actual if self.actual is not None else self.def_val + + +class AdjustmentCollection: + """Sequence of |Adjustment| instances for an auto shape. + + Each represents an available adjustment for a shape of its type. Supports `len()` and indexed + access, e.g. `shape.adjustments[1] = 0.15`. + """ + + def __init__(self, prstGeom: CT_PresetGeometry2D): + super(AdjustmentCollection, self).__init__() + self._adjustments_ = self._initialized_adjustments(prstGeom) + self._prstGeom = prstGeom + + def __getitem__(self, idx: int) -> float: + """Provides indexed access, (e.g. 'adjustments[9]').""" + return self._adjustments_[idx].effective_value + + def __setitem__(self, idx: int, value: float): + """Provides item assignment via an indexed expression, e.g. `adjustments[9] = 999.9`. + + Causes all adjustment values in collection to be written to the XML. + """ + self._adjustments_[idx].effective_value = value + self._rewrite_guides() + + def _initialized_adjustments(self, prstGeom: CT_PresetGeometry2D | None) -> list[Adjustment]: + """Return an initialized list of adjustment values based on the contents of `prstGeom`.""" + if prstGeom is None: + return [] + davs = AutoShapeType.default_adjustment_values(prstGeom.prst) + adjustments = [Adjustment(name, def_val) for name, def_val in davs] + self._update_adjustments_with_actuals(adjustments, prstGeom.gd_lst) + return adjustments + + def _rewrite_guides(self): + """Write `a:gd` elements to the XML, one for each adjustment value. + + Any existing guide elements are overwritten. + """ + guides = [(adj.name, adj.val) for adj in self._adjustments_] + self._prstGeom.rewrite_guides(guides) + + @staticmethod + def _update_adjustments_with_actuals( + adjustments: Iterable[Adjustment], guides: Iterable[CT_GeomGuide] + ): + """Update |Adjustment| instances in `adjustments` with actual values held in `guides`. + + `guides` is a list of `a:gd` elements. Guides with a name that does not match an adjustment + object are skipped. + """ + adjustments_by_name = dict((adj.name, adj) for adj in adjustments) + for gd in guides: + name = gd.name + actual = int(gd.fmla[4:]) + try: + adjustment = adjustments_by_name[name] + except KeyError: + continue + adjustment.actual = actual + return + + @property + def _adjustments(self) -> tuple[Adjustment, ...]: + """Sequence of |Adjustment| objects contained in collection.""" + return tuple(self._adjustments_) + + def __len__(self): + """Implement built-in function len()""" + return len(self._adjustments_) + + +class AutoShapeType: + """Provides access to metadata for an auto-shape of type identified by `autoshape_type_id`. + + Instances are cached, so no more than one instance for a particular auto shape type is in + memory. + + Instances provide the following attributes: + + .. attribute:: autoshape_type_id + + Integer uniquely identifying this auto shape type. Corresponds to a + value in `pptx.constants.MSO` like `MSO_SHAPE.ROUNDED_RECTANGLE`. + + .. attribute:: basename + + Base part of shape name for auto shapes of this type, e.g. `Rounded + Rectangle` becomes `Rounded Rectangle 99` when the distinguishing + integer is added to the shape name. + + .. attribute:: prst + + String identifier for this auto shape type used in the `a:prstGeom` + element. + + """ + + _instances: dict[MSO_AUTO_SHAPE_TYPE, AutoShapeType] = {} + + def __new__(cls, autoshape_type_id: MSO_AUTO_SHAPE_TYPE) -> AutoShapeType: + """Only create new instance on first call for content_type. + + After that, use cached instance. + """ + # -- if there's not a matching instance in the cache, create one -- + if autoshape_type_id not in cls._instances: + inst = super(AutoShapeType, cls).__new__(cls) + cls._instances[autoshape_type_id] = inst + # -- return the instance; note that __init__() gets called either way -- + return cls._instances[autoshape_type_id] + + def __init__(self, autoshape_type_id: MSO_AUTO_SHAPE_TYPE): + """Initialize attributes from constant values in `pptx.spec`.""" + # -- skip loading if this instance is from the cache -- + if hasattr(self, "_loaded"): + return + # -- raise on bad autoshape_type_id -- + if autoshape_type_id not in autoshape_types: + raise KeyError( + "no autoshape type with id '%s' in pptx.spec.autoshape_types" % autoshape_type_id + ) + # -- otherwise initialize new instance -- + autoshape_type = autoshape_types[autoshape_type_id] + self._autoshape_type_id = autoshape_type_id + self._basename = autoshape_type["basename"] + self._loaded = True + + @property + def autoshape_type_id(self) -> MSO_AUTO_SHAPE_TYPE: + """MSO_AUTO_SHAPE_TYPE enumeration member identifying this auto shape type.""" + return self._autoshape_type_id + + @property + def basename(self) -> str: + """Base of shape name for this auto shape type. + + A shape name is like "Rounded Rectangle 7" and appears as an XML attribute for example at + `p:sp/p:nvSpPr/p:cNvPr{name}`. This basename value is the name less the distinguishing + integer. This value is escaped because at least one autoshape-type name includes double + quotes ('"No" Symbol'). + """ + return saxutils.escape(self._basename, {'"': """}) + + @classmethod + def default_adjustment_values(cls, prst: MSO_AUTO_SHAPE_TYPE) -> tuple[AdjustmentValue, ...]: + """Sequence of (name, value) pair adjustment value defaults for `prst` autoshape-type.""" + return autoshape_types[prst]["avLst"] + + @classmethod + def id_from_prst(cls, prst: str) -> MSO_AUTO_SHAPE_TYPE: + """Select auto shape type with matching `prst`. + + e.g. `MSO_SHAPE.RECTANGLE` corresponding to preset geometry keyword `"rect"`. + """ + return MSO_AUTO_SHAPE_TYPE.from_xml(prst) + + @property + def prst(self): + """ + Preset geometry identifier string for this auto shape. Used in the + `prst` attribute of `a:prstGeom` element to specify the geometry + to be used in rendering the shape, for example `'roundRect'`. + """ + return MSO_AUTO_SHAPE_TYPE.to_xml(self._autoshape_type_id) + + +class Shape(BaseShape): + """A shape that can appear on a slide. + + Corresponds to the `p:sp` element that can appear in any of the slide-type parts + (slide, slideLayout, slideMaster, notesPage, notesMaster, handoutMaster). + """ + + def __init__(self, sp: CT_Shape, parent: ProvidesPart): + super(Shape, self).__init__(sp, parent) + self._sp = sp + + @lazyproperty + def adjustments(self) -> AdjustmentCollection: + """Read-only reference to |AdjustmentCollection| instance for this shape.""" + return AdjustmentCollection(self._sp.prstGeom) + + @property + def auto_shape_type(self): + """Enumeration value identifying the type of this auto shape. + + Like `MSO_SHAPE.ROUNDED_RECTANGLE`. Raises |ValueError| if this shape is not an auto shape. + """ + if not self._sp.is_autoshape: + raise ValueError("shape is not an auto shape") + return self._sp.prst + + @lazyproperty + def fill(self): + """|FillFormat| instance for this shape. + + Provides access to fill properties such as fill color. + """ + return FillFormat.from_fill_parent(self._sp.spPr) + + def get_or_add_ln(self): + """Return the `a:ln` element containing the line format properties XML for this shape.""" + return self._sp.get_or_add_ln() + + @property + def has_text_frame(self) -> bool: + """|True| if this shape can contain text. Always |True| for an AutoShape.""" + return True + + @lazyproperty + def line(self): + """|LineFormat| instance for this shape. + + Provides access to line properties such as line color. + """ + return LineFormat(self) + + @property + def ln(self): + """The `a:ln` element containing the line format properties such as line color and width. + + |None| if no `a:ln` element is present. + """ + return self._sp.ln + + @property + def shape_type(self) -> MSO_SHAPE_TYPE: + """Unique integer identifying the type of this shape, like `MSO_SHAPE_TYPE.TEXT_BOX`.""" + if self.is_placeholder: + return MSO_SHAPE_TYPE.PLACEHOLDER + if self._sp.has_custom_geometry: + return MSO_SHAPE_TYPE.FREEFORM + if self._sp.is_autoshape: + return MSO_SHAPE_TYPE.AUTO_SHAPE + if self._sp.is_textbox: + return MSO_SHAPE_TYPE.TEXT_BOX + raise NotImplementedError("Shape instance of unrecognized shape type") + + @property + def text(self) -> str: + """Read/write. Text in shape as a single string. + + The returned string will contain a newline character (`"\\n"`) separating each paragraph + and a vertical-tab (`"\\v"`) character for each line break (soft carriage return) in the + shape's text. + + Assignment to `text` replaces any text previously contained in the shape, along with any + paragraph or font formatting applied to it. A newline character (`"\\n"`) in the assigned + text causes a new paragraph to be started. A vertical-tab (`"\\v"`) character in the + assigned text causes a line-break (soft carriage-return) to be inserted. (The vertical-tab + character appears in clipboard text copied from PowerPoint as its str encoding of + line-breaks.) + """ + return self.text_frame.text + + @text.setter + def text(self, text: str): + self.text_frame.text = text + + @property + def text_frame(self): + """|TextFrame| instance for this shape. + + Contains the text of the shape and provides access to text formatting properties. + """ + txBody = self._sp.get_or_add_txBody() + return TextFrame(txBody, self) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/base.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/base.py new file mode 100644 index 0000000000000000000000000000000000000000..751235023b37130ce317b5e0898f1af20d153168 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/base.py @@ -0,0 +1,244 @@ +"""Base shape-related objects such as BaseShape.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +from pptx.action import ActionSetting +from pptx.dml.effect import ShadowFormat +from pptx.shared import ElementProxy +from pptx.util import lazyproperty + +if TYPE_CHECKING: + from pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDER + from pptx.oxml.shapes import ShapeElement + from pptx.oxml.shapes.shared import CT_Placeholder + from pptx.parts.slide import BaseSlidePart + from pptx.types import ProvidesPart + from pptx.util import Length + + +class BaseShape(object): + """Base class for shape objects. + + Subclasses include |Shape|, |Picture|, and |GraphicFrame|. + """ + + def __init__(self, shape_elm: ShapeElement, parent: ProvidesPart): + super().__init__() + self._element = shape_elm + self._parent = parent + + def __eq__(self, other: object) -> bool: + """|True| if this shape object proxies the same element as *other*. + + Equality for proxy objects is defined as referring to the same XML element, whether or not + they are the same proxy object instance. + """ + if not isinstance(other, BaseShape): + return False + return self._element is other._element + + def __ne__(self, other: object) -> bool: + if not isinstance(other, BaseShape): + return True + return self._element is not other._element + + @lazyproperty + def click_action(self) -> ActionSetting: + """|ActionSetting| instance providing access to click behaviors. + + Click behaviors are hyperlink-like behaviors including jumping to a hyperlink (web page) + or to another slide in the presentation. The click action is that defined on the overall + shape, not a run of text within the shape. An |ActionSetting| object is always returned, + even when no click behavior is defined on the shape. + """ + cNvPr = self._element._nvXxPr.cNvPr # pyright: ignore[reportPrivateUsage] + return ActionSetting(cNvPr, self) + + @property + def element(self) -> ShapeElement: + """`lxml` element for this shape, e.g. a CT_Shape instance. + + Note that manipulating this element improperly can produce an invalid presentation file. + Make sure you know what you're doing if you use this to change the underlying XML. + """ + return self._element + + @property + def has_chart(self) -> bool: + """|True| if this shape is a graphic frame containing a chart object. + + |False| otherwise. When |True|, the chart object can be accessed using the ``.chart`` + property. + """ + # This implementation is unconditionally False, the True version is + # on GraphicFrame subclass. + return False + + @property + def has_table(self) -> bool: + """|True| if this shape is a graphic frame containing a table object. + + |False| otherwise. When |True|, the table object can be accessed using the ``.table`` + property. + """ + # This implementation is unconditionally False, the True version is + # on GraphicFrame subclass. + return False + + @property + def has_text_frame(self) -> bool: + """|True| if this shape can contain text.""" + # overridden on Shape to return True. Only has text frame + return False + + @property + def height(self) -> Length: + """Read/write. Integer distance between top and bottom extents of shape in EMUs.""" + return self._element.cy + + @height.setter + def height(self, value: Length): + self._element.cy = value + + @property + def is_placeholder(self) -> bool: + """True if this shape is a placeholder. + + A shape is a placeholder if it has a element. + """ + return self._element.has_ph_elm + + @property + def left(self) -> Length: + """Integer distance of the left edge of this shape from the left edge of the slide. + + Read/write. Expressed in English Metric Units (EMU) + """ + return self._element.x + + @left.setter + def left(self, value: Length): + self._element.x = value + + @property + def name(self) -> str: + """Name of this shape, e.g. 'Picture 7'.""" + return self._element.shape_name + + @name.setter + def name(self, value: str): + self._element._nvXxPr.cNvPr.name = value # pyright: ignore[reportPrivateUsage] + + @property + def part(self) -> BaseSlidePart: + """The package part containing this shape. + + A |BaseSlidePart| subclass in this case. Access to a slide part should only be required if + you are extending the behavior of |pp| API objects. + """ + return cast("BaseSlidePart", self._parent.part) + + @property + def placeholder_format(self) -> _PlaceholderFormat: + """Provides access to placeholder-specific properties such as placeholder type. + + Raises |ValueError| on access if the shape is not a placeholder. + """ + ph = self._element.ph + if ph is None: + raise ValueError("shape is not a placeholder") + return _PlaceholderFormat(ph) + + @property + def rotation(self) -> float: + """Degrees of clockwise rotation. + + Read/write float. Negative values can be assigned to indicate counter-clockwise rotation, + e.g. assigning -45.0 will change setting to 315.0. + """ + return self._element.rot + + @rotation.setter + def rotation(self, value: float): + self._element.rot = value + + @lazyproperty + def shadow(self) -> ShadowFormat: + """|ShadowFormat| object providing access to shadow for this shape. + + A |ShadowFormat| object is always returned, even when no shadow is + explicitly defined on this shape (i.e. it inherits its shadow + behavior). + """ + return ShadowFormat(self._element.spPr) + + @property + def shape_id(self) -> int: + """Read-only positive integer identifying this shape. + + The id of a shape is unique among all shapes on a slide. + """ + return self._element.shape_id + + @property + def shape_type(self) -> MSO_SHAPE_TYPE: + """A member of MSO_SHAPE_TYPE classifying this shape by type. + + Like ``MSO_SHAPE_TYPE.CHART``. Must be implemented by subclasses. + """ + raise NotImplementedError(f"{type(self).__name__} does not implement `.shape_type`") + + @property + def top(self) -> Length: + """Distance from the top edge of the slide to the top edge of this shape. + + Read/write. Expressed in English Metric Units (EMU) + """ + return self._element.y + + @top.setter + def top(self, value: Length): + self._element.y = value + + @property + def width(self) -> Length: + """Distance between left and right extents of this shape. + + Read/write. Expressed in English Metric Units (EMU). + """ + return self._element.cx + + @width.setter + def width(self, value: Length): + self._element.cx = value + + +class _PlaceholderFormat(ElementProxy): + """Provides properties specific to placeholders, such as the placeholder type. + + Accessed via the :attr:`~.BaseShape.placeholder_format` property of a placeholder shape, + """ + + def __init__(self, element: CT_Placeholder): + super().__init__(element) + self._ph = element + + @property + def element(self) -> CT_Placeholder: + """The `p:ph` element proxied by this object.""" + return self._ph + + @property + def idx(self) -> int: + """Integer placeholder 'idx' attribute.""" + return self._ph.idx + + @property + def type(self) -> PP_PLACEHOLDER: + """Placeholder type. + + A member of the :ref:`PpPlaceholderType` enumeration, e.g. PP_PLACEHOLDER.CHART + """ + return self._ph.type diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/connector.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/connector.py new file mode 100644 index 0000000000000000000000000000000000000000..070b080d53be19df81b6d71d65f0e5b11c92e561 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/connector.py @@ -0,0 +1,297 @@ +"""Connector (line) shape and related objects. + +A connector is a line shape having end-points that can be connected to other +objects (but not to other connectors). A connector can be straight, have +elbows, or can be curved. +""" + +from __future__ import annotations + +from pptx.dml.line import LineFormat +from pptx.enum.shapes import MSO_SHAPE_TYPE +from pptx.shapes.base import BaseShape +from pptx.util import Emu, lazyproperty + + +class Connector(BaseShape): + """Connector (line) shape. + + A connector is a linear shape having end-points that can be connected to + other objects (but not to other connectors). A connector can be straight, + have elbows, or can be curved. + """ + + def begin_connect(self, shape, cxn_pt_idx): + """ + **EXPERIMENTAL** - *The current implementation only works properly + with rectangular shapes, such as pictures and rectangles. Use with + other shape types may cause unexpected visual alignment of the + connected end-point and could lead to a load error if cxn_pt_idx + exceeds the connection point count available on the connected shape. + That said, a quick test should reveal what to expect when using this + method with other shape types.* + + Connect the beginning of this connector to *shape* at the connection + point specified by *cxn_pt_idx*. Each shape has zero or more + connection points and they are identified by index, starting with 0. + Generally, the first connection point of a shape is at the top center + of its bounding box and numbering proceeds counter-clockwise from + there. However this is only a convention and may vary, especially + with non built-in shapes. + """ + self._connect_begin_to(shape, cxn_pt_idx) + self._move_begin_to_cxn(shape, cxn_pt_idx) + + @property + def begin_x(self): + """ + Return the X-position of the begin point of this connector, in + English Metric Units (as a |Length| object). + """ + cxnSp = self._element + x, cx, flipH = cxnSp.x, cxnSp.cx, cxnSp.flipH + begin_x = x + cx if flipH else x + return Emu(begin_x) + + @begin_x.setter + def begin_x(self, value): + cxnSp = self._element + x, cx, flipH, new_x = cxnSp.x, cxnSp.cx, cxnSp.flipH, int(value) + + if flipH: + old_x = x + cx + dx = abs(new_x - old_x) + if new_x >= old_x: + cxnSp.cx = cx + dx + elif dx <= cx: + cxnSp.cx = cx - dx + else: + cxnSp.flipH = False + cxnSp.x = new_x + cxnSp.cx = dx - cx + else: + dx = abs(new_x - x) + if new_x <= x: + cxnSp.x = new_x + cxnSp.cx = cx + dx + elif dx <= cx: + cxnSp.x = new_x + cxnSp.cx = cx - dx + else: + cxnSp.flipH = True + cxnSp.x = x + cx + cxnSp.cx = dx - cx + + @property + def begin_y(self): + """ + Return the Y-position of the begin point of this connector, in + English Metric Units (as a |Length| object). + """ + cxnSp = self._element + y, cy, flipV = cxnSp.y, cxnSp.cy, cxnSp.flipV + begin_y = y + cy if flipV else y + return Emu(begin_y) + + @begin_y.setter + def begin_y(self, value): + cxnSp = self._element + y, cy, flipV, new_y = cxnSp.y, cxnSp.cy, cxnSp.flipV, int(value) + + if flipV: + old_y = y + cy + dy = abs(new_y - old_y) + if new_y >= old_y: + cxnSp.cy = cy + dy + elif dy <= cy: + cxnSp.cy = cy - dy + else: + cxnSp.flipV = False + cxnSp.y = new_y + cxnSp.cy = dy - cy + else: + dy = abs(new_y - y) + if new_y <= y: + cxnSp.y = new_y + cxnSp.cy = cy + dy + elif dy <= cy: + cxnSp.y = new_y + cxnSp.cy = cy - dy + else: + cxnSp.flipV = True + cxnSp.y = y + cy + cxnSp.cy = dy - cy + + def end_connect(self, shape, cxn_pt_idx): + """ + **EXPERIMENTAL** - *The current implementation only works properly + with rectangular shapes, such as pictures and rectangles. Use with + other shape types may cause unexpected visual alignment of the + connected end-point and could lead to a load error if cxn_pt_idx + exceeds the connection point count available on the connected shape. + That said, a quick test should reveal what to expect when using this + method with other shape types.* + + Connect the ending of this connector to *shape* at the connection + point specified by *cxn_pt_idx*. + """ + self._connect_end_to(shape, cxn_pt_idx) + self._move_end_to_cxn(shape, cxn_pt_idx) + + @property + def end_x(self): + """ + Return the X-position of the end point of this connector, in English + Metric Units (as a |Length| object). + """ + cxnSp = self._element + x, cx, flipH = cxnSp.x, cxnSp.cx, cxnSp.flipH + end_x = x if flipH else x + cx + return Emu(end_x) + + @end_x.setter + def end_x(self, value): + cxnSp = self._element + x, cx, flipH, new_x = cxnSp.x, cxnSp.cx, cxnSp.flipH, int(value) + + if flipH: + dx = abs(new_x - x) + if new_x <= x: + cxnSp.x = new_x + cxnSp.cx = cx + dx + elif dx <= cx: + cxnSp.x = new_x + cxnSp.cx = cx - dx + else: + cxnSp.flipH = False + cxnSp.x = x + cx + cxnSp.cx = dx - cx + else: + old_x = x + cx + dx = abs(new_x - old_x) + if new_x >= old_x: + cxnSp.cx = cx + dx + elif dx <= cx: + cxnSp.cx = cx - dx + else: + cxnSp.flipH = True + cxnSp.x = new_x + cxnSp.cx = dx - cx + + @property + def end_y(self): + """ + Return the Y-position of the end point of this connector, in English + Metric Units (as a |Length| object). + """ + cxnSp = self._element + y, cy, flipV = cxnSp.y, cxnSp.cy, cxnSp.flipV + end_y = y if flipV else y + cy + return Emu(end_y) + + @end_y.setter + def end_y(self, value): + cxnSp = self._element + y, cy, flipV, new_y = cxnSp.y, cxnSp.cy, cxnSp.flipV, int(value) + + if flipV: + dy = abs(new_y - y) + if new_y <= y: + cxnSp.y = new_y + cxnSp.cy = cy + dy + elif dy <= cy: + cxnSp.y = new_y + cxnSp.cy = cy - dy + else: + cxnSp.flipV = False + cxnSp.y = y + cy + cxnSp.cy = dy - cy + else: + old_y = y + cy + dy = abs(new_y - old_y) + if new_y >= old_y: + cxnSp.cy = cy + dy + elif dy <= cy: + cxnSp.cy = cy - dy + else: + cxnSp.flipV = True + cxnSp.y = new_y + cxnSp.cy = dy - cy + + def get_or_add_ln(self): + """Helper method required by |LineFormat|.""" + return self._element.spPr.get_or_add_ln() + + @lazyproperty + def line(self): + """|LineFormat| instance for this connector. + + Provides access to line properties such as line color, width, and + line style. + """ + return LineFormat(self) + + @property + def ln(self): + """Helper method required by |LineFormat|. + + The ```` element containing the line format properties such as + line color and width. |None| if no `` element is present. + """ + return self._element.spPr.ln + + @property + def shape_type(self): + """Member of `MSO_SHAPE_TYPE` identifying the type of this shape. + + Unconditionally `MSO_SHAPE_TYPE.LINE` for a `Connector` object. + """ + return MSO_SHAPE_TYPE.LINE + + def _connect_begin_to(self, shape, cxn_pt_idx): + """ + Add or update a stCxn element for this connector that connects its + begin point to the connection point of *shape* specified by + *cxn_pt_idx*. + """ + cNvCxnSpPr = self._element.nvCxnSpPr.cNvCxnSpPr + stCxn = cNvCxnSpPr.get_or_add_stCxn() + stCxn.id = shape.shape_id + stCxn.idx = cxn_pt_idx + + def _connect_end_to(self, shape, cxn_pt_idx): + """ + Add or update an endCxn element for this connector that connects its + end point to the connection point of *shape* specified by + *cxn_pt_idx*. + """ + cNvCxnSpPr = self._element.nvCxnSpPr.cNvCxnSpPr + endCxn = cNvCxnSpPr.get_or_add_endCxn() + endCxn.id = shape.shape_id + endCxn.idx = cxn_pt_idx + + def _move_begin_to_cxn(self, shape, cxn_pt_idx): + """ + Move the begin point of this connector to coordinates of the + connection point of *shape* specified by *cxn_pt_idx*. + """ + x, y, cx, cy = shape.left, shape.top, shape.width, shape.height + self.begin_x, self.begin_y = { + 0: (int(x + cx / 2), y), + 1: (x, int(y + cy / 2)), + 2: (int(x + cx / 2), y + cy), + 3: (x + cx, int(y + cy / 2)), + }[cxn_pt_idx] + + def _move_end_to_cxn(self, shape, cxn_pt_idx): + """ + Move the end point of this connector to the coordinates of the + connection point of *shape* specified by *cxn_pt_idx*. + """ + x, y, cx, cy = shape.left, shape.top, shape.width, shape.height + self.end_x, self.end_y = { + 0: (int(x + cx / 2), y), + 1: (x, int(y + cy / 2)), + 2: (int(x + cx / 2), y + cy), + 3: (x + cx, int(y + cy / 2)), + }[cxn_pt_idx] diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/freeform.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/freeform.py new file mode 100644 index 0000000000000000000000000000000000000000..e05b3484fc7407b2b06edf8c500bbbba9de58bdd --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/freeform.py @@ -0,0 +1,338 @@ +"""Objects related to construction of freeform shapes.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING, Iterable, Iterator + +from pptx.util import Emu, lazyproperty + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + + from pptx.oxml.shapes.autoshape import ( + CT_Path2D, + CT_Path2DClose, + CT_Path2DLineTo, + CT_Path2DMoveTo, + CT_Shape, + ) + from pptx.shapes.shapetree import _BaseGroupShapes # pyright: ignore[reportPrivateUsage] + from pptx.util import Length + +CT_DrawingOperation: TypeAlias = "CT_Path2DClose | CT_Path2DLineTo | CT_Path2DMoveTo" +DrawingOperation: TypeAlias = "_LineSegment | _MoveTo | _Close" + + +class FreeformBuilder(Sequence[DrawingOperation]): + """Allows a freeform shape to be specified and created. + + The initial pen position is provided on construction. From there, drawing proceeds using + successive calls to draw line segments. The freeform shape may be closed by calling the + :meth:`close` method. + + A shape may have more than one contour, in which case overlapping areas are "subtracted". A + contour is a sequence of line segments beginning with a "move-to" operation. A move-to + operation is automatically inserted in each new freeform; additional move-to ops can be + inserted with the `.move_to()` method. + """ + + def __init__( + self, + shapes: _BaseGroupShapes, + start_x: Length, + start_y: Length, + x_scale: float, + y_scale: float, + ): + super(FreeformBuilder, self).__init__() + self._shapes = shapes + self._start_x = start_x + self._start_y = start_y + self._x_scale = x_scale + self._y_scale = y_scale + + def __getitem__( # pyright: ignore[reportIncompatibleMethodOverride] + self, idx: int + ) -> DrawingOperation: + return self._drawing_operations.__getitem__(idx) + + def __iter__(self) -> Iterator[DrawingOperation]: + return self._drawing_operations.__iter__() + + def __len__(self): + return self._drawing_operations.__len__() + + @classmethod + def new( + cls, + shapes: _BaseGroupShapes, + start_x: float, + start_y: float, + x_scale: float, + y_scale: float, + ): + """Return a new |FreeformBuilder| object. + + The initial pen location is specified (in local coordinates) by + (`start_x`, `start_y`). + """ + return cls(shapes, Emu(int(round(start_x))), Emu(int(round(start_y))), x_scale, y_scale) + + def add_line_segments(self, vertices: Iterable[tuple[float, float]], close: bool = True): + """Add a straight line segment to each point in `vertices`. + + `vertices` must be an iterable of (x, y) pairs (2-tuples). Each x and y value is rounded + to the nearest integer before use. The optional `close` parameter determines whether the + resulting contour is `closed` or left `open`. + + Returns this |FreeformBuilder| object so it can be used in chained calls. + """ + for x, y in vertices: + self._add_line_segment(x, y) + if close: + self._add_close() + return self + + def convert_to_shape(self, origin_x: Length = Emu(0), origin_y: Length = Emu(0)): + """Return new freeform shape positioned relative to specified offset. + + `origin_x` and `origin_y` locate the origin of the local coordinate system in slide + coordinates (EMU), perhaps most conveniently by use of a |Length| object. + + Note that this method may be called more than once to add multiple shapes of the same + geometry in different locations on the slide. + """ + sp = self._add_freeform_sp(origin_x, origin_y) + path = self._start_path(sp) + for drawing_operation in self: + drawing_operation.apply_operation_to(path) + return self._shapes._shape_factory(sp) # pyright: ignore[reportPrivateUsage] + + def move_to(self, x: float, y: float): + """Move pen to (x, y) (local coordinates) without drawing line. + + Returns this |FreeformBuilder| object so it can be used in chained calls. + """ + self._drawing_operations.append(_MoveTo.new(self, x, y)) + return self + + @property + def shape_offset_x(self) -> Length: + """Return x distance of shape origin from local coordinate origin. + + The returned integer represents the leftmost extent of the freeform shape, in local + coordinates. Note that the bounding box of the shape need not start at the local origin. + """ + min_x = self._start_x + for drawing_operation in self: + if isinstance(drawing_operation, _Close): + continue + min_x = min(min_x, drawing_operation.x) + return Emu(min_x) + + @property + def shape_offset_y(self) -> Length: + """Return y distance of shape origin from local coordinate origin. + + The returned integer represents the topmost extent of the freeform shape, in local + coordinates. Note that the bounding box of the shape need not start at the local origin. + """ + min_y = self._start_y + for drawing_operation in self: + if isinstance(drawing_operation, _Close): + continue + min_y = min(min_y, drawing_operation.y) + return Emu(min_y) + + def _add_close(self): + """Add a close |_Close| operation to the drawing sequence.""" + self._drawing_operations.append(_Close.new()) + + def _add_freeform_sp(self, origin_x: Length, origin_y: Length): + """Add a freeform `p:sp` element having no drawing elements. + + `origin_x` and `origin_y` are specified in slide coordinates, and represent the location + of the local coordinates origin on the slide. + """ + spTree = self._shapes._spTree # pyright: ignore[reportPrivateUsage] + return spTree.add_freeform_sp( + origin_x + self._left, origin_y + self._top, self._width, self._height + ) + + def _add_line_segment(self, x: float, y: float) -> None: + """Add a |_LineSegment| operation to the drawing sequence.""" + self._drawing_operations.append(_LineSegment.new(self, x, y)) + + @lazyproperty + def _drawing_operations(self) -> list[DrawingOperation]: + """Return the sequence of drawing operation objects for freeform.""" + return [] + + @property + def _dx(self) -> Length: + """Return width of this shape's path in local units.""" + min_x = max_x = self._start_x + for drawing_operation in self: + if isinstance(drawing_operation, _Close): + continue + min_x = min(min_x, drawing_operation.x) + max_x = max(max_x, drawing_operation.x) + return Emu(max_x - min_x) + + @property + def _dy(self) -> Length: + """Return integer height of this shape's path in local units.""" + min_y = max_y = self._start_y + for drawing_operation in self: + if isinstance(drawing_operation, _Close): + continue + min_y = min(min_y, drawing_operation.y) + max_y = max(max_y, drawing_operation.y) + return Emu(max_y - min_y) + + @property + def _height(self): + """Return vertical size of this shape's path in slide coordinates. + + This value is based on the actual extents of the shape and does not include any + positioning offset. + """ + return int(round(self._dy * self._y_scale)) + + @property + def _left(self): + """Return leftmost extent of this shape's path in slide coordinates. + + Note that this value does not include any positioning offset; it assumes the drawing + (local) coordinate origin is at (0, 0) on the slide. + """ + return int(round(self.shape_offset_x * self._x_scale)) + + def _local_to_shape(self, local_x: Length, local_y: Length) -> tuple[Length, Length]: + """Translate local coordinates point to shape coordinates. + + Shape coordinates have the same unit as local coordinates, but are offset such that the + origin of the shape coordinate system (0, 0) is located at the top-left corner of the + shape bounding box. + """ + return Emu(local_x - self.shape_offset_x), Emu(local_y - self.shape_offset_y) + + def _start_path(self, sp: CT_Shape) -> CT_Path2D: + """Return a newly created `a:path` element added to `sp`. + + The returned `a:path` element has an `a:moveTo` element representing the shape starting + point as its only child. + """ + path = sp.add_path(w=self._dx, h=self._dy) + path.add_moveTo(*self._local_to_shape(self._start_x, self._start_y)) + return path + + @property + def _top(self): + """Return topmost extent of this shape's path in slide coordinates. + + Note that this value does not include any positioning offset; it assumes the drawing + (local) coordinate origin is located at slide coordinates (0, 0) (top-left corner of + slide). + """ + return int(round(self.shape_offset_y * self._y_scale)) + + @property + def _width(self): + """Return width of this shape's path in slide coordinates. + + This value is based on the actual extents of the shape path and does not include any + positioning offset. + """ + return int(round(self._dx * self._x_scale)) + + +class _BaseDrawingOperation(object): + """Base class for freeform drawing operations. + + A drawing operation has at least one location (x, y) in local coordinates. + """ + + def __init__(self, freeform_builder: FreeformBuilder, x: Length, y: Length): + super(_BaseDrawingOperation, self).__init__() + self._freeform_builder = freeform_builder + self._x = x + self._y = y + + def apply_operation_to(self, path: CT_Path2D) -> CT_DrawingOperation: + """Add the XML element(s) implementing this operation to `path`. + + Must be implemented by each subclass. + """ + raise NotImplementedError("must be implemented by each subclass") + + @property + def x(self) -> Length: + """Return the horizontal (x) target location of this operation. + + The returned value is an integer in local coordinates. + """ + return self._x + + @property + def y(self) -> Length: + """Return the vertical (y) target location of this operation. + + The returned value is an integer in local coordinates. + """ + return self._y + + +class _Close(object): + """Specifies adding a `` element to the current contour.""" + + @classmethod + def new(cls) -> _Close: + """Return a new _Close object.""" + return cls() + + def apply_operation_to(self, path: CT_Path2D) -> CT_Path2DClose: + """Add `a:close` element to `path`.""" + return path.add_close() + + +class _LineSegment(_BaseDrawingOperation): + """Specifies a straight line segment ending at the specified point.""" + + @classmethod + def new(cls, freeform_builder: FreeformBuilder, x: float, y: float) -> _LineSegment: + """Return a new _LineSegment object ending at point *(x, y)*. + + Both `x` and `y` are rounded to the nearest integer before use. + """ + return cls(freeform_builder, Emu(int(round(x))), Emu(int(round(y)))) + + def apply_operation_to(self, path: CT_Path2D) -> CT_Path2DLineTo: + """Add `a:lnTo` element to `path` for this line segment. + + Returns the `a:lnTo` element newly added to the path. + """ + return path.add_lnTo( + Emu(self._x - self._freeform_builder.shape_offset_x), + Emu(self._y - self._freeform_builder.shape_offset_y), + ) + + +class _MoveTo(_BaseDrawingOperation): + """Specifies a new pen position.""" + + @classmethod + def new(cls, freeform_builder: FreeformBuilder, x: float, y: float) -> _MoveTo: + """Return a new _MoveTo object for move to point `(x, y)`. + + Both `x` and `y` are rounded to the nearest integer before use. + """ + return cls(freeform_builder, Emu(int(round(x))), Emu(int(round(y)))) + + def apply_operation_to(self, path: CT_Path2D) -> CT_Path2DMoveTo: + """Add `a:moveTo` element to `path` for this line segment.""" + return path.add_moveTo( + Emu(self._x - self._freeform_builder.shape_offset_x), + Emu(self._y - self._freeform_builder.shape_offset_y), + ) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/graphfrm.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/graphfrm.py new file mode 100644 index 0000000000000000000000000000000000000000..c0ed2bbab71d282f8d601b53a68f83add5f06b93 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/graphfrm.py @@ -0,0 +1,166 @@ +"""Graphic Frame shape and related objects. + +A graphic frame is a common container for table, chart, smart art, and media +objects. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +from pptx.enum.shapes import MSO_SHAPE_TYPE +from pptx.shapes.base import BaseShape +from pptx.shared import ParentedElementProxy +from pptx.spec import ( + GRAPHIC_DATA_URI_CHART, + GRAPHIC_DATA_URI_OLEOBJ, + GRAPHIC_DATA_URI_TABLE, +) +from pptx.table import Table +from pptx.util import lazyproperty + +if TYPE_CHECKING: + from pptx.chart.chart import Chart + from pptx.dml.effect import ShadowFormat + from pptx.oxml.shapes.graphfrm import CT_GraphicalObjectData, CT_GraphicalObjectFrame + from pptx.parts.chart import ChartPart + from pptx.parts.slide import BaseSlidePart + from pptx.types import ProvidesPart + + +class GraphicFrame(BaseShape): + """Container shape for table, chart, smart art, and media objects. + + Corresponds to a `p:graphicFrame` element in the shape tree. + """ + + def __init__(self, graphicFrame: CT_GraphicalObjectFrame, parent: ProvidesPart): + super().__init__(graphicFrame, parent) + self._graphicFrame = graphicFrame + + @property + def chart(self) -> Chart: + """The |Chart| object containing the chart in this graphic frame. + + Raises |ValueError| if this graphic frame does not contain a chart. + """ + if not self.has_chart: + raise ValueError("shape does not contain a chart") + return self.chart_part.chart + + @property + def chart_part(self) -> ChartPart: + """The |ChartPart| object containing the chart in this graphic frame.""" + chart_rId = self._graphicFrame.chart_rId + if chart_rId is None: + raise ValueError("this graphic frame does not contain a chart") + return cast("ChartPart", self.part.related_part(chart_rId)) + + @property + def has_chart(self) -> bool: + """|True| if this graphic frame contains a chart object. |False| otherwise. + + When |True|, the chart object can be accessed using the `.chart` property. + """ + return self._graphicFrame.graphicData_uri == GRAPHIC_DATA_URI_CHART + + @property + def has_table(self) -> bool: + """|True| if this graphic frame contains a table object, |False| otherwise. + + When |True|, the table object can be accessed using the `.table` property. + """ + return self._graphicFrame.graphicData_uri == GRAPHIC_DATA_URI_TABLE + + @property + def ole_format(self) -> _OleFormat: + """_OleFormat object for this graphic-frame shape. + + Raises `ValueError` on a GraphicFrame instance that does not contain an OLE object. + + An shape that contains an OLE object will have `.shape_type` of either + `EMBEDDED_OLE_OBJECT` or `LINKED_OLE_OBJECT`. + """ + if not self._graphicFrame.has_oleobj: + raise ValueError("not an OLE-object shape") + return _OleFormat(self._graphicFrame.graphicData, self._parent) + + @lazyproperty + def shadow(self) -> ShadowFormat: + """Unconditionally raises |NotImplementedError|. + + Access to the shadow effect for graphic-frame objects is content-specific (i.e. different + for charts, tables, etc.) and has not yet been implemented. + """ + raise NotImplementedError("shadow property on GraphicFrame not yet supported") + + @property + def shape_type(self) -> MSO_SHAPE_TYPE: + """Optional member of `MSO_SHAPE_TYPE` identifying the type of this shape. + + Possible values are `MSO_SHAPE_TYPE.CHART`, `MSO_SHAPE_TYPE.TABLE`, + `MSO_SHAPE_TYPE.EMBEDDED_OLE_OBJECT`, `MSO_SHAPE_TYPE.LINKED_OLE_OBJECT`. + + This value is `None` when none of these four types apply, for example when the shape + contains SmartArt. + """ + graphicData_uri = self._graphicFrame.graphicData_uri + if graphicData_uri == GRAPHIC_DATA_URI_CHART: + return MSO_SHAPE_TYPE.CHART + elif graphicData_uri == GRAPHIC_DATA_URI_TABLE: + return MSO_SHAPE_TYPE.TABLE + elif graphicData_uri == GRAPHIC_DATA_URI_OLEOBJ: + return ( + MSO_SHAPE_TYPE.EMBEDDED_OLE_OBJECT + if self._graphicFrame.is_embedded_ole_obj + else MSO_SHAPE_TYPE.LINKED_OLE_OBJECT + ) + else: + return None # pyright: ignore[reportReturnType] + + @property + def table(self) -> Table: + """The |Table| object contained in this graphic frame. + + Raises |ValueError| if this graphic frame does not contain a table. + """ + if not self.has_table: + raise ValueError("shape does not contain a table") + tbl = self._graphicFrame.graphic.graphicData.tbl + return Table(tbl, self) + + +class _OleFormat(ParentedElementProxy): + """Provides attributes on an embedded OLE object.""" + + part: BaseSlidePart # pyright: ignore[reportIncompatibleMethodOverride] + + def __init__(self, graphicData: CT_GraphicalObjectData, parent: ProvidesPart): + super().__init__(graphicData, parent) + self._graphicData = graphicData + + @property + def blob(self) -> bytes | None: + """Optional bytes of OLE object, suitable for loading or saving as a file. + + This value is `None` if the embedded object does not represent a "file". + """ + blob_rId = self._graphicData.blob_rId + if blob_rId is None: + return None + return self.part.related_part(blob_rId).blob + + @property + def prog_id(self) -> str | None: + """str "progId" attribute of this embedded OLE object. + + The progId is a str like "Excel.Sheet.12" that identifies the "file-type" of the embedded + object, or perhaps more precisely, the application (aka. "server" in OLE parlance) to be + used to open this object. + """ + return self._graphicData.progId + + @property + def show_as_icon(self) -> bool | None: + """True when OLE object should appear as an icon (rather than preview).""" + return self._graphicData.showAsIcon diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/group.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/group.py new file mode 100644 index 0000000000000000000000000000000000000000..7173758511215354c139eedb2da18cf92b96ba7d --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/group.py @@ -0,0 +1,69 @@ +"""GroupShape and related objects.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pptx.dml.effect import ShadowFormat +from pptx.enum.shapes import MSO_SHAPE_TYPE +from pptx.shapes.base import BaseShape +from pptx.util import lazyproperty + +if TYPE_CHECKING: + from pptx.action import ActionSetting + from pptx.oxml.shapes.groupshape import CT_GroupShape + from pptx.shapes.shapetree import GroupShapes + from pptx.types import ProvidesPart + + +class GroupShape(BaseShape): + """A shape that acts as a container for other shapes.""" + + def __init__(self, grpSp: CT_GroupShape, parent: ProvidesPart): + super().__init__(grpSp, parent) + self._grpSp = grpSp + + @lazyproperty + def click_action(self) -> ActionSetting: + """Unconditionally raises `TypeError`. + + A group shape cannot have a click action or hover action. + """ + raise TypeError("a group shape cannot have a click action") + + @property + def has_text_frame(self) -> bool: + """Unconditionally |False|. + + A group shape does not have a textframe and cannot itself contain text. This does not + impact the ability of shapes contained by the group to each have their own text. + """ + return False + + @lazyproperty + def shadow(self) -> ShadowFormat: + """|ShadowFormat| object representing shadow effect for this group. + + A |ShadowFormat| object is always returned, even when no shadow is explicitly defined on + this group shape (i.e. when the group inherits its shadow behavior). + """ + return ShadowFormat(self._grpSp.grpSpPr) + + @property + def shape_type(self) -> MSO_SHAPE_TYPE: + """Member of :ref:`MsoShapeType` identifying the type of this shape. + + Unconditionally `MSO_SHAPE_TYPE.GROUP` in this case + """ + return MSO_SHAPE_TYPE.GROUP + + @lazyproperty + def shapes(self) -> GroupShapes: + """|GroupShapes| object for this group. + + The |GroupShapes| object provides access to the group's member shapes and provides methods + for adding new ones. + """ + from pptx.shapes.shapetree import GroupShapes + + return GroupShapes(self._element, self) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/picture.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/picture.py new file mode 100644 index 0000000000000000000000000000000000000000..59182860d7b55078ee221ee393980706bd02b5e8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/picture.py @@ -0,0 +1,203 @@ +"""Shapes based on the `p:pic` element, including Picture and Movie.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pptx.dml.line import LineFormat +from pptx.enum.shapes import MSO_SHAPE, MSO_SHAPE_TYPE, PP_MEDIA_TYPE +from pptx.shapes.base import BaseShape +from pptx.shared import ParentedElementProxy +from pptx.util import lazyproperty + +if TYPE_CHECKING: + from pptx.oxml.shapes.picture import CT_Picture + from pptx.oxml.shapes.shared import CT_LineProperties + from pptx.types import ProvidesPart + + +class _BasePicture(BaseShape): + """Base class for shapes based on a `p:pic` element.""" + + def __init__(self, pic: CT_Picture, parent: ProvidesPart): + super(_BasePicture, self).__init__(pic, parent) + self._pic = pic + + @property + def crop_bottom(self) -> float: + """|float| representing relative portion cropped from shape bottom. + + Read/write. 1.0 represents 100%. For example, 25% is represented by 0.25. Negative values + are valid as are values greater than 1.0. + """ + return self._pic.srcRect_b + + @crop_bottom.setter + def crop_bottom(self, value: float): + self._pic.srcRect_b = value + + @property + def crop_left(self) -> float: + """|float| representing relative portion cropped from left of shape. + + Read/write. 1.0 represents 100%. A negative value extends the side beyond the image + boundary. + """ + return self._pic.srcRect_l + + @crop_left.setter + def crop_left(self, value: float): + self._pic.srcRect_l = value + + @property + def crop_right(self) -> float: + """|float| representing relative portion cropped from right of shape. + + Read/write. 1.0 represents 100%. + """ + return self._pic.srcRect_r + + @crop_right.setter + def crop_right(self, value: float): + self._pic.srcRect_r = value + + @property + def crop_top(self) -> float: + """|float| representing relative portion cropped from shape top. + + Read/write. 1.0 represents 100%. + """ + return self._pic.srcRect_t + + @crop_top.setter + def crop_top(self, value: float): + self._pic.srcRect_t = value + + def get_or_add_ln(self): + """Return the `a:ln` element for this `p:pic`-based image. + + The `a:ln` element contains the line format properties XML. + """ + return self._pic.get_or_add_ln() + + @lazyproperty + def line(self) -> LineFormat: + """Provides access to properties of the picture outline, such as its color and width.""" + return LineFormat(self) + + @property + def ln(self) -> CT_LineProperties | None: + """The `a:ln` element for this `p:pic`. + + Contains the line format properties such as line color and width. |None| if no `a:ln` + element is present. + """ + return self._pic.ln + + +class Movie(_BasePicture): + """A movie shape, one that places a video on a slide. + + Like |Picture|, a movie shape is based on the `p:pic` element. A movie is composed of a video + and a *poster frame*, the placeholder image that represents the video before it is played. + """ + + @lazyproperty + def media_format(self) -> _MediaFormat: + """The |_MediaFormat| object for this movie. + + The |_MediaFormat| object provides access to formatting properties for the movie. + """ + return _MediaFormat(self._pic, self) + + @property + def media_type(self) -> PP_MEDIA_TYPE: + """Member of :ref:`PpMediaType` describing this shape. + + The return value is unconditionally `PP_MEDIA_TYPE.MOVIE` in this case. + """ + return PP_MEDIA_TYPE.MOVIE + + @property + def poster_frame(self): + """Return |Image| object containing poster frame for this movie. + + Returns |None| if this movie has no poster frame (uncommon). + """ + slide_part, rId = self.part, self._pic.blip_rId + if rId is None: + return None + return slide_part.get_image(rId) + + @property + def shape_type(self) -> MSO_SHAPE_TYPE: + """Return member of :ref:`MsoShapeType` describing this shape. + + The return value is unconditionally `MSO_SHAPE_TYPE.MEDIA` in this + case. + """ + return MSO_SHAPE_TYPE.MEDIA + + +class Picture(_BasePicture): + """A picture shape, one that places an image on a slide. + + Based on the `p:pic` element. + """ + + @property + def auto_shape_type(self) -> MSO_SHAPE | None: + """Member of MSO_SHAPE indicating masking shape. + + A picture can be masked by any of the so-called "auto-shapes" available in PowerPoint, + such as an ellipse or triangle. When a picture is masked by a shape, the shape assumes the + same dimensions as the picture and the portion of the picture outside the shape boundaries + does not appear. Note the default value for a newly-inserted picture is + `MSO_AUTO_SHAPE_TYPE.RECTANGLE`, which performs no cropping because the extents of the + rectangle exactly correspond to the extents of the picture. + + The available shapes correspond to the members of :ref:`MsoAutoShapeType`. + + The return value can also be |None|, indicating the picture either has no geometry (not + expected) or has custom geometry, like a freeform shape. A picture with no geometry will + have no visible representation on the slide, although it can be selected. This is because + without geometry, there is no "inside-the-shape" for it to appear in. + """ + prstGeom = self._pic.spPr.prstGeom + if prstGeom is None: # ---generally means cropped with freeform--- + return None + return prstGeom.prst + + @auto_shape_type.setter + def auto_shape_type(self, member: MSO_SHAPE): + MSO_SHAPE.validate(member) + spPr = self._pic.spPr + prstGeom = spPr.prstGeom + if prstGeom is None: + spPr._remove_custGeom() # pyright: ignore[reportPrivateUsage] + prstGeom = spPr._add_prstGeom() # pyright: ignore[reportPrivateUsage] + prstGeom.prst = member + + @property + def image(self): + """The |Image| object for this picture. + + Provides access to the properties and bytes of the image in this picture shape. + """ + slide_part, rId = self.part, self._pic.blip_rId + if rId is None: + raise ValueError("no embedded image") + return slide_part.get_image(rId) + + @property + def shape_type(self) -> MSO_SHAPE_TYPE: + """Unconditionally `MSO_SHAPE_TYPE.PICTURE` in this case.""" + return MSO_SHAPE_TYPE.PICTURE + + +class _MediaFormat(ParentedElementProxy): + """Provides access to formatting properties for a Media object. + + Media format properties are things like start point, volume, and + compression type. + """ diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/placeholder.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/placeholder.py new file mode 100644 index 0000000000000000000000000000000000000000..c44837befa530583522a99a90935477d86ffdc33 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/placeholder.py @@ -0,0 +1,407 @@ +"""Placeholder-related objects. + +Specific to shapes having a `p:ph` element. A placeholder has distinct behaviors +depending on whether it appears on a slide, layout, or master. Hence there is a +non-trivial class inheritance structure. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDER +from pptx.oxml.shapes.graphfrm import CT_GraphicalObjectFrame +from pptx.oxml.shapes.picture import CT_Picture +from pptx.shapes.autoshape import Shape +from pptx.shapes.graphfrm import GraphicFrame +from pptx.shapes.picture import Picture +from pptx.util import Emu + +if TYPE_CHECKING: + from pptx.oxml.shapes.autoshape import CT_Shape + + +class _InheritsDimensions(object): + """ + Mixin class that provides inherited dimension behavior. Specifically, + left, top, width, and height report the value from the layout placeholder + where they would have otherwise reported |None|. This behavior is + distinctive to placeholders. :meth:`_base_placeholder` must be overridden + by all subclasses to provide lookup of the appropriate base placeholder + to inherit from. + """ + + @property + def height(self): + """ + The effective height of this placeholder shape; its directly-applied + height if it has one, otherwise the height of its parent layout + placeholder. + """ + return self._effective_value("height") + + @height.setter + def height(self, value): + self._element.cy = value + + @property + def left(self): + """ + The effective left of this placeholder shape; its directly-applied + left if it has one, otherwise the left of its parent layout + placeholder. + """ + return self._effective_value("left") + + @left.setter + def left(self, value): + self._element.x = value + + @property + def shape_type(self): + """ + Member of :ref:`MsoShapeType` specifying the type of this shape. + Unconditionally ``MSO_SHAPE_TYPE.PLACEHOLDER`` in this case. + Read-only. + """ + return MSO_SHAPE_TYPE.PLACEHOLDER + + @property + def top(self): + """ + The effective top of this placeholder shape; its directly-applied + top if it has one, otherwise the top of its parent layout + placeholder. + """ + return self._effective_value("top") + + @top.setter + def top(self, value): + self._element.y = value + + @property + def width(self): + """ + The effective width of this placeholder shape; its directly-applied + width if it has one, otherwise the width of its parent layout + placeholder. + """ + return self._effective_value("width") + + @width.setter + def width(self, value): + self._element.cx = value + + @property + def _base_placeholder(self): + """ + Return the layout or master placeholder shape this placeholder + inherits from. Not to be confused with an instance of + |BasePlaceholder| (necessarily). + """ + raise NotImplementedError("Must be implemented by all subclasses.") + + def _effective_value(self, attr_name): + """ + The effective value of *attr_name* on this placeholder shape; its + directly-applied value if it has one, otherwise the value on the + layout placeholder it inherits from. + """ + directly_applied_value = getattr(super(_InheritsDimensions, self), attr_name) + if directly_applied_value is not None: + return directly_applied_value + return self._inherited_value(attr_name) + + def _inherited_value(self, attr_name): + """ + Return the attribute value, e.g. 'width' of the base placeholder this + placeholder inherits from. + """ + base_placeholder = self._base_placeholder + if base_placeholder is None: + return None + inherited_value = getattr(base_placeholder, attr_name) + return inherited_value + + +class _BaseSlidePlaceholder(_InheritsDimensions, Shape): + """Base class for placeholders on slides. + + Provides common behaviors such as inherited dimensions. + """ + + @property + def is_placeholder(self): + """ + Boolean indicating whether this shape is a placeholder. + Unconditionally |True| in this case. + """ + return True + + @property + def shape_type(self): + """ + Member of :ref:`MsoShapeType` specifying the type of this shape. + Unconditionally ``MSO_SHAPE_TYPE.PLACEHOLDER`` in this case. + Read-only. + """ + return MSO_SHAPE_TYPE.PLACEHOLDER + + @property + def _base_placeholder(self): + """ + Return the layout placeholder this slide placeholder inherits from. + Not to be confused with an instance of |BasePlaceholder| + (necessarily). + """ + layout, idx = self.part.slide_layout, self._element.ph_idx + return layout.placeholders.get(idx=idx) + + def _replace_placeholder_with(self, element): + """ + Substitute *element* for this placeholder element in the shapetree. + This placeholder's `._element` attribute is set to |None| and its + original element is free for garbage collection. Any attribute access + (including a method call) on this placeholder after this call raises + |AttributeError|. + """ + element._nvXxPr.nvPr._insert_ph(self._element.ph) + self._element.addprevious(element) + self._element.getparent().remove(self._element) + self._element = None + + +class BasePlaceholder(Shape): + """ + NOTE: This class is deprecated and will be removed from a future release + along with the properties *idx*, *orient*, *ph_type*, and *sz*. The *idx* + property will be available via the .placeholder_format property. The + others will be accessed directly from the oxml layer as they are only + used for internal purposes. + + Base class for placeholder subclasses that differentiate the varying + behaviors of placeholders on a master, layout, and slide. + """ + + @property + def idx(self): + """ + Integer placeholder 'idx' attribute, e.g. 0 + """ + return self._sp.ph_idx + + @property + def orient(self): + """ + Placeholder orientation, e.g. ST_Direction.HORZ + """ + return self._sp.ph_orient + + @property + def ph_type(self): + """ + Placeholder type, e.g. PP_PLACEHOLDER.CENTER_TITLE + """ + return self._sp.ph_type + + @property + def sz(self): + """ + Placeholder 'sz' attribute, e.g. ST_PlaceholderSize.FULL + """ + return self._sp.ph_sz + + +class LayoutPlaceholder(_InheritsDimensions, Shape): + """Placeholder shape on a slide layout. + + Provides differentiated behavior for slide layout placeholders, in particular, inheriting + shape properties from the master placeholder having the same type, when a matching one exists. + """ + + element: CT_Shape # pyright: ignore[reportIncompatibleMethodOverride] + + @property + def _base_placeholder(self): + """ + Return the master placeholder this layout placeholder inherits from. + """ + base_ph_type = { + PP_PLACEHOLDER.BODY: PP_PLACEHOLDER.BODY, + PP_PLACEHOLDER.CHART: PP_PLACEHOLDER.BODY, + PP_PLACEHOLDER.BITMAP: PP_PLACEHOLDER.BODY, + PP_PLACEHOLDER.CENTER_TITLE: PP_PLACEHOLDER.TITLE, + PP_PLACEHOLDER.ORG_CHART: PP_PLACEHOLDER.BODY, + PP_PLACEHOLDER.DATE: PP_PLACEHOLDER.DATE, + PP_PLACEHOLDER.FOOTER: PP_PLACEHOLDER.FOOTER, + PP_PLACEHOLDER.MEDIA_CLIP: PP_PLACEHOLDER.BODY, + PP_PLACEHOLDER.OBJECT: PP_PLACEHOLDER.BODY, + PP_PLACEHOLDER.PICTURE: PP_PLACEHOLDER.BODY, + PP_PLACEHOLDER.SLIDE_NUMBER: PP_PLACEHOLDER.SLIDE_NUMBER, + PP_PLACEHOLDER.SUBTITLE: PP_PLACEHOLDER.BODY, + PP_PLACEHOLDER.TABLE: PP_PLACEHOLDER.BODY, + PP_PLACEHOLDER.TITLE: PP_PLACEHOLDER.TITLE, + }[self._element.ph_type] + slide_master = self.part.slide_master + return slide_master.placeholders.get(base_ph_type, None) + + +class MasterPlaceholder(BasePlaceholder): + """Placeholder shape on a slide master.""" + + element: CT_Shape # pyright: ignore[reportIncompatibleMethodOverride] + + +class NotesSlidePlaceholder(_InheritsDimensions, Shape): + """ + Placeholder shape on a notes slide. Inherits shape properties from the + placeholder on the notes master that has the same type (e.g. 'body'). + """ + + @property + def _base_placeholder(self): + """ + Return the notes master placeholder this notes slide placeholder + inherits from, or |None| if no placeholder of the matching type is + present. + """ + notes_master = self.part.notes_master + ph_type = self.element.ph_type + return notes_master.placeholders.get(ph_type=ph_type) + + +class SlidePlaceholder(_BaseSlidePlaceholder): + """ + Placeholder shape on a slide. Inherits shape properties from its + corresponding slide layout placeholder. + """ + + +class ChartPlaceholder(_BaseSlidePlaceholder): + """Placeholder shape that can only accept a chart.""" + + def insert_chart(self, chart_type, chart_data): + """ + Return a |PlaceholderGraphicFrame| object containing a new chart of + *chart_type* depicting *chart_data* and having the same position and + size as this placeholder. *chart_type* is one of the + :ref:`XlChartType` enumeration values. *chart_data* is a |ChartData| + object populated with the categories and series values for the chart. + Note that the new |Chart| object is not returned directly. The chart + object may be accessed using the + :attr:`~.PlaceholderGraphicFrame.chart` property of the returned + |PlaceholderGraphicFrame| object. + """ + rId = self.part.add_chart_part(chart_type, chart_data) + graphicFrame = self._new_chart_graphicFrame( + rId, self.left, self.top, self.width, self.height + ) + self._replace_placeholder_with(graphicFrame) + return PlaceholderGraphicFrame(graphicFrame, self._parent) + + def _new_chart_graphicFrame(self, rId, x, y, cx, cy): + """ + Return a newly created `p:graphicFrame` element having the specified + position and size and containing the chart identified by *rId*. + """ + id_, name = self.shape_id, self.name + return CT_GraphicalObjectFrame.new_chart_graphicFrame(id_, name, rId, x, y, cx, cy) + + +class PicturePlaceholder(_BaseSlidePlaceholder): + """Placeholder shape that can only accept a picture.""" + + def insert_picture(self, image_file): + """Return a |PlaceholderPicture| object depicting the image in `image_file`. + + `image_file` may be either a path (string) or a file-like object. The image is + cropped to fill the entire space of the placeholder. A |PlaceholderPicture| + object has all the properties and methods of a |Picture| shape except that the + value of its :attr:`~._BaseSlidePlaceholder.shape_type` property is + `MSO_SHAPE_TYPE.PLACEHOLDER` instead of `MSO_SHAPE_TYPE.PICTURE`. + """ + pic = self._new_placeholder_pic(image_file) + self._replace_placeholder_with(pic) + return PlaceholderPicture(pic, self._parent) + + def _new_placeholder_pic(self, image_file): + """ + Return a new `p:pic` element depicting the image in *image_file*, + suitable for use as a placeholder. In particular this means not + having an `a:xfrm` element, allowing its extents to be inherited from + its layout placeholder. + """ + rId, desc, image_size = self._get_or_add_image(image_file) + shape_id, name = self.shape_id, self.name + pic = CT_Picture.new_ph_pic(shape_id, name, desc, rId) + pic.crop_to_fit(image_size, (self.width, self.height)) + return pic + + def _get_or_add_image(self, image_file): + """ + Return an (rId, description, image_size) 3-tuple identifying the + related image part containing *image_file* and describing the image. + """ + image_part, rId = self.part.get_or_add_image_part(image_file) + desc, image_size = image_part.desc, image_part._px_size + return rId, desc, image_size + + +class PlaceholderGraphicFrame(GraphicFrame): + """ + Placeholder shape populated with a table, chart, or smart art. + """ + + @property + def is_placeholder(self): + """ + Boolean indicating whether this shape is a placeholder. + Unconditionally |True| in this case. + """ + return True + + +class PlaceholderPicture(_InheritsDimensions, Picture): + """ + Placeholder shape populated with a picture. + """ + + @property + def _base_placeholder(self): + """ + Return the layout placeholder this picture placeholder inherits from. + """ + layout, idx = self.part.slide_layout, self._element.ph_idx + return layout.placeholders.get(idx=idx) + + +class TablePlaceholder(_BaseSlidePlaceholder): + """Placeholder shape that can only accept a table.""" + + def insert_table(self, rows, cols): + """Return |PlaceholderGraphicFrame| object containing a `rows` by `cols` table. + + The position and width of the table are those of the placeholder and its height + is proportional to the number of rows. A |PlaceholderGraphicFrame| object has + all the properties and methods of a |GraphicFrame| shape except that the value + of its :attr:`~._BaseSlidePlaceholder.shape_type` property is unconditionally + `MSO_SHAPE_TYPE.PLACEHOLDER`. Note that the return value is not the new table + but rather *contains* the new table. The table can be accessed using the + :attr:`~.PlaceholderGraphicFrame.table` property of the returned + |PlaceholderGraphicFrame| object. + """ + graphicFrame = self._new_placeholder_table(rows, cols) + self._replace_placeholder_with(graphicFrame) + return PlaceholderGraphicFrame(graphicFrame, self._parent) + + def _new_placeholder_table(self, rows, cols): + """ + Return a newly added `p:graphicFrame` element containing an empty + table with *rows* rows and *cols* columns, positioned at the location + of this placeholder and having its same width. The table's height is + determined by the number of rows. + """ + shape_id, name, height = self.shape_id, self.name, Emu(rows * 370840) + return CT_GraphicalObjectFrame.new_table_graphicFrame( + shape_id, name, rows, cols, self.left, self.top, self.width, height + ) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/shapetree.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/shapetree.py new file mode 100644 index 0000000000000000000000000000000000000000..29623f1f5890f7cedc5eb5b055c31186ee240344 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/shapetree.py @@ -0,0 +1,1190 @@ +"""The shape tree, the structure that holds a slide's shapes.""" + +from __future__ import annotations + +import io +import os +from typing import IO, TYPE_CHECKING, Callable, Iterable, Iterator, cast + +from pptx.enum.shapes import PP_PLACEHOLDER, PROG_ID +from pptx.media import SPEAKER_IMAGE_BYTES, Video +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.oxml.ns import qn +from pptx.oxml.shapes.autoshape import CT_Shape +from pptx.oxml.shapes.graphfrm import CT_GraphicalObjectFrame +from pptx.oxml.shapes.picture import CT_Picture +from pptx.oxml.simpletypes import ST_Direction +from pptx.shapes.autoshape import AutoShapeType, Shape +from pptx.shapes.base import BaseShape +from pptx.shapes.connector import Connector +from pptx.shapes.freeform import FreeformBuilder +from pptx.shapes.graphfrm import GraphicFrame +from pptx.shapes.group import GroupShape +from pptx.shapes.picture import Movie, Picture +from pptx.shapes.placeholder import ( + ChartPlaceholder, + LayoutPlaceholder, + MasterPlaceholder, + NotesSlidePlaceholder, + PicturePlaceholder, + PlaceholderGraphicFrame, + PlaceholderPicture, + SlidePlaceholder, + TablePlaceholder, +) +from pptx.shared import ParentedElementProxy +from pptx.util import Emu, lazyproperty + +if TYPE_CHECKING: + from pptx.chart.chart import Chart + from pptx.chart.data import ChartData + from pptx.enum.chart import XL_CHART_TYPE + from pptx.enum.shapes import MSO_CONNECTOR_TYPE, MSO_SHAPE + from pptx.oxml.shapes import ShapeElement + from pptx.oxml.shapes.connector import CT_Connector + from pptx.oxml.shapes.groupshape import CT_GroupShape + from pptx.parts.image import ImagePart + from pptx.parts.slide import SlidePart + from pptx.slide import Slide, SlideLayout + from pptx.types import ProvidesPart + from pptx.util import Length + +# +-- _BaseShapes +# | | +# | +-- _BaseGroupShapes +# | | | +# | | +-- GroupShapes +# | | | +# | | +-- SlideShapes +# | | +# | +-- LayoutShapes +# | | +# | +-- MasterShapes +# | | +# | +-- NotesSlideShapes +# | | +# | +-- BasePlaceholders +# | | +# | +-- LayoutPlaceholders +# | | +# | +-- MasterPlaceholders +# | | +# | +-- NotesSlidePlaceholders +# | +# +-- SlidePlaceholders + + +class _BaseShapes(ParentedElementProxy): + """Base class for a shape collection appearing in a slide-type object. + + Subclasses include Slide, SlideLayout, and SlideMaster. Provides common methods. + """ + + def __init__(self, spTree: CT_GroupShape, parent: ProvidesPart): + super(_BaseShapes, self).__init__(spTree, parent) + self._spTree = spTree + self._cached_max_shape_id = None + + def __getitem__(self, idx: int) -> BaseShape: + """Return shape at `idx` in sequence, e.g. `shapes[2]`.""" + shape_elms = list(self._iter_member_elms()) + try: + shape_elm = shape_elms[idx] + except IndexError: + raise IndexError("shape index out of range") + return self._shape_factory(shape_elm) + + def __iter__(self) -> Iterator[BaseShape]: + """Generate a reference to each shape in the collection, in sequence.""" + for shape_elm in self._iter_member_elms(): + yield self._shape_factory(shape_elm) + + def __len__(self) -> int: + """Return count of shapes in this shape tree. + + A group shape contributes 1 to the total, without regard to the number of shapes contained + in the group. + """ + shape_elms = list(self._iter_member_elms()) + return len(shape_elms) + + def clone_placeholder(self, placeholder: LayoutPlaceholder) -> None: + """Add a new placeholder shape based on `placeholder`.""" + sp = placeholder.element + ph_type, orient, sz, idx = (sp.ph_type, sp.ph_orient, sp.ph_sz, sp.ph_idx) + id_ = self._next_shape_id + name = self._next_ph_name(ph_type, id_, orient) + self._spTree.add_placeholder(id_, name, ph_type, orient, sz, idx) + + def ph_basename(self, ph_type: PP_PLACEHOLDER) -> str: + """Return the base name for a placeholder of `ph_type` in this shape collection. + + There is some variance between slide types, for example a notes slide uses a different + name for the body placeholder, so this method can be overriden by subclasses. + """ + return { + PP_PLACEHOLDER.BITMAP: "ClipArt Placeholder", + PP_PLACEHOLDER.BODY: "Text Placeholder", + PP_PLACEHOLDER.CENTER_TITLE: "Title", + PP_PLACEHOLDER.CHART: "Chart Placeholder", + PP_PLACEHOLDER.DATE: "Date Placeholder", + PP_PLACEHOLDER.FOOTER: "Footer Placeholder", + PP_PLACEHOLDER.HEADER: "Header Placeholder", + PP_PLACEHOLDER.MEDIA_CLIP: "Media Placeholder", + PP_PLACEHOLDER.OBJECT: "Content Placeholder", + PP_PLACEHOLDER.ORG_CHART: "SmartArt Placeholder", + PP_PLACEHOLDER.PICTURE: "Picture Placeholder", + PP_PLACEHOLDER.SLIDE_NUMBER: "Slide Number Placeholder", + PP_PLACEHOLDER.SUBTITLE: "Subtitle", + PP_PLACEHOLDER.TABLE: "Table Placeholder", + PP_PLACEHOLDER.TITLE: "Title", + }[ph_type] + + @property + def turbo_add_enabled(self) -> bool: + """True if "turbo-add" mode is enabled. Read/Write. + + EXPERIMENTAL: This feature can radically improve performance when adding large numbers + (hundreds of shapes) to a slide. It works by caching the last shape ID used and + incrementing that value to assign the next shape id. This avoids repeatedly searching all + shape ids in the slide each time a new ID is required. + + Performance is not noticeably improved for a slide with a relatively small number of + shapes, but because the search time rises with the square of the shape count, this option + can be useful for optimizing generation of a slide composed of many shapes. + + Shape-id collisions can occur (causing a repair error on load) if more than one |Slide| + object is used to interact with the same slide in the presentation. Note that the |Slides| + collection creates a new |Slide| object each time a slide is accessed (e.g. `slide = + prs.slides[0]`, so you must be careful to limit use to a single |Slide| object. + """ + return self._cached_max_shape_id is not None + + @turbo_add_enabled.setter + def turbo_add_enabled(self, value: bool): + enable = bool(value) + self._cached_max_shape_id = self._spTree.max_shape_id if enable else None + + @staticmethod + def _is_member_elm(shape_elm: ShapeElement) -> bool: + """Return true if `shape_elm` represents a member of this collection, False otherwise.""" + return True + + def _iter_member_elms(self) -> Iterator[ShapeElement]: + """Generate each child of the `p:spTree` element that corresponds to a shape. + + Items appear in XML document order. + """ + for shape_elm in self._spTree.iter_shape_elms(): + if self._is_member_elm(shape_elm): + yield shape_elm + + def _next_ph_name(self, ph_type: PP_PLACEHOLDER, id: int, orient: str) -> str: + """Next unique placeholder name for placeholder shape of type `ph_type`. + + Usually will be standard placeholder root name suffixed with id-1, e.g. + _next_ph_name(ST_PlaceholderType.TBL, 4, 'horz') ==> 'Table Placeholder 3'. The number is + incremented as necessary to make the name unique within the collection. If `orient` is + `'vert'`, the placeholder name is prefixed with `'Vertical '`. + """ + basename = self.ph_basename(ph_type) + + # prefix rootname with 'Vertical ' if orient is 'vert' + if orient == ST_Direction.VERT: + basename = "Vertical %s" % basename + + # increment numpart as necessary to make name unique + numpart = id - 1 + names = self._spTree.xpath("//p:cNvPr/@name") + while True: + name = "%s %d" % (basename, numpart) + if name not in names: + break + numpart += 1 + + return name + + @property + def _next_shape_id(self) -> int: + """Return a unique shape id suitable for use with a new shape. + + The returned id is 1 greater than the maximum shape id used so far. In practice, the + minimum id is 2 because the spTree element is always assigned id="1". + """ + # ---presence of cached-max-shape-id indicates turbo mode is on--- + if self._cached_max_shape_id is not None: + self._cached_max_shape_id += 1 + return self._cached_max_shape_id + + return self._spTree.max_shape_id + 1 + + def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: + """Return an instance of the appropriate shape proxy class for `shape_elm`.""" + return BaseShapeFactory(shape_elm, self) + + +class _BaseGroupShapes(_BaseShapes): + """Base class for shape-trees that can add shapes.""" + + part: SlidePart # pyright: ignore[reportIncompatibleMethodOverride] + _element: CT_GroupShape + + def __init__(self, grpSp: CT_GroupShape, parent: ProvidesPart): + super(_BaseGroupShapes, self).__init__(grpSp, parent) + self._grpSp = grpSp + + def add_chart( + self, + chart_type: XL_CHART_TYPE, + x: Length, + y: Length, + cx: Length, + cy: Length, + chart_data: ChartData, + ) -> Chart: + """Add a new chart of `chart_type` to the slide. + + The chart is positioned at (`x`, `y`), has size (`cx`, `cy`), and depicts `chart_data`. + `chart_type` is one of the :ref:`XlChartType` enumeration values. `chart_data` is a + |ChartData| object populated with the categories and series values for the chart. + + Note that a |GraphicFrame| shape object is returned, not the |Chart| object contained in + that graphic frame shape. The chart object may be accessed using the :attr:`chart` + property of the returned |GraphicFrame| object. + """ + rId = self.part.add_chart_part(chart_type, chart_data) + graphicFrame = self._add_chart_graphicFrame(rId, x, y, cx, cy) + self._recalculate_extents() + return cast("Chart", self._shape_factory(graphicFrame)) + + def add_connector( + self, + connector_type: MSO_CONNECTOR_TYPE, + begin_x: Length, + begin_y: Length, + end_x: Length, + end_y: Length, + ) -> Connector: + """Add a newly created connector shape to the end of this shape tree. + + `connector_type` is a member of the :ref:`MsoConnectorType` enumeration and the end-point + values are specified as EMU values. The returned connector is of type `connector_type` and + has begin and end points as specified. + """ + cxnSp = self._add_cxnSp(connector_type, begin_x, begin_y, end_x, end_y) + self._recalculate_extents() + return cast(Connector, self._shape_factory(cxnSp)) + + def add_group_shape(self, shapes: Iterable[BaseShape] = ()) -> GroupShape: + """Return a |GroupShape| object newly appended to this shape tree. + + The group shape is empty and must be populated with shapes using methods on its shape + tree, available on its `.shapes` property. The position and extents of the group shape are + determined by the shapes it contains; its position and extents are recalculated each time + a shape is added to it. + """ + shapes = tuple(shapes) + grpSp = self._element.add_grpSp() + for shape in shapes: + grpSp.insert_element_before( + shape._element, "p:extLst" # pyright: ignore[reportPrivateUsage] + ) + if shapes: + grpSp.recalculate_extents() + return cast(GroupShape, self._shape_factory(grpSp)) + + def add_ole_object( + self, + object_file: str | IO[bytes], + prog_id: str, + left: Length, + top: Length, + width: Length | None = None, + height: Length | None = None, + icon_file: str | IO[bytes] | None = None, + icon_width: Length | None = None, + icon_height: Length | None = None, + ) -> GraphicFrame: + """Return newly-created GraphicFrame shape embedding `object_file`. + + The returned graphic-frame shape contains `object_file` as an embedded OLE object. It is + displayed as an icon at `left`, `top` with size `width`, `height`. `width` and `height` + may be omitted when `prog_id` is a member of `PROG_ID`, in which case the default icon + size is used. This is advised for best appearance where applicable because it avoids an + icon with a "stretched" appearance. + + `object_file` may either be a str path to a file or file-like object (such as + `io.BytesIO`) containing the bytes of the object to be embedded (such as an Excel file). + + `prog_id` can be either a member of `pptx.enum.shapes.PROG_ID` or a str value like + `"Adobe.Exchange.7"` determined by inspecting the XML generated by PowerPoint for an + object of the desired type. + + `icon_file` may either be a str path to an image file or a file-like object containing the + image. The image provided will be displayed in lieu of the OLE object; double-clicking on + the image opens the object (subject to operating-system limitations). The image file can + be any supported image file. Those produced by PowerPoint itself are generally EMF and can + be harvested from a PPTX package that embeds such an object. PNG and JPG also work fine. + + `icon_width` and `icon_height` are `Length` values (e.g. Emu() or Inches()) that describe + the size of the icon image within the shape. These should be omitted unless a custom + `icon_file` is provided. The dimensions must be discovered by inspecting the XML. + Automatic resizing of the OLE-object shape can occur when the icon is double-clicked if + these values are not as set by PowerPoint. This behavior may only manifest in the Windows + version of PowerPoint. + """ + graphicFrame = _OleObjectElementCreator.graphicFrame( + self, + self._next_shape_id, + object_file, + prog_id, + left, + top, + width, + height, + icon_file, + icon_width, + icon_height, + ) + self._spTree.append(graphicFrame) + self._recalculate_extents() + return cast(GraphicFrame, self._shape_factory(graphicFrame)) + + def add_picture( + self, + image_file: str | IO[bytes], + left: Length, + top: Length, + width: Length | None = None, + height: Length | None = None, + ) -> Picture: + """Add picture shape displaying image in `image_file`. + + `image_file` can be either a path to a file (a string) or a file-like object. The picture + is positioned with its top-left corner at (`top`, `left`). If `width` and `height` are + both |None|, the native size of the image is used. If only one of `width` or `height` is + used, the unspecified dimension is calculated to preserve the aspect ratio of the image. + If both are specified, the picture is stretched to fit, without regard to its native + aspect ratio. + """ + image_part, rId = self.part.get_or_add_image_part(image_file) + pic = self._add_pic_from_image_part(image_part, rId, left, top, width, height) + self._recalculate_extents() + return cast(Picture, self._shape_factory(pic)) + + def add_shape( + self, autoshape_type_id: MSO_SHAPE, left: Length, top: Length, width: Length, height: Length + ) -> Shape: + """Return new |Shape| object appended to this shape tree. + + `autoshape_type_id` is a member of :ref:`MsoAutoShapeType` e.g. `MSO_SHAPE.RECTANGLE` + specifying the type of shape to be added. The remaining arguments specify the new shape's + position and size. + """ + autoshape_type = AutoShapeType(autoshape_type_id) + sp = self._add_sp(autoshape_type, left, top, width, height) + self._recalculate_extents() + return cast(Shape, self._shape_factory(sp)) + + def add_textbox(self, left: Length, top: Length, width: Length, height: Length) -> Shape: + """Return newly added text box shape appended to this shape tree. + + The text box is of the specified size, located at the specified position on the slide. + """ + sp = self._add_textbox_sp(left, top, width, height) + self._recalculate_extents() + return cast(Shape, self._shape_factory(sp)) + + def build_freeform( + self, start_x: float = 0, start_y: float = 0, scale: tuple[float, float] | float = 1.0 + ) -> FreeformBuilder: + """Return |FreeformBuilder| object to specify a freeform shape. + + The optional `start_x` and `start_y` arguments specify the starting pen position in local + coordinates. They will be rounded to the nearest integer before use and each default to + zero. + + The optional `scale` argument specifies the size of local coordinates proportional to + slide coordinates (EMU). If the vertical scale is different than the horizontal scale + (local coordinate units are "rectangular"), a pair of numeric values can be provided as + the `scale` argument, e.g. `scale=(1.0, 2.0)`. In this case the first number is + interpreted as the horizontal (X) scale and the second as the vertical (Y) scale. + + A convenient method for calculating scale is to divide a |Length| object by an equivalent + count of local coordinate units, e.g. `scale = Inches(1)/1000` for 1000 local units per + inch. + """ + x_scale, y_scale = scale if isinstance(scale, tuple) else (scale, scale) + + return FreeformBuilder.new(self, start_x, start_y, x_scale, y_scale) + + def index(self, shape: BaseShape) -> int: + """Return the index of `shape` in this sequence. + + Raises |ValueError| if `shape` is not in the collection. + """ + shape_elms = list(self._element.iter_shape_elms()) + return shape_elms.index(shape.element) + + def _add_chart_graphicFrame( + self, rId: str, x: Length, y: Length, cx: Length, cy: Length + ) -> CT_GraphicalObjectFrame: + """Return new `p:graphicFrame` element appended to this shape tree. + + The `p:graphicFrame` element has the specified position and size and refers to the chart + part identified by `rId`. + """ + shape_id = self._next_shape_id + name = "Chart %d" % (shape_id - 1) + graphicFrame = CT_GraphicalObjectFrame.new_chart_graphicFrame( + shape_id, name, rId, x, y, cx, cy + ) + self._spTree.append(graphicFrame) + return graphicFrame + + def _add_cxnSp( + self, + connector_type: MSO_CONNECTOR_TYPE, + begin_x: Length, + begin_y: Length, + end_x: Length, + end_y: Length, + ) -> CT_Connector: + """Return a newly-added `p:cxnSp` element as specified. + + The `p:cxnSp` element is for a connector of `connector_type` beginning at (`begin_x`, + `begin_y`) and extending to (`end_x`, `end_y`). + """ + id_ = self._next_shape_id + name = "Connector %d" % (id_ - 1) + + flipH, flipV = begin_x > end_x, begin_y > end_y + x, y = min(begin_x, end_x), min(begin_y, end_y) + cx, cy = abs(end_x - begin_x), abs(end_y - begin_y) + + return self._element.add_cxnSp(id_, name, connector_type, x, y, cx, cy, flipH, flipV) + + def _add_pic_from_image_part( + self, + image_part: ImagePart, + rId: str, + x: Length, + y: Length, + cx: Length | None, + cy: Length | None, + ) -> CT_Picture: + """Return a newly appended `p:pic` element as specified. + + The `p:pic` element displays the image in `image_part` with size and position specified by + `x`, `y`, `cx`, and `cy`. The element is appended to the shape tree, causing it to be + displayed first in z-order on the slide. + """ + id_ = self._next_shape_id + scaled_cx, scaled_cy = image_part.scale(cx, cy) + name = "Picture %d" % (id_ - 1) + desc = image_part.desc + pic = self._grpSp.add_pic(id_, name, desc, rId, x, y, scaled_cx, scaled_cy) + return pic + + def _add_sp( + self, autoshape_type: AutoShapeType, x: Length, y: Length, cx: Length, cy: Length + ) -> CT_Shape: + """Return newly-added `p:sp` element as specified. + + `p:sp` element is of `autoshape_type` at position (`x`, `y`) and of size (`cx`, `cy`). + """ + id_ = self._next_shape_id + name = "%s %d" % (autoshape_type.basename, id_ - 1) + sp = self._grpSp.add_autoshape(id_, name, autoshape_type.prst, x, y, cx, cy) + return sp + + def _add_textbox_sp(self, x: Length, y: Length, cx: Length, cy: Length) -> CT_Shape: + """Return newly-appended textbox `p:sp` element. + + Element has position (`x`, `y`) and size (`cx`, `cy`). + """ + id_ = self._next_shape_id + name = "TextBox %d" % (id_ - 1) + sp = self._spTree.add_textbox(id_, name, x, y, cx, cy) + return sp + + def _recalculate_extents(self) -> None: + """Adjust position and size to incorporate all contained shapes. + + This would typically be called when a contained shape is added, removed, or its position + or size updated. + """ + # ---default behavior is to do nothing, GroupShapes overrides to + # produce the distinctive behavior of groups and subgroups.--- + pass + + +class GroupShapes(_BaseGroupShapes): + """The sequence of child shapes belonging to a group shape. + + Note that this collection can itself contain a group shape, making this part of a recursive, + tree data structure (acyclic graph). + """ + + def _recalculate_extents(self) -> None: + """Adjust position and size to incorporate all contained shapes. + + This would typically be called when a contained shape is added, removed, or its position + or size updated. + """ + self._grpSp.recalculate_extents() + + +class SlideShapes(_BaseGroupShapes): + """Sequence of shapes appearing on a slide. + + The first shape in the sequence is the backmost in z-order and the last shape is topmost. + Supports indexed access, len(), index(), and iteration. + """ + + parent: Slide # pyright: ignore[reportIncompatibleMethodOverride] + + def add_movie( + self, + movie_file: str | IO[bytes], + left: Length, + top: Length, + width: Length, + height: Length, + poster_frame_image: str | IO[bytes] | None = None, + mime_type: str = CT.VIDEO, + ) -> GraphicFrame: + """Return newly added movie shape displaying video in `movie_file`. + + **EXPERIMENTAL.** This method has important limitations: + + * The size must be specified; no auto-scaling such as that provided by :meth:`add_picture` + is performed. + * The MIME type of the video file should be specified, e.g. 'video/mp4'. The provided + video file is not interrogated for its type. The MIME type `video/unknown` is used by + default (and works fine in tests as of this writing). + * A poster frame image must be provided, it cannot be automatically extracted from the + video file. If no poster frame is provided, the default "media loudspeaker" image will + be used. + + Return a newly added movie shape to the slide, positioned at (`left`, `top`), having size + (`width`, `height`), and containing `movie_file`. Before the video is started, + `poster_frame_image` is displayed as a placeholder for the video. + """ + movie_pic = _MoviePicElementCreator.new_movie_pic( + self, + self._next_shape_id, + movie_file, + left, + top, + width, + height, + poster_frame_image, + mime_type, + ) + self._spTree.append(movie_pic) + self._add_video_timing(movie_pic) + return cast(GraphicFrame, self._shape_factory(movie_pic)) + + def add_table( + self, rows: int, cols: int, left: Length, top: Length, width: Length, height: Length + ) -> GraphicFrame: + """Add a |GraphicFrame| object containing a table. + + The table has the specified number of `rows` and `cols` and the specified position and + size. `width` is evenly distributed between the columns of the new table. Likewise, + `height` is evenly distributed between the rows. Note that the `.table` property on the + returned |GraphicFrame| shape must be used to access the enclosed |Table| object. + """ + graphicFrame = self._add_graphicFrame_containing_table(rows, cols, left, top, width, height) + return cast(GraphicFrame, self._shape_factory(graphicFrame)) + + def clone_layout_placeholders(self, slide_layout: SlideLayout) -> None: + """Add placeholder shapes based on those in `slide_layout`. + + Z-order of placeholders is preserved. Latent placeholders (date, slide number, and footer) + are not cloned. + """ + for placeholder in slide_layout.iter_cloneable_placeholders(): + self.clone_placeholder(placeholder) + + @property + def placeholders(self) -> SlidePlaceholders: + """Sequence of placeholder shapes in this slide.""" + return self.parent.placeholders + + @property + def title(self) -> Shape | None: + """The title placeholder shape on the slide. + + |None| if the slide has no title placeholder. + """ + for elm in self._spTree.iter_ph_elms(): + if elm.ph_idx == 0: + return cast(Shape, self._shape_factory(elm)) + return None + + def _add_graphicFrame_containing_table( + self, rows: int, cols: int, x: Length, y: Length, cx: Length, cy: Length + ) -> CT_GraphicalObjectFrame: + """Return a newly added `p:graphicFrame` element containing a table as specified.""" + _id = self._next_shape_id + name = "Table %d" % (_id - 1) + graphicFrame = self._spTree.add_table(_id, name, rows, cols, x, y, cx, cy) + return graphicFrame + + def _add_video_timing(self, pic: CT_Picture) -> None: + """Add a `p:video` element under `p:sld/p:timing`. + + The element will refer to the specified `pic` element by its shape id, and cause the video + play controls to appear for that video. + """ + sld = self._spTree.xpath("/p:sld")[0] + childTnLst = sld.get_or_add_childTnLst() + childTnLst.add_video(pic.shape_id) + + def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: + """Return an instance of the appropriate shape proxy class for `shape_elm`.""" + return SlideShapeFactory(shape_elm, self) + + +class LayoutShapes(_BaseShapes): + """Sequence of shapes appearing on a slide layout. + + The first shape in the sequence is the backmost in z-order and the last shape is topmost. + Supports indexed access, len(), index(), and iteration. + """ + + def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: + """Return an instance of the appropriate shape proxy class for `shape_elm`.""" + return _LayoutShapeFactory(shape_elm, self) + + +class MasterShapes(_BaseShapes): + """Sequence of shapes appearing on a slide master. + + The first shape in the sequence is the backmost in z-order and the last shape is topmost. + Supports indexed access, len(), and iteration. + """ + + def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: + """Return an instance of the appropriate shape proxy class for `shape_elm`.""" + return _MasterShapeFactory(shape_elm, self) + + +class NotesSlideShapes(_BaseShapes): + """Sequence of shapes appearing on a notes slide. + + The first shape in the sequence is the backmost in z-order and the last shape is topmost. + Supports indexed access, len(), index(), and iteration. + """ + + def ph_basename(self, ph_type: PP_PLACEHOLDER) -> str: + """Return the base name for a placeholder of `ph_type` in this shape collection. + + A notes slide uses a different name for the body placeholder and has some unique + placeholder types, so this method overrides the default in the base class. + """ + return { + PP_PLACEHOLDER.BODY: "Notes Placeholder", + PP_PLACEHOLDER.DATE: "Date Placeholder", + PP_PLACEHOLDER.FOOTER: "Footer Placeholder", + PP_PLACEHOLDER.HEADER: "Header Placeholder", + PP_PLACEHOLDER.SLIDE_IMAGE: "Slide Image Placeholder", + PP_PLACEHOLDER.SLIDE_NUMBER: "Slide Number Placeholder", + }[ph_type] + + def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: + """Return appropriate shape object for `shape_elm` appearing on a notes slide.""" + return _NotesSlideShapeFactory(shape_elm, self) + + +class BasePlaceholders(_BaseShapes): + """Base class for placeholder collections. + + Subclasses differentiate behaviors for a master, layout, and slide. By default, placeholder + shapes are constructed using |BaseShapeFactory|. Subclasses should override + :method:`_shape_factory` to use custom placeholder classes. + """ + + @staticmethod + def _is_member_elm(shape_elm: ShapeElement) -> bool: + """True if `shape_elm` is a placeholder shape, False otherwise.""" + return shape_elm.has_ph_elm + + +class LayoutPlaceholders(BasePlaceholders): + """Sequence of |LayoutPlaceholder| instance for each placeholder shape on a slide layout.""" + + __iter__: Callable[ # pyright: ignore[reportIncompatibleMethodOverride] + [], Iterator[LayoutPlaceholder] + ] + + def get(self, idx: int, default: LayoutPlaceholder | None = None) -> LayoutPlaceholder | None: + """The first placeholder shape with matching `idx` value, or `default` if not found.""" + for placeholder in self: + if placeholder.element.ph_idx == idx: + return placeholder + return default + + def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: + """Return an instance of the appropriate shape proxy class for `shape_elm`.""" + return _LayoutShapeFactory(shape_elm, self) + + +class MasterPlaceholders(BasePlaceholders): + """Sequence of MasterPlaceholder representing the placeholder shapes on a slide master.""" + + __iter__: Callable[ # pyright: ignore[reportIncompatibleMethodOverride] + [], Iterator[MasterPlaceholder] + ] + + def get(self, ph_type: PP_PLACEHOLDER, default: MasterPlaceholder | None = None): + """Return the first placeholder shape with type `ph_type` (e.g. 'body'). + + Returns `default` if no such placeholder shape is present in the collection. + """ + for placeholder in self: + if placeholder.ph_type == ph_type: + return placeholder + return default + + def _shape_factory( # pyright: ignore[reportIncompatibleMethodOverride] + self, placeholder_elm: CT_Shape + ) -> MasterPlaceholder: + """Return an instance of the appropriate shape proxy class for `shape_elm`.""" + return cast(MasterPlaceholder, _MasterShapeFactory(placeholder_elm, self)) + + +class NotesSlidePlaceholders(MasterPlaceholders): + """Sequence of placeholder shapes on a notes slide.""" + + __iter__: Callable[ # pyright: ignore[reportIncompatibleMethodOverride] + [], Iterator[NotesSlidePlaceholder] + ] + + def _shape_factory( # pyright: ignore[reportIncompatibleMethodOverride] + self, placeholder_elm: CT_Shape + ) -> NotesSlidePlaceholder: + """Return an instance of the appropriate placeholder proxy class for `placeholder_elm`.""" + return cast(NotesSlidePlaceholder, _NotesSlideShapeFactory(placeholder_elm, self)) + + +class SlidePlaceholders(ParentedElementProxy): + """Collection of placeholder shapes on a slide. + + Supports iteration, :func:`len`, and dictionary-style lookup on the `idx` value of the + placeholders it contains. + """ + + _element: CT_GroupShape + + def __getitem__(self, idx: int): + """Access placeholder shape having `idx`. + + Note that while this looks like list access, idx is actually a dictionary key and will + raise |KeyError| if no placeholder with that idx value is in the collection. + """ + for e in self._element.iter_ph_elms(): + if e.ph_idx == idx: + return SlideShapeFactory(e, self) + raise KeyError("no placeholder on this slide with idx == %d" % idx) + + def __iter__(self): + """Generate placeholder shapes in `idx` order.""" + ph_elms = sorted([e for e in self._element.iter_ph_elms()], key=lambda e: e.ph_idx) + return (SlideShapeFactory(e, self) for e in ph_elms) + + def __len__(self) -> int: + """Return count of placeholder shapes.""" + return len(list(self._element.iter_ph_elms())) + + +def BaseShapeFactory(shape_elm: ShapeElement, parent: ProvidesPart) -> BaseShape: + """Return an instance of the appropriate shape proxy class for `shape_elm`.""" + tag = shape_elm.tag + + if isinstance(shape_elm, CT_Picture): + videoFiles = shape_elm.xpath("./p:nvPicPr/p:nvPr/a:videoFile") + if videoFiles: + return Movie(shape_elm, parent) + return Picture(shape_elm, parent) + + shape_cls = { + qn("p:cxnSp"): Connector, + qn("p:grpSp"): GroupShape, + qn("p:sp"): Shape, + qn("p:graphicFrame"): GraphicFrame, + }.get(tag, BaseShape) + + return shape_cls(shape_elm, parent) # pyright: ignore[reportArgumentType] + + +def _LayoutShapeFactory(shape_elm: ShapeElement, parent: ProvidesPart) -> BaseShape: + """Return appropriate shape object for `shape_elm` on a slide layout.""" + if isinstance(shape_elm, CT_Shape) and shape_elm.has_ph_elm: + return LayoutPlaceholder(shape_elm, parent) + return BaseShapeFactory(shape_elm, parent) + + +def _MasterShapeFactory(shape_elm: ShapeElement, parent: ProvidesPart) -> BaseShape: + """Return appropriate shape object for `shape_elm` on a slide master.""" + if isinstance(shape_elm, CT_Shape) and shape_elm.has_ph_elm: + return MasterPlaceholder(shape_elm, parent) + return BaseShapeFactory(shape_elm, parent) + + +def _NotesSlideShapeFactory(shape_elm: ShapeElement, parent: ProvidesPart) -> BaseShape: + """Return appropriate shape object for `shape_elm` on a notes slide.""" + if isinstance(shape_elm, CT_Shape) and shape_elm.has_ph_elm: + return NotesSlidePlaceholder(shape_elm, parent) + return BaseShapeFactory(shape_elm, parent) + + +def _SlidePlaceholderFactory(shape_elm: ShapeElement, parent: ProvidesPart): + """Return a placeholder shape of the appropriate type for `shape_elm`.""" + tag = shape_elm.tag + if tag == qn("p:sp"): + Constructor = { + PP_PLACEHOLDER.BITMAP: PicturePlaceholder, + PP_PLACEHOLDER.CHART: ChartPlaceholder, + PP_PLACEHOLDER.PICTURE: PicturePlaceholder, + PP_PLACEHOLDER.TABLE: TablePlaceholder, + }.get(shape_elm.ph_type, SlidePlaceholder) + elif tag == qn("p:graphicFrame"): + Constructor = PlaceholderGraphicFrame + elif tag == qn("p:pic"): + Constructor = PlaceholderPicture + else: + Constructor = BaseShapeFactory + return Constructor(shape_elm, parent) # pyright: ignore[reportArgumentType] + + +def SlideShapeFactory(shape_elm: ShapeElement, parent: ProvidesPart) -> BaseShape: + """Return appropriate shape object for `shape_elm` on a slide.""" + if shape_elm.has_ph_elm: + return _SlidePlaceholderFactory(shape_elm, parent) + return BaseShapeFactory(shape_elm, parent) + + +class _MoviePicElementCreator(object): + """Functional service object for creating a new movie p:pic element. + + It's entire external interface is its :meth:`new_movie_pic` class method that returns a new + `p:pic` element containing the specified video. This class is not intended to be constructed + or an instance of it retained by the caller; it is a "one-shot" object, really a function + wrapped in a object such that its helper methods can be organized here. + """ + + def __init__( + self, + shapes: SlideShapes, + shape_id: int, + movie_file: str | IO[bytes], + x: Length, + y: Length, + cx: Length, + cy: Length, + poster_frame_file: str | IO[bytes] | None, + mime_type: str | None, + ): + super(_MoviePicElementCreator, self).__init__() + self._shapes = shapes + self._shape_id = shape_id + self._movie_file = movie_file + self._x, self._y, self._cx, self._cy = x, y, cx, cy + self._poster_frame_file = poster_frame_file + self._mime_type = mime_type + + @classmethod + def new_movie_pic( + cls, + shapes: SlideShapes, + shape_id: int, + movie_file: str | IO[bytes], + x: Length, + y: Length, + cx: Length, + cy: Length, + poster_frame_image: str | IO[bytes] | None, + mime_type: str | None, + ) -> CT_Picture: + """Return a new `p:pic` element containing video in `movie_file`. + + If `mime_type` is None, 'video/unknown' is used. If `poster_frame_file` is None, the + default "media loudspeaker" image is used. + """ + return cls(shapes, shape_id, movie_file, x, y, cx, cy, poster_frame_image, mime_type)._pic + + @property + def _media_rId(self) -> str: + """Return the rId of RT.MEDIA relationship to video part. + + For historical reasons, there are two relationships to the same part; one is the video rId + and the other is the media rId. + """ + return self._video_part_rIds[0] + + @lazyproperty + def _pic(self) -> CT_Picture: + """Return the new `p:pic` element referencing the video.""" + return CT_Picture.new_video_pic( + self._shape_id, + self._shape_name, + self._video_rId, + self._media_rId, + self._poster_frame_rId, + self._x, + self._y, + self._cx, + self._cy, + ) + + @lazyproperty + def _poster_frame_image_file(self) -> str | IO[bytes]: + """Return the image file for video placeholder image. + + If no poster frame file is provided, the default "media loudspeaker" image is used. + """ + poster_frame_file = self._poster_frame_file + if poster_frame_file is None: + return io.BytesIO(SPEAKER_IMAGE_BYTES) + return poster_frame_file + + @lazyproperty + def _poster_frame_rId(self) -> str: + """Return the rId of relationship to poster frame image. + + The poster frame is the image used to represent the video before it's played. + """ + _, poster_frame_rId = self._slide_part.get_or_add_image_part(self._poster_frame_image_file) + return poster_frame_rId + + @property + def _shape_name(self) -> str: + """Return the appropriate shape name for the p:pic shape. + + A movie shape is named with the base filename of the video. + """ + return self._video.filename + + @property + def _slide_part(self) -> SlidePart: + """Return SlidePart object for slide containing this movie.""" + return self._shapes.part + + @lazyproperty + def _video(self) -> Video: + """Return a |Video| object containing the movie file.""" + return Video.from_path_or_file_like(self._movie_file, self._mime_type) + + @lazyproperty + def _video_part_rIds(self) -> tuple[str, str]: + """Return the rIds for relationships to media part for video. + + This is where the media part and its relationships to the slide are actually created. + """ + media_rId, video_rId = self._slide_part.get_or_add_video_media_part(self._video) + return media_rId, video_rId + + @property + def _video_rId(self) -> str: + """Return the rId of RT.VIDEO relationship to video part. + + For historical reasons, there are two relationships to the same part; one is the video rId + and the other is the media rId. + """ + return self._video_part_rIds[1] + + +class _OleObjectElementCreator(object): + """Functional service object for creating a new OLE-object p:graphicFrame element. + + It's entire external interface is its :meth:`graphicFrame` class method that returns a new + `p:graphicFrame` element containing the specified embedded OLE-object shape. This class is not + intended to be constructed or an instance of it retained by the caller; it is a "one-shot" + object, really a function wrapped in a object such that its helper methods can be organized + here. + """ + + def __init__( + self, + shapes: _BaseGroupShapes, + shape_id: int, + ole_object_file: str | IO[bytes], + prog_id: PROG_ID | str, + x: Length, + y: Length, + cx: Length | None, + cy: Length | None, + icon_file: str | IO[bytes] | None, + icon_width: Length | None, + icon_height: Length | None, + ): + self._shapes = shapes + self._shape_id = shape_id + self._ole_object_file = ole_object_file + self._prog_id_arg = prog_id + self._x = x + self._y = y + self._cx_arg = cx + self._cy_arg = cy + self._icon_file_arg = icon_file + self._icon_width_arg = icon_width + self._icon_height_arg = icon_height + + @classmethod + def graphicFrame( + cls, + shapes: _BaseGroupShapes, + shape_id: int, + ole_object_file: str | IO[bytes], + prog_id: PROG_ID | str, + x: Length, + y: Length, + cx: Length | None, + cy: Length | None, + icon_file: str | IO[bytes] | None, + icon_width: Length | None, + icon_height: Length | None, + ) -> CT_GraphicalObjectFrame: + """Return new `p:graphicFrame` element containing embedded `ole_object_file`.""" + return cls( + shapes, + shape_id, + ole_object_file, + prog_id, + x, + y, + cx, + cy, + icon_file, + icon_width, + icon_height, + )._graphicFrame + + @lazyproperty + def _graphicFrame(self) -> CT_GraphicalObjectFrame: + """Newly-created `p:graphicFrame` element referencing embedded OLE-object.""" + return CT_GraphicalObjectFrame.new_ole_object_graphicFrame( + self._shape_id, + self._shape_name, + self._ole_object_rId, + self._progId, + self._icon_rId, + self._x, + self._y, + self._cx, + self._cy, + self._icon_width, + self._icon_height, + ) + + @lazyproperty + def _cx(self) -> Length: + """Emu object specifying width of "show-as-icon" image for OLE shape.""" + # --- a user-specified width overrides any default --- + if self._cx_arg is not None: + return self._cx_arg + + # --- the default width is specified by the PROG_ID member if prog_id is one, + # --- otherwise it gets the default icon width. + return ( + Emu(self._prog_id_arg.width) if isinstance(self._prog_id_arg, PROG_ID) else Emu(965200) + ) + + @lazyproperty + def _cy(self) -> Length: + """Emu object specifying height of "show-as-icon" image for OLE shape.""" + # --- a user-specified width overrides any default --- + if self._cy_arg is not None: + return self._cy_arg + + # --- the default height is specified by the PROG_ID member if prog_id is one, + # --- otherwise it gets the default icon height. + return ( + Emu(self._prog_id_arg.height) if isinstance(self._prog_id_arg, PROG_ID) else Emu(609600) + ) + + @lazyproperty + def _icon_height(self) -> Length: + """Vertical size of enclosed EMF icon within the OLE graphic-frame. + + This must be specified when a custom icon is used, to avoid stretching of the image and + possible undesired resizing by PowerPoint when the OLE shape is double-clicked to open it. + + The correct size can be determined by creating an example PPTX using PowerPoint and then + inspecting the XML of the OLE graphics-frame (p:oleObj.imgH). + """ + return self._icon_height_arg if self._icon_height_arg is not None else Emu(609600) + + @lazyproperty + def _icon_image_file(self) -> str | IO[bytes]: + """Reference to image file containing icon to show in lieu of this object. + + This can be either a str path or a file-like object (io.BytesIO typically). + """ + # --- a user-specified icon overrides any default --- + if self._icon_file_arg is not None: + return self._icon_file_arg + + # --- A prog_id belonging to PROG_ID gets its icon filename from there. A + # --- user-specified (str) prog_id gets the default icon. + icon_filename = ( + self._prog_id_arg.icon_filename + if isinstance(self._prog_id_arg, PROG_ID) + else "generic-icon.emf" + ) + + _thisdir = os.path.split(__file__)[0] + return os.path.abspath(os.path.join(_thisdir, "..", "templates", icon_filename)) + + @lazyproperty + def _icon_rId(self) -> str: + """str rId like "rId7" of rel to icon (image) representing OLE-object part.""" + _, rId = self._slide_part.get_or_add_image_part(self._icon_image_file) + return rId + + @lazyproperty + def _icon_width(self) -> Length: + """Width of enclosed EMF icon within the OLE graphic-frame. + + This must be specified when a custom icon is used, to avoid stretching of the image and + possible undesired resizing by PowerPoint when the OLE shape is double-clicked to open it. + """ + return self._icon_width_arg if self._icon_width_arg is not None else Emu(965200) + + @lazyproperty + def _ole_object_rId(self) -> str: + """str rId like "rId6" of relationship to embedded ole_object part. + + This is where the ole_object part and its relationship to the slide are actually created. + """ + return self._slide_part.add_embedded_ole_object_part( + self._prog_id_arg, self._ole_object_file + ) + + @lazyproperty + def _progId(self) -> str: + """str like "Excel.Sheet.12" identifying program used to open object. + + This value appears in the `progId` attribute of the `p:oleObj` element for the object. + """ + prog_id_arg = self._prog_id_arg + + # --- member of PROG_ID enumeration knows its progId keyphrase, otherwise caller + # --- has specified it explicitly (as str) + return prog_id_arg.progId if isinstance(prog_id_arg, PROG_ID) else prog_id_arg + + @lazyproperty + def _shape_name(self) -> str: + """str name like "Object 1" for the embedded ole_object shape. + + The name is formed from the prefix "Object " and the shape-id decremented by 1. + """ + return "Object %d" % (self._shape_id - 1) + + @lazyproperty + def _slide_part(self) -> SlidePart: + """SlidePart object for this slide.""" + return self._shapes.part diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/shared.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shared.py new file mode 100644 index 0000000000000000000000000000000000000000..da2a171829a47ef9f1451d3ddd4e0678c7349652 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/shared.py @@ -0,0 +1,82 @@ +"""Objects shared by pptx modules.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from pptx.opc.package import XmlPart + from pptx.oxml.xmlchemy import BaseOxmlElement + from pptx.types import ProvidesPart + + +class ElementProxy(object): + """Base class for lxml element proxy classes. + + An element proxy class is one whose primary responsibilities are fulfilled by manipulating the + attributes and child elements of an XML element. They are the most common type of class in + python-pptx other than custom element (oxml) classes. + """ + + def __init__(self, element: BaseOxmlElement): + self._element = element + + def __eq__(self, other: object) -> bool: + """Return |True| if this proxy object refers to the same oxml element as does *other*. + + ElementProxy objects are value objects and should maintain no mutable local state. + Equality for proxy objects is defined as referring to the same XML element, whether or not + they are the same proxy object instance. + """ + if not isinstance(other, ElementProxy): + return False + return self._element is other._element + + def __ne__(self, other: object) -> bool: + if not isinstance(other, ElementProxy): + return True + return self._element is not other._element + + @property + def element(self): + """The lxml element proxied by this object.""" + return self._element + + +class ParentedElementProxy(ElementProxy): + """Provides access to ancestor objects and part. + + An ancestor may occasionally be required to provide a service, such as add or drop a + relationship. Provides the :attr:`_parent` attribute to subclasses and the public + :attr:`parent` read-only property. + """ + + def __init__(self, element: BaseOxmlElement, parent: ProvidesPart): + super(ParentedElementProxy, self).__init__(element) + self._parent = parent + + @property + def parent(self): + """The ancestor proxy object to this one. + + For example, the parent of a shape is generally the |SlideShapes| object that contains it. + """ + return self._parent + + @property + def part(self) -> XmlPart: + """The package part containing this object.""" + return self._parent.part + + +class PartElementProxy(ElementProxy): + """Provides common members for proxy-objects that wrap a part's root element, e.g. `p:sld`.""" + + def __init__(self, element: BaseOxmlElement, part: XmlPart): + super(PartElementProxy, self).__init__(element) + self._part = part + + @property + def part(self) -> XmlPart: + """The package part containing this object.""" + return self._part diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/slide.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/slide.py new file mode 100644 index 0000000000000000000000000000000000000000..3b1b65d8e12f87ecb68241e97feb714a36e32afd --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/slide.py @@ -0,0 +1,498 @@ +"""Slide-related objects, including masters, layouts, and notes.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Iterator, cast + +from pptx.dml.fill import FillFormat +from pptx.enum.shapes import PP_PLACEHOLDER +from pptx.shapes.shapetree import ( + LayoutPlaceholders, + LayoutShapes, + MasterPlaceholders, + MasterShapes, + NotesSlidePlaceholders, + NotesSlideShapes, + SlidePlaceholders, + SlideShapes, +) +from pptx.shared import ElementProxy, ParentedElementProxy, PartElementProxy +from pptx.util import lazyproperty + +if TYPE_CHECKING: + from pptx.oxml.presentation import CT_SlideIdList, CT_SlideMasterIdList + from pptx.oxml.slide import ( + CT_CommonSlideData, + CT_NotesSlide, + CT_Slide, + CT_SlideLayoutIdList, + CT_SlideMaster, + ) + from pptx.parts.presentation import PresentationPart + from pptx.parts.slide import SlideLayoutPart, SlideMasterPart, SlidePart + from pptx.presentation import Presentation + from pptx.shapes.placeholder import LayoutPlaceholder, MasterPlaceholder + from pptx.shapes.shapetree import NotesSlidePlaceholder + from pptx.text.text import TextFrame + + +class _BaseSlide(PartElementProxy): + """Base class for slide objects, including masters, layouts and notes.""" + + _element: CT_Slide + + @lazyproperty + def background(self) -> _Background: + """|_Background| object providing slide background properties. + + This property returns a |_Background| object whether or not the + slide, master, or layout has an explicitly defined background. + + The same |_Background| object is returned on every call for the same + slide object. + """ + return _Background(self._element.cSld) + + @property + def name(self) -> str: + """String representing the internal name of this slide. + + Returns an empty string (`''`) if no name is assigned. Assigning an empty string or |None| + to this property causes any name to be removed. + """ + return self._element.cSld.name + + @name.setter + def name(self, value: str | None): + new_value = "" if value is None else value + self._element.cSld.name = new_value + + +class _BaseMaster(_BaseSlide): + """Base class for master objects such as |SlideMaster| and |NotesMaster|. + + Provides access to placeholders and regular shapes. + """ + + @lazyproperty + def placeholders(self) -> MasterPlaceholders: + """|MasterPlaceholders| collection of placeholder shapes in this master. + + Sequence sorted in `idx` order. + """ + return MasterPlaceholders(self._element.spTree, self) + + @lazyproperty + def shapes(self): + """ + Instance of |MasterShapes| containing sequence of shape objects + appearing on this slide. + """ + return MasterShapes(self._element.spTree, self) + + +class NotesMaster(_BaseMaster): + """Proxy for the notes master XML document. + + Provides access to shapes, the most commonly used of which are placeholders. + """ + + +class NotesSlide(_BaseSlide): + """Notes slide object. + + Provides access to slide notes placeholder and other shapes on the notes handout + page. + """ + + element: CT_NotesSlide # pyright: ignore[reportIncompatibleMethodOverride] + + def clone_master_placeholders(self, notes_master: NotesMaster) -> None: + """Selectively add placeholder shape elements from `notes_master`. + + Selected placeholder shape elements from `notes_master` are added to the shapes + collection of this notes slide. Z-order of placeholders is preserved. Certain + placeholders (header, date, footer) are not cloned. + """ + + def iter_cloneable_placeholders() -> Iterator[MasterPlaceholder]: + """Generate a reference to each cloneable placeholder in `notes_master`. + + These are the placeholders that should be cloned to a notes slide when the a new notes + slide is created. + """ + cloneable = ( + PP_PLACEHOLDER.SLIDE_IMAGE, + PP_PLACEHOLDER.BODY, + PP_PLACEHOLDER.SLIDE_NUMBER, + ) + for placeholder in notes_master.placeholders: + if placeholder.element.ph_type in cloneable: + yield placeholder + + shapes = self.shapes + for placeholder in iter_cloneable_placeholders(): + shapes.clone_placeholder(cast("LayoutPlaceholder", placeholder)) + + @property + def notes_placeholder(self) -> NotesSlidePlaceholder | None: + """the notes placeholder on this notes slide, the shape that contains the actual notes text. + + Return |None| if no notes placeholder is present; while this is probably uncommon, it can + happen if the notes master does not have a body placeholder, or if the notes placeholder + has been deleted from the notes slide. + """ + for placeholder in self.placeholders: + if placeholder.placeholder_format.type == PP_PLACEHOLDER.BODY: + return placeholder + return None + + @property + def notes_text_frame(self) -> TextFrame | None: + """The text frame of the notes placeholder on this notes slide. + + |None| if there is no notes placeholder. This is a shortcut to accommodate the common case + of simply adding "notes" text to the notes "page". + """ + notes_placeholder = self.notes_placeholder + if notes_placeholder is None: + return None + return notes_placeholder.text_frame + + @lazyproperty + def placeholders(self) -> NotesSlidePlaceholders: + """Instance of |NotesSlidePlaceholders| for this notes-slide. + + Contains the sequence of placeholder shapes in this notes slide. + """ + return NotesSlidePlaceholders(self.element.spTree, self) + + @lazyproperty + def shapes(self) -> NotesSlideShapes: + """Sequence of shape objects appearing on this notes slide.""" + return NotesSlideShapes(self._element.spTree, self) + + +class Slide(_BaseSlide): + """Slide object. Provides access to shapes and slide-level properties.""" + + part: SlidePart # pyright: ignore[reportIncompatibleMethodOverride] + + @property + def follow_master_background(self): + """|True| if this slide inherits the slide master background. + + Assigning |False| causes background inheritance from the master to be + interrupted; if there is no custom background for this slide, + a default background is added. If a custom background already exists + for this slide, assigning |False| has no effect. + + Assigning |True| causes any custom background for this slide to be + deleted and inheritance from the master restored. + """ + return self._element.bg is None + + @property + def has_notes_slide(self) -> bool: + """`True` if this slide has a notes slide, `False` otherwise. + + A notes slide is created by :attr:`.notes_slide` when one doesn't exist; use this property + to test for a notes slide without the possible side effect of creating one. + """ + return self.part.has_notes_slide + + @property + def notes_slide(self) -> NotesSlide: + """The |NotesSlide| instance for this slide. + + If the slide does not have a notes slide, one is created. The same single instance is + returned on each call. + """ + return self.part.notes_slide + + @lazyproperty + def placeholders(self) -> SlidePlaceholders: + """Sequence of placeholder shapes in this slide.""" + return SlidePlaceholders(self._element.spTree, self) + + @lazyproperty + def shapes(self) -> SlideShapes: + """Sequence of shape objects appearing on this slide.""" + return SlideShapes(self._element.spTree, self) + + @property + def slide_id(self) -> int: + """Integer value that uniquely identifies this slide within this presentation. + + The slide id does not change if the position of this slide in the slide sequence is changed + by adding, rearranging, or deleting slides. + """ + return self.part.slide_id + + @property + def slide_layout(self) -> SlideLayout: + """|SlideLayout| object this slide inherits appearance from.""" + return self.part.slide_layout + + +class Slides(ParentedElementProxy): + """Sequence of slides belonging to an instance of |Presentation|. + + Has list semantics for access to individual slides. Supports indexed access, len(), and + iteration. + """ + + part: PresentationPart # pyright: ignore[reportIncompatibleMethodOverride] + + def __init__(self, sldIdLst: CT_SlideIdList, prs: Presentation): + super(Slides, self).__init__(sldIdLst, prs) + self._sldIdLst = sldIdLst + + def __getitem__(self, idx: int) -> Slide: + """Provide indexed access, (e.g. 'slides[0]').""" + try: + sldId = self._sldIdLst.sldId_lst[idx] + except IndexError: + raise IndexError("slide index out of range") + return self.part.related_slide(sldId.rId) + + def __iter__(self) -> Iterator[Slide]: + """Support iteration, e.g. `for slide in slides:`.""" + for sldId in self._sldIdLst.sldId_lst: + yield self.part.related_slide(sldId.rId) + + def __len__(self) -> int: + """Support len() built-in function, e.g. `len(slides) == 4`.""" + return len(self._sldIdLst) + + def add_slide(self, slide_layout: SlideLayout) -> Slide: + """Return a newly added slide that inherits layout from `slide_layout`.""" + rId, slide = self.part.add_slide(slide_layout) + slide.shapes.clone_layout_placeholders(slide_layout) + self._sldIdLst.add_sldId(rId) + return slide + + def get(self, slide_id: int, default: Slide | None = None) -> Slide | None: + """Return the slide identified by int `slide_id` in this presentation. + + Returns `default` if not found. + """ + slide = self.part.get_slide(slide_id) + if slide is None: + return default + return slide + + def index(self, slide: Slide) -> int: + """Map `slide` to its zero-based position in this slide sequence. + + Raises |ValueError| on *slide* not present. + """ + for idx, this_slide in enumerate(self): + if this_slide == slide: + return idx + raise ValueError("%s is not in slide collection" % slide) + + +class SlideLayout(_BaseSlide): + """Slide layout object. + + Provides access to placeholders, regular shapes, and slide layout-level properties. + """ + + part: SlideLayoutPart # pyright: ignore[reportIncompatibleMethodOverride] + + def iter_cloneable_placeholders(self) -> Iterator[LayoutPlaceholder]: + """Generate layout-placeholders on this slide-layout that should be cloned to a new slide. + + Used when creating a new slide from this slide-layout. + """ + latent_ph_types = ( + PP_PLACEHOLDER.DATE, + PP_PLACEHOLDER.FOOTER, + PP_PLACEHOLDER.SLIDE_NUMBER, + ) + for ph in self.placeholders: + if ph.element.ph_type not in latent_ph_types: + yield ph + + @lazyproperty + def placeholders(self) -> LayoutPlaceholders: + """Sequence of placeholder shapes in this slide layout. + + Placeholders appear in `idx` order. + """ + return LayoutPlaceholders(self._element.spTree, self) + + @lazyproperty + def shapes(self) -> LayoutShapes: + """Sequence of shapes appearing on this slide layout.""" + return LayoutShapes(self._element.spTree, self) + + @property + def slide_master(self) -> SlideMaster: + """Slide master from which this slide-layout inherits properties.""" + return self.part.slide_master + + @property + def used_by_slides(self): + """Tuple of slide objects based on this slide layout.""" + # ---getting Slides collection requires going around the horn a bit--- + slides = self.part.package.presentation_part.presentation.slides + return tuple(s for s in slides if s.slide_layout == self) + + +class SlideLayouts(ParentedElementProxy): + """Sequence of slide layouts belonging to a slide-master. + + Supports indexed access, len(), iteration, index() and remove(). + """ + + part: SlideMasterPart # pyright: ignore[reportIncompatibleMethodOverride] + + def __init__(self, sldLayoutIdLst: CT_SlideLayoutIdList, parent: SlideMaster): + super(SlideLayouts, self).__init__(sldLayoutIdLst, parent) + self._sldLayoutIdLst = sldLayoutIdLst + + def __getitem__(self, idx: int) -> SlideLayout: + """Provides indexed access, e.g. `slide_layouts[2]`.""" + try: + sldLayoutId = self._sldLayoutIdLst.sldLayoutId_lst[idx] + except IndexError: + raise IndexError("slide layout index out of range") + return self.part.related_slide_layout(sldLayoutId.rId) + + def __iter__(self) -> Iterator[SlideLayout]: + """Generate each |SlideLayout| in the collection, in sequence.""" + for sldLayoutId in self._sldLayoutIdLst.sldLayoutId_lst: + yield self.part.related_slide_layout(sldLayoutId.rId) + + def __len__(self) -> int: + """Support len() built-in function, e.g. `len(slides) == 4`.""" + return len(self._sldLayoutIdLst) + + def get_by_name(self, name: str, default: SlideLayout | None = None) -> SlideLayout | None: + """Return SlideLayout object having `name`, or `default` if not found.""" + for slide_layout in self: + if slide_layout.name == name: + return slide_layout + return default + + def index(self, slide_layout: SlideLayout) -> int: + """Return zero-based index of `slide_layout` in this collection. + + Raises `ValueError` if `slide_layout` is not present in this collection. + """ + for idx, this_layout in enumerate(self): + if slide_layout == this_layout: + return idx + raise ValueError("layout not in this SlideLayouts collection") + + def remove(self, slide_layout: SlideLayout) -> None: + """Remove `slide_layout` from the collection. + + Raises ValueError when `slide_layout` is in use; a slide layout which is the basis for one + or more slides cannot be removed. + """ + # ---raise if layout is in use--- + if slide_layout.used_by_slides: + raise ValueError("cannot remove slide-layout in use by one or more slides") + + # ---target layout is identified by its index in this collection--- + target_idx = self.index(slide_layout) + + # --remove layout from p:sldLayoutIds of its master + # --this stops layout from showing up, but doesn't remove it from package + target_sldLayoutId = self._sldLayoutIdLst.sldLayoutId_lst[target_idx] + self._sldLayoutIdLst.remove(target_sldLayoutId) + + # --drop relationship from master to layout + # --this removes layout from package, along with everything (only) it refers to, + # --including images (not used elsewhere) and hyperlinks + slide_layout.slide_master.part.drop_rel(target_sldLayoutId.rId) + + +class SlideMaster(_BaseMaster): + """Slide master object. + + Provides access to slide layouts. Access to placeholders, regular shapes, and slide master-level + properties is inherited from |_BaseMaster|. + """ + + _element: CT_SlideMaster # pyright: ignore[reportIncompatibleVariableOverride] + + @lazyproperty + def slide_layouts(self) -> SlideLayouts: + """|SlideLayouts| object providing access to this slide-master's layouts.""" + return SlideLayouts(self._element.get_or_add_sldLayoutIdLst(), self) + + +class SlideMasters(ParentedElementProxy): + """Sequence of |SlideMaster| objects belonging to a presentation. + + Has list access semantics, supporting indexed access, len(), and iteration. + """ + + part: PresentationPart # pyright: ignore[reportIncompatibleMethodOverride] + + def __init__(self, sldMasterIdLst: CT_SlideMasterIdList, parent: Presentation): + super(SlideMasters, self).__init__(sldMasterIdLst, parent) + self._sldMasterIdLst = sldMasterIdLst + + def __getitem__(self, idx: int) -> SlideMaster: + """Provides indexed access, e.g. `slide_masters[2]`.""" + try: + sldMasterId = self._sldMasterIdLst.sldMasterId_lst[idx] + except IndexError: + raise IndexError("slide master index out of range") + return self.part.related_slide_master(sldMasterId.rId) + + def __iter__(self): + """Generate each |SlideMaster| instance in the collection, in sequence.""" + for smi in self._sldMasterIdLst.sldMasterId_lst: + yield self.part.related_slide_master(smi.rId) + + def __len__(self): + """Support len() built-in function, e.g. `len(slide_masters) == 4`.""" + return len(self._sldMasterIdLst) + + +class _Background(ElementProxy): + """Provides access to slide background properties. + + Note that the presence of this object does not by itself imply an + explicitly-defined background; a slide with an inherited background still + has a |_Background| object. + """ + + def __init__(self, cSld: CT_CommonSlideData): + super(_Background, self).__init__(cSld) + self._cSld = cSld + + @lazyproperty + def fill(self): + """|FillFormat| instance for this background. + + This |FillFormat| object is used to interrogate or specify the fill + of the slide background. + + Note that accessing this property is potentially destructive. A slide + background can also be specified by a background style reference and + accessing this property will remove that reference, if present, and + replace it with NoFill. This is frequently the case for a slide + master background. + + This is also the case when there is no explicitly defined background + (background is inherited); merely accessing this property will cause + the background to be set to NoFill and the inheritance link will be + interrupted. This is frequently the case for a slide background. + + Of course, if you are accessing this property in order to set the + fill, then these changes are of no consequence, but the existing + background cannot be reliably interrogated using this property unless + you have already established it is an explicit fill. + + If the background is already a fill, then accessing this property + makes no changes to the current background. + """ + bgPr = self._cSld.get_or_add_bgPr() + return FillFormat.from_fill_parent(bgPr) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/spec.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/spec.py new file mode 100644 index 0000000000000000000000000000000000000000..1e7bffb366b159ff44a30c4c8a65edda43e2bbcb --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/spec.py @@ -0,0 +1,632 @@ +"""Mappings from the ISO/IEC 29500 spec. + +Some of these are inferred from PowerPoint application behavior +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, TypedDict + +from pptx.enum.shapes import MSO_SHAPE + +GRAPHIC_DATA_URI_CHART = "http://schemas.openxmlformats.org/drawingml/2006/chart" +GRAPHIC_DATA_URI_OLEOBJ = "http://schemas.openxmlformats.org/presentationml/2006/ole" +GRAPHIC_DATA_URI_TABLE = "http://schemas.openxmlformats.org/drawingml/2006/table" + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + +AdjustmentValue: TypeAlias = tuple[str, int] + + +class ShapeSpec(TypedDict): + basename: str + avLst: tuple[AdjustmentValue, ...] + + +# ============================================================================ +# AutoShape type specs +# ============================================================================ + +autoshape_types: dict[MSO_SHAPE, ShapeSpec] = { + MSO_SHAPE.ACTION_BUTTON_BACK_OR_PREVIOUS: { + "basename": "Action Button: Back or Previous", + "avLst": (), + }, + MSO_SHAPE.ACTION_BUTTON_BEGINNING: { + "basename": "Action Button: Beginning", + "avLst": (), + }, + MSO_SHAPE.ACTION_BUTTON_CUSTOM: {"basename": "Action Button: Custom", "avLst": ()}, + MSO_SHAPE.ACTION_BUTTON_DOCUMENT: { + "basename": "Action Button: Document", + "avLst": (), + }, + MSO_SHAPE.ACTION_BUTTON_END: {"basename": "Action Button: End", "avLst": ()}, + MSO_SHAPE.ACTION_BUTTON_FORWARD_OR_NEXT: { + "basename": "Action Button: Forward or Next", + "avLst": (), + }, + MSO_SHAPE.ACTION_BUTTON_HELP: {"basename": "Action Button: Help", "avLst": ()}, + MSO_SHAPE.ACTION_BUTTON_HOME: {"basename": "Action Button: Home", "avLst": ()}, + MSO_SHAPE.ACTION_BUTTON_INFORMATION: { + "basename": "Action Button: Information", + "avLst": (), + }, + MSO_SHAPE.ACTION_BUTTON_MOVIE: {"basename": "Action Button: Movie", "avLst": ()}, + MSO_SHAPE.ACTION_BUTTON_RETURN: {"basename": "Action Button: Return", "avLst": ()}, + MSO_SHAPE.ACTION_BUTTON_SOUND: {"basename": "Action Button: Sound", "avLst": ()}, + MSO_SHAPE.ARC: {"basename": "Arc", "avLst": (("adj1", 16200000), ("adj2", 0))}, + MSO_SHAPE.BALLOON: { + "basename": "Rounded Rectangular Callout", + "avLst": (("adj1", -20833), ("adj2", 62500), ("adj3", 16667)), + }, + MSO_SHAPE.BENT_ARROW: { + "basename": "Bent Arrow", + "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 43750)), + }, + MSO_SHAPE.BENT_UP_ARROW: { + "basename": "Bent-Up Arrow", + "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000)), + }, + MSO_SHAPE.BEVEL: {"basename": "Bevel", "avLst": (("adj", 12500),)}, + MSO_SHAPE.BLOCK_ARC: { + "basename": "Block Arc", + "avLst": (("adj1", 10800000), ("adj2", 0), ("adj3", 25000)), + }, + MSO_SHAPE.CAN: {"basename": "Can", "avLst": (("adj", 25000),)}, + MSO_SHAPE.CHART_PLUS: {"basename": "Chart Plus", "avLst": ()}, + MSO_SHAPE.CHART_STAR: {"basename": "Chart Star", "avLst": ()}, + MSO_SHAPE.CHART_X: {"basename": "Chart X", "avLst": ()}, + MSO_SHAPE.CHEVRON: {"basename": "Chevron", "avLst": (("adj", 50000),)}, + MSO_SHAPE.CHORD: { + "basename": "Chord", + "avLst": (("adj1", 2700000), ("adj2", 16200000)), + }, + MSO_SHAPE.CIRCULAR_ARROW: { + "basename": "Circular Arrow", + "avLst": ( + ("adj1", 12500), + ("adj2", 1142319), + ("adj3", 20457681), + ("adj4", 10800000), + ("adj5", 12500), + ), + }, + MSO_SHAPE.CLOUD: {"basename": "Cloud", "avLst": ()}, + MSO_SHAPE.CLOUD_CALLOUT: { + "basename": "Cloud Callout", + "avLst": (("adj1", -20833), ("adj2", 62500)), + }, + MSO_SHAPE.CORNER: { + "basename": "Corner", + "avLst": (("adj1", 50000), ("adj2", 50000)), + }, + MSO_SHAPE.CORNER_TABS: {"basename": "Corner Tabs", "avLst": ()}, + MSO_SHAPE.CROSS: {"basename": "Cross", "avLst": (("adj", 25000),)}, + MSO_SHAPE.CUBE: {"basename": "Cube", "avLst": (("adj", 25000),)}, + MSO_SHAPE.CURVED_DOWN_ARROW: { + "basename": "Curved Down Arrow", + "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 25000)), + }, + MSO_SHAPE.CURVED_DOWN_RIBBON: { + "basename": "Curved Down Ribbon", + "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 12500)), + }, + MSO_SHAPE.CURVED_LEFT_ARROW: { + "basename": "Curved Left Arrow", + "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 25000)), + }, + MSO_SHAPE.CURVED_RIGHT_ARROW: { + "basename": "Curved Right Arrow", + "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 25000)), + }, + MSO_SHAPE.CURVED_UP_ARROW: { + "basename": "Curved Up Arrow", + "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 25000)), + }, + MSO_SHAPE.CURVED_UP_RIBBON: { + "basename": "Curved Up Ribbon", + "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 12500)), + }, + MSO_SHAPE.DECAGON: {"basename": "Decagon", "avLst": (("vf", 105146),)}, + MSO_SHAPE.DIAGONAL_STRIPE: { + "basename": "Diagonal Stripe", + "avLst": (("adj", 50000),), + }, + MSO_SHAPE.DIAMOND: {"basename": "Diamond", "avLst": ()}, + MSO_SHAPE.DODECAGON: {"basename": "Dodecagon", "avLst": ()}, + MSO_SHAPE.DONUT: {"basename": "Donut", "avLst": (("adj", 25000),)}, + MSO_SHAPE.DOUBLE_BRACE: {"basename": "Double Brace", "avLst": (("adj", 8333),)}, + MSO_SHAPE.DOUBLE_BRACKET: { + "basename": "Double Bracket", + "avLst": (("adj", 16667),), + }, + MSO_SHAPE.DOUBLE_WAVE: { + "basename": "Double Wave", + "avLst": (("adj1", 6250), ("adj2", 0)), + }, + MSO_SHAPE.DOWN_ARROW: { + "basename": "Down Arrow", + "avLst": (("adj1", 50000), ("adj2", 50000)), + }, + MSO_SHAPE.DOWN_ARROW_CALLOUT: { + "basename": "Down Arrow Callout", + "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 64977)), + }, + MSO_SHAPE.DOWN_RIBBON: { + "basename": "Down Ribbon", + "avLst": (("adj1", 16667), ("adj2", 50000)), + }, + MSO_SHAPE.EXPLOSION1: {"basename": "Explosion", "avLst": ()}, + MSO_SHAPE.EXPLOSION2: {"basename": "Explosion", "avLst": ()}, + MSO_SHAPE.FLOWCHART_ALTERNATE_PROCESS: { + "basename": "Alternate process", + "avLst": (), + }, + MSO_SHAPE.FLOWCHART_CARD: {"basename": "Card", "avLst": ()}, + MSO_SHAPE.FLOWCHART_COLLATE: {"basename": "Collate", "avLst": ()}, + MSO_SHAPE.FLOWCHART_CONNECTOR: {"basename": "Connector", "avLst": ()}, + MSO_SHAPE.FLOWCHART_DATA: {"basename": "Data", "avLst": ()}, + MSO_SHAPE.FLOWCHART_DECISION: {"basename": "Decision", "avLst": ()}, + MSO_SHAPE.FLOWCHART_DELAY: {"basename": "Delay", "avLst": ()}, + MSO_SHAPE.FLOWCHART_DIRECT_ACCESS_STORAGE: { + "basename": "Direct Access Storage", + "avLst": (), + }, + MSO_SHAPE.FLOWCHART_DISPLAY: {"basename": "Display", "avLst": ()}, + MSO_SHAPE.FLOWCHART_DOCUMENT: {"basename": "Document", "avLst": ()}, + MSO_SHAPE.FLOWCHART_EXTRACT: {"basename": "Extract", "avLst": ()}, + MSO_SHAPE.FLOWCHART_INTERNAL_STORAGE: {"basename": "Internal Storage", "avLst": ()}, + MSO_SHAPE.FLOWCHART_MAGNETIC_DISK: {"basename": "Magnetic Disk", "avLst": ()}, + MSO_SHAPE.FLOWCHART_MANUAL_INPUT: {"basename": "Manual Input", "avLst": ()}, + MSO_SHAPE.FLOWCHART_MANUAL_OPERATION: {"basename": "Manual Operation", "avLst": ()}, + MSO_SHAPE.FLOWCHART_MERGE: {"basename": "Merge", "avLst": ()}, + MSO_SHAPE.FLOWCHART_MULTIDOCUMENT: {"basename": "Multidocument", "avLst": ()}, + MSO_SHAPE.FLOWCHART_OFFLINE_STORAGE: {"basename": "Offline Storage", "avLst": ()}, + MSO_SHAPE.FLOWCHART_OFFPAGE_CONNECTOR: { + "basename": "Off-page Connector", + "avLst": (), + }, + MSO_SHAPE.FLOWCHART_OR: {"basename": "Or", "avLst": ()}, + MSO_SHAPE.FLOWCHART_PREDEFINED_PROCESS: { + "basename": "Predefined Process", + "avLst": (), + }, + MSO_SHAPE.FLOWCHART_PREPARATION: {"basename": "Preparation", "avLst": ()}, + MSO_SHAPE.FLOWCHART_PROCESS: {"basename": "Process", "avLst": ()}, + MSO_SHAPE.FLOWCHART_PUNCHED_TAPE: {"basename": "Punched Tape", "avLst": ()}, + MSO_SHAPE.FLOWCHART_SEQUENTIAL_ACCESS_STORAGE: { + "basename": "Sequential Access Storage", + "avLst": (), + }, + MSO_SHAPE.FLOWCHART_SORT: {"basename": "Sort", "avLst": ()}, + MSO_SHAPE.FLOWCHART_STORED_DATA: {"basename": "Stored Data", "avLst": ()}, + MSO_SHAPE.FLOWCHART_SUMMING_JUNCTION: {"basename": "Summing Junction", "avLst": ()}, + MSO_SHAPE.FLOWCHART_TERMINATOR: {"basename": "Terminator", "avLst": ()}, + MSO_SHAPE.FOLDED_CORNER: {"basename": "Folded Corner", "avLst": ()}, + MSO_SHAPE.FRAME: {"basename": "Frame", "avLst": (("adj1", 12500),)}, + MSO_SHAPE.FUNNEL: {"basename": "Funnel", "avLst": ()}, + MSO_SHAPE.GEAR_6: { + "basename": "Gear 6", + "avLst": (("adj1", 15000), ("adj2", 3526)), + }, + MSO_SHAPE.GEAR_9: { + "basename": "Gear 9", + "avLst": (("adj1", 10000), ("adj2", 1763)), + }, + MSO_SHAPE.HALF_FRAME: { + "basename": "Half Frame", + "avLst": (("adj1", 33333), ("adj2", 33333)), + }, + MSO_SHAPE.HEART: {"basename": "Heart", "avLst": ()}, + MSO_SHAPE.HEPTAGON: { + "basename": "Heptagon", + "avLst": (("hf", 102572), ("vf", 105210)), + }, + MSO_SHAPE.HEXAGON: { + "basename": "Hexagon", + "avLst": (("adj", 25000), ("vf", 115470)), + }, + MSO_SHAPE.HORIZONTAL_SCROLL: { + "basename": "Horizontal Scroll", + "avLst": (("adj", 12500),), + }, + MSO_SHAPE.ISOSCELES_TRIANGLE: { + "basename": "Isosceles Triangle", + "avLst": (("adj", 50000),), + }, + MSO_SHAPE.LEFT_ARROW: { + "basename": "Left Arrow", + "avLst": (("adj1", 50000), ("adj2", 50000)), + }, + MSO_SHAPE.LEFT_ARROW_CALLOUT: { + "basename": "Left Arrow Callout", + "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 64977)), + }, + MSO_SHAPE.LEFT_BRACE: { + "basename": "Left Brace", + "avLst": (("adj1", 8333), ("adj2", 50000)), + }, + MSO_SHAPE.LEFT_BRACKET: {"basename": "Left Bracket", "avLst": (("adj", 8333),)}, + MSO_SHAPE.LEFT_CIRCULAR_ARROW: { + "basename": "Left Circular Arrow", + "avLst": ( + ("adj1", 12500), + ("adj2", -1142319), + ("adj3", 1142319), + ("adj4", 10800000), + ("adj5", 12500), + ), + }, + MSO_SHAPE.LEFT_RIGHT_ARROW: { + "basename": "Left-Right Arrow", + "avLst": (("adj1", 50000), ("adj2", 50000)), + }, + MSO_SHAPE.LEFT_RIGHT_ARROW_CALLOUT: { + "basename": "Left-Right Arrow Callout", + "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 48123)), + }, + MSO_SHAPE.LEFT_RIGHT_CIRCULAR_ARROW: { + "basename": "Left Right Circular Arrow", + "avLst": ( + ("adj1", 12500), + ("adj2", 1142319), + ("adj3", 20457681), + ("adj4", 11942319), + ("adj5", 12500), + ), + }, + MSO_SHAPE.LEFT_RIGHT_RIBBON: { + "basename": "Left Right Ribbon", + "avLst": (("adj1", 50000), ("adj2", 50000), ("adj3", 16667)), + }, + MSO_SHAPE.LEFT_RIGHT_UP_ARROW: { + "basename": "Left-Right-Up Arrow", + "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000)), + }, + MSO_SHAPE.LEFT_UP_ARROW: { + "basename": "Left-Up Arrow", + "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000)), + }, + MSO_SHAPE.LIGHTNING_BOLT: {"basename": "Lightning Bolt", "avLst": ()}, + MSO_SHAPE.LINE_CALLOUT_1: { + "basename": "Line Callout 1", + "avLst": (("adj1", 18750), ("adj2", -8333), ("adj3", 112500), ("adj4", -38333)), + }, + MSO_SHAPE.LINE_CALLOUT_1_ACCENT_BAR: { + "basename": "Line Callout 1 (Accent Bar)", + "avLst": (("adj1", 18750), ("adj2", -8333), ("adj3", 112500), ("adj4", -38333)), + }, + MSO_SHAPE.LINE_CALLOUT_1_BORDER_AND_ACCENT_BAR: { + "basename": "Line Callout 1 (Border and Accent Bar)", + "avLst": (("adj1", 18750), ("adj2", -8333), ("adj3", 112500), ("adj4", -38333)), + }, + MSO_SHAPE.LINE_CALLOUT_1_NO_BORDER: { + "basename": "Line Callout 1 (No Border)", + "avLst": (("adj1", 18750), ("adj2", -8333), ("adj3", 112500), ("adj4", -38333)), + }, + MSO_SHAPE.LINE_CALLOUT_2: { + "basename": "Line Callout 2", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 112500), + ("adj6", -46667), + ), + }, + MSO_SHAPE.LINE_CALLOUT_2_ACCENT_BAR: { + "basename": "Line Callout 2 (Accent Bar)", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 112500), + ("adj6", -46667), + ), + }, + MSO_SHAPE.LINE_CALLOUT_2_BORDER_AND_ACCENT_BAR: { + "basename": "Line Callout 2 (Border and Accent Bar)", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 112500), + ("adj6", -46667), + ), + }, + MSO_SHAPE.LINE_CALLOUT_2_NO_BORDER: { + "basename": "Line Callout 2 (No Border)", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 112500), + ("adj6", -46667), + ), + }, + MSO_SHAPE.LINE_CALLOUT_3: { + "basename": "Line Callout 3", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 100000), + ("adj6", -16667), + ("adj7", 112963), + ("adj8", -8333), + ), + }, + MSO_SHAPE.LINE_CALLOUT_3_ACCENT_BAR: { + "basename": "Line Callout 3 (Accent Bar)", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 100000), + ("adj6", -16667), + ("adj7", 112963), + ("adj8", -8333), + ), + }, + MSO_SHAPE.LINE_CALLOUT_3_BORDER_AND_ACCENT_BAR: { + "basename": "Line Callout 3 (Border and Accent Bar)", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 100000), + ("adj6", -16667), + ("adj7", 112963), + ("adj8", -8333), + ), + }, + MSO_SHAPE.LINE_CALLOUT_3_NO_BORDER: { + "basename": "Line Callout 3 (No Border)", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 100000), + ("adj6", -16667), + ("adj7", 112963), + ("adj8", -8333), + ), + }, + MSO_SHAPE.LINE_CALLOUT_4: { + "basename": "Line Callout 3", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 100000), + ("adj6", -16667), + ("adj7", 112963), + ("adj8", -8333), + ), + }, + MSO_SHAPE.LINE_CALLOUT_4_ACCENT_BAR: { + "basename": "Line Callout 3 (Accent Bar)", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 100000), + ("adj6", -16667), + ("adj7", 112963), + ("adj8", -8333), + ), + }, + MSO_SHAPE.LINE_CALLOUT_4_BORDER_AND_ACCENT_BAR: { + "basename": "Line Callout 3 (Border and Accent Bar)", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 100000), + ("adj6", -16667), + ("adj7", 112963), + ("adj8", -8333), + ), + }, + MSO_SHAPE.LINE_CALLOUT_4_NO_BORDER: { + "basename": "Line Callout 3 (No Border)", + "avLst": ( + ("adj1", 18750), + ("adj2", -8333), + ("adj3", 18750), + ("adj4", -16667), + ("adj5", 100000), + ("adj6", -16667), + ("adj7", 112963), + ("adj8", -8333), + ), + }, + MSO_SHAPE.LINE_INVERSE: {"basename": "Straight Connector", "avLst": ()}, + MSO_SHAPE.MATH_DIVIDE: { + "basename": "Division", + "avLst": (("adj1", 23520), ("adj2", 5880), ("adj3", 11760)), + }, + MSO_SHAPE.MATH_EQUAL: { + "basename": "Equal", + "avLst": (("adj1", 23520), ("adj2", 11760)), + }, + MSO_SHAPE.MATH_MINUS: {"basename": "Minus", "avLst": (("adj1", 23520),)}, + MSO_SHAPE.MATH_MULTIPLY: {"basename": "Multiply", "avLst": (("adj1", 23520),)}, + MSO_SHAPE.MATH_NOT_EQUAL: { + "basename": "Not Equal", + "avLst": (("adj1", 23520), ("adj2", 6600000), ("adj3", 11760)), + }, + MSO_SHAPE.MATH_PLUS: {"basename": "Plus", "avLst": (("adj1", 23520),)}, + MSO_SHAPE.MOON: {"basename": "Moon", "avLst": (("adj", 50000),)}, + MSO_SHAPE.NON_ISOSCELES_TRAPEZOID: { + "basename": "Non-isosceles Trapezoid", + "avLst": (("adj1", 25000), ("adj2", 25000)), + }, + MSO_SHAPE.NOTCHED_RIGHT_ARROW: { + "basename": "Notched Right Arrow", + "avLst": (("adj1", 50000), ("adj2", 50000)), + }, + MSO_SHAPE.NO_SYMBOL: {"basename": '"No" Symbol', "avLst": (("adj", 18750),)}, + MSO_SHAPE.OCTAGON: {"basename": "Octagon", "avLst": (("adj", 29289),)}, + MSO_SHAPE.OVAL: {"basename": "Oval", "avLst": ()}, + MSO_SHAPE.OVAL_CALLOUT: { + "basename": "Oval Callout", + "avLst": (("adj1", -20833), ("adj2", 62500)), + }, + MSO_SHAPE.PARALLELOGRAM: {"basename": "Parallelogram", "avLst": (("adj", 25000),)}, + MSO_SHAPE.PENTAGON: {"basename": "Pentagon", "avLst": (("adj", 50000),)}, + MSO_SHAPE.PIE: {"basename": "Pie", "avLst": (("adj1", 0), ("adj2", 16200000))}, + MSO_SHAPE.PIE_WEDGE: {"basename": "Pie", "avLst": ()}, + MSO_SHAPE.PLAQUE: {"basename": "Plaque", "avLst": (("adj", 16667),)}, + MSO_SHAPE.PLAQUE_TABS: {"basename": "Plaque Tabs", "avLst": ()}, + MSO_SHAPE.QUAD_ARROW: { + "basename": "Quad Arrow", + "avLst": (("adj1", 22500), ("adj2", 22500), ("adj3", 22500)), + }, + MSO_SHAPE.QUAD_ARROW_CALLOUT: { + "basename": "Quad Arrow Callout", + "avLst": (("adj1", 18515), ("adj2", 18515), ("adj3", 18515), ("adj4", 48123)), + }, + MSO_SHAPE.RECTANGLE: {"basename": "Rectangle", "avLst": ()}, + MSO_SHAPE.RECTANGULAR_CALLOUT: { + "basename": "Rectangular Callout", + "avLst": (("adj1", -20833), ("adj2", 62500)), + }, + MSO_SHAPE.REGULAR_PENTAGON: { + "basename": "Regular Pentagon", + "avLst": (("hf", 105146), ("vf", 110557)), + }, + MSO_SHAPE.RIGHT_ARROW: { + "basename": "Right Arrow", + "avLst": (("adj1", 50000), ("adj2", 50000)), + }, + MSO_SHAPE.RIGHT_ARROW_CALLOUT: { + "basename": "Right Arrow Callout", + "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 64977)), + }, + MSO_SHAPE.RIGHT_BRACE: { + "basename": "Right Brace", + "avLst": (("adj1", 8333), ("adj2", 50000)), + }, + MSO_SHAPE.RIGHT_BRACKET: {"basename": "Right Bracket", "avLst": (("adj", 8333),)}, + MSO_SHAPE.RIGHT_TRIANGLE: {"basename": "Right Triangle", "avLst": ()}, + MSO_SHAPE.ROUNDED_RECTANGLE: { + "basename": "Rounded Rectangle", + "avLst": (("adj", 16667),), + }, + MSO_SHAPE.ROUNDED_RECTANGULAR_CALLOUT: { + "basename": "Rounded Rectangular Callout", + "avLst": (("adj1", -20833), ("adj2", 62500), ("adj3", 16667)), + }, + MSO_SHAPE.ROUND_1_RECTANGLE: { + "basename": "Round Single Corner Rectangle", + "avLst": (("adj", 16667),), + }, + MSO_SHAPE.ROUND_2_DIAG_RECTANGLE: { + "basename": "Round Diagonal Corner Rectangle", + "avLst": (("adj1", 16667), ("adj2", 0)), + }, + MSO_SHAPE.ROUND_2_SAME_RECTANGLE: { + "basename": "Round Same Side Corner Rectangle", + "avLst": (("adj1", 16667), ("adj2", 0)), + }, + MSO_SHAPE.SMILEY_FACE: {"basename": "Smiley Face", "avLst": (("adj", 4653),)}, + MSO_SHAPE.SNIP_1_RECTANGLE: { + "basename": "Snip Single Corner Rectangle", + "avLst": (("adj", 16667),), + }, + MSO_SHAPE.SNIP_2_DIAG_RECTANGLE: { + "basename": "Snip Diagonal Corner Rectangle", + "avLst": (("adj1", 0), ("adj2", 16667)), + }, + MSO_SHAPE.SNIP_2_SAME_RECTANGLE: { + "basename": "Snip Same Side Corner Rectangle", + "avLst": (("adj1", 16667), ("adj2", 0)), + }, + MSO_SHAPE.SNIP_ROUND_RECTANGLE: { + "basename": "Snip and Round Single Corner Rectangle", + "avLst": (("adj1", 16667), ("adj2", 16667)), + }, + MSO_SHAPE.SQUARE_TABS: {"basename": "Square Tabs", "avLst": ()}, + MSO_SHAPE.STAR_10_POINT: { + "basename": "10-Point Star", + "avLst": (("adj", 42533), ("hf", 105146)), + }, + MSO_SHAPE.STAR_12_POINT: {"basename": "12-Point Star", "avLst": (("adj", 37500),)}, + MSO_SHAPE.STAR_16_POINT: {"basename": "16-Point Star", "avLst": (("adj", 37500),)}, + MSO_SHAPE.STAR_24_POINT: {"basename": "24-Point Star", "avLst": (("adj", 37500),)}, + MSO_SHAPE.STAR_32_POINT: {"basename": "32-Point Star", "avLst": (("adj", 37500),)}, + MSO_SHAPE.STAR_4_POINT: {"basename": "4-Point Star", "avLst": (("adj", 12500),)}, + MSO_SHAPE.STAR_5_POINT: { + "basename": "5-Point Star", + "avLst": (("adj", 19098), ("hf", 105146), ("vf", 110557)), + }, + MSO_SHAPE.STAR_6_POINT: { + "basename": "6-Point Star", + "avLst": (("adj", 28868), ("hf", 115470)), + }, + MSO_SHAPE.STAR_7_POINT: { + "basename": "7-Point Star", + "avLst": (("adj", 34601), ("hf", 102572), ("vf", 105210)), + }, + MSO_SHAPE.STAR_8_POINT: {"basename": "8-Point Star", "avLst": (("adj", 37500),)}, + MSO_SHAPE.STRIPED_RIGHT_ARROW: { + "basename": "Striped Right Arrow", + "avLst": (("adj1", 50000), ("adj2", 50000)), + }, + MSO_SHAPE.SUN: {"basename": "Sun", "avLst": (("adj", 25000),)}, + MSO_SHAPE.SWOOSH_ARROW: { + "basename": "Swoosh Arrow", + "avLst": (("adj1", 25000), ("adj2", 16667)), + }, + MSO_SHAPE.TEAR: {"basename": "Teardrop", "avLst": (("adj", 100000),)}, + MSO_SHAPE.TRAPEZOID: {"basename": "Trapezoid", "avLst": (("adj", 25000),)}, + MSO_SHAPE.UP_ARROW: { + "basename": "Up Arrow", + "avLst": (("adj1", 50000), ("adj2", 50000)), + }, + MSO_SHAPE.UP_ARROW_CALLOUT: { + "basename": "Up Arrow Callout", + "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 64977)), + }, + MSO_SHAPE.UP_DOWN_ARROW: { + "basename": "Up-Down Arrow", + "avLst": (("adj1", 50000), ("adj1", 50000), ("adj2", 50000), ("adj2", 50000)), + }, + MSO_SHAPE.UP_DOWN_ARROW_CALLOUT: { + "basename": "Up-Down Arrow Callout", + "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 48123)), + }, + MSO_SHAPE.UP_RIBBON: { + "basename": "Up Ribbon", + "avLst": (("adj1", 16667), ("adj2", 50000)), + }, + MSO_SHAPE.U_TURN_ARROW: { + "basename": "U-Turn Arrow", + "avLst": ( + ("adj1", 25000), + ("adj2", 25000), + ("adj3", 25000), + ("adj4", 43750), + ("adj5", 75000), + ), + }, + MSO_SHAPE.VERTICAL_SCROLL: { + "basename": "Vertical Scroll", + "avLst": (("adj", 12500),), + }, + MSO_SHAPE.WAVE: {"basename": "Wave", "avLst": (("adj1", 12500), ("adj2", 0))}, +} diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/table.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/table.py new file mode 100644 index 0000000000000000000000000000000000000000..3bdf54ba6091feedb202ba86caf6fdb330772f49 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/table.py @@ -0,0 +1,496 @@ +"""Table-related objects such as Table and Cell.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Iterator + +from pptx.dml.fill import FillFormat +from pptx.oxml.table import TcRange +from pptx.shapes import Subshape +from pptx.text.text import TextFrame +from pptx.util import Emu, lazyproperty + +if TYPE_CHECKING: + from pptx.enum.text import MSO_VERTICAL_ANCHOR + from pptx.oxml.table import CT_Table, CT_TableCell, CT_TableCol, CT_TableRow + from pptx.parts.slide import BaseSlidePart + from pptx.shapes.graphfrm import GraphicFrame + from pptx.types import ProvidesPart + from pptx.util import Length + + +class Table(object): + """A DrawingML table object. + + Not intended to be constructed directly, use + :meth:`.Slide.shapes.add_table` to add a table to a slide. + """ + + def __init__(self, tbl: CT_Table, graphic_frame: GraphicFrame): + super(Table, self).__init__() + self._tbl = tbl + self._graphic_frame = graphic_frame + + def cell(self, row_idx: int, col_idx: int) -> _Cell: + """Return cell at `row_idx`, `col_idx`. + + Return value is an instance of |_Cell|. `row_idx` and `col_idx` are zero-based, e.g. + cell(0, 0) is the top, left cell in the table. + """ + return _Cell(self._tbl.tc(row_idx, col_idx), self) + + @lazyproperty + def columns(self) -> _ColumnCollection: + """|_ColumnCollection| instance for this table. + + Provides access to |_Column| objects representing the table's columns. |_Column| objects + are accessed using list notation, e.g. `col = tbl.columns[0]`. + """ + return _ColumnCollection(self._tbl, self) + + @property + def first_col(self) -> bool: + """When `True`, indicates first column should have distinct formatting. + + Read/write. Distinct formatting is used, for example, when the first column contains row + headings (is a side-heading column). + """ + return self._tbl.firstCol + + @first_col.setter + def first_col(self, value: bool): + self._tbl.firstCol = value + + @property + def first_row(self) -> bool: + """When `True`, indicates first row should have distinct formatting. + + Read/write. Distinct formatting is used, for example, when the first row contains column + headings. + """ + return self._tbl.firstRow + + @first_row.setter + def first_row(self, value: bool): + self._tbl.firstRow = value + + @property + def horz_banding(self) -> bool: + """When `True`, indicates rows should have alternating shading. + + Read/write. Used to allow rows to be traversed more easily without losing track of which + row is being read. + """ + return self._tbl.bandRow + + @horz_banding.setter + def horz_banding(self, value: bool): + self._tbl.bandRow = value + + def iter_cells(self) -> Iterator[_Cell]: + """Generate _Cell object for each cell in this table. + + Each grid cell is generated in left-to-right, top-to-bottom order. + """ + return (_Cell(tc, self) for tc in self._tbl.iter_tcs()) + + @property + def last_col(self) -> bool: + """When `True`, indicates the rightmost column should have distinct formatting. + + Read/write. Used, for example, when a row totals column appears at the far right of the + table. + """ + return self._tbl.lastCol + + @last_col.setter + def last_col(self, value: bool): + self._tbl.lastCol = value + + @property + def last_row(self) -> bool: + """When `True`, indicates the bottom row should have distinct formatting. + + Read/write. Used, for example, when a totals row appears as the bottom row. + """ + return self._tbl.lastRow + + @last_row.setter + def last_row(self, value: bool): + self._tbl.lastRow = value + + def notify_height_changed(self) -> None: + """Called by a row when its height changes. + + Triggers the graphic frame to recalculate its total height (as the sum of the row + heights). + """ + new_table_height = Emu(sum([row.height for row in self.rows])) + self._graphic_frame.height = new_table_height + + def notify_width_changed(self) -> None: + """Called by a column when its width changes. + + Triggers the graphic frame to recalculate its total width (as the sum of the column + widths). + """ + new_table_width = Emu(sum([col.width for col in self.columns])) + self._graphic_frame.width = new_table_width + + @property + def part(self) -> BaseSlidePart: + """The package part containing this table.""" + return self._graphic_frame.part + + @lazyproperty + def rows(self): + """|_RowCollection| instance for this table. + + Provides access to |_Row| objects representing the table's rows. |_Row| objects are + accessed using list notation, e.g. `col = tbl.rows[0]`. + """ + return _RowCollection(self._tbl, self) + + @property + def vert_banding(self) -> bool: + """When `True`, indicates columns should have alternating shading. + + Read/write. Used to allow columns to be traversed more easily without losing track of + which column is being read. + """ + return self._tbl.bandCol + + @vert_banding.setter + def vert_banding(self, value: bool): + self._tbl.bandCol = value + + +class _Cell(Subshape): + """Table cell""" + + def __init__(self, tc: CT_TableCell, parent: ProvidesPart): + super(_Cell, self).__init__(parent) + self._tc = tc + + def __eq__(self, other: object) -> bool: + """|True| if this object proxies the same element as `other`. + + Equality for proxy objects is defined as referring to the same XML element, whether or not + they are the same proxy object instance. + """ + if not isinstance(other, type(self)): + return False + return self._tc is other._tc + + def __ne__(self, other: object) -> bool: + if not isinstance(other, type(self)): + return True + return self._tc is not other._tc + + @lazyproperty + def fill(self) -> FillFormat: + """|FillFormat| instance for this cell. + + Provides access to fill properties such as foreground color. + """ + tcPr = self._tc.get_or_add_tcPr() + return FillFormat.from_fill_parent(tcPr) + + @property + def is_merge_origin(self) -> bool: + """True if this cell is the top-left grid cell in a merged cell.""" + return self._tc.is_merge_origin + + @property + def is_spanned(self) -> bool: + """True if this cell is spanned by a merge-origin cell. + + A merge-origin cell "spans" the other grid cells in its merge range, consuming their area + and "shadowing" the spanned grid cells. + + Note this value is |False| for a merge-origin cell. A merge-origin cell spans other grid + cells, but is not itself a spanned cell. + """ + return self._tc.is_spanned + + @property + def margin_left(self) -> Length: + """Left margin of cells. + + Read/write. If assigned |None|, the default value is used, 0.1 inches for left and right + margins and 0.05 inches for top and bottom. + """ + return self._tc.marL + + @margin_left.setter + def margin_left(self, margin_left: Length | None): + self._validate_margin_value(margin_left) + self._tc.marL = margin_left + + @property + def margin_right(self) -> Length: + """Right margin of cell.""" + return self._tc.marR + + @margin_right.setter + def margin_right(self, margin_right: Length | None): + self._validate_margin_value(margin_right) + self._tc.marR = margin_right + + @property + def margin_top(self) -> Length: + """Top margin of cell.""" + return self._tc.marT + + @margin_top.setter + def margin_top(self, margin_top: Length | None): + self._validate_margin_value(margin_top) + self._tc.marT = margin_top + + @property + def margin_bottom(self) -> Length: + """Bottom margin of cell.""" + return self._tc.marB + + @margin_bottom.setter + def margin_bottom(self, margin_bottom: Length | None): + self._validate_margin_value(margin_bottom) + self._tc.marB = margin_bottom + + def merge(self, other_cell: _Cell) -> None: + """Create merged cell from this cell to `other_cell`. + + This cell and `other_cell` specify opposite corners of the merged cell range. Either + diagonal of the cell region may be specified in either order, e.g. self=bottom-right, + other_cell=top-left, etc. + + Raises |ValueError| if the specified range already contains merged cells anywhere within + its extents or if `other_cell` is not in the same table as `self`. + """ + tc_range = TcRange(self._tc, other_cell._tc) + + if not tc_range.in_same_table: + raise ValueError("other_cell from different table") + if tc_range.contains_merged_cell: + raise ValueError("range contains one or more merged cells") + + tc_range.move_content_to_origin() + + row_count, col_count = tc_range.dimensions + + for tc in tc_range.iter_top_row_tcs(): + tc.rowSpan = row_count + for tc in tc_range.iter_left_col_tcs(): + tc.gridSpan = col_count + for tc in tc_range.iter_except_left_col_tcs(): + tc.hMerge = True + for tc in tc_range.iter_except_top_row_tcs(): + tc.vMerge = True + + @property + def span_height(self) -> int: + """int count of rows spanned by this cell. + + The value of this property may be misleading (often 1) on cells where `.is_merge_origin` + is not |True|, since only a merge-origin cell contains complete span information. This + property is only intended for use on cells known to be a merge origin by testing + `.is_merge_origin`. + """ + return self._tc.rowSpan + + @property + def span_width(self) -> int: + """int count of columns spanned by this cell. + + The value of this property may be misleading (often 1) on cells where `.is_merge_origin` + is not |True|, since only a merge-origin cell contains complete span information. This + property is only intended for use on cells known to be a merge origin by testing + `.is_merge_origin`. + """ + return self._tc.gridSpan + + def split(self) -> None: + """Remove merge from this (merge-origin) cell. + + The merged cell represented by this object will be "unmerged", yielding a separate + unmerged cell for each grid cell previously spanned by this merge. + + Raises |ValueError| when this cell is not a merge-origin cell. Test with + `.is_merge_origin` before calling. + """ + if not self.is_merge_origin: + raise ValueError("not a merge-origin cell; only a merge-origin cell can be sp" "lit") + + tc_range = TcRange.from_merge_origin(self._tc) + + for tc in tc_range.iter_tcs(): + tc.rowSpan = tc.gridSpan = 1 + tc.hMerge = tc.vMerge = False + + @property + def text(self) -> str: + """Textual content of cell as a single string. + + The returned string will contain a newline character (`"\\n"`) separating each paragraph + and a vertical-tab (`"\\v"`) character for each line break (soft carriage return) in the + cell's text. + + Assignment to `text` replaces all text currently contained in the cell. A newline + character (`"\\n"`) in the assigned text causes a new paragraph to be started. A + vertical-tab (`"\\v"`) character in the assigned text causes a line-break (soft + carriage-return) to be inserted. (The vertical-tab character appears in clipboard text + copied from PowerPoint as its encoding of line-breaks.) + """ + return self.text_frame.text + + @text.setter + def text(self, text: str): + self.text_frame.text = text + + @property + def text_frame(self) -> TextFrame: + """|TextFrame| containing the text that appears in the cell.""" + txBody = self._tc.get_or_add_txBody() + return TextFrame(txBody, self) + + @property + def vertical_anchor(self) -> MSO_VERTICAL_ANCHOR | None: + """Vertical alignment of this cell. + + This value is a member of the :ref:`MsoVerticalAnchor` enumeration or |None|. A value of + |None| indicates the cell has no explicitly applied vertical anchor setting and its + effective value is inherited from its style-hierarchy ancestors. + + Assigning |None| to this property causes any explicitly applied vertical anchor setting to + be cleared and inheritance of its effective value to be restored. + """ + return self._tc.anchor + + @vertical_anchor.setter + def vertical_anchor(self, mso_anchor_idx: MSO_VERTICAL_ANCHOR | None): + self._tc.anchor = mso_anchor_idx + + @staticmethod + def _validate_margin_value(margin_value: Length | None) -> None: + """Raise ValueError if `margin_value` is not a positive integer value or |None|.""" + if not isinstance(margin_value, int) and margin_value is not None: + tmpl = "margin value must be integer or None, got '%s'" + raise TypeError(tmpl % margin_value) + + +class _Column(Subshape): + """Table column""" + + def __init__(self, gridCol: CT_TableCol, parent: _ColumnCollection): + super(_Column, self).__init__(parent) + self._parent = parent + self._gridCol = gridCol + + @property + def width(self) -> Length: + """Width of column in EMU.""" + return self._gridCol.w + + @width.setter + def width(self, width: Length): + self._gridCol.w = width + self._parent.notify_width_changed() + + +class _Row(Subshape): + """Table row""" + + def __init__(self, tr: CT_TableRow, parent: _RowCollection): + super(_Row, self).__init__(parent) + self._parent = parent + self._tr = tr + + @property + def cells(self): + """Read-only reference to collection of cells in row. + + An individual cell is referenced using list notation, e.g. `cell = row.cells[0]`. + """ + return _CellCollection(self._tr, self) + + @property + def height(self) -> Length: + """Height of row in EMU.""" + return self._tr.h + + @height.setter + def height(self, height: Length): + self._tr.h = height + self._parent.notify_height_changed() + + +class _CellCollection(Subshape): + """Horizontal sequence of row cells""" + + def __init__(self, tr: CT_TableRow, parent: _Row): + super(_CellCollection, self).__init__(parent) + self._parent = parent + self._tr = tr + + def __getitem__(self, idx: int) -> _Cell: + """Provides indexed access, (e.g. 'cells[0]').""" + if idx < 0 or idx >= len(self._tr.tc_lst): + msg = "cell index [%d] out of range" % idx + raise IndexError(msg) + return _Cell(self._tr.tc_lst[idx], self) + + def __iter__(self) -> Iterator[_Cell]: + """Provides iterability.""" + return (_Cell(tc, self) for tc in self._tr.tc_lst) + + def __len__(self) -> int: + """Supports len() function (e.g. 'len(cells) == 1').""" + return len(self._tr.tc_lst) + + +class _ColumnCollection(Subshape): + """Sequence of table columns.""" + + def __init__(self, tbl: CT_Table, parent: Table): + super(_ColumnCollection, self).__init__(parent) + self._parent = parent + self._tbl = tbl + + def __getitem__(self, idx: int): + """Provides indexed access, (e.g. 'columns[0]').""" + if idx < 0 or idx >= len(self._tbl.tblGrid.gridCol_lst): + msg = "column index [%d] out of range" % idx + raise IndexError(msg) + return _Column(self._tbl.tblGrid.gridCol_lst[idx], self) + + def __len__(self): + """Supports len() function (e.g. 'len(columns) == 1').""" + return len(self._tbl.tblGrid.gridCol_lst) + + def notify_width_changed(self): + """Called by a column when its width changes. Pass along to parent.""" + self._parent.notify_width_changed() + + +class _RowCollection(Subshape): + """Sequence of table rows""" + + def __init__(self, tbl: CT_Table, parent: Table): + super(_RowCollection, self).__init__(parent) + self._parent = parent + self._tbl = tbl + + def __getitem__(self, idx: int) -> _Row: + """Provides indexed access, (e.g. 'rows[0]').""" + if idx < 0 or idx >= len(self): + msg = "row index [%d] out of range" % idx + raise IndexError(msg) + return _Row(self._tbl.tr_lst[idx], self) + + def __len__(self): + """Supports len() function (e.g. 'len(rows) == 1').""" + return len(self._tbl.tr_lst) + + def notify_height_changed(self): + """Called by a row when its height changes. Pass along to parent.""" + self._parent.notify_height_changed() diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/default.pptx b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/default.pptx new file mode 100644 index 0000000000000000000000000000000000000000..e7fd6565f1be7add12a3133ef44954cd9c672f4a Binary files /dev/null and b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/default.pptx differ diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/docx-icon.emf b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/docx-icon.emf new file mode 100644 index 0000000000000000000000000000000000000000..f027d72a9e6a33af46e2b544ef2f1d828f536dbb --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/docx-icon.emf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbfa051aa5f1ec1993f0ce056f67112ce4af3a8c3ac6fccfc219399ed6dc625d +size 127228 diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/generic-icon.emf b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/generic-icon.emf new file mode 100644 index 0000000000000000000000000000000000000000..d0914e003548ff8099862e9b42b5e101cc7f8149 Binary files /dev/null and b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/generic-icon.emf differ diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/notes.xml b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/notes.xml new file mode 100644 index 0000000000000000000000000000000000000000..654effbb9860aa6d8f8c29189ce558e452a20e7a --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/notes.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/notesMaster.xml b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/notesMaster.xml new file mode 100644 index 0000000000000000000000000000000000000000..80008e070416e8e771d172b64d756694be3a973f --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/notesMaster.xml @@ -0,0 +1,352 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 10/17/16 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/pptx-icon.emf b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/pptx-icon.emf new file mode 100644 index 0000000000000000000000000000000000000000..e9b1ce8812d913ab719966fcd4e838604c4adb93 Binary files /dev/null and b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/pptx-icon.emf differ diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/theme.xml b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/theme.xml new file mode 100644 index 0000000000000000000000000000000000000000..bf57418d7dec87080273bccdcaa3aa4f29d0366a --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/theme.xml @@ -0,0 +1,321 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/xlsx-icon.emf b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/xlsx-icon.emf new file mode 100644 index 0000000000000000000000000000000000000000..102afbe371dbb7db17e534db023a7e6e7bf47aec --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/xlsx-icon.emf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14e52936cebdf16e5a6629ce707415c26122fe54af322872a2d25fec618a69ee +size 130380 diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/__init__.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/fonts.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/fonts.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae054a83aca29a4dfbfde275e0386a9c79ccfae --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/fonts.py @@ -0,0 +1,399 @@ +"""Objects related to system font file lookup.""" + +from __future__ import annotations + +import os +import sys +from struct import calcsize, unpack_from + +from pptx.util import lazyproperty + + +class FontFiles(object): + """A class-based singleton serving as a lazy cache for system font details.""" + + _font_files = None + + @classmethod + def find(cls, family_name: str, is_bold: bool, is_italic: bool) -> str: + """Return the absolute path to an installed OpenType font. + + File is matched by `family_name` and the styles `is_bold` and `is_italic`. + """ + if cls._font_files is None: + cls._font_files = cls._installed_fonts() + return cls._font_files[(family_name, is_bold, is_italic)] + + @classmethod + def _installed_fonts(cls): + """ + Return a dict mapping a font descriptor to its font file path, + containing all the font files resident on the current machine. The + font descriptor is a (family_name, is_bold, is_italic) 3-tuple. + """ + fonts = {} + for d in cls._font_directories(): + for key, path in cls._iter_font_files_in(d): + fonts[key] = path + return fonts + + @classmethod + def _font_directories(cls): + """ + Return a sequence of directory paths likely to contain fonts on the + current platform. + """ + if sys.platform.startswith("darwin"): + return cls._os_x_font_directories() + if sys.platform.startswith("win32"): + return cls._windows_font_directories() + raise OSError("unsupported operating system") + + @classmethod + def _iter_font_files_in(cls, directory): + """ + Generate the OpenType font files found in and under *directory*. Each + item is a key/value pair. The key is a (family_name, is_bold, + is_italic) 3-tuple, like ('Arial', True, False), and the value is the + absolute path to the font file. + """ + for root, dirs, files in os.walk(directory): + for filename in files: + file_ext = os.path.splitext(filename)[1] + if file_ext.lower() not in (".otf", ".ttf"): + continue + path = os.path.abspath(os.path.join(root, filename)) + with _Font.open(path) as f: + yield ((f.family_name, f.is_bold, f.is_italic), path) + + @classmethod + def _os_x_font_directories(cls): + """ + Return a sequence of directory paths on a Mac in which fonts are + likely to be located. + """ + os_x_font_dirs = [ + "/Library/Fonts", + "/Network/Library/Fonts", + "/System/Library/Fonts", + ] + home = os.environ.get("HOME") + if home is not None: + os_x_font_dirs.extend( + [os.path.join(home, "Library", "Fonts"), os.path.join(home, ".fonts")] + ) + return os_x_font_dirs + + @classmethod + def _windows_font_directories(cls): + """ + Return a sequence of directory paths on Windows in which fonts are + likely to be located. + """ + return [r"C:\Windows\Fonts"] + + +class _Font(object): + """ + A wrapper around an OTF/TTF font file stream that knows how to parse it + for its name and style characteristics, e.g. bold and italic. + """ + + def __init__(self, stream): + self._stream = stream + + def __enter__(self): + return self + + def __exit__(self, exception_type, exception_value, exception_tb): + self._stream.close() + + @property + def is_bold(self): + """ + |True| if this font is marked as a bold style of its font family. + """ + try: + return self._tables["head"].is_bold + except KeyError: + # some files don't have a head table + return False + + @property + def is_italic(self): + """ + |True| if this font is marked as an italic style of its font family. + """ + try: + return self._tables["head"].is_italic + except KeyError: + # some files don't have a head table + return False + + @classmethod + def open(cls, font_file_path): + """ + Return a |_Font| instance loaded from *font_file_path*. + """ + return cls(_Stream.open(font_file_path)) + + @property + def family_name(self): + """ + The name of the typeface family for this font, e.g. 'Arial'. The full + typeface name includes optional style names, such as 'Regular' or + 'Bold Italic'. This attribute is only the common base name shared by + all fonts in the family. + """ + return self._tables["name"].family_name + + @lazyproperty + def _fields(self): + """5-tuple containing the fields read from the font file header. + + Also known as the offset table. + """ + # sfnt_version, tbl_count, search_range, entry_selector, range_shift + return self._stream.read_fields(">4sHHHH", 0) + + def _iter_table_records(self): + """ + Generate a (tag, offset, length) 3-tuple for each of the tables in + this font file. + """ + count = self._table_count + bufr = self._stream.read(offset=12, length=count * 16) + tmpl = ">4sLLL" + for i in range(count): + offset = i * 16 + tag, checksum, off, len_ = unpack_from(tmpl, bufr, offset) + yield tag.decode("utf-8"), off, len_ + + @lazyproperty + def _tables(self): + """ + A mapping of OpenType table tag, e.g. 'name', to a table object + providing access to the contents of that table. + """ + return dict( + (tag, _TableFactory(tag, self._stream, off, len_)) + for tag, off, len_ in self._iter_table_records() + ) + + @property + def _table_count(self): + """ + The number of tables in this OpenType font file. + """ + return self._fields[1] + + +class _Stream(object): + """A thin wrapper around a binary file that facilitates reading C-struct values.""" + + def __init__(self, file): + self._file = file + + @classmethod + def open(cls, path): + """Return |_Stream| providing binary access to contents of file at `path`.""" + return cls(open(path, "rb")) + + def close(self): + """ + Close the wrapped file. Using the stream after closing raises an + exception. + """ + self._file.close() + + def read(self, offset, length): + """ + Return *length* bytes from this stream starting at *offset*. + """ + self._file.seek(offset) + return self._file.read(length) + + def read_fields(self, template, offset=0): + """ + Return a tuple containing the C-struct fields in this stream + specified by *template* and starting at *offset*. + """ + self._file.seek(offset) + bufr = self._file.read(calcsize(template)) + return unpack_from(template, bufr) + + +class _BaseTable(object): + """ + Base class for OpenType font file table objects. + """ + + def __init__(self, tag, stream, offset, length): + self._tag = tag + self._stream = stream + self._offset = offset + self._length = length + + +class _HeadTable(_BaseTable): + """ + OpenType font table having the tag 'head' and containing certain header + information for the font, including its bold and/or italic style. + """ + + def __init__(self, tag, stream, offset, length): + super(_HeadTable, self).__init__(tag, stream, offset, length) + + @property + def is_bold(self): + """ + |True| if this font is marked as having emboldened characters. + """ + return bool(self._macStyle & 1) + + @property + def is_italic(self): + """ + |True| if this font is marked as having italicized characters. + """ + return bool(self._macStyle & 2) + + @lazyproperty + def _fields(self): + """ + A 17-tuple containing the fields in this table. + """ + return self._stream.read_fields(">4s4sLLHHqqhhhhHHHHH", self._offset) + + @property + def _macStyle(self): + """ + The unsigned short value of the 'macStyle' field in this head table. + """ + return self._fields[12] + + +class _NameTable(_BaseTable): + """ + An OpenType font table having the tag 'name' and containing the + name-related strings for the font. + """ + + def __init__(self, tag, stream, offset, length): + super(_NameTable, self).__init__(tag, stream, offset, length) + + @property + def family_name(self): + """ + The name of the typeface family for this font, e.g. 'Arial'. + """ + + def find_first(dict_, keys, default=None): + for key in keys: + value = dict_.get(key) + if value is not None: + return value + return default + + # keys for Unicode, Mac, and Windows family name, respectively + return find_first(self._names, ((0, 1), (1, 1), (3, 1))) + + @staticmethod + def _decode_name(raw_name, platform_id, encoding_id): + """ + Return the unicode name decoded from *raw_name* using the encoding + implied by the combination of *platform_id* and *encoding_id*. + """ + if platform_id == 1: + # reject non-Roman Mac font names + if encoding_id != 0: + return None + return raw_name.decode("mac-roman") + elif platform_id in (0, 3): + return raw_name.decode("utf-16-be") + else: + return None + + def _iter_names(self): + """Generate a key/value pair for each name in this table. + + The key is a (platform_id, name_id) 2-tuple and the value is the unicode text + corresponding to that key. + """ + table_format, count, strings_offset = self._table_header + table_bytes = self._table_bytes + + for idx in range(count): + platform_id, name_id, name = self._read_name(table_bytes, idx, strings_offset) + if name is None: + continue + yield ((platform_id, name_id), name) + + @staticmethod + def _name_header(bufr, idx): + """ + The (platform_id, encoding_id, language_id, name_id, length, + name_str_offset) 6-tuple encoded in each name record C-struct. + """ + name_hdr_offset = 6 + idx * 12 + return unpack_from(">HHHHHH", bufr, name_hdr_offset) + + @staticmethod + def _raw_name_string(bufr, strings_offset, str_offset, length): + """ + Return the *length* bytes comprising the encoded string in *bufr* at + *str_offset* in the strings area beginning at *strings_offset*. + """ + offset = strings_offset + str_offset + tmpl = "%ds" % length + return unpack_from(tmpl, bufr, offset)[0] + + def _read_name(self, bufr, idx, strings_offset): + """Return a (platform_id, name_id, name) 3-tuple for name at `idx` in `bufr`. + + The triple looks like (0, 1, 'Arial'). `strings_offset` is the for the name at + `idx` position in `bufr`. `strings_offset` is the index into `bufr` where actual + name strings begin. The returned name is a unicode string. + """ + platform_id, enc_id, lang_id, name_id, length, str_offset = self._name_header(bufr, idx) + name = self._read_name_text(bufr, platform_id, enc_id, strings_offset, str_offset, length) + return platform_id, name_id, name + + def _read_name_text( + self, bufr, platform_id, encoding_id, strings_offset, name_str_offset, length + ): + """ + Return the unicode name string at *name_str_offset* or |None| if + decoding its format is not supported. + """ + raw_name = self._raw_name_string(bufr, strings_offset, name_str_offset, length) + return self._decode_name(raw_name, platform_id, encoding_id) + + @lazyproperty + def _table_bytes(self): + """ + The binary contents of this name table. + """ + return self._stream.read(self._offset, self._length) + + @property + def _table_header(self): + """ + The (table_format, name_count, strings_offset) 3-tuple contained + in the header of this table. + """ + return unpack_from(">HHH", self._table_bytes) + + @lazyproperty + def _names(self): + """A mapping of (platform_id, name_id) keys to string names for this font.""" + return dict(self._iter_names()) + + +def _TableFactory(tag, stream, offset, length): + """ + Return an instance of |Table| appropriate to *tag*, loaded from + *font_file* with content of *length* starting at *offset*. + """ + TableClass = {"head": _HeadTable, "name": _NameTable}.get(tag, _BaseTable) + return TableClass(tag, stream, offset, length) diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/layout.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/layout.py new file mode 100644 index 0000000000000000000000000000000000000000..d2b439939208a2220d1d3a2caeaa5741a5021e81 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/layout.py @@ -0,0 +1,325 @@ +"""Objects related to layout of rendered text, such as TextFitter.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from PIL import ImageFont + +if TYPE_CHECKING: + from pptx.util import Length + + +class TextFitter(tuple): + """Value object that knows how to fit text into given rectangular extents.""" + + def __new__(cls, line_source, extents, font_file): + width, height = extents + return tuple.__new__(cls, (line_source, width, height, font_file)) + + @classmethod + def best_fit_font_size( + cls, text: str, extents: tuple[Length, Length], max_size: int, font_file: str + ) -> int: + """Return whole-number best fit point size less than or equal to `max_size`. + + The return value is the largest whole-number point size less than or equal to + `max_size` that allows `text` to fit completely within `extents` when rendered + using font defined in `font_file`. + """ + line_source = _LineSource(text) + text_fitter = cls(line_source, extents, font_file) + return text_fitter._best_fit_font_size(max_size) + + def _best_fit_font_size(self, max_size): + """ + Return the largest whole-number point size less than or equal to + *max_size* that this fitter can fit. + """ + predicate = self._fits_inside_predicate + sizes = _BinarySearchTree.from_ordered_sequence(range(1, int(max_size) + 1)) + return sizes.find_max(predicate) + + def _break_line(self, line_source, point_size): + """ + Return a (line, remainder) pair where *line* is the longest line in + *line_source* that will fit in this fitter's width and *remainder* is + a |_LineSource| object containing the text following the break point. + """ + lines = _BinarySearchTree.from_ordered_sequence(line_source) + predicate = self._fits_in_width_predicate(point_size) + return lines.find_max(predicate) + + def _fits_in_width_predicate(self, point_size): + """ + Return a function taking a text string value and returns |True| if + that text fits in this fitter when rendered at *point_size*. Used as + predicate for _break_line() + """ + + def predicate(line): + """ + Return |True| if *line* fits in this fitter when rendered at + *point_size*. + """ + cx = _rendered_size(line.text, point_size, self._font_file)[0] + return cx <= self._width + + return predicate + + @property + def _fits_inside_predicate(self): + """Return function taking an integer point size argument. + + The function returns |True| if the text in this fitter can be wrapped to fit + entirely within its extents when rendered at that point size. + """ + + def predicate(point_size): + """Return |True| when text in `line_source` can be wrapped to fit. + + Fit means text can be broken into lines that fit entirely within `extents` + when rendered at `point_size` using the font defined in `font_file`. + """ + text_lines = self._wrap_lines(self._line_source, point_size) + cy = _rendered_size("Ty", point_size, self._font_file)[1] + return (cy * len(text_lines)) <= self._height + + return predicate + + @property + def _font_file(self): + return self[3] + + @property + def _height(self): + return self[2] + + @property + def _line_source(self): + return self[0] + + @property + def _width(self): + return self[1] + + def _wrap_lines(self, line_source, point_size): + """ + Return a sequence of str values representing the text in + *line_source* wrapped within this fitter when rendered at + *point_size*. + """ + text, remainder = self._break_line(line_source, point_size) + lines = [text] + if remainder: + lines.extend(self._wrap_lines(remainder, point_size)) + return lines + + +class _BinarySearchTree(object): + """ + A node in a binary search tree. Uniform for root, subtree root, and leaf + nodes. + """ + + def __init__(self, value): + self._value = value + self._lesser = None + self._greater = None + + def find_max(self, predicate, max_=None): + """ + Return the largest item in or under this node that satisfies + *predicate*. + """ + if predicate(self.value): + max_ = self.value + next_node = self._greater + else: + next_node = self._lesser + if next_node is None: + return max_ + return next_node.find_max(predicate, max_) + + @classmethod + def from_ordered_sequence(cls, iseq): + """ + Return the root of a balanced binary search tree populated with the + values in iterable *iseq*. + """ + seq = list(iseq) + # optimize for usually all fits by making longest first + bst = cls(seq.pop()) + bst._insert_from_ordered_sequence(seq) + return bst + + def insert(self, value): + """ + Insert a new node containing *value* into this tree such that its + structure as a binary search tree is preserved. + """ + side = "_lesser" if value < self.value else "_greater" + child = getattr(self, side) + if child is None: + setattr(self, side, _BinarySearchTree(value)) + else: + child.insert(value) + + def tree(self, level=0, prefix=""): + """ + A string representation of the tree rooted in this node, useful for + debugging purposes. + """ + text = "%s%s\n" % (prefix, self.value.text) + prefix = "%s└── " % (" " * level) + if self._lesser: + text += self._lesser.tree(level + 1, prefix) + if self._greater: + text += self._greater.tree(level + 1, prefix) + return text + + @property + def value(self): + """ + The value object contained in this node. + """ + return self._value + + @staticmethod + def _bisect(seq): + """ + Return a (medial_value, greater_values, lesser_values) 3-tuple + obtained by bisecting sequence *seq*. + """ + if len(seq) == 0: + return [], None, [] + mid_idx = int(len(seq) / 2) + mid = seq[mid_idx] + greater = seq[mid_idx + 1 :] + lesser = seq[:mid_idx] + return mid, greater, lesser + + def _insert_from_ordered_sequence(self, seq): + """ + Insert the new values contained in *seq* into this tree such that + a balanced tree is produced. + """ + if len(seq) == 0: + return + mid, greater, lesser = self._bisect(seq) + self.insert(mid) + self._insert_from_ordered_sequence(greater) + self._insert_from_ordered_sequence(lesser) + + +class _LineSource(object): + """ + Generates all the possible even-word line breaks in a string of text, + each in the form of a (line, remainder) 2-tuple where *line* contains the + text before the break and *remainder* the text after as a |_LineSource| + object. Its boolean value is |True| when it contains text, |False| when + its text is the empty string or whitespace only. + """ + + def __init__(self, text): + self._text = text + + def __bool__(self): + """ + Gives this object boolean behaviors (in Python 3). bool(line_source) + is False if it contains the empty string or whitespace only. + """ + return self._text.strip() != "" + + def __eq__(self, other): + return self._text == other._text + + def __iter__(self): + """ + Generate a (text, remainder) pair for each possible even-word line + break in this line source, where *text* is a str value and remainder + is a |_LineSource| value. + """ + words = self._text.split() + for idx in range(1, len(words) + 1): + line_text = " ".join(words[:idx]) + remainder_text = " ".join(words[idx:]) + remainder = _LineSource(remainder_text) + yield _Line(line_text, remainder) + + def __nonzero__(self): + """ + Gives this object boolean behaviors (in Python 2). bool(line_source) + is False if it contains the empty string or whitespace only. + """ + return self._text.strip() != "" + + def __repr__(self): + return "<_LineSource('%s')>" % self._text + + +class _Line(tuple): + """ + A candidate line broken at an even word boundary from a string of text, + and a |_LineSource| value containing the text that remains after the line + is broken at this spot. + """ + + def __new__(cls, text, remainder): + return tuple.__new__(cls, (text, remainder)) + + def __gt__(self, other): + return len(self.text) > len(other.text) + + def __lt__(self, other): + return not self.__gt__(other) + + def __len__(self): + return len(self.text) + + def __repr__(self): + return "'%s' => '%s'" % (self.text, self.remainder) + + @property + def remainder(self): + return self[1] + + @property + def text(self): + return self[0] + + +class _Fonts(object): + """ + A memoizing cache for ImageFont objects. + """ + + fonts = {} + + @classmethod + def font(cls, font_path, point_size): + if (font_path, point_size) not in cls.fonts: + cls.fonts[(font_path, point_size)] = ImageFont.truetype(font_path, point_size) + return cls.fonts[(font_path, point_size)] + + +def _rendered_size(text, point_size, font_file): + """ + Return a (width, height) pair representing the size of *text* in English + Metric Units (EMU) when rendered at *point_size* in the font defined in + *font_file*. + """ + emu_per_inch = 914400 + px_per_inch = 72.0 + + font = _Fonts.font(font_file, point_size) + try: + px_width, px_height = font.getsize(text) + except AttributeError: + left, top, right, bottom = font.getbbox(text) + px_width, px_height = right - left, bottom - top + + emu_width = int(px_width / px_per_inch * emu_per_inch) + emu_height = int(px_height / px_per_inch * emu_per_inch) + + return emu_width, emu_height diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/text.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/text.py new file mode 100644 index 0000000000000000000000000000000000000000..e139410c2c58745856fcd6e8df5a6786ee100875 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/text/text.py @@ -0,0 +1,681 @@ +"""Text-related objects such as TextFrame and Paragraph.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Iterator, cast + +from pptx.dml.fill import FillFormat +from pptx.enum.dml import MSO_FILL +from pptx.enum.lang import MSO_LANGUAGE_ID +from pptx.enum.text import MSO_AUTO_SIZE, MSO_UNDERLINE, MSO_VERTICAL_ANCHOR +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.oxml.simpletypes import ST_TextWrappingType +from pptx.shapes import Subshape +from pptx.text.fonts import FontFiles +from pptx.text.layout import TextFitter +from pptx.util import Centipoints, Emu, Length, Pt, lazyproperty + +if TYPE_CHECKING: + from pptx.dml.color import ColorFormat + from pptx.enum.text import ( + MSO_TEXT_UNDERLINE_TYPE, + MSO_VERTICAL_ANCHOR, + PP_PARAGRAPH_ALIGNMENT, + ) + from pptx.oxml.action import CT_Hyperlink + from pptx.oxml.text import ( + CT_RegularTextRun, + CT_TextBody, + CT_TextCharacterProperties, + CT_TextParagraph, + CT_TextParagraphProperties, + ) + from pptx.types import ProvidesExtents, ProvidesPart + + +class TextFrame(Subshape): + """The part of a shape that contains its text. + + Not all shapes have a text frame. Corresponds to the `p:txBody` element that can + appear as a child element of `p:sp`. Not intended to be constructed directly. + """ + + def __init__(self, txBody: CT_TextBody, parent: ProvidesPart): + super(TextFrame, self).__init__(parent) + self._element = self._txBody = txBody + self._parent = parent + + def add_paragraph(self): + """ + Return new |_Paragraph| instance appended to the sequence of + paragraphs contained in this text frame. + """ + p = self._txBody.add_p() + return _Paragraph(p, self) + + @property + def auto_size(self) -> MSO_AUTO_SIZE | None: + """Resizing strategy used to fit text within this shape. + + Determins the type of automatic resizing used to fit the text of this shape within its + bounding box when the text would otherwise extend beyond the shape boundaries. May be + |None|, `MSO_AUTO_SIZE.NONE`, `MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT`, or + `MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE`. + """ + return self._bodyPr.autofit + + @auto_size.setter + def auto_size(self, value: MSO_AUTO_SIZE | None): + self._bodyPr.autofit = value + + def clear(self): + """Remove all paragraphs except one empty one.""" + for p in self._txBody.p_lst[1:]: + self._txBody.remove(p) + p = self.paragraphs[0] + p.clear() + + def fit_text( + self, + font_family: str = "Calibri", + max_size: int = 18, + bold: bool = False, + italic: bool = False, + font_file: str | None = None, + ): + """Fit text-frame text entirely within bounds of its shape. + + Make the text in this text frame fit entirely within the bounds of its shape by setting + word wrap on and applying the "best-fit" font size to all the text it contains. + + :attr:`TextFrame.auto_size` is set to :attr:`MSO_AUTO_SIZE.NONE`. The font size will not + be set larger than `max_size` points. If the path to a matching TrueType font is provided + as `font_file`, that font file will be used for the font metrics. If `font_file` is |None|, + best efforts are made to locate a font file with matchhing `font_family`, `bold`, and + `italic` installed on the current system (usually succeeds if the font is installed). + """ + # ---no-op when empty as fit behavior not defined for that case--- + if self.text == "": + return # pragma: no cover + + font_size = self._best_fit_font_size(font_family, max_size, bold, italic, font_file) + self._apply_fit(font_family, font_size, bold, italic) + + @property + def margin_bottom(self) -> Length: + """|Length| value representing the inset of text from the bottom text frame border. + + :meth:`pptx.util.Inches` provides a convenient way of setting the value, e.g. + `text_frame.margin_bottom = Inches(0.05)`. + """ + return self._bodyPr.bIns + + @margin_bottom.setter + def margin_bottom(self, emu: Length): + self._bodyPr.bIns = emu + + @property + def margin_left(self) -> Length: + """Inset of text from left text frame border as |Length| value.""" + return self._bodyPr.lIns + + @margin_left.setter + def margin_left(self, emu: Length): + self._bodyPr.lIns = emu + + @property + def margin_right(self) -> Length: + """Inset of text from right text frame border as |Length| value.""" + return self._bodyPr.rIns + + @margin_right.setter + def margin_right(self, emu: Length): + self._bodyPr.rIns = emu + + @property + def margin_top(self) -> Length: + """Inset of text from top text frame border as |Length| value.""" + return self._bodyPr.tIns + + @margin_top.setter + def margin_top(self, emu: Length): + self._bodyPr.tIns = emu + + @property + def paragraphs(self) -> tuple[_Paragraph, ...]: + """Sequence of paragraphs in this text frame. + + A text frame always contains at least one paragraph. + """ + return tuple([_Paragraph(p, self) for p in self._txBody.p_lst]) + + @property + def text(self) -> str: + """All text in this text-frame as a single string. + + Read/write. The return value contains all text in this text-frame. A line-feed character + (`"\\n"`) separates the text for each paragraph. A vertical-tab character (`"\\v"`) appears + for each line break (aka. soft carriage-return) encountered. + + The vertical-tab character is how PowerPoint represents a soft carriage return in clipboard + text, which is why that encoding was chosen. + + Assignment replaces all text in the text frame. A new paragraph is added for each line-feed + character (`"\\n"`) encountered. A line-break (soft carriage-return) is inserted for each + vertical-tab character (`"\\v"`) encountered. + + Any control character other than newline, tab, or vertical-tab are escaped as plain-text + like "_x001B_" (for ESC (ASCII 32) in this example). + """ + return "\n".join(paragraph.text for paragraph in self.paragraphs) + + @text.setter + def text(self, text: str): + txBody = self._txBody + txBody.clear_content() + for p_text in text.split("\n"): + p = txBody.add_p() + p.append_text(p_text) + + @property + def vertical_anchor(self) -> MSO_VERTICAL_ANCHOR | None: + """Represents the vertical alignment of text in this text frame. + + |None| indicates the effective value should be inherited from this object's style hierarchy. + """ + return self._txBody.bodyPr.anchor + + @vertical_anchor.setter + def vertical_anchor(self, value: MSO_VERTICAL_ANCHOR | None): + bodyPr = self._txBody.bodyPr + bodyPr.anchor = value + + @property + def word_wrap(self) -> bool | None: + """`True` when lines of text in this shape are wrapped to fit within the shape's width. + + Read-write. Valid values are True, False, or None. True and False turn word wrap on and + off, respectively. Assigning None to word wrap causes any word wrap setting to be removed + from the text frame, causing it to inherit this setting from its style hierarchy. + """ + return { + ST_TextWrappingType.SQUARE: True, + ST_TextWrappingType.NONE: False, + None: None, + }[self._txBody.bodyPr.wrap] + + @word_wrap.setter + def word_wrap(self, value: bool | None): + if value not in (True, False, None): + raise ValueError( # pragma: no cover + "assigned value must be True, False, or None, got %s" % value + ) + self._txBody.bodyPr.wrap = { + True: ST_TextWrappingType.SQUARE, + False: ST_TextWrappingType.NONE, + None: None, + }[value] + + def _apply_fit(self, font_family: str, font_size: int, is_bold: bool, is_italic: bool): + """Arrange text in this text frame to fit inside its extents. + + This is accomplished by setting auto size off, wrap on, and setting the font of + all its text to `font_family`, `font_size`, `is_bold`, and `is_italic`. + """ + self.auto_size = MSO_AUTO_SIZE.NONE + self.word_wrap = True + self._set_font(font_family, font_size, is_bold, is_italic) + + def _best_fit_font_size( + self, family: str, max_size: int, bold: bool, italic: bool, font_file: str | None + ) -> int: + """Return font-size in points that best fits text in this text-frame. + + The best-fit font size is the largest integer point size not greater than `max_size` that + allows all the text in this text frame to fit inside its extents when rendered using the + font described by `family`, `bold`, and `italic`. If `font_file` is specified, it is used + to calculate the fit, whether or not it matches `family`, `bold`, and `italic`. + """ + if font_file is None: + font_file = FontFiles.find(family, bold, italic) + return TextFitter.best_fit_font_size(self.text, self._extents, max_size, font_file) + + @property + def _bodyPr(self): + return self._txBody.bodyPr + + @property + def _extents(self) -> tuple[Length, Length]: + """(cx, cy) 2-tuple representing the effective rendering area of this text-frame. + + Margins are taken into account. + """ + parent = cast("ProvidesExtents", self._parent) + return ( + Length(parent.width - self.margin_left - self.margin_right), + Length(parent.height - self.margin_top - self.margin_bottom), + ) + + def _set_font(self, family: str, size: int, bold: bool, italic: bool): + """Set the font properties of all the text in this text frame.""" + + def iter_rPrs(txBody: CT_TextBody) -> Iterator[CT_TextCharacterProperties]: + for p in txBody.p_lst: + for elm in p.content_children: + yield elm.get_or_add_rPr() + # generate a:endParaRPr for each element + yield p.get_or_add_endParaRPr() + + def set_rPr_font( + rPr: CT_TextCharacterProperties, name: str, size: int, bold: bool, italic: bool + ): + f = Font(rPr) + f.name, f.size, f.bold, f.italic = family, Pt(size), bold, italic + + txBody = self._element + for rPr in iter_rPrs(txBody): + set_rPr_font(rPr, family, size, bold, italic) + + +class Font(object): + """Character properties object, providing font size, font name, bold, italic, etc. + + Corresponds to `a:rPr` child element of a run. Also appears as `a:defRPr` and + `a:endParaRPr` in paragraph and `a:defRPr` in list style elements. + """ + + def __init__(self, rPr: CT_TextCharacterProperties): + super(Font, self).__init__() + self._element = self._rPr = rPr + + @property + def bold(self) -> bool | None: + """Get or set boolean bold value of |Font|, e.g. `paragraph.font.bold = True`. + + If set to |None|, the bold setting is cleared and is inherited from an enclosing shape's + setting, or a setting in a style or master. Returns None if no bold attribute is present, + meaning the effective bold value is inherited from a master or the theme. + """ + return self._rPr.b + + @bold.setter + def bold(self, value: bool | None): + self._rPr.b = value + + @lazyproperty + def color(self) -> ColorFormat: + """The |ColorFormat| instance that provides access to the color settings for this font.""" + if self.fill.type != MSO_FILL.SOLID: + self.fill.solid() + return self.fill.fore_color + + @lazyproperty + def fill(self) -> FillFormat: + """|FillFormat| instance for this font. + + Provides access to fill properties such as fill color. + """ + return FillFormat.from_fill_parent(self._rPr) + + @property + def italic(self) -> bool | None: + """Get or set boolean italic value of |Font| instance. + + Has the same behaviors as bold with respect to None values. + """ + return self._rPr.i + + @italic.setter + def italic(self, value: bool | None): + self._rPr.i = value + + @property + def language_id(self) -> MSO_LANGUAGE_ID | None: + """Get or set the language id of this |Font| instance. + + The language id is a member of the :ref:`MsoLanguageId` enumeration. Assigning |None| + removes any language setting, the same behavior as assigning `MSO_LANGUAGE_ID.NONE`. + """ + lang = self._rPr.lang + if lang is None: + return MSO_LANGUAGE_ID.NONE + return self._rPr.lang + + @language_id.setter + def language_id(self, value: MSO_LANGUAGE_ID | None): + if value == MSO_LANGUAGE_ID.NONE: + value = None + self._rPr.lang = value + + @property + def name(self) -> str | None: + """Get or set the typeface name for this |Font| instance. + + Causes the text it controls to appear in the named font, if a matching font is found. + Returns |None| if the typeface is currently inherited from the theme. Setting it to |None| + removes any override of the theme typeface. + """ + latin = self._rPr.latin + if latin is None: + return None + return latin.typeface + + @name.setter + def name(self, value: str | None): + if value is None: + self._rPr._remove_latin() # pyright: ignore[reportPrivateUsage] + else: + latin = self._rPr.get_or_add_latin() + latin.typeface = value + + @property + def size(self) -> Length | None: + """Indicates the font height in English Metric Units (EMU). + + Read/write. |None| indicates the font size should be inherited from its style hierarchy, + such as a placeholder or document defaults (usually 18pt). |Length| is a subclass of |int| + having properties for convenient conversion into points or other length units. Likewise, + the :class:`pptx.util.Pt` class allows convenient specification of point values:: + + >>> font.size = Pt(24) + >>> font.size + 304800 + >>> font.size.pt + 24.0 + """ + sz = self._rPr.sz + if sz is None: + return None + return Centipoints(sz) + + @size.setter + def size(self, emu: Length | None): + if emu is None: + self._rPr.sz = None + else: + sz = Emu(emu).centipoints + self._rPr.sz = sz + + @property + def underline(self) -> bool | MSO_TEXT_UNDERLINE_TYPE | None: + """Indicaties the underline setting for this font. + + Value is |True|, |False|, |None|, or a member of the :ref:`MsoTextUnderlineType` + enumeration. |None| is the default and indicates the underline setting should be inherited + from the style hierarchy, such as from a placeholder. |True| indicates single underline. + |False| indicates no underline. Other settings such as double and wavy underlining are + indicated with members of the :ref:`MsoTextUnderlineType` enumeration. + """ + u = self._rPr.u + if u is MSO_UNDERLINE.NONE: + return False + if u is MSO_UNDERLINE.SINGLE_LINE: + return True + return u + + @underline.setter + def underline(self, value: bool | MSO_TEXT_UNDERLINE_TYPE | None): + if value is True: + value = MSO_UNDERLINE.SINGLE_LINE + elif value is False: + value = MSO_UNDERLINE.NONE + self._element.u = value + + +class _Hyperlink(Subshape): + """Text run hyperlink object. + + Corresponds to `a:hlinkClick` child element of the run's properties element (`a:rPr`). + """ + + def __init__(self, rPr: CT_TextCharacterProperties, parent: ProvidesPart): + super(_Hyperlink, self).__init__(parent) + self._rPr = rPr + + @property + def address(self) -> str | None: + """The URL of the hyperlink. + + Read/write. URL can be on http, https, mailto, or file scheme; others may work. + """ + if self._hlinkClick is None: + return None + return self.part.target_ref(self._hlinkClick.rId) + + @address.setter + def address(self, url: str | None): + # implements all three of add, change, and remove hyperlink + if self._hlinkClick is not None: + self._remove_hlinkClick() + if url: + self._add_hlinkClick(url) + + def _add_hlinkClick(self, url: str): + rId = self.part.relate_to(url, RT.HYPERLINK, is_external=True) + self._rPr.add_hlinkClick(rId) + + @property + def _hlinkClick(self) -> CT_Hyperlink | None: + return self._rPr.hlinkClick + + def _remove_hlinkClick(self): + assert self._hlinkClick is not None + self.part.drop_rel(self._hlinkClick.rId) + self._rPr._remove_hlinkClick() # pyright: ignore[reportPrivateUsage] + + +class _Paragraph(Subshape): + """Paragraph object. Not intended to be constructed directly.""" + + def __init__(self, p: CT_TextParagraph, parent: ProvidesPart): + super(_Paragraph, self).__init__(parent) + self._element = self._p = p + + def add_line_break(self): + """Add line break at end of this paragraph.""" + self._p.add_br() + + def add_run(self) -> _Run: + """Return a new run appended to the runs in this paragraph.""" + r = self._p.add_r() + return _Run(r, self) + + @property + def alignment(self) -> PP_PARAGRAPH_ALIGNMENT | None: + """Horizontal alignment of this paragraph. + + The value |None| indicates the paragraph should 'inherit' its effective value from its + style hierarchy. Assigning |None| removes any explicit setting, causing its inherited + value to be used. + """ + return self._pPr.algn + + @alignment.setter + def alignment(self, value: PP_PARAGRAPH_ALIGNMENT | None): + self._pPr.algn = value + + def clear(self): + """Remove all content from this paragraph. + + Paragraph properties are preserved. Content includes runs, line breaks, and fields. + """ + for elm in self._element.content_children: + self._element.remove(elm) + return self + + @property + def font(self) -> Font: + """|Font| object containing default character properties for the runs in this paragraph. + + These character properties override default properties inherited from parent objects such + as the text frame the paragraph is contained in and they may be overridden by character + properties set at the run level. + """ + return Font(self._defRPr) + + @property + def level(self) -> int: + """Indentation level of this paragraph. + + Read-write. Integer in range 0..8 inclusive. 0 represents a top-level paragraph and is the + default value. Indentation level is most commonly encountered in a bulleted list, as is + found on a word bullet slide. + """ + return self._pPr.lvl + + @level.setter + def level(self, level: int): + self._pPr.lvl = level + + @property + def line_spacing(self) -> int | float | Length | None: + """The space between baselines in successive lines of this paragraph. + + A value of |None| indicates no explicit value is assigned and its effective value is + inherited from the paragraph's style hierarchy. A numeric value, e.g. `2` or `1.5`, + indicates spacing is applied in multiples of line heights. A |Length| value such as + `Pt(12)` indicates spacing is a fixed height. The |Pt| value class is a convenient way to + apply line spacing in units of points. + """ + pPr = self._p.pPr + if pPr is None: + return None + return pPr.line_spacing + + @line_spacing.setter + def line_spacing(self, value: int | float | Length | None): + pPr = self._p.get_or_add_pPr() + pPr.line_spacing = value + + @property + def runs(self) -> tuple[_Run, ...]: + """Sequence of runs in this paragraph.""" + return tuple(_Run(r, self) for r in self._element.r_lst) + + @property + def space_after(self) -> Length | None: + """The spacing to appear between this paragraph and the subsequent paragraph. + + A value of |None| indicates no explicit value is assigned and its effective value is + inherited from the paragraph's style hierarchy. |Length| objects provide convenience + properties, such as `.pt` and `.inches`, that allow easy conversion to various length + units. + """ + pPr = self._p.pPr + if pPr is None: + return None + return pPr.space_after + + @space_after.setter + def space_after(self, value: Length | None): + pPr = self._p.get_or_add_pPr() + pPr.space_after = value + + @property + def space_before(self) -> Length | None: + """The spacing to appear between this paragraph and the prior paragraph. + + A value of |None| indicates no explicit value is assigned and its effective value is + inherited from the paragraph's style hierarchy. |Length| objects provide convenience + properties, such as `.pt` and `.cm`, that allow easy conversion to various length units. + """ + pPr = self._p.pPr + if pPr is None: + return None + return pPr.space_before + + @space_before.setter + def space_before(self, value: Length | None): + pPr = self._p.get_or_add_pPr() + pPr.space_before = value + + @property + def text(self) -> str: + """Text of paragraph as a single string. + + Read/write. This value is formed by concatenating the text in each run and field making up + the paragraph, adding a vertical-tab character (`"\\v"`) for each line-break element + (``, soft carriage-return) encountered. + + While the encoding of line-breaks as a vertical tab might be surprising at first, doing so + is consistent with PowerPoint's clipboard copy behavior and allows a line-break to be + distinguished from a paragraph boundary within the str return value. + + Assignment causes all content in the paragraph to be replaced. Each vertical-tab character + (`"\\v"`) in the assigned str is translated to a line-break, as is each line-feed + character (`"\\n"`). Contrast behavior of line-feed character in `TextFrame.text` setter. + If line-feed characters are intended to produce new paragraphs, use `TextFrame.text` + instead. Any other control characters in the assigned string are escaped as a hex + representation like "_x001B_" (for ESC (ASCII 27) in this example). + """ + return "".join(elm.text for elm in self._element.content_children) + + @text.setter + def text(self, text: str): + self.clear() + self._element.append_text(text) + + @property + def _defRPr(self) -> CT_TextCharacterProperties: + """The element that defines the default run properties for runs in this paragraph. + + Causes the element to be added if not present. + """ + return self._pPr.get_or_add_defRPr() + + @property + def _pPr(self) -> CT_TextParagraphProperties: + """Contains the properties for this paragraph. + + Causes the element to be added if not present. + """ + return self._p.get_or_add_pPr() + + +class _Run(Subshape): + """Text run object. Corresponds to `a:r` child element in a paragraph.""" + + def __init__(self, r: CT_RegularTextRun, parent: ProvidesPart): + super(_Run, self).__init__(parent) + self._r = r + + @property + def font(self): + """|Font| instance containing run-level character properties for the text in this run. + + Character properties can be and perhaps most often are inherited from parent objects such + as the paragraph and slide layout the run is contained in. Only those specifically + overridden at the run level are contained in the font object. + """ + rPr = self._r.get_or_add_rPr() + return Font(rPr) + + @lazyproperty + def hyperlink(self) -> _Hyperlink: + """Proxy for any `a:hlinkClick` element under the run properties element. + + Created on demand, the hyperlink object is available whether an `a:hlinkClick` element is + present or not, and creates or deletes that element as appropriate in response to actions + on its methods and attributes. + """ + rPr = self._r.get_or_add_rPr() + return _Hyperlink(rPr, self) + + @property + def text(self): + """Read/write. A unicode string containing the text in this run. + + Assignment replaces all text in the run. The assigned value can be a 7-bit ASCII + string, a UTF-8 encoded 8-bit string, or unicode. String values are converted to + unicode assuming UTF-8 encoding. + + Any other control characters in the assigned string other than tab or newline + are escaped as a hex representation. For example, ESC (ASCII 27) is escaped as + "_x001B_". Contrast the behavior of `TextFrame.text` and `_Paragraph.text` with + respect to line-feed and vertical-tab characters. + """ + return self._r.text + + @text.setter + def text(self, text: str): + self._r.text = text diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/types.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/types.py new file mode 100644 index 0000000000000000000000000000000000000000..46d86661b822a3c0e4f7108aa3511aa392162eb1 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/types.py @@ -0,0 +1,36 @@ +"""Abstract types used by `python-pptx`.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from typing_extensions import Protocol + +if TYPE_CHECKING: + from pptx.opc.package import XmlPart + from pptx.util import Length + + +class ProvidesExtents(Protocol): + """An object that has width and height.""" + + @property + def height(self) -> Length: + """Distance between top and bottom extents of shape in EMUs.""" + ... + + @property + def width(self) -> Length: + """Distance between left and right extents of shape in EMUs.""" + ... + + +class ProvidesPart(Protocol): + """An object that provides access to its XmlPart. + + This type is for objects that need access to their part, possibly because they need access to + the package or related parts. + """ + + @property + def part(self) -> XmlPart: ... diff --git a/tasks/tasksmith-74f059424102/environment/source/src/pptx/util.py b/tasks/tasksmith-74f059424102/environment/source/src/pptx/util.py new file mode 100644 index 0000000000000000000000000000000000000000..fdec79298cab3192e506323739d25c04c5ec027c --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/pptx/util.py @@ -0,0 +1,214 @@ +"""Utility functions and classes.""" + +from __future__ import annotations + +import functools +from typing import Any, Callable, Generic, TypeVar, cast + + +class Length(int): + """Base class for length classes Inches, Emu, Cm, Mm, and Pt. + + Provides properties for converting length values to convenient units. + """ + + _EMUS_PER_INCH = 914400 + _EMUS_PER_CENTIPOINT = 127 + _EMUS_PER_CM = 360000 + _EMUS_PER_MM = 36000 + _EMUS_PER_PT = 12700 + + def __new__(cls, emu: int): + return int.__new__(cls, emu) + + @property + def inches(self) -> float: + """Floating point length in inches.""" + return self / float(self._EMUS_PER_INCH) + + @property + def centipoints(self) -> int: + """Integer length in hundredths of a point (1/7200 inch). + + Used internally because PowerPoint stores font size in centipoints. + """ + return self // self._EMUS_PER_CENTIPOINT + + @property + def cm(self) -> float: + """Floating point length in centimeters.""" + return self / float(self._EMUS_PER_CM) + + @property + def emu(self) -> int: + """Integer length in English Metric Units.""" + return self + + @property + def mm(self) -> float: + """Floating point length in millimeters.""" + return self / float(self._EMUS_PER_MM) + + @property + def pt(self) -> float: + """Floating point length in points.""" + return self / float(self._EMUS_PER_PT) + + +class Inches(Length): + """Convenience constructor for length in inches.""" + + def __new__(cls, inches: float): + emu = int(inches * Length._EMUS_PER_INCH) + return Length.__new__(cls, emu) + + +class Centipoints(Length): + """Convenience constructor for length in hundredths of a point.""" + + def __new__(cls, centipoints: int): + emu = int(centipoints * Length._EMUS_PER_CENTIPOINT) + return Length.__new__(cls, emu) + + +class Cm(Length): + """Convenience constructor for length in centimeters.""" + + def __new__(cls, cm: float): + emu = int(cm * Length._EMUS_PER_CM) + return Length.__new__(cls, emu) + + +class Emu(Length): + """Convenience constructor for length in english metric units.""" + + def __new__(cls, emu: int): + return Length.__new__(cls, int(emu)) + + +class Mm(Length): + """Convenience constructor for length in millimeters.""" + + def __new__(cls, mm: float): + emu = int(mm * Length._EMUS_PER_MM) + return Length.__new__(cls, emu) + + +class Pt(Length): + """Convenience value class for specifying a length in points.""" + + def __new__(cls, points: float): + emu = int(points * Length._EMUS_PER_PT) + return Length.__new__(cls, emu) + + +_T = TypeVar("_T") + + +class lazyproperty(Generic[_T]): + """Decorator like @property, but evaluated only on first access. + + Like @property, this can only be used to decorate methods having only a `self` parameter, and + is accessed like an attribute on an instance, i.e. trailing parentheses are not used. Unlike + @property, the decorated method is only evaluated on first access; the resulting value is + cached and that same value returned on second and later access without re-evaluation of the + method. + + Like @property, this class produces a *data descriptor* object, which is stored in the __dict__ + of the *class* under the name of the decorated method ('fget' nominally). The cached value is + stored in the __dict__ of the *instance* under that same name. + + Because it is a data descriptor (as opposed to a *non-data descriptor*), its `__get__()` method + is executed on each access of the decorated attribute; the __dict__ item of the same name is + "shadowed" by the descriptor. + + While this may represent a performance improvement over a property, its greater benefit may be + its other characteristics. One common use is to construct collaborator objects, removing that + "real work" from the constructor, while still only executing once. It also de-couples client + code from any sequencing considerations; if it's accessed from more than one location, it's + assured it will be ready whenever needed. + + Loosely based on: https://stackoverflow.com/a/6849299/1902513. + + A lazyproperty is read-only. There is no counterpart to the optional "setter" (or deleter) + behavior of an @property. This is critically important to maintaining its immutability and + idempotence guarantees. Attempting to assign to a lazyproperty raises AttributeError + unconditionally. + + The parameter names in the methods below correspond to this usage example:: + + class Obj(object) + + @lazyproperty + def fget(self): + return 'some result' + + obj = Obj() + + Not suitable for wrapping a function (as opposed to a method) because it is not callable. + """ + + def __init__(self, fget: Callable[..., _T]) -> None: + """*fget* is the decorated method (a "getter" function). + + A lazyproperty is read-only, so there is only an *fget* function (a regular + @property can also have an fset and fdel function). This name was chosen for + consistency with Python's `property` class which uses this name for the + corresponding parameter. + """ + # --- maintain a reference to the wrapped getter method + self._fget = fget + # --- and store the name of that decorated method + self._name = fget.__name__ + # --- adopt fget's __name__, __doc__, and other attributes + functools.update_wrapper(self, fget) # pyright: ignore + + def __get__(self, obj: Any, type: Any = None) -> _T: + """Called on each access of 'fget' attribute on class or instance. + + *self* is this instance of a lazyproperty descriptor "wrapping" the property + method it decorates (`fget`, nominally). + + *obj* is the "host" object instance when the attribute is accessed from an + object instance, e.g. `obj = Obj(); obj.fget`. *obj* is None when accessed on + the class, e.g. `Obj.fget`. + + *type* is the class hosting the decorated getter method (`fget`) on both class + and instance attribute access. + """ + # --- when accessed on class, e.g. Obj.fget, just return this descriptor + # --- instance (patched above to look like fget). + if obj is None: + return self # type: ignore + + # --- when accessed on instance, start by checking instance __dict__ for + # --- item with key matching the wrapped function's name + value = obj.__dict__.get(self._name) + if value is None: + # --- on first access, the __dict__ item will be absent. Evaluate fget() + # --- and store that value in the (otherwise unused) host-object + # --- __dict__ value of same name ('fget' nominally) + value = self._fget(obj) + obj.__dict__[self._name] = value + return cast(_T, value) + + def __set__(self, obj: Any, value: Any) -> None: + """Raises unconditionally, to preserve read-only behavior. + + This decorator is intended to implement immutable (and idempotent) object + attributes. For that reason, assignment to this property must be explicitly + prevented. + + If this __set__ method was not present, this descriptor would become a + *non-data descriptor*. That would be nice because the cached value would be + accessed directly once set (__dict__ attrs have precedence over non-data + descriptors on instance attribute lookup). The problem is, there would be + nothing to stop assignment to the cached value, which would overwrite the result + of `fget()` and break both the immutability and idempotence guarantees of this + decorator. + + The performance with this __set__() method in place was roughly 0.4 usec per + access when measured on a 2.8GHz development machine; so quite snappy and + probably not a rich target for optimization efforts. + """ + raise AttributeError("can't set attribute") diff --git a/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/PKG-INFO b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..d6ac0e093353675eed0309d5f97020b03da44c65 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/PKG-INFO @@ -0,0 +1,599 @@ +Metadata-Version: 2.4 +Name: python-pptx +Version: 0.6.23 +Summary: Generate and manipulate Open XML PowerPoint (.pptx) files +Home-page: https://github.com/scanny/python-pptx +Author: Steve Canny +Author-email: python-pptx@googlegroups.com +License: MIT +Keywords: powerpoint ppt pptx office open xml +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Topic :: Office/Business :: Office Suites +Classifier: Topic :: Software Development :: Libraries +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: lxml>=3.1.0 +Requires-Dist: Pillow>=3.3.2 +Requires-Dist: XlsxWriter>=0.5.7 +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: requires-dist +Dynamic: summary + +*python-pptx* is a Python library for creating, reading, and updating PowerPoint (.pptx) +files. + +A typical use would be generating a PowerPoint presentation from dynamic content such as +a database query, analytics output, or a JSON payload, perhaps in response to an HTTP +request and downloading the generated PPTX file in response. It runs on any Python +capable platform, including macOS and Linux, and does not require the PowerPoint +application to be installed or licensed. + +It can also be used to analyze PowerPoint files from a corpus, perhaps to extract search +indexing text and images. + +In can also be used to simply automate the production of a slide or two that would be +tedious to get right by hand, which is how this all got started. + +More information is available in the `python-pptx documentation`_. + +Browse `examples with screenshots`_ to get a quick idea what you can do with +python-pptx. + +.. _`python-pptx documentation`: + https://python-pptx.readthedocs.org/en/latest/ + +.. _`examples with screenshots`: + https://python-pptx.readthedocs.org/en/latest/user/quickstart.html + + +.. :changelog: + +Release History +--------------- + +0.6.24-dev0 ++++++++++++++++++++ + +- fix: #943 remove mention of a Px Length subtype + +0.6.23 (2023-11-02) ++++++++++++++++++++ + +- fix: #912 Pillow<=9.5 constraint entails security vulnerability + + +0.6.22 (2023-08-28) ++++++++++++++++++++ + +- Add #909 Add imgW, imgH params to `shapes.add_ole_object()` +- fix: #754 _Relationships.items() raises +- fix: #758 quote in autoshape name must be escaped +- fix: #746 update Python 3.x support in docs +- fix: #748 setup's `license` should be short string +- fix: #762 AttributeError: module 'collections' has no attribute 'abc' + (Windows Python 3.10+) + + +0.6.21 (2021-09-20) ++++++++++++++++++++ + +- Fix #741 _DirPkgReader must implement .__contains__() + + +0.6.20 (2021-09-14) ++++++++++++++++++++ + +- Fix #206 accommodate NULL target-references in relationships. +- Fix #223 escape image filename that appears as literal in XML. +- Fix #517 option to display chart categories/values in reverse order. +- Major refactoring of ancient package loading code. + + +0.6.19 (2021-05-17) ++++++++++++++++++++ + +- Add shapes.add_ole_object(), allowing arbitrary Excel or other binary file to be + embedded as a shape on a slide. The OLE object is represented as an icon. + + +0.6.18 (2019-05-02) ++++++++++++++++++++ + +- .text property getters encode line-break as a vertical-tab (VT, '\v', ASCII 11/x0B). + This is consistent with PowerPoint's copy/paste behavior and allows like-breaks (soft + carriage-return) to be distinguished from paragraph boundary. Previously, a line-break + was encoded as a newline ('\n') and was not distinguishable from a paragraph boundary. + + .text properties include Shape.text, _Cell.text, TextFrame.text, _Paragraph.text and + _Run.text. + +- .text property setters accept vertical-tab character and place a line-break element in + that location. All other control characters other than horizontal-tab ('\t') and + newline ('\n') in range \x00-\x1F are accepted and escaped with plain-text like + "_x001B" for ESC (ASCII 27). + + Previously a control character other than tab or newline in an assigned string would + trigger an exception related to invalid XML character. + + +0.6.17 (2018-12-16) ++++++++++++++++++++ + +- Add SlideLayouts.remove() - Delete unused slide-layout +- Add SlideLayout.used_by_slides - Get slides based on this slide-layout +- Add SlideLayouts.index() - Get index of slide-layout in master +- Add SlideLayouts.get_by_name() - Get slide-layout by its str name + + +0.6.16 (2018-11-09) ++++++++++++++++++++ + +- Feature #395 DataLabels.show_* properties, e.g. .show_percentage +- Feature #453 Chart data tolerates None for labels + + +0.6.15 (2018-09-24) ++++++++++++++++++++ + +- Fix #436 ValueAxis._cross_xAx fails on c:dateAxis + + +0.6.14 (2018-09-24) ++++++++++++++++++++ + +- Add _Cell.merge() +- Add _Cell.split() +- Add _Cell.__eq__() +- Add _Cell.is_merge_origin +- Add _Cell.is_spanned +- Add _Cell.span_height +- Add _Cell.span_width +- Add _Cell.text getter +- Add Table.iter_cells() +- Move pptx.shapes.table module to pptx.table +- Add user documentation 'Working with tables' + + +0.6.13 (2018-09-10) ++++++++++++++++++++ + +- Add Chart.font +- Fix #293 Can't hide title of single-series Chart +- Fix shape.width value is not type Emu +- Fix add a:defRPr with c:rich (fixes some font inheritance breakage) + + +0.6.12 (2018-08-11) ++++++++++++++++++++ + +- Add Picture.auto_shape_type +- Remove Python 2.6 testing from build +- Update dependencies to avoid vulnerable Pillow version +- Fix #260, #301, #382, #401 +- Add _Paragraph.add_line_break() +- Add Connector.line + + +0.6.11 (2018-07-25) ++++++++++++++++++++ + +- Add gradient fill. +- Add experimental "turbo-add" option for producing large shape-count slides. + + +0.6.10 (2018-06-11) ++++++++++++++++++++ + +- Add `shape.shadow` property to autoshape, connector, picture, and group + shape, returning a `ShadowFormat` object. +- Add `ShadowFormat` object with read/write (boolean) `.inherit` property. +- Fix #328 add support for 26+ series in a chart + + +0.6.9 (2018-05-08) +++++++++++++++++++ + +- Add `Picture.crop_x` setters, allowing picture cropping values to be set, + in addition to interrogated. +- Add `Slide.background` and `SlideMaster.background`, allowing the + background fill to be set for an individual slide or for all slides based + on a slide master. +- Add option `shapes` parameter to `Shapes.add_group_shape`, allowing a group + shape to be formed from a number of existing shapes. +- Improve efficiency of `Shapes._next_shape_id` property to improve + performance on high shape-count slides. + + +0.6.8 (2018-04-18) +++++++++++++++++++ + +- Add `GroupShape`, providing properties specific to a group shape, including + its `shapes` property. +- Add `GroupShapes`, providing access to shapes contained in a group shape. +- Add `SlideShapes.add_group_shape()`, allowing a group shape to be added to + a slide. +- Add `GroupShapes.add_group_shape()`, allowing a group shape to be added to + a group shape, enabling recursive, multi-level groups. +- Add support for adding jump-to-named-slide behavior to shape and run + hyperlinks. + + +0.6.7 (2017-10-30) +++++++++++++++++++ + +- Add `SlideShapes.build_freeform()`, allowing freeform shapes (such as maps) + to be specified and added to a slide. +- Add support for patterned fills. +- Add `LineFormat.dash_style` to allow interrogation and setting of dashed + line styles. + + +0.6.6 (2017-06-17) +++++++++++++++++++ + +- Add `SlideShapes.add_movie()`, allowing video media to be added to a slide. + +- fix #190 Accommodate non-conforming part names having '00' index segment. +- fix #273 Accommodate non-conforming part names having no index segment. +- fix #277 ASCII/Unicode error on non-ASCII multi-level category names +- fix #279 BaseShape.id warning appearing on placeholder access. + + +0.6.5 (2017-03-21) +++++++++++++++++++ + +- #267 compensate for non-conforming PowerPoint behavior on c:overlay element + +- compensate for non-conforming (to spec) PowerPoint behavior related to + c:dLbl/c:tx that results in "can't save" error when explicit data labels + are added to bubbles on a bubble chart. + + +0.6.4 (2017-03-17) +++++++++++++++++++ + +- add Chart.chart_title and ChartTitle object +- #263 Use Number type to test for numeric category + + +0.6.3 (2017-02-28) +++++++++++++++++++ + +- add DataLabel.font +- add Axis.axis_title + + +0.6.2 (2017-01-03) +++++++++++++++++++ + +- add support for NotesSlide (slide notes, aka. notes page) +- add support for arbitrary series ordering in XML +- add Plot.categories providing access to hierarchical categories in an + existing chart. +- add support for date axes on category charts, including writing a dateAx + element for the category axis when ChartData categories are date or + datetime. + +**BACKWARD INCOMPATIBILITIES:** + +Some changes were made to the boilerplate XML used to create new charts. This +was done to more closely adhere to the settings PowerPoint uses when creating +a chart using the UI. This may result in some appearance changes in charts +after upgrading. In particular: + +* Chart.has_legend now defaults to True for Line charts. +* Plot.vary_by_categories now defaults to False for Line charts. + + +0.6.1 (2016-10-09) +++++++++++++++++++ + +- add Connector shape type + + +0.6.0 (2016-08-18) +++++++++++++++++++ + +- add XY chart types +- add Bubble chart types +- add Radar chart types +- add Area chart types +- add Doughnut chart types +- add Series.points and Point +- add Point.data_label +- add DataLabel.text_frame +- add DataLabel.position +- add Axis.major_gridlines +- add ChartFormat with .fill and .line +- add Axis.format (fill and line formatting) +- add ValueAxis.crosses and .crosses_at +- add Point.format (fill and line formatting) +- add Slide.slide_id +- add Slides.get() (by slide id) +- add Font.language_id +- support blank (None) data points in created charts +- add Series.marker +- add Point.marker +- add Marker.format, .style, and .size + + +0.5.8 (2015-11-27) +++++++++++++++++++ + +- add Shape.click_action (hyperlink on shape) +- fix: #128 Chart cat and ser names not escaped +- fix: #153 shapes.title raises on no title shape +- fix: #170 remove seek(0) from Image.from_file() + + +0.5.7 (2015-01-17) +++++++++++++++++++ + +- add PicturePlaceholder with .insert_picture() method +- add TablePlaceholder with .insert_table() method +- add ChartPlaceholder with .insert_chart() method +- add Picture.image property, returning Image object +- add Picture.crop_left, .crop_top, .crop_right, and .crop_bottom +- add Shape.placeholder_format and PlaceholderFormat object + +**BACKWARD INCOMPATIBILITIES:** + +Shape.shape_type is now unconditionally `MSO_SHAPE_TYPE.PLACEHOLDER` for all +placeholder shapes. Previously, some placeholder shapes reported +`MSO_SHAPE_TYPE.AUTO_SHAPE`, `MSO_SHAPE_TYPE.CHART`, +`MSO_SHAPE_TYPE.PICTURE`, or `MSO_SHAPE_TYPE.TABLE` for that property. + + +0.5.6 (2014-12-06) +++++++++++++++++++ + +- fix #138 - UnicodeDecodeError in setup.py on Windows 7 Python 3.4 + + +0.5.5 (2014-11-17) +++++++++++++++++++ + +- feature #51 - add Python 3 support + + +0.5.4 (2014-11-15) +++++++++++++++++++ + +- feature #43 - image native size in shapes.add_picture() is now calculated + based on DPI attribute in image file, if present, defaulting to 72 dpi. +- feature #113 - Add Paragraph.space_before, Paragraph.space_after, and + Paragraph.line_spacing + + +0.5.3 (2014-11-09) +++++++++++++++++++ + +- add experimental feature TextFrame.fit_text() + + +0.5.2 (2014-10-26) +++++++++++++++++++ + +- fix #127 - Shape.text_frame fails on shape having no txBody + + +0.5.1 (2014-09-22) +++++++++++++++++++ + +- feature #120 - add Shape.rotation +- feature #97 - add Font.underline +- issue #117 - add BMP image support +- issue #95 - add BaseShape.name setter +- issue #107 - all .text properties should return unicode, not str +- feature #106 - add .text getters to Shape, TextFrame, and Paragraph + +- Rename Shape.textframe to Shape.text_frame. + **Shape.textframe property (by that name) is deprecated.** + + +0.5.0 (2014-09-13) +++++++++++++++++++ + +- Add support for creating and manipulating bar, column, line, and pie charts +- Major refactoring of XML layer (oxml) +- Rationalized graphical object shape access + **Note backward incompatibilities below** + +**BACKWARD INCOMPATIBILITIES:** + +A table is no longer treated as a shape. Rather it is a graphical object +contained in a GraphicFrame shape, as are Chart and SmartArt objects. + +Example:: + + table = shapes.add_table(...) + + # becomes + + graphic_frame = shapes.add_table(...) + table = graphic_frame.table + + # or + + table = shapes.add_table(...).table + +As the enclosing shape, the id, name, shape type, position, and size are +attributes of the enclosing GraphicFrame object. + +The contents of a GraphicFrame shape can be identified using three available +properties on a shape: has_table, has_chart, and has_smart_art. The enclosed +graphical object is obtained using the properties GraphicFrame.table and +GraphicFrame.chart. SmartArt is not yet supported. Accessing one of these +properties on a GraphicFrame not containing the corresponding object raises +an exception. + + +0.4.2 (2014-04-29) +++++++++++++++++++ + +- fix: issue #88 -- raises on supported image file having uppercase extension +- fix: issue #89 -- raises on add_slide() where non-contiguous existing ids + + +0.4.1 (2014-04-29) +++++++++++++++++++ + +- Rename Presentation.slidemasters to Presentation.slide_masters. + Presentation.slidemasters property is deprecated. +- Rename Presentation.slidelayouts to Presentation.slide_layouts. + Presentation.slidelayouts property is deprecated. +- Rename SlideMaster.slidelayouts to SlideMaster.slide_layouts. + SlideMaster.slidelayouts property is deprecated. +- Rename SlideLayout.slidemaster to SlideLayout.slide_master. + SlideLayout.slidemaster property is deprecated. +- Rename Slide.slidelayout to Slide.slide_layout. Slide.slidelayout property + is deprecated. +- Add SlideMaster.shapes to access shapes on slide master. +- Add SlideMaster.placeholders to access placeholder shapes on slide master. +- Add _MasterPlaceholder class. +- Add _LayoutPlaceholder class with position and size inheritable from master + placeholder. +- Add _SlidePlaceholder class with position and size inheritable from layout + placeholder. +- Add Table.left, top, width, and height read/write properties. +- Add rudimentary GroupShape with left, top, width, and height properties. +- Add rudimentary Connector with left, top, width, and height properties. +- Add TextFrame.auto_size property. +- Add Presentation.slide_width and .slide_height read/write properties. +- Add LineFormat class providing access to read and change line color and + width. +- Add AutoShape.line +- Add Picture.line + +- Rationalize enumerations. **Note backward incompatibilities below** + +**BACKWARD INCOMPATIBILITIES:** + +The following enumerations were moved/renamed during the rationalization of +enumerations: + +- ``pptx.enum.MSO_COLOR_TYPE`` --> ``pptx.enum.dml.MSO_COLOR_TYPE`` +- ``pptx.enum.MSO_FILL`` --> ``pptx.enum.dml.MSO_FILL`` +- ``pptx.enum.MSO_THEME_COLOR`` --> ``pptx.enum.dml.MSO_THEME_COLOR`` +- ``pptx.constants.MSO.ANCHOR_*`` --> ``pptx.enum.text.MSO_ANCHOR.*`` +- ``pptx.constants.MSO_SHAPE`` --> ``pptx.enum.shapes.MSO_SHAPE`` +- ``pptx.constants.PP.ALIGN_*`` --> ``pptx.enum.text.PP_ALIGN.*`` +- ``pptx.constants.MSO.{SHAPE_TYPES}`` --> + ``pptx.enum.shapes.MSO_SHAPE_TYPE.*`` + +Documentation for all enumerations is available in the Enumerations section +of the User Guide. + + +0.3.2 (2014-02-07) +++++++++++++++++++ + +- Hotfix: issue #80 generated presentations fail to load in Keynote and other + Apple applications + + +0.3.1 (2014-01-10) +++++++++++++++++++ + +- Hotfix: failed to load certain presentations containing images with + uppercase extension + + +0.3.0 (2013-12-12) +++++++++++++++++++ + +- Add read/write font color property supporting RGB, theme color, and inherit + color types +- Add font typeface and italic support +- Add text frame margins and word-wrap +- Add support for external relationships, e.g. linked spreadsheet +- Add hyperlink support for text run in shape and table cell +- Add fill color and brightness for shape and table cell, fill can also be set + to transparent (no fill) +- Add read/write position and size properties to shape and picture +- Replace PIL dependency with Pillow +- Restructure modules to better suit size of library + + +0.2.6 (2013-06-22) +++++++++++++++++++ + +- Add read/write access to core document properties +- Hotfix to accomodate connector shapes in _AutoShapeType +- Hotfix to allow customXml parts to load when present + + +0.2.5 (2013-06-11) +++++++++++++++++++ + +- Add paragraph alignment property (left, right, centered, etc.) +- Add vertical alignment within table cell (top, middle, bottom) +- Add table cell margin properties +- Add table boolean properties: first column (row header), first row (column + headings), last row (for e.g. totals row), last column (for e.g. row + totals), horizontal banding, and vertical banding. +- Add support for auto shape adjustment values, e.g. change radius of corner + rounding on rounded rectangle, position of callout arrow, etc. + + +0.2.4 (2013-05-16) +++++++++++++++++++ + +- Add support for auto shapes (e.g. polygons, flowchart symbols, etc.) + + +0.2.3 (2013-05-05) +++++++++++++++++++ + +- Add support for table shapes +- Add indentation support to textbox shapes, enabling multi-level bullets on + bullet slides. + + +0.2.2 (2013-03-25) +++++++++++++++++++ + +- Add support for opening and saving a presentation from/to a file-like + object. +- Refactor XML handling to use lxml objectify + + +0.2.1 (2013-02-25) +++++++++++++++++++ + +- Add support for Python 2.6 +- Add images from a stream (e.g. StringIO) in addition to a path, allowing + images retrieved from a database or network resource to be inserted without + saving first. +- Expand text methods to accept unicode and UTF-8 encoded 8-bit strings. +- Fix potential install bug triggered by importing ``__version__`` from + package ``__init__.py`` file. + + +0.2.0 (2013-02-10) +++++++++++++++++++ + +First non-alpha release with basic capabilities: + +- open presentation/template or use built-in default template +- add slide +- set placeholder text (e.g. bullet slides) +- add picture +- add text box diff --git a/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/SOURCES.txt b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..368806924c6dce1995ad22f416d61006435c3c7f --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/SOURCES.txt @@ -0,0 +1,502 @@ +HISTORY.rst +LICENSE +MANIFEST.in +README.rst +pyproject.toml +setup.cfg +setup.py +tox.ini +features/act-action.feature +features/act-hyperlink.feature +features/cht-axis-props.feature +features/cht-axistitle-props.feature +features/cht-category-access.feature +features/cht-category-props.feature +features/cht-chart.feature +features/cht-charttitle-props.feature +features/cht-data-props.feature +features/cht-datalabels.feature +features/cht-gridlines-props.feature +features/cht-legend-access.feature +features/cht-legend-props.feature +features/cht-marker-props.feature +features/cht-plot-props.feature +features/cht-point-access.feature +features/cht-point-props.feature +features/cht-replace-data.feature +features/cht-series.feature +features/cht-ticklabels-props.feature +features/dml-color.feature +features/dml-effect.feature +features/dml-fill.feature +features/dml-line.feature +features/environment.py +features/ph-inherit-props.feature +features/ph-insert-shape.feature +features/ph-phfmt-props.feature +features/ph-placeholder-props.feature +features/prs-coreprops.feature +features/prs-default-template.feature +features/prs-open-save.feature +features/prs-presentation-props.feature +features/shp-autoshape.feature +features/shp-connector.feature +features/shp-freeform.feature +features/shp-graphicframe.feature +features/shp-groupshape.feature +features/shp-movie-props.feature +features/shp-picture.feature +features/shp-placeholder.feature +features/shp-shapes.feature +features/shp-shared.feature +features/sld-background.feature +features/sld-slide.feature +features/sld-slides.feature +features/tbl-cell.feature +features/tbl-column.feature +features/tbl-table.feature +features/txt-fit-text.feature +features/txt-font-color.feature +features/txt-font-props.feature +features/txt-paragraph.feature +features/txt-text.feature +features/txt-textframe.feature +features/steps/action.py +features/steps/axis.py +features/steps/background.py +features/steps/category.py +features/steps/chart.py +features/steps/chartdata.py +features/steps/color.py +features/steps/coreprops.py +features/steps/datalabel.py +features/steps/effect.py +features/steps/fill.py +features/steps/font.py +features/steps/font_color.py +features/steps/helpers.py +features/steps/legend.py +features/steps/line.py +features/steps/picture.py +features/steps/placeholder.py +features/steps/plot.py +features/steps/presentation.py +features/steps/series.py +features/steps/shape.py +features/steps/shapes.py +features/steps/slide.py +features/steps/slides.py +features/steps/table.py +features/steps/text.py +features/steps/text_frame.py +features/steps/test_files/72-dpi.tiff +features/steps/test_files/CVS_LOGO.WMF +features/steps/test_files/act-props.pptm +features/steps/test_files/calibriz.ttf +features/steps/test_files/cht-axis-props.pptx +features/steps/test_files/cht-category-access.pptx +features/steps/test_files/cht-chart-props.pptx +features/steps/test_files/cht-chart-type.pptx +features/steps/test_files/cht-charts.pptx +features/steps/test_files/cht-datalabels.pptx +features/steps/test_files/cht-gridlines-props.pptx +features/steps/test_files/cht-legend-props.pptx +features/steps/test_files/cht-legend.pptx +features/steps/test_files/cht-marker-props.pptx +features/steps/test_files/cht-plot-props.pptx +features/steps/test_files/cht-point-access.pptx +features/steps/test_files/cht-point-props.pptx +features/steps/test_files/cht-replace-data.pptx +features/steps/test_files/cht-series.pptx +features/steps/test_files/cht-ticklabels-props.pptx +features/steps/test_files/dml-effect.pptx +features/steps/test_files/dml-fill.pptx +features/steps/test_files/dml-line.pptx +features/steps/test_files/ext-rels.pptx +features/steps/test_files/font-color.pptx +features/steps/test_files/just-two-mice.mp4 +features/steps/test_files/just-two-mice.png +features/steps/test_files/lyt-shapes.pptx +features/steps/test_files/minimal.pptx +features/steps/test_files/monty-truth.png +features/steps/test_files/mst-placeholders.pptx +features/steps/test_files/mst-shapes.pptx +features/steps/test_files/mst-slide-layouts.pptx +features/steps/test_files/ph-inherit-props.pptx +features/steps/test_files/ph-populated-placeholders.pptx +features/steps/test_files/ph-unpopulated-placeholders.pptx +features/steps/test_files/pic.emf +features/steps/test_files/prs-add-slide.pptx +features/steps/test_files/prs-notes.pptx +features/steps/test_files/prs-properties.pptx +features/steps/test_files/prs-slide-masters.pptx +features/steps/test_files/python-icon.jpeg +features/steps/test_files/python-powered.png +features/steps/test_files/python.bmp +features/steps/test_files/shp-access-chart.pptx +features/steps/test_files/shp-access-ole-object.pptx +features/steps/test_files/shp-autoshape-adjustments.pptx +features/steps/test_files/shp-autoshape-props.pptx +features/steps/test_files/shp-common-props.pptx +features/steps/test_files/shp-connector-props.pptx +features/steps/test_files/shp-embedded-docx.docx +features/steps/test_files/shp-embedded-pptx.pptx +features/steps/test_files/shp-embedded-xlsx.xlsx +features/steps/test_files/shp-freeform.pptx +features/steps/test_files/shp-groupshape.pptx +features/steps/test_files/shp-movie-props.pptx +features/steps/test_files/shp-picture.pptx +features/steps/test_files/shp-pos-and-size.pptx +features/steps/test_files/shp-shapes.pptx +features/steps/test_files/sld-background.pptx +features/steps/test_files/sld-blank.pptx +features/steps/test_files/sld-notes.pptx +features/steps/test_files/sld-slide.pptx +features/steps/test_files/sld-slides.pptx +features/steps/test_files/sonic.gif +features/steps/test_files/tbl-cell.pptx +features/steps/test_files/test.pptx +features/steps/test_files/txt-fit-text.pptx +features/steps/test_files/txt-font-props.pptx +features/steps/test_files/txt-font-typeface.pptx +features/steps/test_files/txt-paragraph-spacing.pptx +features/steps/test_files/txt-text-frame.pptx +features/steps/test_files/txt-text.pptx +features/steps/test_files/extracted-pptx/[Content_Types].xml +features/steps/test_files/extracted-pptx/_rels/.rels +features/steps/test_files/extracted-pptx/docProps/app.xml +features/steps/test_files/extracted-pptx/docProps/core.xml +features/steps/test_files/extracted-pptx/docProps/thumbnail.jpeg +features/steps/test_files/extracted-pptx/ppt/presProps.xml +features/steps/test_files/extracted-pptx/ppt/presentation.xml +features/steps/test_files/extracted-pptx/ppt/tableStyles.xml +features/steps/test_files/extracted-pptx/ppt/viewProps.xml +features/steps/test_files/extracted-pptx/ppt/_rels/presentation.xml.rels +features/steps/test_files/extracted-pptx/ppt/printerSettings/printerSettings1.bin +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout1.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout10.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout11.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout2.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout3.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout4.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout5.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout6.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout7.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout8.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout9.xml +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout10.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout11.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout2.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout3.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout4.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout5.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout6.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout7.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout8.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout9.xml.rels +features/steps/test_files/extracted-pptx/ppt/slideMasters/slideMaster1.xml +features/steps/test_files/extracted-pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels +features/steps/test_files/extracted-pptx/ppt/slides/slide1.xml +features/steps/test_files/extracted-pptx/ppt/slides/_rels/slide1.xml.rels +features/steps/test_files/extracted-pptx/ppt/theme/theme1.xml +src/pptx/__init__.py +src/pptx/action.py +src/pptx/api.py +src/pptx/exc.py +src/pptx/media.py +src/pptx/package.py +src/pptx/presentation.py +src/pptx/shared.py +src/pptx/slide.py +src/pptx/spec.py +src/pptx/table.py +src/pptx/types.py +src/pptx/util.py +src/pptx/chart/__init__.py +src/pptx/chart/axis.py +src/pptx/chart/category.py +src/pptx/chart/chart.py +src/pptx/chart/data.py +src/pptx/chart/datalabel.py +src/pptx/chart/legend.py +src/pptx/chart/marker.py +src/pptx/chart/plot.py +src/pptx/chart/point.py +src/pptx/chart/series.py +src/pptx/chart/xlsx.py +src/pptx/chart/xmlwriter.py +src/pptx/dml/__init__.py +src/pptx/dml/chtfmt.py +src/pptx/dml/color.py +src/pptx/dml/effect.py +src/pptx/dml/fill.py +src/pptx/dml/line.py +src/pptx/enum/__init__.py +src/pptx/enum/action.py +src/pptx/enum/base.py +src/pptx/enum/chart.py +src/pptx/enum/dml.py +src/pptx/enum/lang.py +src/pptx/enum/shapes.py +src/pptx/enum/text.py +src/pptx/opc/__init__.py +src/pptx/opc/constants.py +src/pptx/opc/oxml.py +src/pptx/opc/package.py +src/pptx/opc/packuri.py +src/pptx/opc/serialized.py +src/pptx/opc/shared.py +src/pptx/opc/spec.py +src/pptx/oxml/__init__.py +src/pptx/oxml/action.py +src/pptx/oxml/coreprops.py +src/pptx/oxml/ns.py +src/pptx/oxml/presentation.py +src/pptx/oxml/simpletypes.py +src/pptx/oxml/slide.py +src/pptx/oxml/table.py +src/pptx/oxml/text.py +src/pptx/oxml/theme.py +src/pptx/oxml/xmlchemy.py +src/pptx/oxml/chart/__init__.py +src/pptx/oxml/chart/axis.py +src/pptx/oxml/chart/chart.py +src/pptx/oxml/chart/datalabel.py +src/pptx/oxml/chart/legend.py +src/pptx/oxml/chart/marker.py +src/pptx/oxml/chart/plot.py +src/pptx/oxml/chart/series.py +src/pptx/oxml/chart/shared.py +src/pptx/oxml/dml/__init__.py +src/pptx/oxml/dml/color.py +src/pptx/oxml/dml/fill.py +src/pptx/oxml/dml/line.py +src/pptx/oxml/shapes/__init__.py +src/pptx/oxml/shapes/autoshape.py +src/pptx/oxml/shapes/connector.py +src/pptx/oxml/shapes/graphfrm.py +src/pptx/oxml/shapes/groupshape.py +src/pptx/oxml/shapes/picture.py +src/pptx/oxml/shapes/shared.py +src/pptx/parts/__init__.py +src/pptx/parts/chart.py +src/pptx/parts/coreprops.py +src/pptx/parts/embeddedpackage.py +src/pptx/parts/image.py +src/pptx/parts/media.py +src/pptx/parts/presentation.py +src/pptx/parts/slide.py +src/pptx/shapes/__init__.py +src/pptx/shapes/autoshape.py +src/pptx/shapes/base.py +src/pptx/shapes/connector.py +src/pptx/shapes/freeform.py +src/pptx/shapes/graphfrm.py +src/pptx/shapes/group.py +src/pptx/shapes/picture.py +src/pptx/shapes/placeholder.py +src/pptx/shapes/shapetree.py +src/pptx/templates/default.pptx +src/pptx/templates/docx-icon.emf +src/pptx/templates/generic-icon.emf +src/pptx/templates/notes.xml +src/pptx/templates/notesMaster.xml +src/pptx/templates/pptx-icon.emf +src/pptx/templates/theme.xml +src/pptx/templates/xlsx-icon.emf +src/pptx/text/__init__.py +src/pptx/text/fonts.py +src/pptx/text/layout.py +src/pptx/text/text.py +src/python_pptx.egg-info/PKG-INFO +src/python_pptx.egg-info/SOURCES.txt +src/python_pptx.egg-info/dependency_links.txt +src/python_pptx.egg-info/not-zip-safe +src/python_pptx.egg-info/requires.txt +src/python_pptx.egg-info/top_level.txt +tests/__init__.py +tests/test_action.py +tests/test_api.py +tests/test_media.py +tests/test_package.py +tests/test_presentation.py +tests/test_shared.py +tests/test_slide.py +tests/test_table.py +tests/test_util.py +tests/unitdata.py +tests/chart/__init__.py +tests/chart/test_axis.py +tests/chart/test_category.py +tests/chart/test_chart.py +tests/chart/test_data.py +tests/chart/test_datalabel.py +tests/chart/test_legend.py +tests/chart/test_marker.py +tests/chart/test_plot.py +tests/chart/test_point.py +tests/chart/test_series.py +tests/chart/test_xlsx.py +tests/chart/test_xmlwriter.py +tests/dml/__init__.py +tests/dml/test_chtfmt.py +tests/dml/test_color.py +tests/dml/test_effect.py +tests/dml/test_fill.py +tests/dml/test_line.py +tests/enum/__init__.py +tests/enum/test_base.py +tests/enum/test_shapes.py +tests/opc/__init__.py +tests/opc/test_oxml.py +tests/opc/test_package.py +tests/opc/test_packuri.py +tests/opc/test_serialized.py +tests/oxml/__init__.py +tests/oxml/test___init__.py +tests/oxml/test_dml.py +tests/oxml/test_ns.py +tests/oxml/test_presentation.py +tests/oxml/test_simpletypes.py +tests/oxml/test_slide.py +tests/oxml/test_table.py +tests/oxml/test_theme.py +tests/oxml/test_xmlchemy.py +tests/oxml/shapes/__init__.py +tests/oxml/shapes/test_autoshape.py +tests/oxml/shapes/test_graphfrm.py +tests/oxml/shapes/test_groupshape.py +tests/oxml/shapes/test_picture.py +tests/oxml/unitdata/__init__.py +tests/oxml/unitdata/dml.py +tests/oxml/unitdata/shape.py +tests/oxml/unitdata/text.py +tests/parts/__init__.py +tests/parts/test_chart.py +tests/parts/test_coreprops.py +tests/parts/test_embeddedpackage.py +tests/parts/test_image.py +tests/parts/test_media.py +tests/parts/test_presentation.py +tests/parts/test_slide.py +tests/shapes/__init__.py +tests/shapes/test_autoshape.py +tests/shapes/test_base.py +tests/shapes/test_connector.py +tests/shapes/test_freeform.py +tests/shapes/test_graphfrm.py +tests/shapes/test_group.py +tests/shapes/test_picture.py +tests/shapes/test_placeholder.py +tests/shapes/test_shapetree.py +tests/test_files/calibriz.ttf +tests/test_files/cdw-logo.eps +tests/test_files/dummy.mp4 +tests/test_files/minimal.pptx +tests/test_files/minimal_slide.xml +tests/test_files/missing_rels_item.pptx +tests/test_files/monty-truth.png +tests/test_files/no-core-props.pptx +tests/test_files/no-slides.pptx +tests/test_files/presentation.xml +tests/test_files/python-icon.jpeg +tests/test_files/python-powered.png +tests/test_files/python.bmp +tests/test_files/slideLayout1.xml +tests/test_files/test.pptx +tests/test_files/test_slides.pptx +tests/test_files/expanded_pptx/[Content_Types].xml +tests/test_files/expanded_pptx/_rels/.rels +tests/test_files/expanded_pptx/docProps/app.xml +tests/test_files/expanded_pptx/docProps/core.xml +tests/test_files/expanded_pptx/docProps/thumbnail.jpeg +tests/test_files/expanded_pptx/ppt/presProps.xml +tests/test_files/expanded_pptx/ppt/presentation.xml +tests/test_files/expanded_pptx/ppt/tableStyles.xml +tests/test_files/expanded_pptx/ppt/viewProps.xml +tests/test_files/expanded_pptx/ppt/_rels/presentation.xml.rels +tests/test_files/expanded_pptx/ppt/printerSettings/printerSettings1.bin +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout1.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout10.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout11.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout2.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout3.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout4.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout5.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout6.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout7.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout8.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout9.xml +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout10.xml.rels +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout11.xml.rels +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout2.xml.rels +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout3.xml.rels +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout4.xml.rels +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout5.xml.rels +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout6.xml.rels +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout7.xml.rels +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout8.xml.rels +tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout9.xml.rels +tests/test_files/expanded_pptx/ppt/slideMasters/slideMaster1.xml +tests/test_files/expanded_pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels +tests/test_files/expanded_pptx/ppt/slides/slide1.xml +tests/test_files/expanded_pptx/ppt/slides/_rels/slide1.xml.rels +tests/test_files/expanded_pptx/ppt/theme/theme1.xml +tests/test_files/snippets/2x2-area-date.txt +tests/test_files/snippets/2x2-area-float.txt +tests/test_files/snippets/2x2-area-stacked-100.txt +tests/test_files/snippets/2x2-area-stacked.txt +tests/test_files/snippets/2x2-area.txt +tests/test_files/snippets/2x2-bar-clustered-date.txt +tests/test_files/snippets/2x2-bar-clustered-float.txt +tests/test_files/snippets/2x2-bar-clustered.txt +tests/test_files/snippets/2x2-bar-stacked-100.txt +tests/test_files/snippets/2x2-bar-stacked.txt +tests/test_files/snippets/2x2-column-clustered.txt +tests/test_files/snippets/2x2-column-stacked-100.txt +tests/test_files/snippets/2x2-column-stacked.txt +tests/test_files/snippets/2x2-line-date.txt +tests/test_files/snippets/2x2-line-float.txt +tests/test_files/snippets/2x2-line-markers-stacked-100.txt +tests/test_files/snippets/2x2-line-markers-stacked.txt +tests/test_files/snippets/2x2-line-markers.txt +tests/test_files/snippets/2x2-line-stacked-100.txt +tests/test_files/snippets/2x2-line-stacked.txt +tests/test_files/snippets/2x2-line.txt +tests/test_files/snippets/2x3-bubble-3d.txt +tests/test_files/snippets/2x3-bubble.txt +tests/test_files/snippets/2x3-xy-lines-no-markers.txt +tests/test_files/snippets/2x3-xy-lines.txt +tests/test_files/snippets/2x3-xy-smooth-no-markers.txt +tests/test_files/snippets/2x3-xy-smooth.txt +tests/test_files/snippets/2x3-xy.txt +tests/test_files/snippets/2x5-radar.txt +tests/test_files/snippets/3x1-pie-exploded.txt +tests/test_files/snippets/3x1-pie.txt +tests/test_files/snippets/3x2-doughnut-exploded.txt +tests/test_files/snippets/3x2-doughnut.txt +tests/test_files/snippets/4x2-multi-cat-bar.txt +tests/test_files/snippets/adjust-ser-count.txt +tests/test_files/snippets/cat-labels.txt +tests/test_files/snippets/content-types-xml.txt +tests/test_files/snippets/default-notes.txt +tests/test_files/snippets/default-notesMaster.txt +tests/test_files/snippets/default-theme.txt +tests/test_files/snippets/freeform.txt +tests/test_files/snippets/package-rels-xml.txt +tests/test_files/snippets/placeholders.txt +tests/test_files/snippets/presentation-rels-xml.txt +tests/test_files/snippets/relationships.txt +tests/test_files/snippets/rels-load-from-xml.txt +tests/test_files/snippets/rewrite-ser.txt +tests/test_files/snippets/timing.txt +tests/text/__init__.py +tests/text/test_fonts.py +tests/text/test_layout.py +tests/text/test_text.py +tests/unitutil/__init__.py +tests/unitutil/cxml.py +tests/unitutil/file.py +tests/unitutil/mock.py \ No newline at end of file diff --git a/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/dependency_links.txt b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/not-zip-safe b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/not-zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/not-zip-safe @@ -0,0 +1 @@ + diff --git a/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/requires.txt b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..f10d0e36c089d1d3a2fc8960571f527902c9a6fc --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/requires.txt @@ -0,0 +1,3 @@ +lxml>=3.1.0 +Pillow>=3.3.2 +XlsxWriter>=0.5.7 diff --git a/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/top_level.txt b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..b6bc7493e05e9abc4c9e5beea49e80db9c459248 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/top_level.txt @@ -0,0 +1 @@ +pptx diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/__init__.py b/tasks/tasksmith-74f059424102/environment/source/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/__init__.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_axis.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_axis.py new file mode 100644 index 0000000000000000000000000000000000000000..9dbb50f511216a89607d14ecac28a21b9ac10c9e --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_axis.py @@ -0,0 +1,1219 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.chart.axis` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.axis import ( + AxisTitle, + CategoryAxis, + DateAxis, + MajorGridlines, + TickLabels, + ValueAxis, + _BaseAxis, +) +from pptx.dml.chtfmt import ChartFormat +from pptx.enum.chart import ( + XL_AXIS_CROSSES, + XL_CATEGORY_TYPE, + XL_TICK_MARK, +) +from pptx.enum.chart import ( + XL_TICK_LABEL_POSITION as XL_TICK_LBL_POS, +) +from pptx.text.text import Font + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, instance_mock + + +class Describe_BaseAxis(object): + """Unit-test suite for `pptx.chart.axis._BaseAxis` objects.""" + + def it_provides_access_to_its_title(self, title_fixture): + axis, AxisTitle_, axis_title_ = title_fixture + axis_title = axis.axis_title + AxisTitle_.assert_called_once_with(axis._element.title) + assert axis_title is axis_title_ + + def it_provides_access_to_its_format(self, format_fixture): + axis, ChartFormat_, format_ = format_fixture + format = axis.format + ChartFormat_.assert_called_once_with(axis._xAx) + assert format is format_ + + def it_knows_whether_it_has_major_gridlines(self, major_gridlines_get_fixture): + base_axis, expected_value = major_gridlines_get_fixture + assert base_axis.has_major_gridlines is expected_value + + def it_can_change_whether_it_has_major_gridlines(self, major_gridlines_set_fixture): + base_axis, new_value, expected_xml = major_gridlines_set_fixture + base_axis.has_major_gridlines = new_value + assert base_axis._element.xml == expected_xml + + def it_knows_whether_it_has_minor_gridlines(self, minor_gridlines_get_fixture): + base_axis, expected_value = minor_gridlines_get_fixture + assert base_axis.has_minor_gridlines is expected_value + + def it_can_change_whether_it_has_minor_gridlines(self, minor_gridlines_set_fixture): + base_axis, new_value, expected_xml = minor_gridlines_set_fixture + base_axis.has_minor_gridlines = new_value + assert base_axis._element.xml == expected_xml + + def it_knows_whether_it_has_a_title(self, has_title_get_fixture): + axis, expected_value = has_title_get_fixture + assert axis.has_title is expected_value + + def it_can_change_whether_it_has_a_title(self, has_title_set_fixture): + axis, new_value, expected_xml = has_title_set_fixture + axis.has_title = new_value + assert axis._element.xml == expected_xml + + def it_provides_access_to_its_major_gridlines(self, maj_grdlns_fixture): + axis, MajorGridlines_, xAx, major_gridlines_ = maj_grdlns_fixture + + major_gridlines = axis.major_gridlines + + MajorGridlines_.assert_called_once_with(xAx) + assert major_gridlines is major_gridlines_ + + def it_knows_its_major_tick_setting(self, major_tick_get_fixture): + axis, expected_value = major_tick_get_fixture + assert axis.major_tick_mark == expected_value + + def it_can_change_its_major_tick_mark(self, major_tick_set_fixture): + axis, new_value, expected_xml = major_tick_set_fixture + axis.major_tick_mark = new_value + assert axis._element.xml == expected_xml + + def it_knows_its_maximum_scale(self, maximum_scale_get_fixture): + axis, expected_value = maximum_scale_get_fixture + assert axis.maximum_scale == expected_value + + def it_can_change_its_maximum_scale(self, maximum_scale_set_fixture): + axis, new_value, expected_xml = maximum_scale_set_fixture + axis.maximum_scale = new_value + assert axis._element.xml == expected_xml + + def it_knows_its_minimum_scale(self, minimum_scale_get_fixture): + axis, expected_value = minimum_scale_get_fixture + assert axis.minimum_scale == expected_value + + def it_can_change_its_minimum_scale(self, minimum_scale_set_fixture): + axis, new_value, expected_xml = minimum_scale_set_fixture + axis.minimum_scale = new_value + assert axis._element.xml == expected_xml + + def it_knows_its_minor_tick_setting(self, minor_tick_get_fixture): + axis, expected_value = minor_tick_get_fixture + assert axis.minor_tick_mark == expected_value + + def it_can_change_its_minor_tick_mark(self, minor_tick_set_fixture): + axis, new_value, expected_xml = minor_tick_set_fixture + axis.minor_tick_mark = new_value + assert axis._element.xml == expected_xml + + def it_knows_whether_it_renders_in_reverse_order(self, reverse_order_get_fixture): + xAx, expected_value = reverse_order_get_fixture + assert _BaseAxis(xAx).reverse_order == expected_value + + def it_can_change_whether_it_renders_in_reverse_order(self, reverse_order_set_fixture): + xAx, new_value, expected_xml = reverse_order_set_fixture + axis = _BaseAxis(xAx) + + axis.reverse_order = new_value + + assert axis._element.xml == expected_xml + + def it_knows_its_tick_label_position(self, tick_lbl_pos_get_fixture): + axis, expected_value = tick_lbl_pos_get_fixture + assert axis.tick_label_position == expected_value + + def it_can_change_its_tick_label_position(self, tick_lbl_pos_set_fixture): + axis, new_value, expected_xml = tick_lbl_pos_set_fixture + axis.tick_label_position = new_value + assert axis._element.xml == expected_xml + + def it_provides_access_to_the_tick_labels(self, tick_labels_fixture): + axis, tick_labels_, TickLabels_, xAx = tick_labels_fixture + tick_labels = axis.tick_labels + TickLabels_.assert_called_once_with(xAx) + assert tick_labels is tick_labels_ + + def it_knows_whether_it_is_visible(self, visible_get_fixture): + axis, expected_bool_value = visible_get_fixture + assert axis.visible is expected_bool_value + + def it_can_change_whether_it_is_visible(self, visible_set_fixture): + axis, new_value, expected_xml = visible_set_fixture + axis.visible = new_value + assert axis._element.xml == expected_xml + + def but_it_raises_on_assign_non_bool_to_visible(self): + axis = _BaseAxis(None) + with pytest.raises(ValueError): + axis.visible = "foobar" + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=["c:catAx", "c:dateAx", "c:valAx"]) + def format_fixture(self, request, ChartFormat_, format_): + xAx_cxml = request.param + axis = _BaseAxis(element(xAx_cxml)) + return axis, ChartFormat_, format_ + + @pytest.fixture( + params=[ + ("c:catAx", False), + ("c:catAx/c:title", True), + ("c:dateAx", False), + ("c:dateAx/c:title", True), + ("c:valAx", False), + ("c:valAx/c:title", True), + ] + ) + def has_title_get_fixture(self, request): + xAx_cxml, expected_value = request.param + axis = _BaseAxis(element(xAx_cxml)) + return axis, expected_value + + @pytest.fixture( + params=[ + ("c:catAx", True, "c:catAx/c:title/(c:layout,c:overlay{val=0})"), + ("c:catAx/c:title", True, "c:catAx/c:title"), + ("c:catAx/c:title", False, "c:catAx"), + ("c:catAx", False, "c:catAx"), + ("c:dateAx", True, "c:dateAx/c:title/(c:layout,c:overlay{val=0})"), + ("c:dateAx/c:title", True, "c:dateAx/c:title"), + ("c:dateAx/c:title", False, "c:dateAx"), + ("c:dateAx", False, "c:dateAx"), + ("c:valAx", True, "c:valAx/c:title/(c:layout,c:overlay{val=0})"), + ("c:valAx/c:title", True, "c:valAx/c:title"), + ("c:valAx/c:title", False, "c:valAx"), + ("c:valAx", False, "c:valAx"), + ] + ) + def has_title_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + axis = _BaseAxis(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return axis, new_value, expected_xml + + @pytest.fixture(params=["c:catAx", "c:dateAx", "c:valAx"]) + def maj_grdlns_fixture(self, request, MajorGridlines_, major_gridlines_): + xAx_cxml = request.param + xAx = element(xAx_cxml) + axis = _BaseAxis(xAx) + return axis, MajorGridlines_, xAx, major_gridlines_ + + @pytest.fixture( + params=[ + ("c:catAx", False), + ("c:catAx/c:majorGridlines", True), + ("c:dateAx", False), + ("c:dateAx/c:majorGridlines", True), + ("c:valAx", False), + ("c:valAx/c:majorGridlines", True), + ] + ) + def major_gridlines_get_fixture(self, request): + xAx_cxml, expected_value = request.param + base_axis = _BaseAxis(element(xAx_cxml)) + return base_axis, expected_value + + @pytest.fixture( + params=[ + ("c:catAx", True, "c:catAx/c:majorGridlines"), + ("c:catAx/c:majorGridlines", True, "c:catAx/c:majorGridlines"), + ("c:catAx/c:majorGridlines", False, "c:catAx"), + ("c:catAx", False, "c:catAx"), + ("c:dateAx", True, "c:dateAx/c:majorGridlines"), + ("c:dateAx/c:majorGridlines", True, "c:dateAx/c:majorGridlines"), + ("c:dateAx/c:majorGridlines", False, "c:dateAx"), + ("c:dateAx", False, "c:dateAx"), + ("c:valAx", True, "c:valAx/c:majorGridlines"), + ("c:valAx/c:majorGridlines", True, "c:valAx/c:majorGridlines"), + ("c:valAx/c:majorGridlines", False, "c:valAx"), + ("c:valAx", False, "c:valAx"), + ] + ) + def major_gridlines_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + base_axis = _BaseAxis(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return base_axis, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:catAx", XL_TICK_MARK.CROSS), + ("c:catAx/c:majorTickMark", XL_TICK_MARK.CROSS), + ("c:catAx/c:majorTickMark{val=out}", XL_TICK_MARK.OUTSIDE), + ("c:dateAx", XL_TICK_MARK.CROSS), + ("c:dateAx/c:majorTickMark", XL_TICK_MARK.CROSS), + ("c:dateAx/c:majorTickMark{val=out}", XL_TICK_MARK.OUTSIDE), + ("c:valAx", XL_TICK_MARK.CROSS), + ("c:valAx/c:majorTickMark", XL_TICK_MARK.CROSS), + ("c:valAx/c:majorTickMark{val=in}", XL_TICK_MARK.INSIDE), + ] + ) + def major_tick_get_fixture(self, request): + xAx_cxml, expected_value = request.param + axis = _BaseAxis(element(xAx_cxml)) + return axis, expected_value + + @pytest.fixture( + params=[ + ("c:catAx", XL_TICK_MARK.INSIDE, "c:catAx/c:majorTickMark{val=in}"), + ( + "c:catAx/c:majorTickMark{val=in}", + XL_TICK_MARK.OUTSIDE, + "c:catAx/c:majorTickMark{val=out}", + ), + ("c:catAx/c:majorTickMark{val=out}", XL_TICK_MARK.CROSS, "c:catAx"), + ("c:catAx", XL_TICK_MARK.CROSS, "c:catAx"), + ("c:catAx/c:majorTickMark{val=cross}", XL_TICK_MARK.CROSS, "c:catAx"), + ("c:dateAx", XL_TICK_MARK.INSIDE, "c:dateAx/c:majorTickMark{val=in}"), + ( + "c:dateAx/c:majorTickMark{val=in}", + XL_TICK_MARK.OUTSIDE, + "c:dateAx/c:majorTickMark{val=out}", + ), + ("c:dateAx/c:majorTickMark{val=out}", XL_TICK_MARK.CROSS, "c:dateAx"), + ("c:dateAx", XL_TICK_MARK.CROSS, "c:dateAx"), + ("c:dateAx/c:majorTickMark{val=cross}", XL_TICK_MARK.CROSS, "c:dateAx"), + ("c:valAx", XL_TICK_MARK.INSIDE, "c:valAx/c:majorTickMark{val=in}"), + ( + "c:valAx/c:majorTickMark{val=in}", + XL_TICK_MARK.OUTSIDE, + "c:valAx/c:majorTickMark{val=out}", + ), + ("c:valAx/c:majorTickMark{val=out}", XL_TICK_MARK.CROSS, "c:valAx"), + ("c:valAx", XL_TICK_MARK.CROSS, "c:valAx"), + ("c:valAx/c:majorTickMark{val=cross}", XL_TICK_MARK.CROSS, "c:valAx"), + ] + ) + def major_tick_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + axis = _BaseAxis(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return axis, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:catAx/c:scaling", None), + ("c:catAx/c:scaling/c:max{val=12.34}", 12.34), + ("c:dateAx/c:scaling", None), + ("c:dateAx/c:scaling/c:max{val=42.24}", 42.24), + ("c:valAx/c:scaling", None), + ("c:valAx/c:scaling/c:max{val=23.45}", 23.45), + ] + ) + def maximum_scale_get_fixture(self, request): + xAx_cxml, expected_value = request.param + axis = _BaseAxis(element(xAx_cxml)) + return axis, expected_value + + @pytest.fixture( + params=[ + ("c:catAx/c:scaling", 34.56, "c:catAx/c:scaling/c:max{val=34.56}"), + ( + "c:catAx/c:scaling/c:max{val=34.56}", + 42.42, + "c:catAx/c:scaling/c:max{val=42.42}", + ), + ("c:catAx/c:scaling/c:max{val=42.42}", None, "c:catAx/c:scaling"), + ("c:catAx/c:scaling", None, "c:catAx/c:scaling"), + ("c:dateAx/c:scaling", 45.67, "c:dateAx/c:scaling/c:max{val=45.67}"), + ( + "c:dateAx/c:scaling/c:max{val=45.67}", + 42.42, + "c:dateAx/c:scaling/c:max{val=42.42}", + ), + ("c:dateAx/c:scaling/c:max{val=42.42}", None, "c:dateAx/c:scaling"), + ("c:dateAx/c:scaling", None, "c:dateAx/c:scaling"), + ("c:valAx/c:scaling", 56.78, "c:valAx/c:scaling/c:max{val=56.78}"), + ( + "c:valAx/c:scaling/c:max{val=56.78}", + 42.42, + "c:valAx/c:scaling/c:max{val=42.42}", + ), + ("c:valAx/c:scaling/c:max{val=42.42}", None, "c:valAx/c:scaling"), + ("c:valAx/c:scaling", None, "c:valAx/c:scaling"), + ] + ) + def maximum_scale_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + axis = _BaseAxis(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return axis, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:catAx/c:scaling", None), + ("c:catAx/c:scaling/c:min{val=12.34}", 12.34), + ("c:dateAx/c:scaling", None), + ("c:dateAx/c:scaling/c:min{val=42.24}", 42.24), + ("c:valAx/c:scaling", None), + ("c:valAx/c:scaling/c:min{val=23.45}", 23.45), + ] + ) + def minimum_scale_get_fixture(self, request): + xAx_cxml, expected_value = request.param + axis = _BaseAxis(element(xAx_cxml)) + return axis, expected_value + + @pytest.fixture( + params=[ + ("c:catAx/c:scaling", 34.56, "c:catAx/c:scaling/c:min{val=34.56}"), + ( + "c:catAx/c:scaling/c:min{val=34.56}", + 42.42, + "c:catAx/c:scaling/c:min{val=42.42}", + ), + ("c:catAx/c:scaling/c:min{val=42.42}", None, "c:catAx/c:scaling"), + ("c:catAx/c:scaling", None, "c:catAx/c:scaling"), + ("c:dateAx/c:scaling", 45.67, "c:dateAx/c:scaling/c:min{val=45.67}"), + ( + "c:dateAx/c:scaling/c:min{val=45.67}", + 42.42, + "c:dateAx/c:scaling/c:min{val=42.42}", + ), + ("c:dateAx/c:scaling/c:min{val=42.42}", None, "c:dateAx/c:scaling"), + ("c:dateAx/c:scaling", None, "c:dateAx/c:scaling"), + ("c:valAx/c:scaling", 56.78, "c:valAx/c:scaling/c:min{val=56.78}"), + ( + "c:valAx/c:scaling/c:min{val=56.78}", + 42.42, + "c:valAx/c:scaling/c:min{val=42.42}", + ), + ("c:valAx/c:scaling/c:min{val=42.42}", None, "c:valAx/c:scaling"), + ("c:valAx/c:scaling", None, "c:valAx/c:scaling"), + ] + ) + def minimum_scale_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + axis = _BaseAxis(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return axis, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:catAx", False), + ("c:catAx/c:minorGridlines", True), + ("c:dateAx", False), + ("c:dateAx/c:minorGridlines", True), + ("c:valAx", False), + ("c:valAx/c:minorGridlines", True), + ] + ) + def minor_gridlines_get_fixture(self, request): + xAx_cxml, expected_value = request.param + base_axis = _BaseAxis(element(xAx_cxml)) + return base_axis, expected_value + + @pytest.fixture( + params=[ + ("c:catAx", True, "c:catAx/c:minorGridlines"), + ("c:catAx/c:minorGridlines", True, "c:catAx/c:minorGridlines"), + ("c:catAx/c:minorGridlines", False, "c:catAx"), + ("c:catAx", False, "c:catAx"), + ("c:dateAx", True, "c:dateAx/c:minorGridlines"), + ("c:dateAx/c:minorGridlines", True, "c:dateAx/c:minorGridlines"), + ("c:dateAx/c:minorGridlines", False, "c:dateAx"), + ("c:dateAx", False, "c:dateAx"), + ("c:valAx", True, "c:valAx/c:minorGridlines"), + ("c:valAx/c:minorGridlines", True, "c:valAx/c:minorGridlines"), + ("c:valAx/c:minorGridlines", False, "c:valAx"), + ("c:valAx", False, "c:valAx"), + ] + ) + def minor_gridlines_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + base_axis = _BaseAxis(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return base_axis, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:catAx", XL_TICK_MARK.CROSS), + ("c:catAx/c:minorTickMark", XL_TICK_MARK.CROSS), + ("c:catAx/c:minorTickMark{val=out}", XL_TICK_MARK.OUTSIDE), + ("c:dateAx", XL_TICK_MARK.CROSS), + ("c:dateAx/c:minorTickMark", XL_TICK_MARK.CROSS), + ("c:dateAx/c:minorTickMark{val=out}", XL_TICK_MARK.OUTSIDE), + ("c:valAx", XL_TICK_MARK.CROSS), + ("c:valAx/c:minorTickMark", XL_TICK_MARK.CROSS), + ("c:valAx/c:minorTickMark{val=in}", XL_TICK_MARK.INSIDE), + ] + ) + def minor_tick_get_fixture(self, request): + xAx_cxml, expected_value = request.param + axis = _BaseAxis(element(xAx_cxml)) + return axis, expected_value + + @pytest.fixture( + params=[ + ("c:catAx", XL_TICK_MARK.INSIDE, "c:catAx/c:minorTickMark{val=in}"), + ( + "c:catAx/c:minorTickMark{val=in}", + XL_TICK_MARK.OUTSIDE, + "c:catAx/c:minorTickMark{val=out}", + ), + ("c:catAx/c:minorTickMark{val=out}", XL_TICK_MARK.CROSS, "c:catAx"), + ("c:catAx", XL_TICK_MARK.CROSS, "c:catAx"), + ("c:catAx/c:minorTickMark{val=cross}", XL_TICK_MARK.CROSS, "c:catAx"), + ("c:dateAx", XL_TICK_MARK.INSIDE, "c:dateAx/c:minorTickMark{val=in}"), + ( + "c:dateAx/c:minorTickMark{val=in}", + XL_TICK_MARK.OUTSIDE, + "c:dateAx/c:minorTickMark{val=out}", + ), + ("c:dateAx/c:minorTickMark{val=out}", XL_TICK_MARK.CROSS, "c:dateAx"), + ("c:dateAx", XL_TICK_MARK.CROSS, "c:dateAx"), + ("c:dateAx/c:minorTickMark{val=cross}", XL_TICK_MARK.CROSS, "c:dateAx"), + ("c:valAx", XL_TICK_MARK.INSIDE, "c:valAx/c:minorTickMark{val=in}"), + ( + "c:valAx/c:minorTickMark{val=in}", + XL_TICK_MARK.OUTSIDE, + "c:valAx/c:minorTickMark{val=out}", + ), + ("c:valAx/c:minorTickMark{val=out}", XL_TICK_MARK.CROSS, "c:valAx"), + ("c:valAx", XL_TICK_MARK.CROSS, "c:valAx"), + ("c:valAx/c:minorTickMark{val=cross}", XL_TICK_MARK.CROSS, "c:valAx"), + ] + ) + def minor_tick_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + axis = _BaseAxis(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return axis, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:catAx/c:scaling", False), + ("c:valAx/c:scaling/c:orientation", False), + ("c:catAx/c:scaling/c:orientation{val=minMax}", False), + ("c:valAx/c:scaling/c:orientation{val=maxMin}", True), + ] + ) + def reverse_order_get_fixture(self, request): + xAx_cxml, expected_value = request.param + return element(xAx_cxml), expected_value + + @pytest.fixture( + params=[ + ("c:catAx/c:scaling", False, "c:catAx/c:scaling"), + ("c:catAx/c:scaling", True, "c:catAx/c:scaling/c:orientation{val=maxMin}"), + ("c:valAx/c:scaling/c:orientation", False, "c:valAx/c:scaling"), + ( + "c:valAx/c:scaling/c:orientation", + True, + "c:valAx/c:scaling/c:orientation{val=maxMin}", + ), + ( + "c:dateAx/c:scaling/c:orientation{val=minMax}", + False, + "c:dateAx/c:scaling", + ), + ( + "c:dateAx/c:scaling/c:orientation{val=minMax}", + True, + "c:dateAx/c:scaling/c:orientation{val=maxMin}", + ), + ( + "c:catAx/c:scaling/c:orientation{val=maxMin}", + False, + "c:catAx/c:scaling", + ), + ( + "c:catAx/c:scaling/c:orientation{val=maxMin}", + True, + "c:catAx/c:scaling/c:orientation{val=maxMin}", + ), + ] + ) + def reverse_order_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + xAx, expected_xml = element(xAx_cxml), xml(expected_xAx_cxml) + return xAx, new_value, expected_xml + + @pytest.fixture(params=["c:catAx", "c:dateAx", "c:valAx"]) + def tick_labels_fixture(self, request, TickLabels_, tick_labels_): + xAx_cxml = request.param + xAx = element(xAx_cxml) + axis = _BaseAxis(xAx) + return axis, tick_labels_, TickLabels_, xAx + + @pytest.fixture( + params=[ + ("c:catAx", XL_TICK_LBL_POS.NEXT_TO_AXIS), + ("c:catAx/c:tickLblPos", XL_TICK_LBL_POS.NEXT_TO_AXIS), + ("c:catAx/c:tickLblPos{val=high}", XL_TICK_LBL_POS.HIGH), + ("c:dateAx", XL_TICK_LBL_POS.NEXT_TO_AXIS), + ("c:dateAx/c:tickLblPos", XL_TICK_LBL_POS.NEXT_TO_AXIS), + ("c:dateAx/c:tickLblPos{val=low}", XL_TICK_LBL_POS.LOW), + ("c:valAx", XL_TICK_LBL_POS.NEXT_TO_AXIS), + ("c:valAx/c:tickLblPos", XL_TICK_LBL_POS.NEXT_TO_AXIS), + ("c:valAx/c:tickLblPos{val=none}", XL_TICK_LBL_POS.NONE), + ] + ) + def tick_lbl_pos_get_fixture(self, request): + xAx_cxml, expected_value = request.param + axis = _BaseAxis(element(xAx_cxml)) + return axis, expected_value + + @pytest.fixture( + params=[ + ("c:catAx", XL_TICK_LBL_POS.HIGH, "c:catAx/c:tickLblPos{val=high}"), + ( + "c:catAx/c:tickLblPos{val=high}", + XL_TICK_LBL_POS.LOW, + "c:catAx/c:tickLblPos{val=low}", + ), + ("c:catAx/c:tickLblPos{val=low}", None, "c:catAx/c:tickLblPos"), + ("c:catAx", None, "c:catAx/c:tickLblPos"), + ( + "c:dateAx", + XL_TICK_LBL_POS.NEXT_TO_AXIS, + "c:dateAx/c:tickLblPos{val=nextTo}", + ), + ( + "c:dateAx/c:tickLblPos{val=nextTo}", + XL_TICK_LBL_POS.NONE, + "c:dateAx/c:tickLblPos{val=none}", + ), + ("c:dateAx/c:tickLblPos{val=none}", None, "c:dateAx/c:tickLblPos"), + ("c:valAx", XL_TICK_LBL_POS.HIGH, "c:valAx/c:tickLblPos{val=high}"), + ( + "c:valAx/c:tickLblPos{val=high}", + XL_TICK_LBL_POS.LOW, + "c:valAx/c:tickLblPos{val=low}", + ), + ("c:valAx/c:tickLblPos{val=low}", None, "c:valAx/c:tickLblPos"), + ] + ) + def tick_lbl_pos_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + axis = _BaseAxis(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return axis, new_value, expected_xml + + @pytest.fixture(params=["c:catAx", "c:dateAx", "c:valAx"]) + def title_fixture(self, request, AxisTitle_, axis_title_): + xAx_cxml = request.param + axis = _BaseAxis(element(xAx_cxml)) + return axis, AxisTitle_, axis_title_ + + @pytest.fixture( + params=[ + ("c:catAx", False), + ("c:catAx/c:delete", False), + ("c:catAx/c:delete{val=0}", True), + ("c:catAx/c:delete{val=1}", False), + ("c:catAx/c:delete{val=false}", True), + ("c:dateAx", False), + ("c:dateAx/c:delete", False), + ("c:dateAx/c:delete{val=0}", True), + ("c:dateAx/c:delete{val=1}", False), + ("c:dateAx/c:delete{val=false}", True), + ("c:valAx", False), + ("c:valAx/c:delete", False), + ("c:valAx/c:delete{val=0}", True), + ("c:valAx/c:delete{val=1}", False), + ("c:valAx/c:delete{val=false}", True), + ] + ) + def visible_get_fixture(self, request): + xAx_cxml, expected_bool_value = request.param + axis = _BaseAxis(element(xAx_cxml)) + return axis, expected_bool_value + + @pytest.fixture( + params=[ + ("c:catAx", False, "c:catAx/c:delete"), + ("c:catAx/c:delete", True, "c:catAx/c:delete{val=0}"), + ("c:catAx/c:delete{val=1}", True, "c:catAx/c:delete{val=0}"), + ("c:catAx/c:delete{val=0}", False, "c:catAx/c:delete"), + ("c:catAx", True, "c:catAx/c:delete{val=0}"), + ("c:dateAx", False, "c:dateAx/c:delete"), + ("c:dateAx/c:delete", True, "c:dateAx/c:delete{val=0}"), + ("c:dateAx/c:delete{val=0}", False, "c:dateAx/c:delete"), + ("c:dateAx", True, "c:dateAx/c:delete{val=0}"), + ("c:valAx/c:delete", True, "c:valAx/c:delete{val=0}"), + ("c:valAx/c:delete{val=1}", False, "c:valAx/c:delete"), + ("c:valAx/c:delete{val=0}", True, "c:valAx/c:delete{val=0}"), + ] + ) + def visible_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + axis = _BaseAxis(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return axis, new_value, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def AxisTitle_(self, request, axis_title_): + return class_mock(request, "pptx.chart.axis.AxisTitle", return_value=axis_title_) + + @pytest.fixture + def axis_title_(self, request): + return instance_mock(request, AxisTitle) + + @pytest.fixture + def ChartFormat_(self, request, format_): + return class_mock(request, "pptx.chart.axis.ChartFormat", return_value=format_) + + @pytest.fixture + def format_(self, request): + return instance_mock(request, ChartFormat) + + @pytest.fixture + def MajorGridlines_(self, request, major_gridlines_): + return class_mock(request, "pptx.chart.axis.MajorGridlines", return_value=major_gridlines_) + + @pytest.fixture + def major_gridlines_(self, request): + return instance_mock(request, MajorGridlines) + + @pytest.fixture + def TickLabels_(self, request, tick_labels_): + return class_mock(request, "pptx.chart.axis.TickLabels", return_value=tick_labels_) + + @pytest.fixture + def tick_labels_(self, request): + return instance_mock(request, TickLabels) + + +class DescribeAxisTitle(object): + def it_knows_whether_it_has_a_text_frame(self, has_tf_get_fixture): + axis_title, expected_value = has_tf_get_fixture + value = axis_title.has_text_frame + assert value is expected_value + + def it_can_change_whether_it_has_a_text_frame(self, has_tf_set_fixture): + axis_title, value, expected_xml = has_tf_set_fixture + axis_title.has_text_frame = value + assert axis_title._element.xml == expected_xml + + def it_provides_access_to_its_format(self, format_fixture): + axis_title, ChartFormat_, format_ = format_fixture + format = axis_title.format + ChartFormat_.assert_called_once_with(axis_title._element) + assert format is format_ + + def it_provides_access_to_its_text_frame(self, text_frame_fixture): + axis_title, TextFrame_, text_frame_ = text_frame_fixture + text_frame = axis_title.text_frame + TextFrame_.assert_called_once_with(axis_title._element.tx.rich, axis_title) + assert text_frame is text_frame_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def format_fixture(self, request, ChartFormat_, format_): + axis_title = AxisTitle(element("c:title")) + return axis_title, ChartFormat_, format_ + + @pytest.fixture( + params=[ + ("c:title", False), + ("c:title/c:tx", False), + ("c:title/c:tx/c:strRef", False), + ("c:title/c:tx/c:rich", True), + ] + ) + def has_tf_get_fixture(self, request): + title_cxml, expected_value = request.param + axis_title = AxisTitle(element(title_cxml)) + return axis_title, expected_value + + @pytest.fixture( + params=[ + ( + "c:title{a:b=c}", + True, + "c:title{a:b=c}/c:tx/c:rich/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr" ")", + ), + ( + "c:title{a:b=c}/c:tx", + True, + "c:title{a:b=c}/c:tx/c:rich/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr" ")", + ), + ( + "c:title{a:b=c}/c:tx/c:strRef", + True, + "c:title{a:b=c}/c:tx/c:rich/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr" ")", + ), + ("c:title/c:tx/c:rich", True, "c:title/c:tx/c:rich"), + ("c:title", False, "c:title"), + ("c:title/c:tx", False, "c:title"), + ("c:title/c:tx/c:rich", False, "c:title"), + ("c:title/c:tx/c:strRef", False, "c:title"), + ] + ) + def has_tf_set_fixture(self, request): + title_cxml, value, expected_cxml = request.param + axis_title = AxisTitle(element(title_cxml)) + expected_xml = xml(expected_cxml) + return axis_title, value, expected_xml + + @pytest.fixture + def text_frame_fixture(self, request, TextFrame_): + axis_title = AxisTitle(element("c:title")) + text_frame_ = TextFrame_.return_value + return axis_title, TextFrame_, text_frame_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def ChartFormat_(self, request, format_): + return class_mock(request, "pptx.chart.axis.ChartFormat", return_value=format_) + + @pytest.fixture + def format_(self, request): + return instance_mock(request, ChartFormat) + + @pytest.fixture + def TextFrame_(self, request): + return class_mock(request, "pptx.chart.axis.TextFrame") + + +class DescribeCategoryAxis(object): + def it_knows_its_category_type(self, cat_type_get_fixture): + category_axis, expected_value = cat_type_get_fixture + assert category_axis.category_type is expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def cat_type_get_fixture(self): + category_axis = CategoryAxis(None) + expected_value = XL_CATEGORY_TYPE.CATEGORY_SCALE + return category_axis, expected_value + + +class DescribeDateAxis(object): + def it_knows_its_category_type(self, cat_type_get_fixture): + date_axis, expected_value = cat_type_get_fixture + assert date_axis.category_type is expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def cat_type_get_fixture(self): + date_axis = DateAxis(None) + expected_value = XL_CATEGORY_TYPE.TIME_SCALE + return date_axis, expected_value + + +class DescribeMajorGridlines(object): + def it_provides_access_to_its_format(self, format_fixture): + gridlines, expected_xml, ChartFormat_, format_ = format_fixture + format = gridlines.format + assert gridlines._xAx.xml == expected_xml + ChartFormat_.assert_called_once_with(gridlines._xAx.xpath("c:majorGridlines")[0]) + assert format is format_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:valAx", "c:valAx/c:majorGridlines"), + ("c:catAx/c:majorGridlines", "c:catAx/c:majorGridlines"), + ] + ) + def format_fixture(self, request, ChartFormat_, format_): + xAx_cxml, expected_cxml = request.param + gridlines = MajorGridlines(element(xAx_cxml)) + expected_xml = xml(expected_cxml) + return gridlines, expected_xml, ChartFormat_, format_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def ChartFormat_(self, request, format_): + return class_mock(request, "pptx.chart.axis.ChartFormat", return_value=format_) + + @pytest.fixture + def format_(self, request): + return instance_mock(request, ChartFormat) + + +class DescribeTickLabels(object): + def it_provides_access_to_its_font(self, font_fixture): + tick_labels, Font_, defRPr, font_ = font_fixture + font = tick_labels.font + Font_.assert_called_once_with(defRPr) + assert font is font_ + + def it_adds_a_txPr_to_help_font(self, txPr_fixture): + tick_labels, expected_xml = txPr_fixture + tick_labels.font + assert tick_labels._element.xml == expected_xml + + def it_knows_its_number_format(self, number_format_get_fixture): + tick_labels, expected_value = number_format_get_fixture + assert tick_labels.number_format == expected_value + + def it_can_change_its_number_format(self, number_format_set_fixture): + tick_labels, new_value, expected_xml = number_format_set_fixture + tick_labels.number_format = new_value + assert tick_labels._element.xml == expected_xml + + def it_knows_whether_its_number_format_is_linked(self, number_format_is_linked_get_fixture): + tick_labels, expected_value = number_format_is_linked_get_fixture + assert tick_labels.number_format_is_linked is expected_value + + def it_can_change_whether_its_number_format_is_linked( + self, number_format_is_linked_set_fixture + ): + tick_labels, new_value, expected_xml = number_format_is_linked_set_fixture + tick_labels.number_format_is_linked = new_value + assert tick_labels._element.xml == expected_xml + + def it_knows_its_offset(self, offset_get_fixture): + tick_labels, expected_value = offset_get_fixture + assert tick_labels.offset == expected_value + + def it_can_change_its_offset(self, offset_set_fixture): + tick_labels, new_value, expected_xml = offset_set_fixture + tick_labels.offset = new_value + assert tick_labels._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def font_fixture(self, Font_, font_): + catAx = element("c:catAx/c:txPr/a:p/a:pPr/a:defRPr") + defRPr = catAx.xpath(".//a:defRPr")[0] + tick_labels = TickLabels(catAx) + return tick_labels, Font_, defRPr, font_ + + @pytest.fixture( + params=[ + ("c:catAx", "General"), + ("c:valAx/c:numFmt{formatCode=General}", "General"), + ] + ) + def number_format_get_fixture(self, request): + xAx_cxml, expected_value = request.param + tick_labels = TickLabels(element(xAx_cxml)) + return tick_labels, expected_value + + @pytest.fixture( + params=[ + ( + "c:catAx", + "General", + "c:catAx/c:numFmt{formatCode=General,sourceLinked=0}", + ), + ( + "c:valAx/c:numFmt{formatCode=General}", + "00.00", + "c:valAx/c:numFmt{formatCode=00.00,sourceLinked=0}", + ), + ] + ) + def number_format_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + tick_labels = TickLabels(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return tick_labels, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:catAx", False), + ("c:valAx/c:numFmt", True), + ("c:valAx/c:numFmt{sourceLinked=0}", False), + ("c:catAx/c:numFmt{sourceLinked=1}", True), + ] + ) + def number_format_is_linked_get_fixture(self, request): + xAx_cxml, expected_value = request.param + tick_labels = TickLabels(element(xAx_cxml)) + return tick_labels, expected_value + + @pytest.fixture( + params=[ + ("c:valAx", True, "c:valAx/c:numFmt{sourceLinked=1}"), + ("c:catAx", False, "c:catAx/c:numFmt{sourceLinked=0}"), + ("c:valAx", None, "c:valAx/c:numFmt"), + ("c:catAx/c:numFmt", True, "c:catAx/c:numFmt{sourceLinked=1}"), + ( + "c:valAx/c:numFmt{sourceLinked=1}", + False, + "c:valAx/c:numFmt{sourceLinked=0}", + ), + ] + ) + def number_format_is_linked_set_fixture(self, request): + xAx_cxml, new_value, expected_xAx_cxml = request.param + tick_labels = TickLabels(element(xAx_cxml)) + expected_xml = xml(expected_xAx_cxml) + return tick_labels, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:catAx", 100), + ("c:catAx/c:lblOffset", 100), + ("c:catAx/c:lblOffset{val=420}", 420), + ("c:catAx/c:lblOffset{val=004}", 4), + ("c:catAx/c:lblOffset{val=42%}", 42), + ("c:catAx/c:lblOffset{val=02%}", 2), + ] + ) + def offset_get_fixture(self, request): + catAx_cxml, expected_value = request.param + tick_labels = TickLabels(element(catAx_cxml)) + return tick_labels, expected_value + + @pytest.fixture( + params=[ + ("c:catAx", 420, "c:catAx/c:lblOffset{val=420}"), + ("c:catAx/c:lblOffset{val=420}", 100, "c:catAx"), + ] + ) + def offset_set_fixture(self, request): + catAx_cxml, new_value, expected_catAx_cxml = request.param + tick_labels = TickLabels(element(catAx_cxml)) + expected_xml = xml(expected_catAx_cxml) + return tick_labels, new_value, expected_xml + + @pytest.fixture( + params=[ + ( + "c:valAx{a:b=c}", + "c:valAx{a:b=c}/c:txPr/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr)", + ), + ( + "c:valAx{a:b=c}/c:txPr/(a:bodyPr,a:p)", + "c:valAx{a:b=c}/c:txPr/(a:bodyPr,a:p/a:pPr/a:defRPr)", + ), + ( + "c:valAx{a:b=c}/c:txPr/(a:bodyPr,a:p/a:pPr)", + "c:valAx{a:b=c}/c:txPr/(a:bodyPr,a:p/a:pPr/a:defRPr)", + ), + ] + ) + def txPr_fixture(self, request): + xAx_cxml, expected_cxml = request.param + tick_labels = TickLabels(element(xAx_cxml)) + expected_xml = xml(expected_cxml) + return tick_labels, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def Font_(self, request, font_): + return class_mock(request, "pptx.chart.axis.Font", return_value=font_) + + @pytest.fixture + def font_(self, request): + return instance_mock(request, Font) + + +class DescribeValueAxis(object): + def it_knows_the_other_axis_crossing_type(self, crosses_get_fixture): + value_axis, expected_value = crosses_get_fixture + assert value_axis.crosses == expected_value + + def it_can_change_the_other_axis_crossing_type(self, crosses_set_fixture): + value_axis, new_value, plotArea, expected_xml = crosses_set_fixture + value_axis.crosses = new_value + assert plotArea.xml == expected_xml + + def it_knows_the_other_axis_crossing_value(self, crosses_at_get_fixture): + value_axis, expected_value = crosses_at_get_fixture + assert value_axis.crosses_at == expected_value + + def it_can_change_the_other_axis_crossing_value(self, crosses_at_set_fixture): + value_axis, new_value, plotArea, expected_xml = crosses_at_set_fixture + value_axis.crosses_at = new_value + assert plotArea.xml == expected_xml + + def it_knows_its_major_unit(self, major_unit_get_fixture): + value_axis, expected_value = major_unit_get_fixture + assert value_axis.major_unit == expected_value + + def it_can_change_its_major_unit(self, major_unit_set_fixture): + value_axis, new_value, expected_xml = major_unit_set_fixture + value_axis.major_unit = new_value + assert value_axis._element.xml == expected_xml + + def it_knows_its_minor_unit(self, minor_unit_get_fixture): + value_axis, expected_value = minor_unit_get_fixture + assert value_axis.minor_unit == expected_value + + def it_can_change_its_minor_unit(self, minor_unit_set_fixture): + value_axis, new_value, expected_xml = minor_unit_set_fixture + value_axis.minor_unit = new_value + assert value_axis._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:plotArea/(c:valAx/c:axId{val=42},c:valAx/c:crossAx{val=42})", None), + ( + "c:plotArea/(c:catAx/(c:axId{val=42},c:crossesAt{val=2.4}),c:valAx/" + "c:crossAx{val=42})", + 2.4, + ), + ( + "c:plotArea/(c:dateAx/(c:axId{val=42},c:crossesAt{val=-1.2}),c:valA" + "x/c:crossAx{val=42})", + -1.2, + ), + ] + ) + def crosses_at_get_fixture(self, request): + plotArea_cxml, expected_value = request.param + plotArea = element(plotArea_cxml) + valAx = plotArea.xpath('c:valAx[c:crossAx/@val="42"]')[0] + value_axis = ValueAxis(valAx) + return value_axis, expected_value + + @pytest.fixture( + params=[ + ( + "c:plotArea/(c:valAx/c:axId{val=42},c:valAx/c:crossAx{val=42})", + 2.4, + "c:plotArea/(c:valAx/(c:axId{val=42},c:crossesAt{val=2.4}),c:valAx/" + "c:crossAx{val=42})", + ), + ( + "c:plotArea/(c:catAx/(c:axId{val=42},c:crosses{val=min}),c:valAx/c:" + "crossAx{val=42})", + 1.5, + "c:plotArea/(c:catAx/(c:axId{val=42},c:crossesAt{val=1.5}),c:valAx/" + "c:crossAx{val=42})", + ), + ( + "c:plotArea/(c:dateAx/(c:axId{val=42},c:crossesAt{val=2.4}),c:valAx" + "/c:crossAx{val=42})", + 1.5, + "c:plotArea/(c:dateAx/(c:axId{val=42},c:crossesAt{val=1.5}),c:valAx" + "/c:crossAx{val=42})", + ), + ( + "c:plotArea/(c:catAx/(c:axId{val=42},c:crossesAt{val=1.5}),c:valAx/" + "c:crossAx{val=42})", + None, + "c:plotArea/(c:catAx/(c:axId{val=42}),c:valAx/c:crossAx{val=42})", + ), + ] + ) + def crosses_at_set_fixture(self, request): + plotArea_cxml, new_value, expected_cxml = request.param + plotArea = element(plotArea_cxml) + valAx = plotArea.xpath('c:valAx[c:crossAx/@val="42"]')[0] + value_axis = ValueAxis(valAx) + expected_xml = xml(expected_cxml) + return value_axis, new_value, plotArea, expected_xml + + @pytest.fixture( + params=[ + ("c:plotArea/(c:valAx/c:axId{val=42},c:valAx/c:crossAx{val=42})", "CUSTOM"), + ( + "c:plotArea/(c:catAx/(c:axId{val=42},c:crosses{val=autoZero}),c:val" + "Ax/c:crossAx{val=42})", + "AUTOMATIC", + ), + ( + "c:plotArea/(c:valAx/(c:axId{val=42},c:crosses{val=min}),c:valAx/c:" + "crossAx{val=42})", + "MINIMUM", + ), + ] + ) + def crosses_get_fixture(self, request): + cxml, member = request.param + valAx = element(cxml).xpath('c:valAx[c:crossAx/@val="42"]')[0] + value_axis = ValueAxis(valAx) + expected_value = getattr(XL_AXIS_CROSSES, member) + return value_axis, expected_value + + @pytest.fixture( + params=[ + ( + "c:plotArea/(c:valAx/(c:axId{val=42},c:crossesAt{val=2.4}),c:valAx/" + "c:crossAx{val=42})", + "AUTOMATIC", + "c:plotArea/(c:valAx/(c:axId{val=42},c:crosses{val=autoZero}),c:val" + "Ax/c:crossAx{val=42})", + ), + ( + "c:plotArea/(c:catAx/(c:axId{val=42},c:crosses{val=autoZero}),c:val" + "Ax/c:crossAx{val=42})", + "MINIMUM", + "c:plotArea/(c:catAx/(c:axId{val=42},c:crosses{val=min}),c:valAx/c:" + "crossAx{val=42})", + ), + ( + "c:plotArea/(c:valAx/(c:axId{val=42},c:crosses{val=min}),c:valAx/c:" + "crossAx{val=42})", + "CUSTOM", + "c:plotArea/(c:valAx/(c:axId{val=42},c:crossesAt{val=0.0}),c:valAx/" + "c:crossAx{val=42})", + ), + ( + "c:plotArea/(c:catAx/(c:axId{val=42},c:crossesAt{val=2.4}),c:valAx/" + "c:crossAx{val=42})", + "CUSTOM", + "c:plotArea/(c:catAx/(c:axId{val=42},c:crossesAt{val=2.4}),c:valAx/" + "c:crossAx{val=42})", + ), + ] + ) + def crosses_set_fixture(self, request): + plotArea_cxml, member, expected_cxml = request.param + plotArea = element(plotArea_cxml) + valAx = plotArea.xpath('c:valAx[c:crossAx/@val="42"]')[0] + value_axis = ValueAxis(valAx) + new_value = getattr(XL_AXIS_CROSSES, member) + expected_xml = xml(expected_cxml) + return value_axis, new_value, plotArea, expected_xml + + @pytest.fixture(params=[("c:valAx", None), ("c:valAx/c:majorUnit{val=4.2}", 4.2)]) + def major_unit_get_fixture(self, request): + valAx_cxml, expected_value = request.param + value_axis = ValueAxis(element(valAx_cxml)) + return value_axis, expected_value + + @pytest.fixture( + params=[ + ("c:valAx", 42, "c:valAx/c:majorUnit{val=42.0}"), + ("c:valAx", None, "c:valAx"), + ("c:valAx/c:majorUnit{val=42.0}", 24.0, "c:valAx/c:majorUnit{val=24.0}"), + ("c:valAx/c:majorUnit{val=42.0}", None, "c:valAx"), + ] + ) + def major_unit_set_fixture(self, request): + valAx_cxml, new_value, expected_valAx_cxml = request.param + value_axis = ValueAxis(element(valAx_cxml)) + expected_xml = xml(expected_valAx_cxml) + return value_axis, new_value, expected_xml + + @pytest.fixture(params=[("c:valAx", None), ("c:valAx/c:minorUnit{val=2.4}", 2.4)]) + def minor_unit_get_fixture(self, request): + valAx_cxml, expected_value = request.param + value_axis = ValueAxis(element(valAx_cxml)) + return value_axis, expected_value + + @pytest.fixture( + params=[ + ("c:valAx", 36, "c:valAx/c:minorUnit{val=36.0}"), + ("c:valAx", None, "c:valAx"), + ("c:valAx/c:minorUnit{val=36.0}", 12.6, "c:valAx/c:minorUnit{val=12.6}"), + ("c:valAx/c:minorUnit{val=36.0}", None, "c:valAx"), + ] + ) + def minor_unit_set_fixture(self, request): + valAx_cxml, new_value, expected_valAx_cxml = request.param + value_axis = ValueAxis(element(valAx_cxml)) + expected_xml = xml(expected_valAx_cxml) + return value_axis, new_value, expected_xml diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_category.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_category.py new file mode 100644 index 0000000000000000000000000000000000000000..9319d664b15d5bf3f43bed29cf4bc86cd7f3c0c6 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_category.py @@ -0,0 +1,249 @@ +"""Unit-test suite for the `pptx.chart.category` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.category import Categories, Category, CategoryLevel +from pptx.oxml import parse_xml + +from ..unitutil.cxml import element +from ..unitutil.file import snippet_seq +from ..unitutil.mock import call, class_mock, instance_mock + + +class DescribeCategories(object): + def it_knows_its_length(self, len_fixture): + categories, expected_len = len_fixture + assert len(categories) == expected_len + + def it_supports_indexed_access(self, getitem_fixture): + categories, idx, Category_, pt, category_ = getitem_fixture + category = categories[idx] + Category_.assert_called_once_with(pt, idx) + assert category is category_ + + def it_can_iterate_over_the_categories_it_contains(self, iter_fixture): + ( + categories, + expected_categories, + Category_, + calls, + ) = iter_fixture + assert [c for c in categories] == expected_categories + assert Category_.call_args_list == calls + + def it_knows_its_depth(self, depth_fixture): + categories, expected_value = depth_fixture + assert categories.depth == expected_value + + def it_provides_a_flattened_representation(self, flat_fixture): + categories, expected_values = flat_fixture + flattened_labels = categories.flattened_labels + assert flattened_labels == expected_values + + def it_provides_access_to_its_levels(self, levels_fixture): + categories, CategoryLevel_, calls, expected_levels = levels_fixture + levels = categories.levels + assert CategoryLevel_.call_args_list == calls + assert levels == expected_levels + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:barChart", 0), + ("c:barChart/c:ser/c:cat", 1), + ("c:barChart/c:ser/c:cat/c:multiLvlStrRef/c:lvl", 1), + ("c:barChart/c:ser/c:cat/c:multiLvlStrRef/(c:lvl,c:lvl)", 2), + ("c:barChart/c:ser/c:cat/c:multiLvlStrRef/(c:lvl,c:lvl,c:lvl)", 3), + ] + ) + def depth_fixture(self, request): + xChart_cxml, expected_value = request.param + categories = Categories(element(xChart_cxml)) + return categories, expected_value + + @pytest.fixture( + params=[ + # non-hierarchical (no lvls), 3 categories, one "none" + (0, (("Foo",), ("",), ("Baz",))), + # 2-lvls + (1, (("CA", "SF"), ("CA", "LA"), ("NY", "NY"), ("NY", "Albany"))), + # 3-lvls + ( + 2, + ( + ("USA", "CA", "SF"), + ("USA", "CA", "LA"), + ("USA", "NY", "NY"), + ("USA", "NY", "Albany"), + ("CAN", "AL", "Calgary"), + ("CAN", "AL", "Edmonton"), + ("CAN", "ON", "Toronto"), + ("CAN", "ON", "Ottawa"), + ), + ), + # 1-lvl; not seen in wild but spec does not prohibit + (3, (("SF",), ("LA",), ("NY",))), + ] + ) + def flat_fixture(self, request): + snippet_idx, expected_values = request.param + xChart_xml = snippet_seq("cat-labels")[snippet_idx] + categories = Categories(parse_xml(xChart_xml)) + return categories, expected_values + + @pytest.fixture( + params=[ + ("c:barChart/c:ser/c:cat/(c:ptCount{val=2})", 0, None), + ("c:barChart/c:ser/c:cat/(c:ptCount{val=2},c:pt{idx=1})", 0, None), + ("c:barChart/c:ser/c:cat/(c:ptCount{val=2},c:pt{idx=1})", 1, 0), + ("c:barChart/c:ser/c:cat/c:lvl/(c:ptCount{val=2},c:pt{idx=1})", 1, 0), + ] + ) + def getitem_fixture(self, request, Category_, category_): + xChart_cxml, idx, pt_offset = request.param + xChart = element(xChart_cxml) + pt = None if pt_offset is None else xChart.xpath(".//c:pt")[pt_offset] + categories = Categories(xChart) + return categories, idx, Category_, pt, category_ + + @pytest.fixture + def iter_fixture(self, Category_, category_): + xChart = element("c:barChart/c:ser/c:cat/(c:ptCount{val=2},c:pt{idx=1})") + pt = xChart.xpath(".//c:pt")[0] + categories = Categories(xChart) + expected_categories = [category_, category_] + calls = [call(None, 0), call(pt, 1)] + return categories, expected_categories, Category_, calls + + @pytest.fixture(params=[("c:barChart", 0), ("c:barChart/c:ser/c:cat/c:ptCount{val=4}", 4)]) + def len_fixture(self, request): + xChart_cxml, expected_len = request.param + categories = Categories(element(xChart_cxml)) + return categories, expected_len + + @pytest.fixture( + params=[ + ("c:barChart", 0), + ("c:barChart/c:ser/c:cat", 0), + ("c:barChart/c:ser/c:cat/c:multiLvlStrRef/c:lvl", 1), + ("c:barChart/c:ser/c:cat/c:multiLvlStrRef/(c:lvl,c:lvl)", 2), + ("c:barChart/c:ser/c:cat/c:multiLvlStrRef/(c:lvl,c:lvl,c:lvl)", 3), + ] + ) + def levels_fixture(self, request, CategoryLevel_, category_level_): + xChart_cxml, level_count = request.param + xChart = element(xChart_cxml) + lvls = xChart.xpath(".//c:lvl") + categories = Categories(xChart) + calls = [call(lvl) for lvl in lvls] + expected_levels = [category_level_ for _ in range(level_count)] + return categories, CategoryLevel_, calls, expected_levels + + # fixture components --------------------------------------------- + + @pytest.fixture + def Category_(self, request, category_): + return class_mock(request, "pptx.chart.category.Category", return_value=category_) + + @pytest.fixture + def category_(self, request): + return instance_mock(request, Category) + + @pytest.fixture + def CategoryLevel_(self, request, category_level_): + return class_mock( + request, "pptx.chart.category.CategoryLevel", return_value=category_level_ + ) + + @pytest.fixture + def category_level_(self, request): + return instance_mock(request, CategoryLevel) + + +class DescribeCategory(object): + def it_extends_str(self, base_class_fixture): + category, str_value = base_class_fixture + assert isinstance(category, str) + assert category == str_value + + def it_knows_its_idx(self, idx_fixture): + category, expected_value = idx_fixture + idx = category.idx + assert idx == expected_value + + def it_knows_its_label(self, label_fixture): + category, expected_value = label_fixture + label = category.label + assert label == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=[(None, ""), ('c:pt/c:v"Foo"', "Foo")]) + def base_class_fixture(self, request): + pt_cxml, str_value = request.param + pt = None if pt_cxml is None else element(pt_cxml) + category = Category(pt) + return category, str_value + + @pytest.fixture(params=[(None, 42, 42), ('c:pt{idx=9}/c:v"Bar"', None, 9)]) + def idx_fixture(self, request): + pt_cxml, idx, expected_value = request.param + pt = None if pt_cxml is None else element(pt_cxml) + category = Category(pt, idx) + return category, expected_value + + @pytest.fixture(params=[(None, ""), ('c:pt{idx=9}/c:v"Bar"', "Bar")]) + def label_fixture(self, request): + pt_cxml, expected_value = request.param + pt = None if pt_cxml is None else element(pt_cxml) + category = Category(pt) + return category, expected_value + + +class DescribeCategoryLevel(object): + def it_knows_its_length(self, len_fixture): + category_level, expected_len = len_fixture + assert len(category_level) == expected_len + + def it_supports_indexed_access(self, getitem_fixture): + category_level, idx, Category_, pt, category_ = getitem_fixture + category = category_level[idx] + Category_.assert_called_once_with(pt) + assert category is category_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=[0, 1, 2]) + def getitem_fixture(self, request, Category_, category_): + idx = request.param + lvl_cxml = "c:lvl/(c:pt,c:pt,c:pt)" + lvl = element(lvl_cxml) + pt = lvl.xpath("./c:pt")[idx] + category_level = CategoryLevel(lvl) + return category_level, idx, Category_, pt, category_ + + @pytest.fixture( + params=[ + ("c:lvl", 0), + ("c:lvl/c:pt", 1), + ("c:lvl/(c:pt,c:pt)", 2), + ("c:lvl/(c:pt,c:pt,c:pt)", 3), + ] + ) + def len_fixture(self, request): + lvl_cxml, expected_len = request.param + category_level = CategoryLevel(element(lvl_cxml)) + return category_level, expected_len + + # fixture components --------------------------------------------- + + @pytest.fixture + def Category_(self, request, category_): + return class_mock(request, "pptx.chart.category.Category", return_value=category_) + + @pytest.fixture + def category_(self, request): + return instance_mock(request, Category) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_chart.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_chart.py new file mode 100644 index 0000000000000000000000000000000000000000..667253347f8fcbf73f49f578467e63435e2c5dd2 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_chart.py @@ -0,0 +1,587 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.chart.chart` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.axis import CategoryAxis, DateAxis, ValueAxis +from pptx.chart.chart import Chart, ChartTitle, Legend, _Plots +from pptx.chart.data import ChartData +from pptx.chart.plot import _BasePlot +from pptx.chart.series import SeriesCollection +from pptx.chart.xmlwriter import _BaseSeriesXmlRewriter +from pptx.dml.chtfmt import ChartFormat +from pptx.enum.chart import XL_CHART_TYPE +from pptx.parts.chart import ChartWorkbook +from pptx.text.text import Font + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import ( + call, + class_mock, + function_mock, + instance_mock, + property_mock, +) + + +class DescribeChart(object): + """Unit-test suite for `pptx.chart.chart.Chart` objects.""" + + def it_provides_access_to_its_font(self, font_fixture, Font_, font_): + chartSpace, expected_xml = font_fixture + Font_.return_value = font_ + chart = Chart(chartSpace, None) + + font = chart.font + + assert chartSpace.xml == expected_xml + Font_.assert_called_once_with(chartSpace.xpath("./c:txPr/a:p/a:pPr/a:defRPr")[0]) + assert font is font_ + + def it_knows_whether_it_has_a_title(self, has_title_get_fixture): + chart, expected_value = has_title_get_fixture + assert chart.has_title is expected_value + + def it_can_change_whether_it_has_a_title(self, has_title_set_fixture): + chart, new_value, expected_xml = has_title_set_fixture + chart.has_title = new_value + assert chart._chartSpace.chart.xml == expected_xml + + def it_provides_access_to_the_chart_title(self, title_fixture): + chart, expected_xml, ChartTitle_, chart_title_ = title_fixture + + chart_title = chart.chart_title + + assert chart.element.xpath("c:chart/c:title")[0].xml == expected_xml + ChartTitle_.assert_called_once_with(chart.element.chart.title) + assert chart_title is chart_title_ + + def it_provides_access_to_the_category_axis(self, category_axis_fixture): + chart, category_axis_, AxisCls_, xAx = category_axis_fixture + category_axis = chart.category_axis + AxisCls_.assert_called_once_with(xAx) + assert category_axis is category_axis_ + + def it_raises_when_no_category_axis(self, cat_ax_raise_fixture): + chart = cat_ax_raise_fixture + with pytest.raises(ValueError): + chart.category_axis + + def it_provides_access_to_the_value_axis(self, val_ax_fixture): + chart, ValueAxis_, valAx, value_axis_ = val_ax_fixture + value_axis = chart.value_axis + ValueAxis_.assert_called_once_with(valAx) + assert value_axis is value_axis_ + + def it_raises_when_no_value_axis(self, val_ax_raise_fixture): + chart = val_ax_raise_fixture + with pytest.raises(ValueError): + chart.value_axis + + def it_provides_access_to_its_series(self, series_fixture): + chart, SeriesCollection_, plotArea, series_ = series_fixture + series = chart.series + SeriesCollection_.assert_called_once_with(plotArea) + assert series is series_ + + def it_provides_access_to_its_plots(self, plots_fixture): + chart, plots_, _Plots_, plotArea = plots_fixture + plots = chart.plots + _Plots_.assert_called_once_with(plotArea, chart) + assert plots is plots_ + + def it_knows_whether_it_has_a_legend(self, has_legend_get_fixture): + chart, expected_value = has_legend_get_fixture + assert chart.has_legend == expected_value + + def it_can_change_whether_it_has_a_legend(self, has_legend_set_fixture): + chart, new_value, expected_xml = has_legend_set_fixture + chart.has_legend = new_value + assert chart._chartSpace.xml == expected_xml + + def it_provides_access_to_its_legend(self, legend_fixture): + chart, Legend_, expected_calls, expected_value = legend_fixture + legend = chart.legend + assert Legend_.call_args_list == expected_calls + assert legend is expected_value + + def it_knows_its_chart_type(self, request, PlotTypeInspector_, plot_): + property_mock(request, Chart, "plots", return_value=[plot_]) + PlotTypeInspector_.chart_type.return_value = XL_CHART_TYPE.PIE + chart = Chart(None, None) + + chart_type = chart.chart_type + + PlotTypeInspector_.chart_type.assert_called_once_with(plot_) + assert chart_type == XL_CHART_TYPE.PIE + + def it_knows_its_style(self, style_get_fixture): + chart, expected_value = style_get_fixture + assert chart.chart_style == expected_value + + def it_can_change_its_style(self, style_set_fixture): + chart, new_value, expected_xml = style_set_fixture + chart.chart_style = new_value + assert chart._chartSpace.xml == expected_xml + + def it_can_replace_the_chart_data(self, replace_fixture): + ( + chart, + chart_data_, + SeriesXmlRewriterFactory_, + chart_type, + rewriter_, + chartSpace, + workbook_, + xlsx_blob, + ) = replace_fixture + + chart.replace_data(chart_data_) + + SeriesXmlRewriterFactory_.assert_called_once_with(chart_type, chart_data_) + rewriter_.replace_series_data.assert_called_once_with(chartSpace) + workbook_.update_from_xlsx_blob.assert_called_once_with(xlsx_blob) + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=["c:catAx", "c:dateAx", "c:valAx"]) + def category_axis_fixture(self, request, CategoryAxis_, DateAxis_, ValueAxis_): + ax_tag = request.param + chartSpace_cxml = "c:chartSpace/c:chart/c:plotArea/%s" % ax_tag + chartSpace = element(chartSpace_cxml) + chart = Chart(chartSpace, None) + AxisCls_ = { + "c:catAx": CategoryAxis_, + "c:dateAx": DateAxis_, + "c:valAx": ValueAxis_, + }[ax_tag] + axis_ = AxisCls_.return_value + xAx = chartSpace.xpath(".//%s" % ax_tag)[0] + return chart, axis_, AxisCls_, xAx + + @pytest.fixture + def cat_ax_raise_fixture(self): + chart = Chart(element("c:chartSpace/c:chart/c:plotArea"), None) + return chart + + @pytest.fixture( + params=[ + ( + "c:chartSpace{a:b=c}", + "c:chartSpace{a:b=c}/c:txPr/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr" ")", + ), + ("c:chartSpace/c:txPr/a:p", "c:chartSpace/c:txPr/a:p/a:pPr/a:defRPr"), + ( + "c:chartSpace/c:txPr/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr)", + "c:chartSpace/c:txPr/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr)", + ), + ] + ) + def font_fixture(self, request): + chartSpace_cxml, expected_cxml = request.param + chartSpace = element(chartSpace_cxml) + expected_xml = xml(expected_cxml) + return chartSpace, expected_xml + + @pytest.fixture( + params=[ + ("c:chartSpace/c:chart", False), + ("c:chartSpace/c:chart/c:legend", True), + ] + ) + def has_legend_get_fixture(self, request): + chartSpace_cxml, expected_value = request.param + chart = Chart(element(chartSpace_cxml), None) + return chart, expected_value + + @pytest.fixture(params=[("c:chartSpace/c:chart", True, "c:chartSpace/c:chart/c:legend")]) + def has_legend_set_fixture(self, request): + chartSpace_cxml, new_value, expected_chartSpace_cxml = request.param + chart = Chart(element(chartSpace_cxml), None) + expected_xml = xml(expected_chartSpace_cxml) + return chart, new_value, expected_xml + + @pytest.fixture( + params=[("c:chartSpace/c:chart", False), ("c:chartSpace/c:chart/c:title", True)] + ) + def has_title_get_fixture(self, request): + chartSpace_cxml, expected_value = request.param + chart = Chart(element(chartSpace_cxml), None) + return chart, expected_value + + @pytest.fixture( + params=[ + ("c:chart", True, "c:chart/c:title/(c:layout,c:overlay{val=0})"), + ("c:chart/c:title", True, "c:chart/c:title"), + ("c:chart/c:title", False, "c:chart/c:autoTitleDeleted{val=1}"), + ("c:chart", False, "c:chart/c:autoTitleDeleted{val=1}"), + ] + ) + def has_title_set_fixture(self, request): + chart_cxml, new_value, expected_cxml = request.param + chart = Chart(element("c:chartSpace/%s" % chart_cxml), None) + expected_xml = xml(expected_cxml) + return chart, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:chartSpace/c:chart", False), + ("c:chartSpace/c:chart/c:legend", True), + ] + ) + def legend_fixture(self, request, Legend_, legend_): + chartSpace_cxml, has_legend = request.param + chartSpace = element(chartSpace_cxml) + chart = Chart(chartSpace, None) + expected_value, expected_calls = None, [] + if has_legend: + expected_value = legend_ + legend_elm = chartSpace.chart.legend + expected_calls.append(call(legend_elm)) + return chart, Legend_, expected_calls, expected_value + + @pytest.fixture + def plots_fixture(self, _Plots_, plots_): + chartSpace = element("c:chartSpace/c:chart/c:plotArea") + plotArea = chartSpace.xpath("./c:chart/c:plotArea")[0] + chart = Chart(chartSpace, None) + return chart, plots_, _Plots_, plotArea + + @pytest.fixture + def replace_fixture( + self, + chart_data_, + SeriesXmlRewriterFactory_, + series_rewriter_, + workbook_, + workbook_prop_, + ): + chartSpace = element("c:chartSpace/c:chart/c:plotArea/c:pieChart") + chart = Chart(chartSpace, None) + chart_type = XL_CHART_TYPE.PIE + xlsx_blob = "fooblob" + chart_data_.xlsx_blob = xlsx_blob + return ( + chart, + chart_data_, + SeriesXmlRewriterFactory_, + chart_type, + series_rewriter_, + chartSpace, + workbook_, + xlsx_blob, + ) + + @pytest.fixture + def series_fixture(self, SeriesCollection_, series_collection_): + chartSpace = element("c:chartSpace/c:chart/c:plotArea") + plotArea = chartSpace.xpath(".//c:plotArea")[0] + chart = Chart(chartSpace, None) + return chart, SeriesCollection_, plotArea, series_collection_ + + @pytest.fixture(params=[("c:chartSpace/c:style{val=42}", 42), ("c:chartSpace", None)]) + def style_get_fixture(self, request): + chartSpace_cxml, expected_value = request.param + chart = Chart(element(chartSpace_cxml), None) + return chart, expected_value + + @pytest.fixture( + params=[ + ("c:chartSpace", 4, "c:chartSpace/c:style{val=4}"), + ("c:chartSpace", None, "c:chartSpace"), + ("c:chartSpace/c:style{val=4}", 2, "c:chartSpace/c:style{val=2}"), + ("c:chartSpace/c:style{val=4}", None, "c:chartSpace"), + ] + ) + def style_set_fixture(self, request): + chartSpace_cxml, new_value, expected_chartSpace_cxml = request.param + chart = Chart(element(chartSpace_cxml), None) + expected_xml = xml(expected_chartSpace_cxml) + return chart, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:chartSpace/c:chart", "c:title/(c:layout,c:overlay{val=0})"), + ("c:chartSpace/c:chart/c:title/c:layout", "c:title/c:layout"), + ] + ) + def title_fixture(self, request, ChartTitle_, chart_title_): + chartSpace_cxml, expected_cxml = request.param + chart = Chart(element(chartSpace_cxml), None) + expected_xml = xml(expected_cxml) + return chart, expected_xml, ChartTitle_, chart_title_ + + @pytest.fixture( + params=[ + ("c:chartSpace/c:chart/c:plotArea/(c:catAx,c:valAx)", 0), + ("c:chartSpace/c:chart/c:plotArea/(c:valAx,c:valAx)", 1), + ] + ) + def val_ax_fixture(self, request, ValueAxis_, value_axis_): + chartSpace_xml, idx = request.param + chartSpace = element(chartSpace_xml) + chart = Chart(chartSpace, None) + valAx = chartSpace.xpath(".//c:valAx")[idx] + return chart, ValueAxis_, valAx, value_axis_ + + @pytest.fixture + def val_ax_raise_fixture(self): + chart = Chart(element("c:chartSpace/c:chart/c:plotArea"), None) + return chart + + # fixture components --------------------------------------------- + + @pytest.fixture + def CategoryAxis_(self, request, category_axis_): + return class_mock(request, "pptx.chart.chart.CategoryAxis", return_value=category_axis_) + + @pytest.fixture + def category_axis_(self, request): + return instance_mock(request, CategoryAxis) + + @pytest.fixture + def chart_data_(self, request): + return instance_mock(request, ChartData) + + @pytest.fixture + def ChartTitle_(self, request, chart_title_): + return class_mock(request, "pptx.chart.chart.ChartTitle", return_value=chart_title_) + + @pytest.fixture + def chart_title_(self, request): + return instance_mock(request, ChartTitle) + + @pytest.fixture + def DateAxis_(self, request, date_axis_): + return class_mock(request, "pptx.chart.chart.DateAxis", return_value=date_axis_) + + @pytest.fixture + def date_axis_(self, request): + return instance_mock(request, DateAxis) + + @pytest.fixture + def Font_(self, request): + return class_mock(request, "pptx.chart.chart.Font") + + @pytest.fixture + def font_(self, request): + return instance_mock(request, Font) + + @pytest.fixture + def Legend_(self, request, legend_): + return class_mock(request, "pptx.chart.chart.Legend", return_value=legend_) + + @pytest.fixture + def legend_(self, request): + return instance_mock(request, Legend) + + @pytest.fixture + def PlotTypeInspector_(self, request): + return class_mock(request, "pptx.chart.chart.PlotTypeInspector") + + @pytest.fixture + def _Plots_(self, request, plots_): + return class_mock(request, "pptx.chart.chart._Plots", return_value=plots_) + + @pytest.fixture + def plot_(self, request): + return instance_mock(request, _BasePlot) + + @pytest.fixture + def plots_(self, request): + return instance_mock(request, _Plots) + + @pytest.fixture + def SeriesCollection_(self, request, series_collection_): + return class_mock( + request, + "pptx.chart.chart.SeriesCollection", + return_value=series_collection_, + ) + + @pytest.fixture + def SeriesXmlRewriterFactory_(self, request, series_rewriter_): + return function_mock( + request, + "pptx.chart.chart.SeriesXmlRewriterFactory", + return_value=series_rewriter_, + autospec=True, + ) + + @pytest.fixture + def series_collection_(self, request): + return instance_mock(request, SeriesCollection) + + @pytest.fixture + def series_rewriter_(self, request): + return instance_mock(request, _BaseSeriesXmlRewriter) + + @pytest.fixture + def ValueAxis_(self, request, value_axis_): + return class_mock(request, "pptx.chart.chart.ValueAxis", return_value=value_axis_) + + @pytest.fixture + def value_axis_(self, request): + return instance_mock(request, ValueAxis) + + @pytest.fixture + def workbook_(self, request): + return instance_mock(request, ChartWorkbook) + + @pytest.fixture + def workbook_prop_(self, request, workbook_): + return property_mock(request, Chart, "_workbook", return_value=workbook_) + + +class DescribeChartTitle(object): + """Unit-test suite for `pptx.chart.chart.ChartTitle` objects.""" + + def it_provides_access_to_its_format(self, format_fixture): + chart_title, ChartFormat_, format_ = format_fixture + format = chart_title.format + ChartFormat_.assert_called_once_with(chart_title.element) + assert format is format_ + + def it_knows_whether_it_has_a_text_frame(self, has_tf_get_fixture): + chart_title, expected_value = has_tf_get_fixture + value = chart_title.has_text_frame + assert value is expected_value + + def it_can_change_whether_it_has_a_text_frame(self, has_tf_set_fixture): + chart_title, value, expected_xml = has_tf_set_fixture + chart_title.has_text_frame = value + assert chart_title._element.xml == expected_xml + + def it_provides_access_to_its_text_frame(self, text_frame_fixture): + chart_title, TextFrame_, text_frame_ = text_frame_fixture + text_frame = chart_title.text_frame + TextFrame_.assert_called_once_with(chart_title._element.tx.rich, chart_title) + assert text_frame is text_frame_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def format_fixture(self, request, ChartFormat_, format_): + chart_title = ChartTitle(element("c:title")) + return chart_title, ChartFormat_, format_ + + @pytest.fixture( + params=[ + ("c:title", False), + ("c:title/c:tx", False), + ("c:title/c:tx/c:strRef", False), + ("c:title/c:tx/c:rich", True), + ] + ) + def has_tf_get_fixture(self, request): + title_cxml, expected_value = request.param + chart_title = ChartTitle(element(title_cxml)) + return chart_title, expected_value + + @pytest.fixture( + params=[ + ( + "c:title{a:b=c}", + True, + "c:title{a:b=c}/c:tx/c:rich/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr" ")", + ), + ( + "c:title{a:b=c}/c:tx", + True, + "c:title{a:b=c}/c:tx/c:rich/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr" ")", + ), + ( + "c:title{a:b=c}/c:tx/c:strRef", + True, + "c:title{a:b=c}/c:tx/c:rich/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr" ")", + ), + ("c:title/c:tx/c:rich", True, "c:title/c:tx/c:rich"), + ("c:title", False, "c:title"), + ("c:title/c:tx", False, "c:title"), + ("c:title/c:tx/c:rich", False, "c:title"), + ("c:title/c:tx/c:strRef", False, "c:title"), + ] + ) + def has_tf_set_fixture(self, request): + title_cxml, value, expected_cxml = request.param + chart_title = ChartTitle(element(title_cxml)) + expected_xml = xml(expected_cxml) + return chart_title, value, expected_xml + + @pytest.fixture + def text_frame_fixture(self, request, TextFrame_): + chart_title = ChartTitle(element("c:title")) + text_frame_ = TextFrame_.return_value + return chart_title, TextFrame_, text_frame_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def ChartFormat_(self, request, format_): + return class_mock(request, "pptx.chart.chart.ChartFormat", return_value=format_) + + @pytest.fixture + def format_(self, request): + return instance_mock(request, ChartFormat) + + @pytest.fixture + def TextFrame_(self, request): + return class_mock(request, "pptx.chart.chart.TextFrame") + + +class Describe_Plots(object): + """Unit-test suite for `pptx.chart.chart._Plots` objects.""" + + def it_supports_indexed_access(self, getitem_fixture): + plots, idx, PlotFactory_, plot_elm, chart_, plot_ = getitem_fixture + plot = plots[idx] + PlotFactory_.assert_called_once_with(plot_elm, chart_) + assert plot is plot_ + + def it_supports_len(self, len_fixture): + plots, expected_len = len_fixture + assert len(plots) == expected_len + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:plotArea/c:barChart", 0), + ("c:plotArea/(c:radarChart,c:barChart)", 1), + ] + ) + def getitem_fixture(self, request, PlotFactory_, chart_, plot_): + plotArea_cxml, idx = request.param + plotArea = element(plotArea_cxml) + plot_elm = plotArea[idx] + plots = _Plots(plotArea, chart_) + return plots, idx, PlotFactory_, plot_elm, chart_, plot_ + + @pytest.fixture( + params=[ + ("c:plotArea", 0), + ("c:plotArea/c:barChart", 1), + ("c:plotArea/(c:barChart,c:lineChart)", 2), + ] + ) + def len_fixture(self, request): + plotArea_cxml, expected_len = request.param + plots = _Plots(element(plotArea_cxml), None) + return plots, expected_len + + # fixture components --------------------------------------------- + + @pytest.fixture + def chart_(self, request): + return instance_mock(request, Chart) + + @pytest.fixture + def PlotFactory_(self, request, plot_): + return function_mock(request, "pptx.chart.chart.PlotFactory", return_value=plot_) + + @pytest.fixture + def plot_(self, request): + return instance_mock(request, _BasePlot) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_data.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6097020d816ec3d3c2c53d8289983d1ae12edb --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_data.py @@ -0,0 +1,893 @@ +# pyright: reportPrivateUsage=false + +"""Test suite for `pptx.chart.data` module.""" + +from __future__ import annotations + +from datetime import date, datetime + +import pytest + +from pptx.chart.data import ( + BubbleChartData, + BubbleDataPoint, + BubbleSeriesData, + Categories, + Category, + CategoryChartData, + CategoryDataPoint, + CategorySeriesData, + ChartData, + XyChartData, + XyDataPoint, + XySeriesData, + _BaseChartData, + _BaseDataPoint, + _BaseSeriesData, +) +from pptx.chart.xlsx import CategoryWorkbookWriter +from pptx.enum.chart import XL_CHART_TYPE + +from ..unitutil.mock import Mock, call, class_mock, instance_mock, property_mock + + +class DescribeChartData(object): + def it_is_a_CategoryChartData_object(self): + assert isinstance(ChartData(), CategoryChartData) + + +class Describe_BaseChartData(object): + """Unit-test suite for `pptx.chart.data._BaseChartData`.""" + + def it_can_generate_chart_part_XML_for_its_data(self, ChartXmlWriter_: Mock): + ChartXmlWriter_.return_value.xml = "ƒøØßår" + chart_data = _BaseChartData() + + xml_bytes = chart_data.xml_bytes(XL_CHART_TYPE.PIE) + + ChartXmlWriter_.assert_called_once_with(XL_CHART_TYPE.PIE, chart_data) + assert xml_bytes == "ƒøØßår".encode("utf-8") + + def it_knows_its_number_format(self, number_format_fixture): + chart_data, expected_value = number_format_fixture + assert chart_data.number_format == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=[(None, "General"), (42, 42)]) + def number_format_fixture(self, request): + number_format, expected_value = request.param + argv = [] if number_format is None else [number_format] + chart_data = _BaseChartData(*argv) + return chart_data, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def ChartXmlWriter_(self, request): + ChartXmlWriter_ = class_mock(request, "pptx.chart.data.ChartXmlWriter") + ChartXmlWriter_.return_value.xml = "ƒøØßår" + return ChartXmlWriter_ + + +class Describe_BaseSeriesData(object): + def it_knows_its_name(self, name_fixture): + name_arg, expected_value = name_fixture + series_data = _BaseSeriesData(None, name_arg, None) + + name = series_data.name + + assert name == expected_value + + def it_knows_its_number_format(self, number_format_fixture): + series_data, expected_value = number_format_fixture + assert series_data.number_format == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=[("Tincture of Foo", "Tincture of Foo"), (None, "")]) + def name_fixture(self, request): + name, expected_value = request.param + return name, expected_value + + @pytest.fixture(params=[("General", 42, 42), ("General", None, "General")]) + def number_format_fixture(self, request, chart_data_): + parent_number_format, number_format, expected_value = request.param + chart_data_.number_format = parent_number_format + series_data = _BaseSeriesData(chart_data_, "Foobar", number_format) + return series_data, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def chart_data_(self, request): + return instance_mock(request, _BaseChartData) + + +class Describe_BaseDataPoint(object): + def it_knows_its_number_format(self, number_format_fixture): + data_point, expected_value = number_format_fixture + assert data_point.number_format == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=[(42, 24, 24), (42, None, 42)]) + def number_format_fixture(self, request, series_data_): + parent_number_format, number_format, expected_value = request.param + series_data_.number_format = parent_number_format + data_point = _BaseDataPoint(series_data_, number_format) + return data_point, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def series_data_(self, request): + return instance_mock(request, _BaseSeriesData) + + +class DescribeCategoryChartData(object): + def it_is_a__BaseChartData_object(self): + assert isinstance(CategoryChartData(), _BaseChartData) + + def it_knows_the_categories_range_ref(self, categories_ref_fixture): + chart_data, expected_value = categories_ref_fixture + assert chart_data.categories_ref == expected_value + + def it_knows_the_values_range_ref_for_a_series(self, values_ref_fixture): + chart_data, workbook_writer_, series_, values_ref_ = values_ref_fixture + values_ref = chart_data.values_ref(series_) + workbook_writer_.values_ref.assert_called_once_with(series_) + assert values_ref is values_ref_ + + def it_provides_access_to_its_categories(self, categories_fixture): + chart_data, Categories_, categories_ = categories_fixture + categories = chart_data.categories + Categories_.assert_called_once_with() + assert categories is categories_ + + def it_can_add_a_category(self, add_cat_fixture): + chart_data, name, categories_, category_ = add_cat_fixture + category = chart_data.add_category(name) + categories_.add_category.assert_called_once_with(name) + assert category is category_ + + def it_can_add_a_series(self, add_ser_fixture): + chart_data, name, values, number_format = add_ser_fixture[:4] + CategorySeriesData_, calls, series_ = add_ser_fixture[4:] + series = chart_data.add_series(name, values, number_format) + CategorySeriesData_.assert_called_once_with(chart_data, name, number_format) + assert chart_data[-1] is series + assert series.add_data_point.call_args_list == calls + assert series is series_ + + def it_can_set_its_categories(self, categories_set_fixture): + chart_data, names, Categories_, categories_, calls = categories_set_fixture + chart_data.categories = names + Categories_.assert_called_once_with() + assert categories_.add_category.call_args_list == calls + assert chart_data._categories is categories_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def add_cat_fixture(self, categories_prop_, categories_, category_): + chart_data = CategoryChartData() + name = "foobar" + categories_.add_category.return_value = category_ + return chart_data, name, categories_, category_ + + @pytest.fixture + def add_ser_fixture(self, CategorySeriesData_, series_): + chart_data = CategoryChartData() + name, values, number_format = "foobar", iter((1, 2, 3)), "0.0" + calls = [call(1), call(2), call(3)] + return ( + chart_data, + name, + values, + number_format, + CategorySeriesData_, + calls, + series_, + ) + + @pytest.fixture + def categories_fixture(self, Categories_, categories_): + chart_data = CategoryChartData() + return chart_data, Categories_, categories_ + + @pytest.fixture + def categories_ref_fixture(self, _workbook_writer_prop_, workbook_writer_): + chart_data = CategoryChartData() + expected_value = categories_ref = "Sheet42!$G$24" + workbook_writer_.categories_ref = categories_ref + return chart_data, expected_value + + @pytest.fixture + def categories_set_fixture(self, Categories_, categories_): + chart_data = CategoryChartData() + names = iter(("a", "b", "c")) + calls = [call("a"), call("b"), call("c")] + return chart_data, names, Categories_, categories_, calls + + @pytest.fixture + def values_ref_fixture(self, _workbook_writer_prop_, workbook_writer_, series_): + chart_data = CategoryChartData() + values_ref_ = "Sheet1!$V$24" + workbook_writer_.values_ref.return_value = values_ref_ + return chart_data, workbook_writer_, series_, values_ref_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def Categories_(self, request, categories_): + return class_mock(request, "pptx.chart.data.Categories", return_value=categories_) + + @pytest.fixture + def CategorySeriesData_(self, request, series_): + return class_mock(request, "pptx.chart.data.CategorySeriesData", return_value=series_) + + @pytest.fixture + def categories_(self, request): + return instance_mock(request, Categories) + + @pytest.fixture + def categories_prop_(self, request, categories_): + return property_mock(request, CategoryChartData, "categories", return_value=categories_) + + @pytest.fixture + def category_(self, request): + return instance_mock(request, Category) + + @pytest.fixture + def series_(self, request): + return instance_mock(request, CategorySeriesData) + + @pytest.fixture + def workbook_writer_(self, request): + return instance_mock(request, CategoryWorkbookWriter) + + @pytest.fixture + def _workbook_writer_prop_(self, request, workbook_writer_): + return property_mock( + request, + CategoryChartData, + "_workbook_writer", + return_value=workbook_writer_, + ) + + +class DescribeCategories(object): + def it_knows_when_its_categories_are_numeric(self, are_numeric_fixture): + categories, expected_value = are_numeric_fixture + assert categories.are_numeric == expected_value + + def it_knows_when_its_categories_are_dates(self, are_dates_fixture): + categories, expected_value = are_dates_fixture + assert categories.are_dates == expected_value + + def it_knows_the_category_hierarchy_depth(self, depth_fixture): + categories, expected_value = depth_fixture + assert categories.depth == expected_value + + def it_knows_the_idx_of_a_category(self, index_fixture): + categories, category_, expected_value = index_fixture + assert categories.index(category_) == expected_value + + def it_knows_its_leaf_category_count(self, leaf_fixture): + categories, expected_value = leaf_fixture + assert categories.leaf_count == expected_value + + def it_knows_its_levels(self, levels_fixture): + categories, expected_value = levels_fixture + assert list(categories.levels) == expected_value + + def it_knows_its_number_format(self, number_format_get_fixture): + categories, expected_value = number_format_get_fixture + assert categories.number_format == expected_value + + def it_can_change_its_number_format(self, number_format_set_fixture): + categories, new_value, expected_value = number_format_set_fixture + categories.number_format = new_value + assert categories.number_format == expected_value + + def it_raises_on_category_depth_not_uniform(self, depth_raises_fixture): + categories = depth_raises_fixture + with pytest.raises(ValueError): + categories.depth + + def it_can_add_a_category(self, add_fixture): + categories, name, Category_, category_ = add_fixture + category = categories.add_category(name) + Category_.assert_called_once_with(name, categories) + assert categories._categories[-1] is category + assert category is category_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def add_fixture(self, Category_, category_): + categories = Categories() + name = "foobar" + return categories, name, Category_, category_ + + @pytest.fixture( + params=[ + ((), False), + (("foo", "bar"), False), + ((1, 2), False), + ((1.2, 2.3), False), + ((date(2016, 12, 21),), True), + ] + ) + def are_dates_fixture(self, request): + labels, expected_value = request.param + categories = Categories() + for label in labels: + categories.add_category(label) + return categories, expected_value + + @pytest.fixture( + params=[ + ((), False), + (("foo", "bar"), False), + ((1, 2), True), + ((1.2, 2.3), True), + ((date(2016, 12, 21),), True), + ] + ) + def are_numeric_fixture(self, request): + labels, expected_value = request.param + categories = Categories() + for label in labels: + categories.add_category(label) + return categories, expected_value + + @pytest.fixture(params=[((), 0), ((1,), 1), ((3,), 3), ((1, 1, 1), 1), ((3, 3, 3), 3)]) + def depth_fixture(self, request): + depths, expected_value = request.param + categories = Categories() + for depth in depths: + categories._categories.append(instance_mock(request, Category, depth=depth)) + return categories, expected_value + + @pytest.fixture + def depth_raises_fixture(self, request): + categories = Categories() + for depth in (1, 2, 1): + categories._categories.append(instance_mock(request, Category, depth=depth)) + return categories + + @pytest.fixture + def index_fixture(self, request): + categories = Categories() + categories_ = [ + instance_mock(request, Category, leaf_count=3), + instance_mock(request, Category, leaf_count=6), + instance_mock(request, Category, leaf_count=9), + ] + category_ = categories_[1] + expected_value = 3 + categories._categories = categories_ + return categories, category_, expected_value + + @pytest.fixture(params=[((), 0), ((1,), 1), ((1, 2, 3), 6)]) + def leaf_fixture(self, request): + leaf_counts, expected_value = request.param + categories = Categories() + for leaf_count in leaf_counts: + categories._categories.append(instance_mock(request, Category, leaf_count=leaf_count)) + return categories, expected_value + + @pytest.fixture( + params=[ + ([(0, "a", ()), (1, "b", ())], [[(0, "a"), (1, "b")]]), + ( + [ + (0, "WEST", ((0, "CA", ()), (1, "LA", ()))), + (2, "EAST", ((2, "NY", ()), (3, "NJ", ()))), + ], + [ + [(0, "CA"), (1, "LA"), (2, "NY"), (3, "NJ")], + [(0, "WEST"), (2, "EAST")], + ], + ), + ] + ) + def levels_fixture(self, request): + cat_data, expected_value = request.param + categories = Categories() + + def iter_cats(cat_tree): + for idx, cat_label, sub_cats in cat_tree: + category_ = instance_mock(request, Category, idx=idx) + category_.label = cat_label + category_.sub_categories = list(iter_cats(sub_cats)) + yield category_ + + categories._categories = list(iter_cats(cat_data)) + + return categories, expected_value + + @pytest.fixture( + params=[ + (None, None, None, "General"), + (None, "foo", None, "General"), + (None, "foo", "bar", "General"), + (None, date(2016, 12, 22), None, r"yyyy\-mm\-dd"), + (None, date(2016, 12, 22), "foo", "General"), + ("#0", 42.24, None, "#0"), + ] + ) + def number_format_get_fixture(self, request): + number_format, cat, subcat, expected_value = request.param + categories = Categories() + if cat is not None: + category = categories.add_category(cat) + if subcat is not None: + category.add_sub_category(subcat) + if number_format is not None: + categories._number_format = number_format + return categories, expected_value + + @pytest.fixture(params=[("0.0", "0.0"), (None, "General")]) + def number_format_set_fixture(self, request): + new_value, expected_value = request.param + categories = Categories() + return categories, new_value, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def Category_(self, request, category_): + return class_mock(request, "pptx.chart.data.Category", return_value=category_) + + @pytest.fixture + def category_(self, request): + return instance_mock(request, Category) + + +class DescribeCategory(object): + def it_knows_its_depth(self, depth_fixture): + category, expected_value = depth_fixture + assert category.depth == expected_value + + def it_knows_its_idx(self, idx_fixture): + category, parent_, idx_ = idx_fixture + idx = category.idx + parent_.index.assert_called_once_with(category) + assert idx == idx_ + + def it_knows_the_index_of_a_sub_category(self, index_fixture): + category, sub_category_, expected_value = index_fixture + index = category.index(sub_category_) + category._parent.index.assert_called_once_with(category) + assert index == expected_value + + def it_knows_its_leaf_category_count(self, leaf_fixture): + category, expected_value = leaf_fixture + assert category.leaf_count == expected_value + + def it_raises_on_depth_not_uniform(self, depth_raises_fixture): + category = depth_raises_fixture + with pytest.raises(ValueError): + category.depth + + def it_knows_its_label(self, label_fixture): + label_arg, expected_value = label_fixture + category = Category(label_arg, None) + + label = category.label + + assert label == expected_value + + def it_knows_its_numeric_string_value(self, num_str_fixture): + category, date_1904, expected_value = num_str_fixture + assert category.numeric_str_val(date_1904) == expected_value + + def it_provides_access_to_its_sub_categories(self, subs_fixture): + category, sub_categories_ = subs_fixture + assert category.sub_categories is sub_categories_ + + def it_can_add_a_sub_category(self, add_sub_fixture): + category, name, Category_, sub_category_ = add_sub_fixture + sub_category = category.add_sub_category(name) + Category_.assert_called_once_with(name, category) + assert category._sub_categories[-1] is sub_category + assert sub_category is sub_category_ + + def it_calculates_an_excel_date_number_to_help(self, excel_date_fixture): + category, date_1904, expected_value = excel_date_fixture + date_number = category._excel_date_number(date_1904) + assert date_number == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def add_sub_fixture(self, request, category_): + category = Category(None, None) + name = "foobar" + Category_ = class_mock(request, "pptx.chart.data.Category", return_value=category_) + return category, name, Category_, category_ + + @pytest.fixture(params=[((), 1), ((1,), 2), ((1, 1, 1), 2), ((2, 2, 2), 3)]) + def depth_fixture(self, request): + depths, expected_value = request.param + category = Category(None, None) + for depth in depths: + category._sub_categories.append(instance_mock(request, Category, depth=depth)) + return category, expected_value + + @pytest.fixture + def depth_raises_fixture(self, request): + category = Category(None, None) + for depth in (1, 2, 1): + category._sub_categories.append(instance_mock(request, Category, depth=depth)) + return category + + @pytest.fixture( + params=[ + (date(2016, 12, 22), False, 42726), + (date(1999, 12, 31), True, 35063), + (datetime(1900, 2, 28), False, 59), + (datetime(1990, 9, 1), True, 31655), + ] + ) + def excel_date_fixture(self, request): + label, date_1904, expected_value = request.param + category = Category(label, None) + return category, date_1904, expected_value + + @pytest.fixture(params=[Categories, Category]) + def idx_fixture(self, request): + parent_cls = request.param + parent_ = instance_mock(request, parent_cls) + category = Category(None, parent_) + parent_.index.return_value = idx_ = 42 + return category, parent_, idx_ + + @pytest.fixture + def index_fixture(self, request, categories_): + category = Category(None, categories_) + sub_categories_ = [ + instance_mock(request, Category, leaf_count=2), + instance_mock(request, Category, leaf_count=4), + instance_mock(request, Category, leaf_count=6), + ] + sub_category_ = sub_categories_[1] + expected_value = 6 + categories_.index.return_value = 4 + category._sub_categories = sub_categories_ + return category, sub_category_, expected_value + + @pytest.fixture(params=[("Able the Label", "Able the Label"), (None, "")]) + def label_fixture(self, request): + label, expected_value = request.param + return label, expected_value + + @pytest.fixture(params=[((), 1), ((1,), 1), ((1, 2, 3), 6)]) + def leaf_fixture(self, request): + leaf_counts, expected_value = request.param + category = Category(None, None) + for leaf_count in leaf_counts: + category._sub_categories.append(instance_mock(request, Category, leaf_count=leaf_count)) + return category, expected_value + + @pytest.fixture( + params=[ + (date(2016, 12, 23), False, "42727.0"), + (42.24, False, "42.24"), + (42, False, "42"), + ("foobar", False, "foobar"), + ] + ) + def num_str_fixture(self, request): + label, date_1904, expected_value = request.param + category = Category(label, None) + return category, date_1904, expected_value + + @pytest.fixture + def subs_fixture(self): + sub_categories_ = [42, 24] + category = Category(None, None) + category._sub_categories = sub_categories_ + return category, sub_categories_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def categories_(self, request): + return instance_mock(request, Categories) + + @pytest.fixture + def category_(self, request): + return instance_mock(request, Category) + + +class DescribeCategorySeriesData(object): + def it_knows_the_categories_range_ref(self, categories_ref_fixture): + series_data, expected_value = categories_ref_fixture + assert series_data.categories_ref == expected_value + + def it_knows_its_values(self, values_fixture): + series_data, expected_values = values_fixture + assert series_data.values == expected_values + + def it_knows_its_values_range_ref(self, values_ref_fixture): + series_data, chart_data_, values_ref_ = values_ref_fixture + values_ref = series_data.values_ref + chart_data_.values_ref.assert_called_once_with(series_data) + assert values_ref is values_ref_ + + def it_provides_access_to_the_chart_categories(self, categories_fixture): + series_data, categories_ = categories_fixture + assert series_data.categories is categories_ + + def it_can_add_a_data_point(self, add_fixture): + series_data, value, number_format = add_fixture[:3] + CategoryDataPoint_, data_point_ = add_fixture[3:] + data_point = series_data.add_data_point(value, number_format) + CategoryDataPoint_.assert_called_once_with(series_data, value, number_format) + assert series_data[-1] is data_point_ + assert data_point is data_point_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def add_fixture(self, request, CategoryDataPoint_, data_point_): + series_data = CategorySeriesData(None, None, None) + value, number_format = 42, "0.0" + return (series_data, value, number_format, CategoryDataPoint_, data_point_) + + @pytest.fixture + def categories_fixture(self, chart_data_, categories_): + series_data = CategorySeriesData(chart_data_, None, None) + chart_data_.categories = categories_ + return series_data, categories_ + + @pytest.fixture + def categories_ref_fixture(self, chart_data_): + series_data = CategorySeriesData(chart_data_, None, None) + expected_value = categories_ref = "Sheet1!$F$42" + chart_data_.categories_ref = categories_ref + return series_data, expected_value + + @pytest.fixture + def values_fixture(self, request): + series_data = CategorySeriesData(None, None, None) + expected_values = [1, 2, 3] + for value in expected_values: + series_data._data_points.append(instance_mock(request, CategoryDataPoint, value=value)) + return series_data, expected_values + + @pytest.fixture + def values_ref_fixture(self, chart_data_): + series_data = CategorySeriesData(chart_data_, None, None) + values_ref_ = "Sheet1!$V$42" + chart_data_.values_ref.return_value = values_ref_ + return series_data, chart_data_, values_ref_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def CategoryDataPoint_(self, request, data_point_): + return class_mock(request, "pptx.chart.data.CategoryDataPoint", return_value=data_point_) + + @pytest.fixture + def categories_(self, request): + return instance_mock(request, Categories) + + @pytest.fixture + def chart_data_(self, request): + return instance_mock(request, CategoryChartData) + + @pytest.fixture + def data_point_(self, request): + return instance_mock(request, CategoryDataPoint) + + +class DescribeBubbleChartData(object): + def it_can_add_a_series(self, add_series_fixture): + chart_data, name, BubbleSeriesData_, series_data_ = add_series_fixture + series_data = chart_data.add_series(name) + BubbleSeriesData_.assert_called_once_with(chart_data, name, None) + assert chart_data[-1] is series_data_ + assert series_data is series_data_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def add_series_fixture(self, request, BubbleSeriesData_, series_data_): + chart_data = BubbleChartData() + name = "Series Name" + return chart_data, name, BubbleSeriesData_, series_data_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def BubbleSeriesData_(self, request, series_data_): + return class_mock(request, "pptx.chart.data.BubbleSeriesData", return_value=series_data_) + + @pytest.fixture + def series_data_(self, request): + return instance_mock(request, BubbleSeriesData) + + +class DescribeXyChartData(object): + def it_is_a__BaseChartData_object(self): + assert isinstance(XyChartData(), _BaseChartData) + + def it_can_add_a_series(self, add_series_fixture): + chart_data, label, XySeriesData_, series_data_ = add_series_fixture + series_data = chart_data.add_series(label) + XySeriesData_.assert_called_once_with(chart_data, label, None) + assert chart_data[-1] is series_data_ + assert series_data is series_data_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def add_series_fixture(self, request, XySeriesData_, series_data_): + chart_data = XyChartData() + label = "Series Label" + return chart_data, label, XySeriesData_, series_data_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def XySeriesData_(self, request, series_data_): + return class_mock(request, "pptx.chart.data.XySeriesData", return_value=series_data_) + + @pytest.fixture + def series_data_(self, request): + return instance_mock(request, XySeriesData) + + +class DescribeBubbleSeriesData(object): + def it_can_add_a_data_point(self, add_data_point_fixture): + series_data, x, y, size, BubbleDataPoint_, data_point_ = add_data_point_fixture + data_point = series_data.add_data_point(x, y, size) + BubbleDataPoint_.assert_called_once_with(series_data, x, y, size, None) + assert series_data[-1] is data_point_ + assert data_point is data_point_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def add_data_point_fixture(self, request, BubbleDataPoint_, data_point_): + series_data = BubbleSeriesData(None, None, None) + x, y, size = 42, 24, 17 + return series_data, x, y, size, BubbleDataPoint_, data_point_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def BubbleDataPoint_(self, request, data_point_): + return class_mock(request, "pptx.chart.data.BubbleDataPoint", return_value=data_point_) + + @pytest.fixture + def data_point_(self, request): + return instance_mock(request, BubbleDataPoint) + + +class DescribeXySeriesData(object): + def it_is_a__BaseSeriesData_object(self, chart_data_): + name, number_format = "Series 42", "#0.0" + series_data = XySeriesData(chart_data_, name, number_format) + assert isinstance(series_data, _BaseSeriesData) + assert series_data._chart_data is chart_data_ + assert series_data.name == name + assert series_data.number_format == number_format + + def it_can_add_a_data_point(self, add_data_point_fixture): + series_data, x, y, XyDataPoint_, data_point_ = add_data_point_fixture + data_point = series_data.add_data_point(x, y) + XyDataPoint_.assert_called_once_with(series_data, x, y, None) + assert series_data[-1] is data_point_ + assert data_point is data_point_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def add_data_point_fixture(self, request, XyDataPoint_, data_point_): + series_data = XySeriesData(None, None, None) + x, y = 42, 24 + return series_data, x, y, XyDataPoint_, data_point_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def chart_data_(self, request): + return instance_mock(request, _BaseChartData) + + @pytest.fixture + def data_point_(self, request): + return instance_mock(request, XyDataPoint) + + @pytest.fixture + def XyDataPoint_(self, request, data_point_): + return class_mock(request, "pptx.chart.data.XyDataPoint", return_value=data_point_) + + +class DescribeCategoryDataPoint(object): + def it_is_a__BaseDataPoint_object(self, series_data_): + data_point = CategoryDataPoint(series_data_, 42, "#,##0.0") + assert isinstance(data_point, _BaseDataPoint) + assert data_point.number_format == "#,##0.0" + assert data_point._series_data is series_data_ + + def it_knows_its_value(self, value_fixture): + data_point, expected_value = value_fixture + assert data_point.value == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def value_fixture(self): + value = 42 + data_point = CategoryDataPoint(None, value, None) + return data_point, value + + # fixture components --------------------------------------------- + + @pytest.fixture + def series_data_(self, request): + return instance_mock(request, CategorySeriesData) + + +class DescribeXyDataPoint(object): + def it_is_a__BaseDataPoint_object(self, series_data_): + data_point = XyDataPoint(series_data_, 42, 24, "00.0") + assert isinstance(data_point, _BaseDataPoint) + assert data_point._series_data is series_data_ + assert data_point.number_format == "00.0" + + def it_knows_its_x_y_values(self, value_fixture): + data_point, x, y = value_fixture + assert data_point.x == x + assert data_point.y == y + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def value_fixture(self): + x, y = 42, 24 + data_point = XyDataPoint(None, x, y, None) + return data_point, x, y + + # fixture components --------------------------------------------- + + @pytest.fixture + def series_data_(self, request): + return instance_mock(request, XySeriesData) + + +class DescribeBubbleDataPoint(object): + def it_is_an_XyDataPoint_subclass(self, series_data_): + x, y, size, number_format = 1, 2, 10, "#00.0" + data_point = BubbleDataPoint(series_data_, x, y, size, number_format) + assert isinstance(data_point, XyDataPoint) + assert data_point._series_data is series_data_ + assert data_point.x == x + assert data_point.y == y + assert data_point.number_format == number_format + + def it_knows_its_x_y_size_values(self, value_fixture): + data_point, x, y, size = value_fixture + assert data_point.x == x + assert data_point.y == y + assert data_point.bubble_size == size + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def value_fixture(self): + x, y, size = 42, 24, 100 + data_point = BubbleDataPoint(None, x, y, size, None) + return data_point, x, y, size + + # fixture components --------------------------------------------- + + @pytest.fixture + def series_data_(self, request): + return instance_mock(request, BubbleSeriesData) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_datalabel.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_datalabel.py new file mode 100644 index 0000000000000000000000000000000000000000..ad02efc10783aaf1cff8c19ea6a244720a8a9d2e --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_datalabel.py @@ -0,0 +1,663 @@ +"""Unit test suite for the pptx.chart.datalabel module""" + +from __future__ import annotations + +import pytest + +from pptx.chart.datalabel import DataLabel, DataLabels +from pptx.enum.chart import XL_LABEL_POSITION +from pptx.text.text import Font + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, instance_mock, method_mock + + +class DescribeDataLabel(object): + def it_has_a_font(self, font_fixture): + data_label, expected_xml = font_fixture + font = data_label.font + assert data_label._ser.xml == expected_xml + assert isinstance(font, Font) + + def it_knows_its_position(self, position_get_fixture): + data_label, expected_value = position_get_fixture + position = data_label.position + assert position == expected_value + + def it_can_change_its_position(self, position_set_fixture): + data_label, value, expected_xml = position_set_fixture + data_label.position = value + assert data_label._element.xml == expected_xml + + def it_knows_whether_it_has_a_text_frame(self, has_tf_get_fixture): + data_label, expected_value = has_tf_get_fixture + value = data_label.has_text_frame + assert value is expected_value + + def it_can_change_whether_it_has_a_text_frame(self, has_tf_set_fixture): + data_label, value, expected_xml = has_tf_set_fixture + data_label.has_text_frame = value + assert data_label._element.xml == expected_xml + + def it_provides_access_to_its_text_frame(self, text_frame_fixture): + data_label, TextFrame_, rich_, text_frame_ = text_frame_fixture + text_frame = data_label.text_frame + TextFrame_.assert_called_once_with(rich_, data_label) + assert text_frame is text_frame_ + + def it_gets_or_adds_rich_element_to_help(self, rich_fixture): + data_label, expected_xml = rich_fixture + rich = data_label._get_or_add_rich() + assert data_label._ser.xml == expected_xml + assert rich is data_label._ser.xpath("c:dLbls/c:dLbl/c:tx/c:rich")[0] + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ( + "c:ser{a:b=c}", + "c:ser{a:b=c}/c:dLbls/(c:dLbl/(c:idx{val=9},c:spPr,c:txPr/(a:bodyPr" + ",a:lstStyle,a:p/a:pPr/a:defRPr),c:showLegendKey{val=0},c:showVal{v" + "al=1},c:showCatName{val=0},c:showSerName{val=0},c:showPercent{val=" + "0},c:showBubbleSize{val=0}),c:showLegendKey{val=0},c:showVal{val=0" + "},c:showCatName{val=0},c:showSerName{val=0},c:showPercent{val=0},c" + ":showBubbleSize{val=0},c:showLeaderLines{val=1})", + ), + ( + "c:ser{a:b=c}/c:dLbls/c:dLbl/(c:idx{val=9},c:txPr/(a:bodyPr,a:p))", + "c:ser{a:b=c}/c:dLbls/c:dLbl/(c:idx{val=9},c:txPr/(a:bodyPr,a:p/a:p" + "Pr/a:defRPr))", + ), + ] + ) + def font_fixture(self, request): + ser_cxml, expected_cxml = request.param + data_label = DataLabel(element(ser_cxml), 9) + expected_xml = xml(expected_cxml) + return data_label, expected_xml + + @pytest.fixture( + params=[ + ("c:ser", False), + ("c:ser/c:dLbls", False), + ("c:ser/c:dLbls/c:dLbl/c:idx{val=42}", False), + ("c:ser/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:strRef)", False), + ("c:ser/c:dLbls/c:dLbl/(c:idx{val=24},c:tx/c:rich)", False), + ("c:ser/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:rich)", True), + ] + ) + def has_tf_get_fixture(self, request): + ser_cxml, expected_value = request.param + data_label = DataLabel(element(ser_cxml), 42) + return data_label, expected_value + + @pytest.fixture( + params=[ + ("c:ser", False, "c:ser"), + ("c:ser/c:dLbls", False, "c:ser/c:dLbls"), + ( + "c:ser/c:dLbls/c:dLbl/c:idx{val=42}", + False, + "c:ser/c:dLbls/c:dLbl/c:idx{val=42}", + ), + ( + "c:ser/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:strRef)", + False, + "c:ser/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:strRef)", + ), + ( + "c:ser/c:dLbls/c:dLbl/(c:idx{val=24},c:tx/c:rich)", + False, + "c:ser/c:dLbls/c:dLbl/(c:idx{val=24},c:tx/c:rich)", + ), + ( + "c:ser/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:rich)", + False, + "c:ser/c:dLbls/c:dLbl/c:idx{val=42}", + ), + ( + "c:ser{a:b=c}", + True, + "c:ser{a:b=c}/c:dLbls/(c:dLbl/(c:idx{val=42},c:tx/c:rich/(a:bodyPr," + "a:lstStyle,a:p/a:pPr/a:defRPr),c:showLegendKey{val=0},c:showVal{va" + "l=1},c:showCatName{val=0},c:showSerName{val=0},c:showPercent{val=0" + "},c:showBubbleSize{val=0}),c:showLegendKey{val=0},c:showVal{val=0}" + ",c:showCatName{val=0},c:showSerName{val=0},c:showPercent{val=0},c:" + "showBubbleSize{val=0},c:showLeaderLines{val=1})", + ), + ( + "c:ser{a:b=c}/c:dLbls", + True, + "c:ser{a:b=c}/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:rich/(a:bodyPr,a" + ":lstStyle,a:p/a:pPr/a:defRPr),c:showLegendKey{val=0},c:showVal{val" + "=1},c:showCatName{val=0},c:showSerName{val=0},c:showPercent{val=0}" + ",c:showBubbleSize{val=0})", + ), + ( + "c:ser{a:b=c}/c:dLbls/c:dLbl/c:idx{val=42}", + True, + "c:ser{a:b=c}/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:rich/(a:bodyPr,a" + ":lstStyle,a:p/a:pPr/a:defRPr))", + ), + ( + "c:ser{a:b=c}/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:strRef)", + True, + "c:ser{a:b=c}/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:rich/(a:bodyPr,a" + ":lstStyle,a:p/a:pPr/a:defRPr))", + ), + ( + "c:ser{a:b=c}/c:dLbls/c:dLbl/(c:idx{val=24},c:tx/c:rich)", + True, + "c:ser{a:b=c}/c:dLbls/(c:dLbl/(c:idx{val=24},c:tx/c:rich),c:dLbl/(c" + ":idx{val=42},c:tx/c:rich/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr)," + "c:showLegendKey{val=0},c:showVal{val=1},c:showCatName{val=0},c:sho" + "wSerName{val=0},c:showPercent{val=0},c:showBubbleSize{val=0}))", + ), + ( + "c:ser{a:b=c}/c:dLbls/c:dLbl/c:idx{val=42}", + True, + "c:ser{a:b=c}/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:rich/(a:bodyPr,a" + ":lstStyle,a:p/a:pPr/a:defRPr))", + ), + ] + ) + def has_tf_set_fixture(self, request): + ser_cxml, value, expected_cxml = request.param + data_label = DataLabel(element(ser_cxml), 42) + expected_xml = xml(expected_cxml) + return data_label, value, expected_xml + + @pytest.fixture( + params=[ + ("c:ser", None), + ("c:ser/c:dLbls/c:dLbl/c:idx{val=42}", None), + ("c:ser/c:dLbls/c:dLbl/(c:idx{val=42},c:dLblPos{val=b})", "BELOW"), + ] + ) + def position_get_fixture(self, request): + ser_cxml, value = request.param + data_label = DataLabel(element(ser_cxml), 42) + expected_value = None if value is None else getattr(XL_LABEL_POSITION, value) + return data_label, expected_value + + @pytest.fixture( + params=[ + ( + "c:ser{a:b=c}", + "CENTER", + "c:ser{a:b=c}/c:dLbls/(c:dLbl/(c:idx{val=42},c:spPr,c:txPr/(a:bodyP" + "r,a:lstStyle,a:p/a:pPr/a:defRPr),c:dLblPos{val=ctr},c:showLegendKe" + "y{val=0},c:showVal{val=1},c:showCatName{val=0},c:showSerName{val=0" + "},c:showPercent{val=0},c:showBubbleSize{val=0}),c:showLegendKey{va" + "l=0},c:showVal{val=0},c:showCatName{val=0},c:showSerName{val=0},c:" + "showPercent{val=0},c:showBubbleSize{val=0},c:showLeaderLines{val=1" + "})", + ), + ( + "c:ser/c:dLbls/c:dLbl/(c:idx{val=42},c:dLblPos{val=ctr})", + "BELOW", + "c:ser/c:dLbls/c:dLbl/(c:idx{val=42},c:dLblPos{val=b})", + ), + ( + "c:ser/c:dLbls/c:dLbl/(c:idx{val=42},c:dLblPos{val=b})", + None, + "c:ser/c:dLbls/c:dLbl/c:idx{val=42}", + ), + ("c:ser", None, "c:ser"), + ] + ) + def position_set_fixture(self, request): + ser_cxml, value, expected_cxml = request.param + data_label = DataLabel(element(ser_cxml), 42) + new_value = None if value is None else getattr(XL_LABEL_POSITION, value) + expected_xml = xml(expected_cxml) + return data_label, new_value, expected_xml + + @pytest.fixture( + params=[ + ( + "c:ser{a:b=c}", + "c:ser{a:b=c}/c:dLbls/(c:dLbl/(c:idx{val=42},c:tx/c:rich/(a:bodyPr," + "a:lstStyle,a:p/a:pPr/a:defRPr),c:showLegendKey{val=0},c:showVal{va" + "l=1},c:showCatName{val=0},c:showSerName{val=0},c:showPercent{val=0" + "},c:showBubbleSize{val=0}),c:showLegendKey{val=0},c:showVal{val=0}" + ",c:showCatName{val=0},c:showSerName{val=0},c:showPercent{val=0},c:" + "showBubbleSize{val=0},c:showLeaderLines{val=1})", + ), + ( + "c:ser{a:b=c}/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:strRef)", + "c:ser{a:b=c}/c:dLbls/c:dLbl/(c:idx{val=42},c:tx/c:rich/(a:bodyPr,a" + ":lstStyle,a:p/a:pPr/a:defRPr))", + ), + ] + ) + def rich_fixture(self, request): + ser_cxml, expected_cxml = request.param + data_label = DataLabel(element(ser_cxml), 42) + expected_xml = xml(expected_cxml) + return data_label, expected_xml + + @pytest.fixture + def text_frame_fixture(self, request, _get_or_add_rich_, TextFrame_): + data_label = DataLabel(None, None) + rich_ = _get_or_add_rich_.return_value + text_frame_ = TextFrame_.return_value + return data_label, TextFrame_, rich_, text_frame_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _get_or_add_rich_(self, request): + return method_mock(request, DataLabel, "_get_or_add_rich") + + @pytest.fixture + def TextFrame_(self, request): + return class_mock(request, "pptx.chart.datalabel.TextFrame") + + +class DescribeDataLabels(object): + def it_provides_access_to_its_font(self, font_fixture): + data_labels, Font_, defRPr, font_ = font_fixture + font = data_labels.font + Font_.assert_called_once_with(defRPr) + assert font is font_ + + def it_adds_a_txPr_to_help_font(self, txPr_fixture): + data_labels, expected_xml = txPr_fixture + data_labels.font + assert data_labels._element.xml == expected_xml + + def it_knows_its_number_format(self, number_format_get_fixture): + data_labels, expected_value = number_format_get_fixture + assert data_labels.number_format == expected_value + + def it_can_change_its_number_format(self, number_format_set_fixture): + data_labels, new_value, expected_xml = number_format_set_fixture + data_labels.number_format = new_value + assert data_labels._element.xml == expected_xml + + def it_knows_whether_its_number_format_is_linked(self, number_format_is_linked_get_fixture): + data_labels, expected_value = number_format_is_linked_get_fixture + assert data_labels.number_format_is_linked is expected_value + + def it_can_change_whether_its_number_format_is_linked( + self, number_format_is_linked_set_fixture + ): + data_labels, new_value, expected_xml = number_format_is_linked_set_fixture + data_labels.number_format_is_linked = new_value + assert data_labels._element.xml == expected_xml + + def it_knows_its_position(self, position_get_fixture): + data_labels, expected_value = position_get_fixture + assert data_labels.position == expected_value + + def it_can_change_its_position(self, position_set_fixture): + data_labels, new_value, expected_xml = position_set_fixture + data_labels.position = new_value + assert data_labels._element.xml == expected_xml + + def it_knows_whether_it_shows_category_name(self, catname_get_fixture): + dLbls, expected_value = catname_get_fixture + data_labels = DataLabels(dLbls) + + show_category_name = data_labels.show_category_name + + assert show_category_name == expected_value + + def it_can_set_whether_it_shows_category_name(self, catname_set_fixture): + dLbls, new_value, expected_xml = catname_set_fixture + data_labels = DataLabels(dLbls) + + data_labels.show_category_name = new_value + + assert data_labels._element.xml == expected_xml + + def it_knows_whether_it_shows_legend_key(self, lgndkey_get_fixture): + dLbls, expected_value = lgndkey_get_fixture + data_labels = DataLabels(dLbls) + + show_legend_key = data_labels.show_legend_key + + assert show_legend_key == expected_value + + def it_can_set_whether_it_shows_legend_key(self, lgndkey_set_fixture): + dLbls, new_value, expected_xml = lgndkey_set_fixture + data_labels = DataLabels(dLbls) + + data_labels.show_legend_key = new_value + + assert data_labels._element.xml == expected_xml + + def it_knows_whether_it_shows_percentage(self, percent_get_fixture): + dLbls, expected_value = percent_get_fixture + data_labels = DataLabels(dLbls) + + show_percentage = data_labels.show_percentage + + assert show_percentage == expected_value + + def it_can_set_whether_it_shows_percentage(self, percent_set_fixture): + dLbls, new_value, expected_xml = percent_set_fixture + data_labels = DataLabels(dLbls) + + data_labels.show_percentage = new_value + + assert data_labels._element.xml == expected_xml + + def it_knows_whether_it_shows_series_name(self, sername_get_fixture): + dLbls, expected_value = sername_get_fixture + data_labels = DataLabels(dLbls) + + show_series_name = data_labels.show_series_name + + assert show_series_name == expected_value + + def it_can_set_whether_it_shows_series_name(self, sername_set_fixture): + dLbls, new_value, expected_xml = sername_set_fixture + data_labels = DataLabels(dLbls) + + data_labels.show_series_name = new_value + + assert data_labels._element.xml == expected_xml + + def it_knows_whether_it_shows_value(self, value_get_fixture): + dLbls, expected_value = value_get_fixture + data_labels = DataLabels(dLbls) + + show_value = data_labels.show_value + + assert show_value == expected_value + + def it_can_set_whether_it_shows_value(self, value_set_fixture): + dLbls, new_value, expected_xml = value_set_fixture + data_labels = DataLabels(dLbls) + + data_labels.show_value = new_value + + assert data_labels._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:dLbls", False), + ("c:dLbls/c:showCatName{val=0}", False), + ("c:dLbls/c:showCatName{val=1}", True), + ("c:dLbls/c:showCatName{val=true}", True), + # ---not an expected situation, but schema-compliant--- + ("c:dLbls/c:showCatName", True), + ] + ) + def catname_get_fixture(self, request): + dLbls_cxml, expected_value = request.param + dLbls = element(dLbls_cxml) + return dLbls, expected_value + + @pytest.fixture( + params=[ + ("c:dLbls", False, "c:dLbls/c:showCatName{val=0}"), + ("c:dLbls", True, "c:dLbls/c:showCatName{val=1}"), + ("c:dLbls/c:showCatName", False, "c:dLbls/c:showCatName{val=0}"), + ("c:dLbls/c:showCatName{val=0}", False, "c:dLbls/c:showCatName{val=0}"), + ("c:dLbls/c:showCatName{val=0}", True, "c:dLbls/c:showCatName{val=1}"), + ("c:dLbls/c:showCatName{val=1}", False, "c:dLbls/c:showCatName{val=0}"), + ] + ) + def catname_set_fixture(self, request): + dLbls_cxml, new_value, expected_dLbls_cxml = request.param + dLbls = element(dLbls_cxml) + expected_dLbls_xml = xml(expected_dLbls_cxml) + return dLbls, new_value, expected_dLbls_xml + + @pytest.fixture + def font_fixture(self, Font_, font_): + dLbls = element("c:dLbls/c:txPr/a:p/a:pPr/a:defRPr") + defRPr = dLbls.xpath(".//a:defRPr")[0] + data_labels = DataLabels(dLbls) + return data_labels, Font_, defRPr, font_ + + @pytest.fixture( + params=[ + ("c:dLbls", False), + ("c:dLbls/c:showLegendKey{val=0}", False), + ("c:dLbls/c:showLegendKey{val=1}", True), + ("c:dLbls/c:showLegendKey{val=true}", True), + # ---not an expected situation, but schema-compliant--- + ("c:dLbls/c:showLegendKey", True), + ] + ) + def lgndkey_get_fixture(self, request): + dLbls_cxml, expected_value = request.param + dLbls = element(dLbls_cxml) + return dLbls, expected_value + + @pytest.fixture( + params=[ + ("c:dLbls", False, "c:dLbls/c:showLegendKey{val=0}"), + ("c:dLbls", True, "c:dLbls/c:showLegendKey{val=1}"), + ("c:dLbls/c:showLegendKey", False, "c:dLbls/c:showLegendKey{val=0}"), + ("c:dLbls/c:showLegendKey{val=0}", False, "c:dLbls/c:showLegendKey{val=0}"), + ("c:dLbls/c:showLegendKey{val=0}", True, "c:dLbls/c:showLegendKey{val=1}"), + ("c:dLbls/c:showLegendKey{val=1}", False, "c:dLbls/c:showLegendKey{val=0}"), + ] + ) + def lgndkey_set_fixture(self, request): + dLbls_cxml, new_value, expected_dLbls_cxml = request.param + dLbls = element(dLbls_cxml) + expected_dLbls_xml = xml(expected_dLbls_cxml) + return dLbls, new_value, expected_dLbls_xml + + @pytest.fixture( + params=[ + ("c:dLbls", "General"), + ("c:dLbls/c:numFmt{formatCode=foobar}", "foobar"), + ] + ) + def number_format_get_fixture(self, request): + dLbls_cxml, expected_value = request.param + data_labels = DataLabels(element(dLbls_cxml)) + return data_labels, expected_value + + @pytest.fixture( + params=[ + ( + "c:dLbls", + "General", + "c:dLbls/c:numFmt{formatCode=General,sourceLinked=0}", + ), + ( + "c:dLbls/c:numFmt{formatCode=General}", + "00.00", + "c:dLbls/c:numFmt{formatCode=00.00,sourceLinked=0}", + ), + ] + ) + def number_format_set_fixture(self, request): + dLbls_cxml, new_value, expected_dLbls_cxml = request.param + data_labels = DataLabels(element(dLbls_cxml)) + expected_xml = xml(expected_dLbls_cxml) + return data_labels, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:dLbls", True), + ("c:dLbls/c:numFmt", True), + ("c:dLbls/c:numFmt{sourceLinked=0}", False), + ("c:dLbls/c:numFmt{sourceLinked=1}", True), + ] + ) + def number_format_is_linked_get_fixture(self, request): + dLbls_cxml, expected_value = request.param + data_labels = DataLabels(element(dLbls_cxml)) + return data_labels, expected_value + + @pytest.fixture( + params=[ + ("c:dLbls", True, "c:dLbls/c:numFmt{sourceLinked=1}"), + ("c:dLbls", False, "c:dLbls/c:numFmt{sourceLinked=0}"), + ("c:dLbls", None, "c:dLbls/c:numFmt"), + ("c:dLbls/c:numFmt", True, "c:dLbls/c:numFmt{sourceLinked=1}"), + ( + "c:dLbls/c:numFmt{sourceLinked=1}", + False, + "c:dLbls/c:numFmt{sourceLinked=0}", + ), + ] + ) + def number_format_is_linked_set_fixture(self, request): + dLbls_cxml, new_value, expected_dLbls_cxml = request.param + data_labels = DataLabels(element(dLbls_cxml)) + expected_xml = xml(expected_dLbls_cxml) + return data_labels, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:dLbls", False), + ("c:dLbls/c:showPercent{val=0}", False), + ("c:dLbls/c:showPercent{val=1}", True), + ("c:dLbls/c:showPercent{val=true}", True), + ("c:dLbls/c:showPercent", True), + ] + ) + def percent_get_fixture(self, request): + dLbls_cxml, expected_value = request.param + dLbls = element(dLbls_cxml) + return dLbls, expected_value + + @pytest.fixture( + params=[ + ("c:dLbls", False, "c:dLbls/c:showPercent{val=0}"), + ("c:dLbls", True, "c:dLbls/c:showPercent{val=1}"), + ("c:dLbls/c:showPercent", False, "c:dLbls/c:showPercent{val=0}"), + ("c:dLbls/c:showPercent{val=0}", False, "c:dLbls/c:showPercent{val=0}"), + ("c:dLbls/c:showPercent{val=0}", True, "c:dLbls/c:showPercent{val=1}"), + ("c:dLbls/c:showPercent{val=1}", False, "c:dLbls/c:showPercent{val=0}"), + ] + ) + def percent_set_fixture(self, request): + dLbls_cxml, new_value, expected_dLbls_cxml = request.param + dLbls = element(dLbls_cxml) + expected_dLbls_xml = xml(expected_dLbls_cxml) + return dLbls, new_value, expected_dLbls_xml + + @pytest.fixture( + params=[ + ("c:dLbls", None), + ("c:dLbls/c:dLblPos{val=inBase}", XL_LABEL_POSITION.INSIDE_BASE), + ] + ) + def position_get_fixture(self, request): + dLbls_cxml, expected_value = request.param + data_labels = DataLabels(element(dLbls_cxml)) + return data_labels, expected_value + + @pytest.fixture( + params=[ + ("c:dLbls", XL_LABEL_POSITION.INSIDE_BASE, "c:dLbls/c:dLblPos{val=inBase}"), + ( + "c:dLbls/c:dLblPos{val=inBase}", + XL_LABEL_POSITION.OUTSIDE_END, + "c:dLbls/c:dLblPos{val=outEnd}", + ), + ("c:dLbls/c:dLblPos{val=inBase}", None, "c:dLbls"), + ("c:dLbls", None, "c:dLbls"), + ] + ) + def position_set_fixture(self, request): + dLbls_cxml, new_value, expected_dLbls_cxml = request.param + data_labels = DataLabels(element(dLbls_cxml)) + expected_xml = xml(expected_dLbls_cxml) + return data_labels, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:dLbls", False), + ("c:dLbls/c:showSerName{val=0}", False), + ("c:dLbls/c:showSerName{val=1}", True), + ("c:dLbls/c:showSerName{val=true}", True), + ("c:dLbls/c:showSerName", True), + ] + ) + def sername_get_fixture(self, request): + dLbls_cxml, expected_value = request.param + dLbls = element(dLbls_cxml) + return dLbls, expected_value + + @pytest.fixture( + params=[ + ("c:dLbls", False, "c:dLbls/c:showSerName{val=0}"), + ("c:dLbls", True, "c:dLbls/c:showSerName{val=1}"), + ("c:dLbls/c:showSerName", False, "c:dLbls/c:showSerName{val=0}"), + ("c:dLbls/c:showSerName{val=0}", False, "c:dLbls/c:showSerName{val=0}"), + ("c:dLbls/c:showSerName{val=0}", True, "c:dLbls/c:showSerName{val=1}"), + ("c:dLbls/c:showSerName{val=1}", False, "c:dLbls/c:showSerName{val=0}"), + ] + ) + def sername_set_fixture(self, request): + dLbls_cxml, new_value, expected_dLbls_cxml = request.param + dLbls = element(dLbls_cxml) + expected_dLbls_xml = xml(expected_dLbls_cxml) + return dLbls, new_value, expected_dLbls_xml + + @pytest.fixture( + params=[ + ( + "c:dLbls{a:b=c}", + "c:dLbls{a:b=c}/c:txPr/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr)", + ), + ( + "c:dLbls{a:b=c}/c:txPr/(a:bodyPr,a:p)", + "c:dLbls{a:b=c}/c:txPr/(a:bodyPr,a:p/a:pPr/a:defRPr)", + ), + ( + "c:dLbls{a:b=c}/c:txPr/(a:bodyPr,a:p/a:pPr)", + "c:dLbls{a:b=c}/c:txPr/(a:bodyPr,a:p/a:pPr/a:defRPr)", + ), + ] + ) + def txPr_fixture(self, request): + dLbls_cxml, expected_cxml = request.param + data_labels = DataLabels(element(dLbls_cxml)) + expected_xml = xml(expected_cxml) + return data_labels, expected_xml + + @pytest.fixture( + params=[ + ("c:dLbls", False), + ("c:dLbls/c:showVal{val=0}", False), + ("c:dLbls/c:showVal{val=1}", True), + ("c:dLbls/c:showVal{val=true}", True), + ("c:dLbls/c:showVal", True), + ] + ) + def value_get_fixture(self, request): + dLbls_cxml, expected_value = request.param + dLbls = element(dLbls_cxml) + return dLbls, expected_value + + @pytest.fixture( + params=[ + ("c:dLbls", False, "c:dLbls/c:showVal{val=0}"), + ("c:dLbls", True, "c:dLbls/c:showVal{val=1}"), + ("c:dLbls/c:showVal", False, "c:dLbls/c:showVal{val=0}"), + ("c:dLbls/c:showVal{val=0}", False, "c:dLbls/c:showVal{val=0}"), + ("c:dLbls/c:showVal{val=0}", True, "c:dLbls/c:showVal{val=1}"), + ("c:dLbls/c:showVal{val=1}", False, "c:dLbls/c:showVal{val=0}"), + ] + ) + def value_set_fixture(self, request): + dLbls_cxml, new_value, expected_dLbls_cxml = request.param + dLbls = element(dLbls_cxml) + expected_dLbls_xml = xml(expected_dLbls_cxml) + return dLbls, new_value, expected_dLbls_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def Font_(self, request, font_): + return class_mock(request, "pptx.chart.datalabel.Font", return_value=font_) + + @pytest.fixture + def font_(self, request): + return instance_mock(request, Font) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_legend.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_legend.py new file mode 100644 index 0000000000000000000000000000000000000000..d77cd9f37ac4a7da1feb2be1c9ff3109aba0ca5e --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_legend.py @@ -0,0 +1,176 @@ +"""Unit-test suite for `pptx.chart.legend` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.legend import Legend +from pptx.enum.chart import XL_LEGEND_POSITION +from pptx.text.text import Font + +from ..unitutil.cxml import element, xml + + +class DescribeLegend(object): + def it_provides_access_to_its_font(self, font_fixture): + legend, expected_xml = font_fixture + font = legend.font + assert legend._element.xml == expected_xml + assert isinstance(font, Font) + assert font._element == legend._element.xpath(".//a:defRPr")[0] + + def it_knows_its_horizontal_offset(self, horz_offset_get_fixture): + legend, expected_value = horz_offset_get_fixture + assert legend.horz_offset == expected_value + + def it_can_change_its_horizontal_offset(self, horz_offset_set_fixture): + legend, new_value, expected_xml = horz_offset_set_fixture + legend.horz_offset = new_value + assert legend._element.xml == expected_xml + + def it_knows_whether_it_should_overlap_the_chart(self, include_in_layout_get_fixture): + legend, expected_value = include_in_layout_get_fixture + assert legend.include_in_layout == expected_value + + def it_can_change_whether_it_overlaps_the_chart(self, include_in_layout_set_fixture): + legend, new_value, expected_xml = include_in_layout_set_fixture + legend.include_in_layout = new_value + assert legend._element.xml == expected_xml + + def it_knows_its_position_with_respect_to_the_chart(self, position_get_fixture): + legend, expected_value = position_get_fixture + assert legend.position == expected_value + + def it_can_change_its_position(self, position_set_fixture): + legend, new_value, expected_xml = position_set_fixture + legend.position = new_value + assert legend._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ( + "c:legend{a:b=c}", + "c:legend{a:b=c}/c:txPr/(a:bodyPr,a:lstStyle,a:p/a:pPr/a:defRPr)", + ) + ] + ) + def font_fixture(self, request): + legend_cxml, expected_cxml = request.param + legend = Legend(element(legend_cxml)) + expected_xml = xml(expected_cxml) + return legend, expected_xml + + @pytest.fixture( + params=[ + ("c:legend", 0.0), + ("c:legend/c:layout", 0.0), + ("c:legend/c:layout/c:manualLayout", 0.0), + ("c:legend/c:layout/c:manualLayout/c:xMode", 0.0), + ("c:legend/c:layout/c:manualLayout/c:xMode{val=edge}", 0.0), + ("c:legend/c:layout/c:manualLayout/c:xMode{val=factor}", 0.0), + ("c:legend/c:layout/c:manualLayout/(c:xMode,c:x{val=0.42})", 0.42), + ( + "c:legend/c:layout/c:manualLayout/(c:xMode{val=factor},c:x{val=0.42" "})", + 0.42, + ), + ] + ) + def horz_offset_get_fixture(self, request): + legend_cxml, expected_value = request.param + legend = Legend(element(legend_cxml)) + return legend, expected_value + + @pytest.fixture( + params=[ + ( + "c:legend", + 0.42, + "c:legend/c:layout/c:manualLayout/(c:xMode,c:x{val=0.42})", + ), + ( + "c:legend/c:layout", + 0.42, + "c:legend/c:layout/c:manualLayout/(c:xMode,c:x{val=0.42})", + ), + ( + "c:legend/c:layout/c:manualLayout", + -0.42, + "c:legend/c:layout/c:manualLayout/(c:xMode,c:x{val=-0.42})", + ), + ( + "c:legend/c:layout/c:manualLayout/c:xMode{val=edge}", + -0.1, + "c:legend/c:layout/c:manualLayout/(c:xMode,c:x{val=-0.1})", + ), + ( + "c:legend/c:layout/c:manualLayout/c:xMode{val=factor}", + 0.2, + "c:legend/c:layout/c:manualLayout/(c:xMode,c:x{val=0.2})", + ), + ("c:legend/c:layout/c:manualLayout", 0, "c:legend/c:layout"), + ] + ) + def horz_offset_set_fixture(self, request): + legend_cxml, new_value, expected_legend_cxml = request.param + legend = Legend(element(legend_cxml)) + expected_xml = xml(expected_legend_cxml) + return legend, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:legend", True), + ("c:legend/c:overlay", True), + ("c:legend/c:overlay{val=1}", True), + ("c:legend/c:overlay{val=0}", False), + ] + ) + def include_in_layout_get_fixture(self, request): + legend_cxml, expected_value = request.param + legend = Legend(element(legend_cxml)) + return legend, expected_value + + @pytest.fixture( + params=[ + ("c:legend", True, "c:legend/c:overlay{val=1}"), + ("c:legend", False, "c:legend/c:overlay{val=0}"), + ("c:legend/c:overlay{val=0}", True, "c:legend/c:overlay{val=1}"), + ("c:legend/c:overlay{val=1}", False, "c:legend/c:overlay{val=0}"), + ("c:legend/c:overlay{val=1}", None, "c:legend"), + ] + ) + def include_in_layout_set_fixture(self, request): + legend_cxml, new_value, expected_legend_cxml = request.param + legend = Legend(element(legend_cxml)) + expected_xml = xml(expected_legend_cxml) + return legend, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:legend", "RIGHT"), + ("c:legend/c:legendPos", "RIGHT"), + ("c:legend/c:legendPos{val=r}", "RIGHT"), + ("c:legend/c:legendPos{val=b}", "BOTTOM"), + ] + ) + def position_get_fixture(self, request): + legend_cxml, expected_enum_member = request.param + legend = Legend(element(legend_cxml)) + expected_value = getattr(XL_LEGEND_POSITION, expected_enum_member) + return legend, expected_value + + @pytest.fixture( + params=[ + ("c:legend/c:legendPos{val=r}", "BOTTOM", "c:legend/c:legendPos{val=b}"), + ("c:legend/c:legendPos{val=b}", "RIGHT", "c:legend/c:legendPos"), + ("c:legend", "TOP", "c:legend/c:legendPos{val=t}"), + ("c:legend/c:legendPos", "CORNER", "c:legend/c:legendPos{val=tr}"), + ] + ) + def position_set_fixture(self, request): + legend_cxml, new_enum_member, expected_legend_cxml = request.param + legend = Legend(element(legend_cxml)) + new_value = getattr(XL_LEGEND_POSITION, new_enum_member) + expected_xml = xml(expected_legend_cxml) + return legend, new_value, expected_xml diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_marker.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_marker.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a8f3c5d6925a2e0d9da49c34649e11d2486c03 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_marker.py @@ -0,0 +1,134 @@ +"""Unit-test suite for the `pptx.chart.marker` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.marker import Marker +from pptx.dml.chtfmt import ChartFormat +from pptx.enum.chart import XL_MARKER_STYLE + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, instance_mock + + +class DescribeMarker(object): + def it_knows_its_size(self, size_get_fixture): + marker, expected_value = size_get_fixture + assert marker.size == expected_value + + def it_can_change_its_size(self, size_set_fixture): + marker, value, expected_xml = size_set_fixture + marker.size = value + assert marker._element.xml == expected_xml + + def it_knows_its_style(self, style_get_fixture): + marker, expected_value = style_get_fixture + assert marker.style == expected_value + + def it_can_change_its_style(self, style_set_fixture): + marker, value, expected_xml = style_set_fixture + marker.style = value + assert marker._element.xml == expected_xml + + def it_provides_access_to_its_format(self, format_fixture): + marker, ChartFormat_, _element, chart_format_, expected_xml = format_fixture + chart_format = marker.format + ChartFormat_.assert_called_once_with(_element.xpath("c:marker")[0]) + assert chart_format is chart_format_ + assert marker._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:ser", "c:ser/c:marker"), + ("c:ser/c:marker", "c:ser/c:marker"), + ("c:dPt", "c:dPt/c:marker"), + ("c:dPt/c:marker", "c:dPt/c:marker"), + ] + ) + def format_fixture(self, request, ChartFormat_, chart_format_): + cxml, expected_cxml = request.param + _element = element(cxml) + marker = Marker(_element) + expected_xml = xml(expected_cxml) + return marker, ChartFormat_, _element, chart_format_, expected_xml + + @pytest.fixture( + params=[ + ("c:ser", None), + ("c:ser/c:marker", None), + ("c:ser/c:marker/c:size{val=24}", 24), + ("c:dPt", None), + ("c:dPt/c:marker", None), + ("c:dPt/c:marker/c:size{val=36}", 36), + ] + ) + def size_get_fixture(self, request): + cxml, expected_value = request.param + marker = Marker(element(cxml)) + return marker, expected_value + + @pytest.fixture( + params=[ + ("c:ser", 42, "c:ser/c:marker/c:size{val=42}"), + ("c:ser/c:marker", 42, "c:ser/c:marker/c:size{val=42}"), + ("c:ser/c:marker/c:size{val=42}", 24, "c:ser/c:marker/c:size{val=24}"), + ("c:ser/c:marker/c:size{val=24}", None, "c:ser/c:marker"), + ("c:ser", None, "c:ser/c:marker"), + ] + ) + def size_set_fixture(self, request): + cxml, value, expected_cxml = request.param + marker = Marker(element(cxml)) + expected_xml = xml(expected_cxml) + return marker, value, expected_xml + + @pytest.fixture( + params=[ + ("c:ser", None), + ("c:ser/c:marker", None), + ("c:ser/c:marker/c:symbol{val=circle}", XL_MARKER_STYLE.CIRCLE), + ("c:dPt", None), + ("c:dPt/c:marker", None), + ("c:dPt/c:marker/c:symbol{val=square}", XL_MARKER_STYLE.SQUARE), + ] + ) + def style_get_fixture(self, request): + cxml, expected_value = request.param + marker = Marker(element(cxml)) + return marker, expected_value + + @pytest.fixture( + params=[ + ("c:ser", XL_MARKER_STYLE.CIRCLE, "c:ser/c:marker/c:symbol{val=circle}"), + ( + "c:ser/c:marker", + XL_MARKER_STYLE.SQUARE, + "c:ser/c:marker/c:symbol{val=square}", + ), + ( + "c:ser/c:marker/c:symbol{val=square}", + XL_MARKER_STYLE.AUTOMATIC, + "c:ser/c:marker/c:symbol{val=auto}", + ), + ("c:ser/c:marker/c:symbol{val=auto}", None, "c:ser/c:marker"), + ("c:ser", None, "c:ser/c:marker"), + ] + ) + def style_set_fixture(self, request): + cxml, value, expected_cxml = request.param + marker = Marker(element(cxml)) + expected_xml = xml(expected_cxml) + return marker, value, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def ChartFormat_(self, request, chart_format_): + return class_mock(request, "pptx.chart.marker.ChartFormat", return_value=chart_format_) + + @pytest.fixture + def chart_format_(self, request): + return instance_mock(request, ChartFormat) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_plot.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..7e0f75e2daaf09508c3e106291e749ac71a0bde4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_plot.py @@ -0,0 +1,471 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.chart.plot` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.category import Categories +from pptx.chart.chart import Chart +from pptx.chart.plot import ( + Area3DPlot, + AreaPlot, + BarPlot, + BubblePlot, + DataLabels, + DoughnutPlot, + LinePlot, + PiePlot, + PlotFactory, + PlotTypeInspector, + RadarPlot, + XyPlot, + _BasePlot, +) +from pptx.chart.series import SeriesCollection +from pptx.enum.chart import XL_CHART_TYPE as XL + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, instance_mock + + +class Describe_BasePlot(object): + def it_knows_which_chart_it_belongs_to(self, chart_fixture): + plot, expected_value = chart_fixture + assert plot.chart == expected_value + + def it_knows_whether_it_has_data_labels(self, has_data_labels_get_fixture): + plot, expected_value = has_data_labels_get_fixture + assert plot.has_data_labels == expected_value + + def it_can_change_whether_it_has_data_labels(self, has_data_labels_set_fixture): + plot, new_value, expected_xml = has_data_labels_set_fixture + plot.has_data_labels = new_value + assert plot._element.xml == expected_xml + + def it_knows_whether_it_varies_color_by_category(self, vary_by_categories_get_fixture): + plot, expected_value = vary_by_categories_get_fixture + assert plot.vary_by_categories == expected_value + + def it_can_change_whether_it_varies_color_by_category(self, vary_by_categories_set_fixture): + plot, new_value, expected_xml = vary_by_categories_set_fixture + plot.vary_by_categories = new_value + assert plot._element.xml == expected_xml + + def it_provides_access_to_its_categories(self, categories_fixture): + plot, categories_, Categories_, xChart = categories_fixture + categories = plot.categories + Categories_.assert_called_once_with(xChart) + assert categories is categories_ + + def it_provides_access_to_the_data_labels(self, data_labels_fixture): + plot, data_labels_, DataLabels_, dLbls = data_labels_fixture + data_labels = plot.data_labels + DataLabels_.assert_called_once_with(dLbls) + assert data_labels is data_labels_ + + def it_provides_access_to_its_series(self, series_fixture): + plot, series_, SeriesCollection_, xChart = series_fixture + series = plot.series + SeriesCollection_.assert_called_once_with(xChart) + assert series is series_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def categories_fixture(self, categories_, Categories_): + xChart = element("c:barChart") + plot = _BasePlot(xChart, None) + return plot, categories_, Categories_, xChart + + @pytest.fixture + def chart_fixture(self, chart_): + plot = _BasePlot(None, chart_) + expected_value = chart_ + return plot, expected_value + + @pytest.fixture + def data_labels_fixture(self, DataLabels_, data_labels_): + barChart = element("c:barChart/c:dLbls") + dLbls = barChart[0] + plot = _BasePlot(barChart, None) + return plot, data_labels_, DataLabels_, dLbls + + @pytest.fixture( + params=[ + ("c:barChart", False), + ("c:barChart/c:dLbls", True), + ("c:lineChart", False), + ("c:lineChart/c:dLbls", True), + ("c:pieChart", False), + ("c:pieChart/c:dLbls", True), + ] + ) + def has_data_labels_get_fixture(self, request): + xChart_cxml, expected_value = request.param + plot = _BasePlot(element(xChart_cxml), None) + return plot, expected_value + + @pytest.fixture( + params=[ + ("c:barChart", True, "c:barChart/c:dLbls/+"), + ("c:barChart/c:dLbls", True, "c:barChart/c:dLbls"), + ("c:barChart", False, "c:barChart"), + ("c:barChart/c:dLbls", False, "c:barChart"), + ("c:bubbleChart", True, "c:bubbleChart/c:dLbls/+"), + ("c:bubbleChart/c:dLbls", False, "c:bubbleChart"), + ("c:lineChart", True, "c:lineChart/c:dLbls/+"), + ("c:lineChart/c:dLbls", False, "c:lineChart"), + ("c:pieChart", True, "c:pieChart/c:dLbls/+"), + ("c:pieChart/c:dLbls", False, "c:pieChart"), + ] + ) + def has_data_labels_set_fixture(self, request): + xChart_cxml, new_value, expected_cxml = request.param + # apply extended suffix to replace trailing '+' where present + if expected_cxml.endswith("+"): + expected_cxml = expected_cxml[:-1] + ( + "(c:showLegendKey{val=0},c:showVal{val=1},c:showCatName{val=" + "0},c:showSerName{val=0},c:showPercent{val=0},c:showBubbleSi" + "ze{val=0},c:showLeaderLines{val=1})" + ) + plot = PlotFactory(element(xChart_cxml), None) + expected_xml = xml(expected_cxml) + return plot, new_value, expected_xml + + @pytest.fixture + def series_fixture(self, SeriesCollection_, series_collection_): + xChart = element("c:barChart") + plot = _BasePlot(xChart, None) + return plot, series_collection_, SeriesCollection_, xChart + + @pytest.fixture( + params=[ + ("c:barChart", True), + ("c:lineChart/c:varyColors", True), + ("c:pieChart/c:varyColors{val=0}", False), + ] + ) + def vary_by_categories_get_fixture(self, request): + xChart_cxml, expected_value = request.param + plot = _BasePlot(element(xChart_cxml), None) + return plot, expected_value + + @pytest.fixture( + params=[ + ("c:barChart", False, "c:barChart/c:varyColors{val=0}"), + ("c:barChart", True, "c:barChart/c:varyColors"), + ("c:lineChart/c:varyColors{val=0}", True, "c:lineChart/c:varyColors"), + ("c:pieChart/c:varyColors{val=1}", False, "c:pieChart/c:varyColors{val=0}"), + ] + ) + def vary_by_categories_set_fixture(self, request): + xChart_cxml, new_value, expected_xChart_cxml = request.param + plot = _BasePlot(element(xChart_cxml), None) + expected_xml = xml(expected_xChart_cxml) + return plot, new_value, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def Categories_(self, request, categories_): + return class_mock(request, "pptx.chart.plot.Categories", return_value=categories_) + + @pytest.fixture + def categories_(self, request): + return instance_mock(request, Categories) + + @pytest.fixture + def chart_(self, request): + return instance_mock(request, Chart) + + @pytest.fixture + def DataLabels_(self, request, data_labels_): + return class_mock(request, "pptx.chart.plot.DataLabels", return_value=data_labels_) + + @pytest.fixture + def data_labels_(self, request): + return instance_mock(request, DataLabels) + + @pytest.fixture + def SeriesCollection_(self, request, series_collection_): + return class_mock( + request, "pptx.chart.plot.SeriesCollection", return_value=series_collection_ + ) + + @pytest.fixture + def series_collection_(self, request): + return instance_mock(request, SeriesCollection) + + +class DescribeBarPlot(object): + def it_knows_its_gap_width(self, gap_width_get_fixture): + bar_plot, expected_value = gap_width_get_fixture + assert bar_plot.gap_width == expected_value + + def it_can_change_its_gap_width(self, gap_width_set_fixture): + bar_plot, new_value, expected_xml = gap_width_set_fixture + bar_plot.gap_width = new_value + assert bar_plot._element.xml == expected_xml + + def it_knows_how_much_it_overlaps_the_adjacent_bar(self, overlap_get_fixture): + bar_plot, expected_value = overlap_get_fixture + assert bar_plot.overlap == expected_value + + def it_can_change_how_much_it_overlaps_the_adjacent_bar(self, overlap_set_fixture): + bar_plot, new_value, expected_xml = overlap_set_fixture + bar_plot.overlap = new_value + assert bar_plot._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:barChart", 150), + ("c:barChart/c:gapWidth", 150), + ("c:barChart/c:gapWidth{val=175}", 175), + ("c:barChart/c:gapWidth{val=042%}", 42), + ] + ) + def gap_width_get_fixture(self, request): + barChart_cxml, expected_value = request.param + bar_plot = BarPlot(element(barChart_cxml), None) + return bar_plot, expected_value + + @pytest.fixture( + params=[ + ("c:barChart", 42, "c:barChart/c:gapWidth{val=42}"), + ("c:barChart", 150, "c:barChart/c:gapWidth"), + ("c:barChart/c:gapWidth{val=200%}", 300, "c:barChart/c:gapWidth{val=300}"), + ] + ) + def gap_width_set_fixture(self, request): + barChart_cxml, new_value, expected_barChart_cxml = request.param + bar_plot = BarPlot(element(barChart_cxml), None) + expected_xml = xml(expected_barChart_cxml) + return bar_plot, new_value, expected_xml + + @pytest.fixture( + params=[ + ("c:barChart", 0), + ("c:barChart/c:overlap", 0), + ("c:barChart/c:overlap{val=42}", 42), + ("c:barChart/c:overlap{val=-42}", -42), + ("c:barChart/c:overlap{val=-042%}", -42), + ] + ) + def overlap_get_fixture(self, request): + barChart_cxml, expected_value = request.param + bar_plot = BarPlot(element(barChart_cxml), None) + return bar_plot, expected_value + + @pytest.fixture( + params=[ + ("c:barChart", 42, "c:barChart/c:overlap{val=42}"), + ("c:barChart/c:overlap{val=42}", 24, "c:barChart/c:overlap{val=24}"), + ("c:barChart/c:overlap{val=42}", -5, "c:barChart/c:overlap{val=-5}"), + ("c:barChart/c:overlap{val=42}", 0, "c:barChart"), + ] + ) + def overlap_set_fixture(self, request): + barChart_cxml, new_value, expected_barChart_cxml = request.param + bar_plot = BarPlot(element(barChart_cxml), None) + expected_xml = xml(expected_barChart_cxml) + return bar_plot, new_value, expected_xml + + +class DescribeBubblePlot(object): + def it_knows_its_bubble_scale(self, bubble_scale_get_fixture): + bubble_plot, expected_value = bubble_scale_get_fixture + assert bubble_plot.bubble_scale == expected_value + + def it_can_change_its_bubble_scale(self, bubble_scale_set_fixture): + bubble_plot, new_value, expected_xml = bubble_scale_set_fixture + bubble_plot.bubble_scale = new_value + assert bubble_plot._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:bubbleChart", 100), + ("c:bubbleChart/c:bubbleScale", 100), + ("c:bubbleChart/c:bubbleScale{val=175}", 175), + ("c:bubbleChart/c:bubbleScale{val=070%}", 70), + ] + ) + def bubble_scale_get_fixture(self, request): + bubbleChart_cxml, expected_value = request.param + bubble_plot = BubblePlot(element(bubbleChart_cxml), None) + return bubble_plot, expected_value + + @pytest.fixture( + params=[ + ("c:bubbleChart", 42, "c:bubbleChart/c:bubbleScale{val=42}"), + ( + "c:bubbleChart/c:bubbleScale{val=042%}", + 150, + "c:bubbleChart/c:bubbleScale{val=150}", + ), + ("c:bubbleChart/c:bubbleScale{val=150}", None, "c:bubbleChart"), + ( + "c:bubbleChart/c:bubbleScale{val=150}", + 100, + "c:bubbleChart/c:bubbleScale", + ), + ("c:bubbleChart", None, "c:bubbleChart"), + ("c:bubbleChart", 100, "c:bubbleChart/c:bubbleScale"), + ] + ) + def bubble_scale_set_fixture(self, request): + bubbleChart_cxml, new_value, expected_cxml = request.param + bubble_plot = BubblePlot(element(bubbleChart_cxml), None) + expected_xml = xml(expected_cxml) + return bubble_plot, new_value, expected_xml + + +class DescribePlotFactory(object): + def it_contructs_a_plot_object_from_a_plot_element(self, call_fixture): + xChart, chart_, PlotClass_, plot_ = call_fixture + plot = PlotFactory(xChart, chart_) + PlotClass_.assert_called_once_with(xChart, chart_) + assert plot is plot_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:areaChart", AreaPlot), + ("c:area3DChart", Area3DPlot), + ("c:barChart", BarPlot), + ("c:bubbleChart", BubblePlot), + ("c:doughnutChart", DoughnutPlot), + ("c:lineChart", LinePlot), + ("c:pieChart", PiePlot), + ("c:radarChart", RadarPlot), + ("c:scatterChart", XyPlot), + ] + ) + def call_fixture(self, request, chart_): + xChart_cxml, PlotCls = request.param + plot_ = instance_mock(request, PlotCls, name="plot_") + class_spec = "pptx.chart.plot.%s" % PlotCls.__name__ + PlotClass_ = class_mock(request, class_spec, return_value=plot_) + xChart = element(xChart_cxml) + return xChart, chart_, PlotClass_, plot_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def chart_(self, request): + return instance_mock(request, Chart) + + +class DescribePlotTypeInspector(object): + def it_can_determine_the_chart_type_of_a_plot(self, chart_type_fixture): + plot, expected_chart_type = chart_type_fixture + chart_type = PlotTypeInspector.chart_type(plot) + assert chart_type is expected_chart_type + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:areaChart", XL.AREA), + ("c:areaChart/c:grouping", XL.AREA), + ("c:areaChart/c:grouping{val=standard}", XL.AREA), + ("c:areaChart/c:grouping{val=stacked}", XL.AREA_STACKED), + ("c:areaChart/c:grouping{val=percentStacked}", XL.AREA_STACKED_100), + ("c:area3DChart", XL.THREE_D_AREA), + ("c:area3DChart/c:grouping", XL.THREE_D_AREA), + ("c:area3DChart/c:grouping{val=standard}", XL.THREE_D_AREA), + ("c:area3DChart/c:grouping{val=stacked}", XL.THREE_D_AREA_STACKED), + ( + "c:area3DChart/c:grouping{val=percentStacked}", + XL.THREE_D_AREA_STACKED_100, + ), + ("c:barChart/c:barDir", XL.COLUMN_CLUSTERED), + ("c:barChart/c:barDir{val=col}", XL.COLUMN_CLUSTERED), + ("c:barChart/(c:barDir{val=col},c:grouping)", XL.COLUMN_CLUSTERED), + ( + "c:barChart/(c:barDir{val=col},c:grouping{val=clustered})", + XL.COLUMN_CLUSTERED, + ), + ( + "c:barChart/(c:barDir{val=col},c:grouping{val=stacked})", + XL.COLUMN_STACKED, + ), + ( + "c:barChart/(c:barDir{val=col},c:grouping{val=percentStacked})", + XL.COLUMN_STACKED_100, + ), + ("c:barChart/c:barDir{val=bar}", XL.BAR_CLUSTERED), + ("c:barChart/(c:barDir{val=bar},c:grouping)", XL.BAR_CLUSTERED), + ( + "c:barChart/(c:barDir{val=bar},c:grouping{val=clustered})", + XL.BAR_CLUSTERED, + ), + ("c:barChart/(c:barDir{val=bar},c:grouping{val=stacked})", XL.BAR_STACKED), + ( + "c:barChart/(c:barDir{val=bar},c:grouping{val=percentStacked})", + XL.BAR_STACKED_100, + ), + ("c:doughnutChart", XL.DOUGHNUT), + ("c:doughnutChart/c:ser/c:explosion{val=25}", XL.DOUGHNUT_EXPLODED), + ("c:lineChart", XL.LINE_MARKERS), + ("c:lineChart/c:grouping", XL.LINE_MARKERS), + ("c:lineChart/c:grouping{val=standard}", XL.LINE_MARKERS), + ("c:lineChart/c:grouping{val=stacked}", XL.LINE_MARKERS_STACKED), + ("c:lineChart/c:grouping{val=percentStacked}", XL.LINE_MARKERS_STACKED_100), + ("c:lineChart/c:ser/c:marker/c:symbol{val=none}", XL.LINE), + ( + "c:lineChart/(c:grouping{val=stacked},c:ser/c:marker/c:symbol{val=n" "one})", + XL.LINE_STACKED, + ), + ( + "c:lineChart/(c:grouping{val=percentStacked},c:ser/c:marker/c:symbo" "l{val=none})", + XL.LINE_STACKED_100, + ), + ("c:pieChart", XL.PIE), + ("c:pieChart/c:ser/c:explosion{val=25}", XL.PIE_EXPLODED), + ("c:scatterChart/c:scatterStyle", XL.XY_SCATTER), + ( + "c:scatterChart/(c:scatterStyle{val=lineMarker},c:ser/c:spPr/a:ln/a" ":noFill)", + XL.XY_SCATTER, + ), + ("c:scatterChart/c:scatterStyle{val=lineMarker}", XL.XY_SCATTER_LINES), + ( + "c:scatterChart/(c:scatterStyle{val=lineMarker},c:ser/c:marker/c:sy" + "mbol{val=none})", + XL.XY_SCATTER_LINES_NO_MARKERS, + ), + ( + "c:scatterChart/(c:scatterStyle{val=lineMarker},c:ser/c:marker/c:sy" + "mbol{val=diamond})", + XL.XY_SCATTER_LINES, + ), + ("c:scatterChart/c:scatterStyle{val=smoothMarker}", XL.XY_SCATTER_SMOOTH), + ( + "c:scatterChart/(c:scatterStyle{val=smoothMarker},c:ser/c:marker/c:" + "symbol{val=none})", + XL.XY_SCATTER_SMOOTH_NO_MARKERS, + ), + ("c:bubbleChart", XL.BUBBLE), + ("c:bubbleChart/c:ser", XL.BUBBLE), + ("c:bubbleChart/c:ser/c:bubble3D", XL.BUBBLE_THREE_D_EFFECT), + ("c:bubbleChart/c:ser/c:bubble3D{val=0}", XL.BUBBLE), + ("c:bubbleChart/c:ser/c:bubble3D{val=1}", XL.BUBBLE_THREE_D_EFFECT), + ("c:radarChart/c:radarStyle", XL.RADAR), + ("c:radarChart/c:radarStyle{val=marker}", XL.RADAR_MARKERS), + ("c:radarChart/c:radarStyle{val=filled}", XL.RADAR_FILLED), + ( + "c:radarChart/(c:radarStyle{val=marker},c:ser/c:marker/c:symbol{val" "=none})", + XL.RADAR, + ), + ] + ) + def chart_type_fixture(self, request): + xChart_cxml, expected_chart_type = request.param + plot = PlotFactory(element(xChart_cxml), None) + return plot, expected_chart_type diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_point.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_point.py new file mode 100644 index 0000000000000000000000000000000000000000..8e00d96758f74861089da631f80b945622924a2e --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_point.py @@ -0,0 +1,221 @@ +"""Unit-test suite for the `pptx.chart.point` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.datalabel import DataLabel +from pptx.chart.marker import Marker +from pptx.chart.point import BubblePoints, CategoryPoints, Point, XyPoints +from pptx.dml.chtfmt import ChartFormat + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, instance_mock + + +class Describe_BasePoints(object): + def it_supports_indexed_access(self, getitem_fixture): + points, idx, Point_, ser, point_ = getitem_fixture + point = points[idx] + Point_.assert_called_once_with(ser, idx) + assert point is point_ + + def it_raises_on_indexed_access_out_of_range(self): + points = XyPoints( + element( + "c:ser/(c:xVal/c:numRef/c:numCache/c:ptCount{val=3},c:yVal/c:num" + "Ref/c:numCache/c:ptCount{val=3})" + ) + ) + with pytest.raises(IndexError): + points[-1] + with pytest.raises(IndexError): + points[3] + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def getitem_fixture(self, request, Point_, point_): + ser = element( + "c:ser/(c:xVal/c:numRef/c:numCache/c:ptCount{val=3},c:yVal/c:num" + "Ref/c:numCache/c:ptCount{val=3})" + ) + points = XyPoints(ser) + idx = 2 + return points, idx, Point_, ser, point_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def Point_(self, request, point_): + return class_mock(request, "pptx.chart.point.Point", return_value=point_) + + @pytest.fixture + def point_(self, request): + return instance_mock(request, Point) + + +class DescribeBubblePoints(object): + def it_supports_len(self, len_fixture): + points, expected_value = len_fixture + assert len(points) == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:ser", 0), + ("c:ser/c:bubbleSize/c:numRef/c:numCache/c:ptCount{val=3}", 0), + ( + "c:ser/(c:xVal/c:numRef/c:numCache/c:ptCount{val=1},c:yVal/c:numRef" + "/c:numCache/c:ptCount{val=2},c:bubbleSize/c:numRef/c:numCache/c:pt" + "Count{val=3})", + 1, + ), + ( + "c:ser/(c:xVal/c:numRef/c:numCache/c:ptCount{val=3},c:yVal/c:numRef" + "/c:numCache/c:ptCount{val=3},c:bubbleSize/c:numRef/c:numCache/c:pt" + "Count{val=3})", + 3, + ), + ] + ) + def len_fixture(self, request): + ser_cxml, expected_value = request.param + points = BubblePoints(element(ser_cxml)) + return points, expected_value + + +class DescribeCategoryPoints(object): + def it_supports_len(self, len_fixture): + points, expected_value = len_fixture + assert len(points) == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:ser", 0), + ("c:ser/c:cat/c:numRef/c:numCache/c:ptCount{val=42}", 42), + ("c:ser/c:cat/c:numRef/c:numCache/c:ptCount{val=24}", 24), + ] + ) + def len_fixture(self, request): + ser_cxml, expected_value = request.param + points = CategoryPoints(element(ser_cxml)) + return points, expected_value + + +class DescribePoint(object): + def it_provides_access_to_its_data_label(self, data_label_fixture): + point, DataLabel_, ser, idx, data_label_ = data_label_fixture + data_label = point.data_label + DataLabel_.assert_called_once_with(ser, idx) + assert data_label is data_label_ + + def it_provides_access_to_its_format(self, format_fixture): + point, ChartFormat_, ser, chart_format_, expected_xml = format_fixture + chart_format = point.format + ChartFormat_.assert_called_once_with(ser.xpath('c:dPt[c:idx/@val="42"]')[0]) + assert chart_format is chart_format_ + assert point._element.xml == expected_xml + + def it_provides_access_to_its_marker(self, marker_fixture): + point, Marker_, dPt, marker_ = marker_fixture + marker = point.marker + Marker_.assert_called_once_with(dPt) + assert marker is marker_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def data_label_fixture(self, DataLabel_, data_label_): + ser, idx = element("c:ser"), 42 + point = Point(ser, idx) + return point, DataLabel_, ser, idx, data_label_ + + @pytest.fixture( + params=[ + ("c:ser", "c:ser/c:dPt/c:idx{val=42}"), + ("c:ser/c:dPt/c:idx{val=42}", "c:ser/c:dPt/c:idx{val=42}"), + ( + "c:ser/c:dPt/c:idx{val=45}", + "c:ser/(c:dPt/c:idx{val=45},c:dPt/c:idx{val=42})", + ), + ] + ) + def format_fixture(self, request, ChartFormat_, chart_format_): + ser_cxml, expected_cxml = request.param + ser = element(ser_cxml) + point = Point(ser, 42) + expected_xml = xml(expected_cxml) + return point, ChartFormat_, ser, chart_format_, expected_xml + + @pytest.fixture + def marker_fixture(self, Marker_, marker_): + ser = element("c:ser/c:dPt/c:idx{val=42}") + point = Point(ser, 42) + dPt = ser[0] + return point, Marker_, dPt, marker_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def ChartFormat_(self, request, chart_format_): + return class_mock(request, "pptx.chart.point.ChartFormat", return_value=chart_format_) + + @pytest.fixture + def chart_format_(self, request): + return instance_mock(request, ChartFormat) + + @pytest.fixture + def DataLabel_(self, request, data_label_): + return class_mock(request, "pptx.chart.point.DataLabel", return_value=data_label_) + + @pytest.fixture + def data_label_(self, request): + return instance_mock(request, DataLabel) + + @pytest.fixture + def Marker_(self, request, marker_): + return class_mock(request, "pptx.chart.point.Marker", return_value=marker_) + + @pytest.fixture + def marker_(self, request): + return instance_mock(request, Marker) + + +class DescribeXyPoints(object): + def it_supports_len(self, len_fixture): + points, expected_value = len_fixture + assert len(points) == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:ser", 0), + ("c:ser/c:xVal", 0), + ("c:ser/c:xVal/c:numRef/c:numCache/c:ptCount{val=3}", 0), + ("c:ser/c:yVal/c:numRef/c:numCache/c:ptCount{val=3}", 0), + ( + "c:ser/(c:xVal/c:numRef/c:numCache/c:ptCount{val=1},c:yVal/c:numRef" + "/c:numCache/c:ptCount{val=3})", + 1, + ), + ( + "c:ser/(c:xVal/c:numRef/c:numCache/c:ptCount{val=3},c:yVal/c:numRef" + "/c:numCache/c:ptCount{val=1})", + 1, + ), + ( + "c:ser/(c:xVal/c:numRef/c:numCache/c:ptCount{val=3},c:yVal/c:numRef" + "/c:numCache/c:ptCount{val=3})", + 3, + ), + ] + ) + def len_fixture(self, request): + ser_cxml, expected_value = request.param + points = XyPoints(element(ser_cxml)) + return points, expected_value diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_series.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_series.py new file mode 100644 index 0000000000000000000000000000000000000000..9a60351e12b80f90cd0932dfbe470a9918f31ba4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_series.py @@ -0,0 +1,551 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.chart.series` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.datalabel import DataLabels +from pptx.chart.marker import Marker +from pptx.chart.point import BubblePoints, CategoryPoints, XyPoints +from pptx.chart.series import ( + AreaSeries, + BarSeries, + BubbleSeries, + LineSeries, + PieSeries, + RadarSeries, + SeriesCollection, + XySeries, + _BaseCategorySeries, + _BaseSeries, + _MarkerMixin, + _SeriesFactory, +) +from pptx.dml.chtfmt import ChartFormat + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, function_mock, instance_mock + + +class Describe_BaseSeries(object): + def it_knows_its_name(self, name_fixture): + series, expected_value = name_fixture + assert series.name == expected_value + + def it_knows_its_position_in_the_series_sequence(self, index_fixture): + series, expected_value = index_fixture + assert series.index == expected_value + + def it_provides_access_to_its_format(self, format_fixture): + series, ChartFormat_, ser, format_ = format_fixture + format = series.format + ChartFormat_.assert_called_once_with(ser) + assert format is format_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def format_fixture(self, ChartFormat_, chart_format_): + ser = element("c:ser") + series = _BaseSeries(ser) + return series, ChartFormat_, ser, chart_format_ + + @pytest.fixture + def index_fixture(self): + ser_cxml, expected_value = "c:ser/c:idx{val=42}", 42 + series = _BaseSeries(element(ser_cxml)) + return series, expected_value + + @pytest.fixture( + params=[ + ("c:ser", ""), + ('c:ser/c:tx/c:strRef/c:strCache/c:pt/c:v"foobar"', "foobar"), + ] + ) + def name_fixture(self, request): + ser_cxml, expected_value = request.param + series = _BaseSeries(element(ser_cxml)) + return series, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def ChartFormat_(self, request, chart_format_): + return class_mock(request, "pptx.chart.series.ChartFormat", return_value=chart_format_) + + @pytest.fixture + def chart_format_(self, request): + return instance_mock(request, ChartFormat) + + +class Describe_BaseCategorySeries(object): + def it_is_a_BaseSeries_subclass(self, subclass_fixture): + base_category_series = subclass_fixture + assert isinstance(base_category_series, _BaseSeries) + + def it_provides_access_to_its_data_labels(self, data_labels_fixture, DataLabels_, data_labels_): + ser, expected_dLbls_xml = data_labels_fixture + DataLabels_.return_value = data_labels_ + series = _BaseCategorySeries(ser) + + data_labels = series.data_labels + + dLbls = ser.xpath("c:dLbls")[0] + assert dLbls.xml == expected_dLbls_xml + DataLabels_.assert_called_once_with(dLbls) + assert data_labels is data_labels_ + + def it_provides_access_to_its_points(self, points_fixture): + series, CategoryPoints_, ser, points_ = points_fixture + points = series.points + CategoryPoints_.assert_called_once_with(ser) + assert points is points_ + + def it_knows_its_values(self, values_get_fixture): + series, expected_value = values_get_fixture + assert series.values == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ( + "c:ser", + "c:dLbls/(c:showLegendKey{val=0},c:showVal{val=0},c:showCatName{val" + "=0},c:showSerName{val=0},c:showPercent{val=0},c:showBubbleSize{val" + "=0},c:showLeaderLines{val=1})", + ), + ("c:ser/c:dLbls", "c:dLbls"), + ] + ) + def data_labels_fixture(self, request): + ser_cxml, expected_dLbls_cxml = request.param + ser = element(ser_cxml) + expected_dLbls_xml = xml(expected_dLbls_cxml) + return ser, expected_dLbls_xml + + @pytest.fixture + def points_fixture(self, CategoryPoints_, points_): + ser = element("c:ser") + series = _BaseCategorySeries(ser) + return series, CategoryPoints_, ser, points_ + + @pytest.fixture + def subclass_fixture(self): + return _BaseCategorySeries(None) + + @pytest.fixture( + params=[ + ("c:ser", ()), + ("c:ser/c:val/c:numRef", ()), + ("c:ser/c:val/c:numLit", ()), + ("c:ser/c:val/c:numRef/c:numCache", ()), + ("c:ser/c:val/c:numRef/c:numCache/c:ptCount{val=0}", ()), + ( + 'c:ser/c:val/c:numRef/c:numCache/(c:ptCount{val=1},c:pt{idx=0}/c:v"' '1.1")', + (1.1,), + ), + ( + 'c:ser/c:val/c:numRef/c:numCache/(c:ptCount{val=3},c:pt{idx=0}/c:v"' + '1.1",c:pt{idx=2}/c:v"3.3")', + (1.1, None, 3.3), + ), + ( + 'c:ser/c:val/c:numLit/(c:ptCount{val=3},c:pt{idx=0}/c:v"1.1",c:pt{i' + 'dx=2}/c:v"3.3")', + (1.1, None, 3.3), + ), + ( + 'c:ser/c:val/c:numRef/c:numCache/(c:ptCount{val=3},c:pt{idx=2}/c:v"' + '3.3",c:pt{idx=0}/c:v"1.1")', + (1.1, None, 3.3), + ), + ] + ) + def values_get_fixture(self, request): + ser_cxml, expected_value = request.param + series = _BaseCategorySeries(element(ser_cxml)) + return series, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def CategoryPoints_(self, request, points_): + return class_mock(request, "pptx.chart.series.CategoryPoints", return_value=points_) + + @pytest.fixture + def DataLabels_(self, request): + return class_mock(request, "pptx.chart.series.DataLabels") + + @pytest.fixture + def data_labels_(self, request): + return instance_mock(request, DataLabels) + + @pytest.fixture + def points_(self, request): + return instance_mock(request, CategoryPoints) + + +class Describe_MarkerMixin(object): + def it_provides_access_to_the_series_marker(self, marker_fixture): + series, Marker_, ser, marker_ = marker_fixture + marker = series.marker + Marker_.assert_called_once_with(ser) + assert marker is marker_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def marker_fixture(self, Marker_, marker_): + ser = element("c:ser") + series = LineSeries(ser) + return series, Marker_, ser, marker_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def Marker_(self, request, marker_): + return class_mock(request, "pptx.chart.series.Marker", return_value=marker_) + + @pytest.fixture + def marker_(self, request): + return instance_mock(request, Marker) + + +class DescribeAreaSeries(object): + def it_is_a_BaseCategorySeries_subclass(self, subclass_fixture): + area_series = subclass_fixture + assert isinstance(area_series, _BaseCategorySeries) + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def subclass_fixture(self): + return AreaSeries(None) + + +class DescribeBarSeries(object): + def it_is_a_BaseCategorySeries_subclass(self, subclass_fixture): + bar_series = subclass_fixture + assert isinstance(bar_series, _BaseCategorySeries) + + def it_knows_whether_it_should_invert_if_negative(self, invert_if_negative_get_fixture): + bar_series, expected_value = invert_if_negative_get_fixture + assert bar_series.invert_if_negative == expected_value + + def it_can_change_whether_it_inverts_if_negative(self, invert_if_negative_set_fixture): + bar_series, new_value, expected_xml = invert_if_negative_set_fixture + bar_series.invert_if_negative = new_value + assert bar_series._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:ser", True), + ("c:ser/c:invertIfNegative", True), + ("c:ser/c:invertIfNegative{val=1}", True), + ("c:ser/c:invertIfNegative{val=0}", False), + ] + ) + def invert_if_negative_get_fixture(self, request): + ser_cxml, expected_value = request.param + bar_series = BarSeries(element(ser_cxml)) + return bar_series, expected_value + + @pytest.fixture( + params=[ + ("c:ser/c:order", True, "c:ser/(c:order,c:invertIfNegative{val=1})"), + ("c:ser/c:order", False, "c:ser/(c:order,c:invertIfNegative{val=0})"), + ( + "c:ser/(c:spPr,c:invertIfNegative{val=0})", + True, + "c:ser/(c:spPr,c:invertIfNegative{val=1})", + ), + ( + "c:ser/(c:tx,c:invertIfNegative{val=1})", + False, + "c:ser/(c:tx,c:invertIfNegative{val=0})", + ), + ] + ) + def invert_if_negative_set_fixture(self, request): + ser_cxml, new_value, expected_ser_cxml = request.param + bar_series = BarSeries(element(ser_cxml)) + expected_xml = xml(expected_ser_cxml) + return bar_series, new_value, expected_xml + + @pytest.fixture + def subclass_fixture(self): + return BarSeries(None) + + +class Describe_BubbleSeries(object): + def it_provides_access_to_its_points(self, points_fixture): + series, BubblePoints_, ser, points_ = points_fixture + points = series.points + BubblePoints_.assert_called_once_with(ser) + assert points is points_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def points_fixture(self, BubblePoints_, points_): + ser = element("c:ser") + series = BubbleSeries(ser) + return series, BubblePoints_, ser, points_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def BubblePoints_(self, request, points_): + return class_mock(request, "pptx.chart.series.BubblePoints", return_value=points_) + + @pytest.fixture + def points_(self, request): + return instance_mock(request, BubblePoints) + + +class DescribeLineSeries(object): + def it_is_a_BaseCategorySeries_subclass(self, subclass_fixture): + line_series = subclass_fixture + assert isinstance(line_series, _BaseCategorySeries) + + def it_uses__MarkerMixin(self, subclass_fixture): + line_series = subclass_fixture + assert isinstance(line_series, _MarkerMixin) + + def it_knows_whether_it_should_use_curve_smoothing(self, smooth_get_fixture): + series, expected_value = smooth_get_fixture + assert series.smooth == expected_value + + def it_can_change_whether_it_uses_curve_smoothing(self, smooth_set_fixture): + series, new_value, expected_xml = smooth_set_fixture + series.smooth = new_value + assert series._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:ser", True), + ("c:ser/c:smooth", True), + ("c:ser/c:smooth{val=1}", True), + ("c:ser/c:smooth{val=0}", False), + ] + ) + def smooth_get_fixture(self, request): + ser_cxml, expected_value = request.param + series = LineSeries(element(ser_cxml)) + return series, expected_value + + @pytest.fixture( + params=[ + ("c:ser", True, "c:ser/c:smooth"), + ("c:ser/c:smooth", False, "c:ser/c:smooth{val=0}"), + ("c:ser/c:smooth{val=0}", True, "c:ser/c:smooth"), + ] + ) + def smooth_set_fixture(self, request): + ser_cxml, new_value, expected_ser_cxml = request.param + series = LineSeries(element(ser_cxml)) + expected_xml = xml(expected_ser_cxml) + return series, new_value, expected_xml + + @pytest.fixture + def subclass_fixture(self): + return LineSeries(None) + + +class DescribePieSeries(object): + def it_is_a_BaseCategorySeries_subclass(self, subclass_fixture): + pie_series = subclass_fixture + assert isinstance(pie_series, _BaseCategorySeries) + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def subclass_fixture(self): + return PieSeries(None) + + +class DescribeRadarSeries(object): + def it_is_a_BaseCategorySeries_subclass(self, subclass_fixture): + radar_series = subclass_fixture + assert isinstance(radar_series, _BaseCategorySeries) + + def it_uses__MarkerMixin(self, subclass_fixture): + line_series = subclass_fixture + assert isinstance(line_series, _MarkerMixin) + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def subclass_fixture(self): + return RadarSeries(None) + + +class Describe_XySeries(object): + def it_uses__MarkerMixin(self, subclass_fixture): + line_series = subclass_fixture + assert isinstance(line_series, _MarkerMixin) + + def it_provides_access_to_its_points(self, points_fixture): + series, XyPoints_, ser, points_ = points_fixture + points = series.points + XyPoints_.assert_called_once_with(ser) + assert points is points_ + + def it_knows_its_values(self, values_get_fixture): + series, expected_values = values_get_fixture + assert series.values == expected_values + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def points_fixture(self, XyPoints_, points_): + ser = element("c:ser") + series = XySeries(ser) + return series, XyPoints_, ser, points_ + + @pytest.fixture + def subclass_fixture(self): + return XySeries(None) + + @pytest.fixture( + params=[ + ("c:ser", ()), + ("c:ser/c:yVal/c:numRef", ()), + ("c:ser/c:val/c:numRef/c:numCache", ()), + ( + "c:ser/c:yVal/c:numRef/c:numCache/(c:ptCount{val=1},c:pt{idx=0}/c:v" '"1.1")', + (1.1,), + ), + ( + "c:ser/c:yVal/c:numRef/c:numCache/(c:ptCount{val=3},c:pt{idx=0}/c:v" + '"1.1",c:pt{idx=2}/c:v"3.3")', + (1.1, None, 3.3), + ), + ("c:ser/c:val/c:numLit", ()), + ( + 'c:ser/c:yVal/c:numLit/(c:ptCount{val=3},c:pt{idx=0}/c:v"1.1",c:pt{' + 'idx=2}/c:v"3.3")', + (1.1, None, 3.3), + ), + ] + ) + def values_get_fixture(self, request): + ser_cxml, expected_values = request.param + series = XySeries(element(ser_cxml)) + return series, expected_values + + # fixture components --------------------------------------------- + + @pytest.fixture + def XyPoints_(self, request, points_): + return class_mock(request, "pptx.chart.series.XyPoints", return_value=points_) + + @pytest.fixture + def points_(self, request): + return instance_mock(request, XyPoints) + + +class DescribeSeriesCollection(object): + def it_supports_indexed_access(self, getitem_fixture): + series_collection, index, _SeriesFactory_, ser, series_ = getitem_fixture + series = series_collection[index] + _SeriesFactory_.assert_called_once_with(ser) + assert series is series_ + + def it_supports_len(self, len_fixture): + series_collection, expected_len = len_fixture + assert len(series_collection) == expected_len + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:barChart/c:ser/c:order{val=42}", 0, 0), + ( + "c:barChart/(c:ser/c:order{val=9},c:ser/c:order{val=6},c:ser/c:orde" "r{val=3})", + 2, + 0, + ), + ( + "c:plotArea/(c:barChart/(c:ser/(c:idx{val=1},c:order{val=3}),c:ser/" + "(c:idx{val=0},c:order{val=0})),c:lineChart/c:ser/(c:idx{val=2},c:o" + "rder{val=1}))", + 1, + 0, + ), + ] + ) + def getitem_fixture(self, request, _SeriesFactory_, series_): + cxml, index, _offset = request.param + parent_elm = element(cxml) + ser = parent_elm.xpath(".//c:ser")[_offset] + series_collection = SeriesCollection(parent_elm) + return series_collection, index, _SeriesFactory_, ser, series_ + + @pytest.fixture( + params=[ + ("c:barChart", 0), + ("c:barChart/c:ser/c:order{val=4}", 1), + ( + "c:barChart/(c:ser/c:order{val=4},c:ser/c:order{val=1},c:ser/c:orde" "r{val=6})", + 3, + ), + ("c:plotArea/c:barChart", 0), + ("c:plotArea/c:barChart/c:ser/c:order{val=4}", 1), + ( + "c:plotArea/c:barChart/(c:ser/c:order{val=4},c:ser/c:order{val=1},c" + ":ser/c:order{val=6})", + 3, + ), + ] + ) + def len_fixture(self, request): + cxml, expected_len = request.param + series_collection = SeriesCollection(element(cxml)) + return series_collection, expected_len + + # fixture components --------------------------------------------- + + @pytest.fixture + def _SeriesFactory_(self, request, series_): + return function_mock(request, "pptx.chart.series._SeriesFactory", return_value=series_) + + @pytest.fixture + def series_(self, request): + return instance_mock(request, _BaseSeries) + + +class Describe_SeriesFactory(object): + def it_contructs_a_series_object_from_a_plot_element(self, call_fixture): + ser, SeriesCls_, series_ = call_fixture + series = _SeriesFactory(ser) + SeriesCls_.assert_called_once_with(ser) + assert series is series_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:areaChart/c:ser", "AreaSeries"), + ("c:barChart/c:ser", "BarSeries"), + ("c:bubbleChart/c:ser", "BubbleSeries"), + ("c:doughnutChart/c:ser", "PieSeries"), + ("c:lineChart/c:ser", "LineSeries"), + ("c:pieChart/c:ser", "PieSeries"), + ("c:radarChart/c:ser", "RadarSeries"), + ("c:scatterChart/c:ser", "XySeries"), + ] + ) + def call_fixture(self, request): + xChart_cxml, cls_name = request.param + ser = element(xChart_cxml).ser_lst[0] + SeriesCls_ = class_mock(request, "pptx.chart.series.%s" % cls_name) + series_ = SeriesCls_.return_value + return ser, SeriesCls_, series_ diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_xlsx.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_xlsx.py new file mode 100644 index 0000000000000000000000000000000000000000..dde9d4d534a343ad616d8d47248c7e3d8f33a93a --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_xlsx.py @@ -0,0 +1,425 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.chart.xlsx` module.""" + +from __future__ import annotations + +import io + +import pytest +from xlsxwriter import Workbook +from xlsxwriter.worksheet import Worksheet + +from pptx.chart.data import ( + BubbleChartData, + Categories, + CategoryChartData, + CategorySeriesData, + XyChartData, +) +from pptx.chart.xlsx import ( + BubbleWorkbookWriter, + CategoryWorkbookWriter, + XyWorkbookWriter, + _BaseWorkbookWriter, +) + +from ..unitutil.mock import ANY, call, class_mock, instance_mock, method_mock + + +class Describe_BaseWorkbookWriter(object): + """Unit-test suite for `pptx.chart.xlsx._BaseWorkbookWriter` objects.""" + + def it_can_generate_a_chart_data_Excel_blob( + self, request, xlsx_file_, workbook_, worksheet_, BytesIO_ + ): + _populate_worksheet_ = method_mock(request, _BaseWorkbookWriter, "_populate_worksheet") + _open_worksheet_ = method_mock(request, _BaseWorkbookWriter, "_open_worksheet") + # --- to make context manager behavior work --- + _open_worksheet_.return_value.__enter__.return_value = (workbook_, worksheet_) + BytesIO_.return_value = xlsx_file_ + xlsx_file_.getvalue.return_value = b"xlsx-blob" + workbook_writer = _BaseWorkbookWriter(None) + + xlsx_blob = workbook_writer.xlsx_blob + + _open_worksheet_.assert_called_once_with(workbook_writer, xlsx_file_) + _populate_worksheet_.assert_called_once_with(workbook_writer, workbook_, worksheet_) + assert xlsx_blob == b"xlsx-blob" + + def it_can_open_a_worksheet_in_a_context(self, open_fixture): + wb_writer, xlsx_file_, workbook_, worksheet_, Workbook_ = open_fixture + + with wb_writer._open_worksheet(xlsx_file_) as (workbook, worksheet): + Workbook_.assert_called_once_with(xlsx_file_, {"in_memory": True}) + workbook_.add_worksheet.assert_called_once_with() + assert workbook is workbook_ + assert worksheet is worksheet_ + workbook_.close.assert_called_once_with() + + def it_raises_on_no_override_of_populate(self, populate_fixture): + workbook_writer = populate_fixture + with pytest.raises(NotImplementedError): + workbook_writer._populate_worksheet(None, None) + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def open_fixture(self, xlsx_file_, workbook_, worksheet_, Workbook_): + workbook_writer = _BaseWorkbookWriter(None) + workbook_.add_worksheet.return_value = worksheet_ + return workbook_writer, xlsx_file_, workbook_, worksheet_, Workbook_ + + @pytest.fixture + def populate_fixture(self): + workbook_writer = _BaseWorkbookWriter(None) + return workbook_writer + + # fixture components --------------------------------------------- + + @pytest.fixture + def BytesIO_(self, request): + return class_mock(request, "pptx.chart.xlsx.io.BytesIO") + + @pytest.fixture + def Workbook_(self, request, workbook_): + return class_mock(request, "pptx.chart.xlsx.Workbook", return_value=workbook_) + + @pytest.fixture + def workbook_(self, request): + return instance_mock(request, Workbook) + + @pytest.fixture + def worksheet_(self, request): + return instance_mock(request, Worksheet) + + @pytest.fixture + def xlsx_file_(self, request): + return instance_mock(request, io.BytesIO) + + +class DescribeCategoryWorkbookWriter(object): + """Unit-test suite for `pptx.chart.xlsx.CategoryWorkbookWriter` objects.""" + + def it_knows_the_categories_range_ref(self, categories_ref_fixture): + workbook_writer, expected_value = categories_ref_fixture + assert workbook_writer.categories_ref == expected_value + + def it_raises_on_cat_ref_on_no_categories(self, cat_ref_raises_fixture): + workbook_writer = cat_ref_raises_fixture + with pytest.raises(ValueError): + workbook_writer.categories_ref + + def it_knows_the_ref_for_a_series_name(self, ser_name_ref_fixture): + workbook_writer, series_, expected_value = ser_name_ref_fixture + assert workbook_writer.series_name_ref(series_) == expected_value + + def it_knows_the_values_range_ref(self, values_ref_fixture): + workbook_writer, series_, expected_value = values_ref_fixture + assert workbook_writer.values_ref(series_) == expected_value + + def it_can_populate_a_worksheet_with_chart_data(self, populate_fixture): + workbook_writer, workbook_, worksheet_ = populate_fixture + workbook_writer._populate_worksheet(workbook_, worksheet_) + workbook_writer._write_categories.assert_called_once_with( + workbook_writer, workbook_, worksheet_ + ) + workbook_writer._write_series.assert_called_once_with( + workbook_writer, workbook_, worksheet_ + ) + + def it_calculates_a_column_reference_to_help(self, col_ref_fixture): + col_num, expected_value = col_ref_fixture + column_reference = CategoryWorkbookWriter._column_reference(col_num) + assert column_reference == expected_value + + def it_raises_on_col_number_out_of_range(self, raises_fixture): + col_num = raises_fixture + with pytest.raises(ValueError): + CategoryWorkbookWriter._column_reference(col_num) + + def it_writes_categories_to_help(self, write_cats_fixture): + workbook_writer, workbook_, worksheet_ = write_cats_fixture[:3] + number_format, calls = write_cats_fixture[3:] + + workbook_writer._write_categories(workbook_, worksheet_) + + workbook_.add_format.assert_called_once_with({"num_format": number_format}) + assert workbook_writer._write_cat_column.call_args_list == calls + + def it_writes_a_category_column_to_help(self, write_cat_fixture): + workbook_writer, worksheet_, col = write_cat_fixture[:3] + level, num_format_, calls = write_cat_fixture[3:] + workbook_writer._write_cat_column(worksheet_, col, level, num_format_) + assert worksheet_.mock_calls == calls + + def it_writes_series_to_help(self, write_sers_fixture): + workbook_writer, workbook_, worksheet_, calls = write_sers_fixture + workbook_writer._write_series(workbook_, worksheet_) + assert worksheet_.mock_calls == calls + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + (1, 1, "Sheet1!$A$2:$A$2"), + (1, 3, "Sheet1!$A$2:$A$4"), + (2, 4, "Sheet1!$A$2:$B$5"), + (3, 8, "Sheet1!$A$2:$C$9"), + ] + ) + def categories_ref_fixture(self, request, chart_data_, categories_): + depth, leaf_count, expected_value = request.param + workbook_writer = CategoryWorkbookWriter(chart_data_) + chart_data_.categories = categories_ + categories_.depth, categories_.leaf_count = depth, leaf_count + return workbook_writer, expected_value + + @pytest.fixture + def cat_ref_raises_fixture(self, request, chart_data_, categories_): + workbook_writer = CategoryWorkbookWriter(chart_data_) + chart_data_.categories = categories_ + categories_.depth = 0 + return workbook_writer + + @pytest.fixture( + params=[ + (2, "B"), + (26, "Z"), + (27, "AA"), + (52, "AZ"), + (53, "BA"), + (676, "YZ"), + (677, "ZA"), + (702, "ZZ"), + (703, "AAA"), + (728, "AAZ"), + (729, "ABA"), + (1378, "AZZ"), + (1379, "BAA"), + (16384, "XFD"), + ] + ) + def col_ref_fixture(self, request): + column_number, expected_value = request.param + return column_number, expected_value + + @pytest.fixture + def populate_fixture(self, workbook_, worksheet_, _write_categories_, _write_series_): + workbook_writer = CategoryWorkbookWriter(None) + return workbook_writer, workbook_, worksheet_ + + @pytest.fixture(params=[0, -1, 16385, 30433]) + def raises_fixture(self, request): + column_number = request.param + return column_number + + @pytest.fixture( + params=[ + (1, 0, "Sheet1!$B$1"), + (1, 3, "Sheet1!$E$1"), + (3, 0, "Sheet1!$D$1"), + (3, 3, "Sheet1!$G$1"), + ] + ) + def ser_name_ref_fixture(self, request, series_data_, categories_): + cat_depth, series_index, expected_value = request.param + workbook_writer = CategoryWorkbookWriter(None) + series_data_.categories = categories_ + categories_.depth = cat_depth + series_data_.index = series_index + return workbook_writer, series_data_, expected_value + + @pytest.fixture( + params=[ + (1, 0, 3, "Sheet1!$B$2:$B$4"), + (1, 1, 3, "Sheet1!$C$2:$C$4"), + (2, 0, 5, "Sheet1!$C$2:$C$6"), + (3, 2, 7, "Sheet1!$F$2:$F$8"), + ] + ) + def values_ref_fixture(self, request, series_data_, categories_): + cat_depth, ser_idx, val_count, expected_value = request.param + workbook_writer = CategoryWorkbookWriter(None) + series_data_.categories = categories_ + categories_.depth = cat_depth + series_data_.index = ser_idx + series_data_.__len__.return_value = val_count + return workbook_writer, series_data_, expected_value + + @pytest.fixture + def write_cat_fixture(self, worksheet_): + workbook_writer = CategoryWorkbookWriter(None) + col, level = 6, ([0, "Foo"], [1, "Bar"]) + num_format = object() + calls = [ + call.set_column(col, col, 10), + call.write(1, col, "Foo", num_format), + call.write(2, col, "Bar", num_format), + ] + return workbook_writer, worksheet_, col, level, num_format, calls + + @pytest.fixture( + params=[ + [[[0, "Foo"], [1, "Bar"], [2, "Baz"]]], + [[[0, "CA"], [1, "NV"], [2, "NY"], [3, "NJ"]], [[0, "WEST"], [2, "EAST"]]], + ] + ) + def write_cats_fixture( + self, + request, + chart_data_, + workbook_, + worksheet_, + categories_, + _write_cat_column_, + ): + levels = request.param + workbook_writer = CategoryWorkbookWriter(chart_data_) + number_format = categories_.number_format = "$#0.#" + num_format = workbook_.add_format.return_value + _depth = len(levels) + calls = [ + call(workbook_writer, worksheet_, _depth - idx - 1, level, num_format) + for (idx, level) in enumerate(levels) + ] + chart_data_.categories = categories_ + categories_.depth = len(levels) + categories_.levels = levels + return workbook_writer, workbook_, worksheet_, number_format, calls + + @pytest.fixture + def write_sers_fixture(self, request, chart_data_, workbook_, worksheet_, categories_): + workbook_writer = CategoryWorkbookWriter(chart_data_) + num_format = workbook_.add_format.return_value + calls = [call.write(0, 1, "S1"), call.write_column(1, 1, (42, 24), num_format)] + ser = instance_mock(request, CategorySeriesData, values=(42, 24)) + ser.name = "S1" + chart_data_.categories = categories_ + categories_.depth = 1 + chart_data_.__iter__.return_value = iter([ser]) + return workbook_writer, workbook_, worksheet_, calls + + # fixture components --------------------------------------------- + + @pytest.fixture + def categories_(self, request): + return instance_mock(request, Categories) + + @pytest.fixture + def chart_data_(self, request): + return instance_mock(request, CategoryChartData) + + @pytest.fixture + def series_data_(self, request): + return instance_mock(request, CategorySeriesData) + + @pytest.fixture + def workbook_(self, request): + return instance_mock(request, Workbook) + + @pytest.fixture + def worksheet_(self, request): + return instance_mock(request, Worksheet) + + @pytest.fixture + def _write_cat_column_(self, request): + return method_mock(request, CategoryWorkbookWriter, "_write_cat_column", autospec=True) + + @pytest.fixture + def _write_categories_(self, request): + return method_mock(request, CategoryWorkbookWriter, "_write_categories", autospec=True) + + @pytest.fixture + def _write_series_(self, request): + return method_mock(request, CategoryWorkbookWriter, "_write_series", autospec=True) + + +class DescribeBubbleWorkbookWriter(object): + """Unit-test suite for `pptx.chart.xlsx.BubbleWorkbookWriter` objects.""" + + def it_can_populate_a_worksheet_with_chart_data(self, populate_fixture): + workbook_writer, workbook_, worksheet_, expected_calls = populate_fixture + workbook_writer._populate_worksheet(workbook_, worksheet_) + assert worksheet_.mock_calls == expected_calls + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def populate_fixture(self, workbook_, worksheet_): + chart_data = BubbleChartData() + series_1 = chart_data.add_series("Series 1") + for pt in ((1, 1.1, 10), (2, 2.2, 20)): + series_1.add_data_point(*pt) + series_2 = chart_data.add_series("Series 2") + for pt in ((3, 3.3, 30), (4, 4.4, 40)): + series_2.add_data_point(*pt) + + workbook_writer = BubbleWorkbookWriter(chart_data) + + expected_calls = [ + call.write_column(1, 0, [1, 2], ANY), + call.write(0, 1, "Series 1"), + call.write_column(1, 1, [1.1, 2.2], ANY), + call.write(0, 2, "Size"), + call.write_column(1, 2, [10, 20], ANY), + call.write_column(5, 0, [3, 4], ANY), + call.write(4, 1, "Series 2"), + call.write_column(5, 1, [3.3, 4.4], ANY), + call.write(4, 2, "Size"), + call.write_column(5, 2, [30, 40], ANY), + ] + return workbook_writer, workbook_, worksheet_, expected_calls + + # fixture components --------------------------------------------- + + @pytest.fixture + def workbook_(self, request): + return instance_mock(request, Workbook) + + @pytest.fixture + def worksheet_(self, request): + return instance_mock(request, Worksheet) + + +class DescribeXyWorkbookWriter(object): + """Unit-test suite for `pptx.chart.xlsx.XyWorkbookWriter` objects.""" + + def it_can_populate_a_worksheet_with_chart_data(self, populate_fixture): + workbook_writer, workbook_, worksheet_, expected_calls = populate_fixture + workbook_writer._populate_worksheet(workbook_, worksheet_) + assert worksheet_.mock_calls == expected_calls + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def populate_fixture(self, workbook_, worksheet_): + chart_data = XyChartData() + series_1 = chart_data.add_series("Series 1") + for pt in ((1, 1.1), (2, 2.2)): + series_1.add_data_point(*pt) + series_2 = chart_data.add_series("Series 2") + for pt in ((3, 3.3), (4, 4.4)): + series_2.add_data_point(*pt) + + workbook_writer = XyWorkbookWriter(chart_data) + + expected_calls = [ + call.write_column(1, 0, [1, 2], ANY), + call.write(0, 1, "Series 1"), + call.write_column(1, 1, [1.1, 2.2], ANY), + call.write_column(5, 0, [3, 4], ANY), + call.write(4, 1, "Series 2"), + call.write_column(5, 1, [3.3, 4.4], ANY), + ] + return workbook_writer, workbook_, worksheet_, expected_calls + + # fixture components --------------------------------------------- + + @pytest.fixture + def workbook_(self, request): + return instance_mock(request, Workbook) + + @pytest.fixture + def worksheet_(self, request): + return instance_mock(request, Worksheet) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_xmlwriter.py b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_xmlwriter.py new file mode 100644 index 0000000000000000000000000000000000000000..bb7354983ec1a4c150463c366cd155b9d5453ba2 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/chart/test_xmlwriter.py @@ -0,0 +1,726 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.chart.xmlwriter` module.""" + +from __future__ import annotations + +from datetime import date +from itertools import islice + +import pytest + +from pptx.chart.data import ( + BubbleChartData, + CategoryChartData, + CategorySeriesData, + XyChartData, + _BaseChartData, + _BaseSeriesData, +) +from pptx.chart.xmlwriter import ( + ChartXmlWriter, + SeriesXmlRewriterFactory, + _AreaChartXmlWriter, + _BarChartXmlWriter, + _BaseSeriesXmlRewriter, + _BubbleChartXmlWriter, + _BubbleSeriesXmlRewriter, + _BubbleSeriesXmlWriter, + _CategorySeriesXmlRewriter, + _CategorySeriesXmlWriter, + _DoughnutChartXmlWriter, + _LineChartXmlWriter, + _PieChartXmlWriter, + _RadarChartXmlWriter, + _XyChartXmlWriter, + _XySeriesXmlRewriter, + _XySeriesXmlWriter, +) +from pptx.enum.chart import XL_CHART_TYPE +from pptx.oxml import parse_xml + +from ..unitutil import count +from ..unitutil.cxml import element, xml +from ..unitutil.file import snippet_seq, snippet_text +from ..unitutil.mock import call, class_mock, instance_mock, method_mock + + +class DescribeChartXmlWriter(object): + def it_contructs_an_xml_writer_for_a_chart_type(self, call_fixture): + chart_type, series_seq_, XmlWriterClass_, xml_writer_ = call_fixture + xml_writer = ChartXmlWriter(chart_type, series_seq_) + XmlWriterClass_.assert_called_once_with(chart_type, series_seq_) + assert xml_writer is xml_writer_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("AREA", _AreaChartXmlWriter), + ("AREA_STACKED", _AreaChartXmlWriter), + ("AREA_STACKED_100", _AreaChartXmlWriter), + ("BAR_CLUSTERED", _BarChartXmlWriter), + ("BAR_STACKED", _BarChartXmlWriter), + ("BAR_STACKED_100", _BarChartXmlWriter), + ("BUBBLE", _BubbleChartXmlWriter), + ("BUBBLE_THREE_D_EFFECT", _BubbleChartXmlWriter), + ("COLUMN_CLUSTERED", _BarChartXmlWriter), + ("COLUMN_STACKED", _BarChartXmlWriter), + ("COLUMN_STACKED_100", _BarChartXmlWriter), + ("DOUGHNUT", _DoughnutChartXmlWriter), + ("DOUGHNUT_EXPLODED", _DoughnutChartXmlWriter), + ("LINE", _LineChartXmlWriter), + ("LINE_MARKERS", _LineChartXmlWriter), + ("LINE_MARKERS_STACKED", _LineChartXmlWriter), + ("LINE_MARKERS_STACKED_100", _LineChartXmlWriter), + ("LINE_STACKED", _LineChartXmlWriter), + ("LINE_STACKED_100", _LineChartXmlWriter), + ("PIE", _PieChartXmlWriter), + ("PIE_EXPLODED", _PieChartXmlWriter), + ("RADAR", _RadarChartXmlWriter), + ("RADAR_FILLED", _RadarChartXmlWriter), + ("RADAR_MARKERS", _RadarChartXmlWriter), + ("XY_SCATTER", _XyChartXmlWriter), + ("XY_SCATTER_LINES", _XyChartXmlWriter), + ("XY_SCATTER_LINES_NO_MARKERS", _XyChartXmlWriter), + ("XY_SCATTER_SMOOTH", _XyChartXmlWriter), + ("XY_SCATTER_SMOOTH_NO_MARKERS", _XyChartXmlWriter), + ] + ) + def call_fixture(self, request, series_seq_): + chart_type_member, XmlWriterClass = request.param + xml_writer_ = instance_mock(request, XmlWriterClass) + class_spec = "pptx.chart.xmlwriter.%s" % XmlWriterClass.__name__ + XmlWriterClass_ = class_mock(request, class_spec, return_value=xml_writer_) + chart_type = getattr(XL_CHART_TYPE, chart_type_member) + return chart_type, series_seq_, XmlWriterClass_, xml_writer_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def series_seq_(self, request): + return instance_mock(request, tuple) + + +class DescribeSeriesXmlRewriterFactory(object): + def it_contructs_an_xml_rewriter_for_a_chart_type(self, call_fixture): + chart_type, chart_data_, XmlRewriterClass_, xml_rewriter_ = call_fixture + + xml_rewriter = SeriesXmlRewriterFactory(chart_type, chart_data_) + + XmlRewriterClass_.assert_called_once_with(chart_data_) + assert xml_rewriter is xml_rewriter_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("BAR_CLUSTERED", _CategorySeriesXmlRewriter), + ("BUBBLE", _BubbleSeriesXmlRewriter), + ("BUBBLE_THREE_D_EFFECT", _BubbleSeriesXmlRewriter), + ("XY_SCATTER", _XySeriesXmlRewriter), + ("XY_SCATTER_LINES", _XySeriesXmlRewriter), + ("XY_SCATTER_LINES_NO_MARKERS", _XySeriesXmlRewriter), + ("XY_SCATTER_SMOOTH", _XySeriesXmlRewriter), + ("XY_SCATTER_SMOOTH_NO_MARKERS", _XySeriesXmlRewriter), + ] + ) + def call_fixture(self, request, chart_data_): + chart_type_member, rewriter_cls = request.param + chart_type = getattr(XL_CHART_TYPE, chart_type_member) + xml_rewriter_ = instance_mock(request, rewriter_cls) + XmlRewriterClass_ = class_mock( + request, + "pptx.chart.xmlwriter.%s" % rewriter_cls.__name__, + return_value=xml_rewriter_, + ) + return chart_type, chart_data_, XmlRewriterClass_, xml_rewriter_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def chart_data_(self, request): + return instance_mock(request, _BaseChartData) + + +class Describe_AreaChartXmlWriter(object): + def it_can_generate_xml_for_area_type_charts(self, xml_fixture): + xml_writer, expected_xml = xml_fixture + assert xml_writer.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("AREA", 2, 2, str, "2x2-area"), + ("AREA", 2, 2, date, "2x2-area-date"), + ("AREA", 2, 2, float, "2x2-area-float"), + ("AREA_STACKED", 2, 2, str, "2x2-area-stacked"), + ("AREA_STACKED_100", 2, 2, str, "2x2-area-stacked-100"), + ] + ) + def xml_fixture(self, request): + member, cat_count, ser_count, cat_type, snippet_name = request.param + chart_type = getattr(XL_CHART_TYPE, member) + chart_data = make_category_chart_data(cat_count, cat_type, ser_count) + xml_writer = _AreaChartXmlWriter(chart_type, chart_data) + expected_xml = snippet_text(snippet_name) + return xml_writer, expected_xml + + +class Describe_BarChartXmlWriter(object): + """Unit-test suite for `pptx.chart.xmlwriter._BarChartXmlWriter`.""" + + @pytest.mark.parametrize( + "member, cat_count, ser_count, cat_type, snippet_name", + ( + ("BAR_CLUSTERED", 2, 2, str, "2x2-bar-clustered"), + ("BAR_CLUSTERED", 2, 2, date, "2x2-bar-clustered-date"), + ("BAR_CLUSTERED", 2, 2, float, "2x2-bar-clustered-float"), + ("BAR_STACKED", 2, 2, str, "2x2-bar-stacked"), + ("BAR_STACKED_100", 2, 2, str, "2x2-bar-stacked-100"), + ("COLUMN_CLUSTERED", 2, 2, str, "2x2-column-clustered"), + ("COLUMN_STACKED", 2, 2, str, "2x2-column-stacked"), + ("COLUMN_STACKED_100", 2, 2, str, "2x2-column-stacked-100"), + ), + ) + def it_can_generate_xml_for_bar_type_charts( + self, member, cat_count, ser_count, cat_type, snippet_name + ): + chart_type = getattr(XL_CHART_TYPE, member) + chart_data = make_category_chart_data(cat_count, cat_type, ser_count) + xml_writer = _BarChartXmlWriter(chart_type, chart_data) + + assert xml_writer.xml == snippet_text(snippet_name) + + def it_can_generate_xml_for_multi_level_cat_charts(self): + chart_data = CategoryChartData() + WEST = chart_data.add_category("WEST") + WEST.add_sub_category("SF") + WEST.add_sub_category("LA") + EAST = chart_data.add_category("EAST") + EAST.add_sub_category("NY") + EAST.add_sub_category("NJ") + chart_data.add_series("Series 1", (1, 2, None, 4)) + chart_data.add_series("Series 2", (5, None, 7, 8)) + xml_writer = _BarChartXmlWriter(XL_CHART_TYPE.BAR_CLUSTERED, chart_data) + + assert xml_writer.xml == snippet_text("4x2-multi-cat-bar") + + +class Describe_BubbleChartXmlWriter(object): + def it_can_generate_xml_for_bubble_charts(self, xml_fixture): + xml_writer, expected_xml = xml_fixture + assert xml_writer.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("BUBBLE", 2, 3, "2x3-bubble"), + ("BUBBLE_THREE_D_EFFECT", 2, 3, "2x3-bubble-3d"), + ] + ) + def xml_fixture(self, request): + enum_member, ser_count, point_count, snippet_name = request.param + chart_type = getattr(XL_CHART_TYPE, enum_member) + chart_data = make_bubble_chart_data(ser_count, point_count) + xml_writer = _BubbleChartXmlWriter(chart_type, chart_data) + expected_xml = snippet_text(snippet_name) + return xml_writer, expected_xml + + +class Describe_DoughnutChartXmlWriter(object): + def it_can_generate_xml_for_doughnut_type_charts(self, xml_fixture): + xml_writer, expected_xml = xml_fixture + assert xml_writer.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("DOUGHNUT", 3, 2, "3x2-doughnut"), + ("DOUGHNUT_EXPLODED", 3, 2, "3x2-doughnut-exploded"), + ] + ) + def xml_fixture(self, request): + enum_member, cat_count, ser_count, snippet_name = request.param + chart_type = getattr(XL_CHART_TYPE, enum_member) + chart_data = make_category_chart_data(cat_count, str, ser_count) + xml_writer = _DoughnutChartXmlWriter(chart_type, chart_data) + expected_xml = snippet_text(snippet_name) + return xml_writer, expected_xml + + +class Describe_LineChartXmlWriter(object): + def it_can_generate_xml_for_a_line_chart(self, xml_fixture): + xml_writer, expected_xml = xml_fixture + assert xml_writer.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("LINE", 2, 2, str, "2x2-line"), + ("LINE", 2, 2, date, "2x2-line-date"), + ("LINE", 2, 2, float, "2x2-line-float"), + ("LINE_MARKERS", 2, 2, str, "2x2-line-markers"), + ("LINE_MARKERS_STACKED", 2, 2, str, "2x2-line-markers-stacked"), + ("LINE_MARKERS_STACKED_100", 2, 2, str, "2x2-line-markers-stacked-100"), + ("LINE_STACKED", 2, 2, str, "2x2-line-stacked"), + ("LINE_STACKED_100", 2, 2, str, "2x2-line-stacked-100"), + ] + ) + def xml_fixture(self, request): + member, cat_count, ser_count, cat_type, snippet_name = request.param + chart_type = getattr(XL_CHART_TYPE, member) + chart_data = make_category_chart_data(cat_count, cat_type, ser_count) + xml_writer = _LineChartXmlWriter(chart_type, chart_data) + expected_xml = snippet_text(snippet_name) + return xml_writer, expected_xml + + +class Describe_PieChartXmlWriter(object): + """Unit-test suite for `pptx.chart.xmlwriter._PieChartXmlWriter`.""" + + @pytest.mark.parametrize( + "enum_member, cat_count, ser_count, snippet_name", + ( + ("PIE", 3, 1, "3x1-pie"), + ("PIE_EXPLODED", 3, 1, "3x1-pie-exploded"), + ), + ) + def it_can_generate_xml_for_a_pie_chart(self, enum_member, cat_count, ser_count, snippet_name): + chart_type = getattr(XL_CHART_TYPE, enum_member) + chart_data = make_category_chart_data(cat_count, str, ser_count) + xml_writer = _PieChartXmlWriter(chart_type, chart_data) + + assert xml_writer.xml == snippet_text(snippet_name) + + +class Describe_RadarChartXmlWriter(object): + """Unit-test suite for `pptx.chart.xmlwriter._RadarChartXmlWriter`.""" + + def it_can_generate_xml_for_a_radar_chart(self): + series_data_seq = make_category_chart_data(cat_count=5, cat_type=str, ser_count=2) + xml_writer = _RadarChartXmlWriter(XL_CHART_TYPE.RADAR, series_data_seq) + + assert xml_writer.xml == snippet_text("2x5-radar") + + +class Describe_XyChartXmlWriter(object): + def it_can_generate_xml_for_xy_charts(self, xml_fixture): + xml_writer, expected_xml = xml_fixture + assert xml_writer.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("XY_SCATTER", 2, 3, "2x3-xy"), + ("XY_SCATTER_LINES", 2, 3, "2x3-xy-lines"), + ("XY_SCATTER_LINES_NO_MARKERS", 2, 3, "2x3-xy-lines-no-markers"), + ("XY_SCATTER_SMOOTH", 2, 3, "2x3-xy-smooth"), + ("XY_SCATTER_SMOOTH_NO_MARKERS", 2, 3, "2x3-xy-smooth-no-markers"), + ] + ) + def xml_fixture(self, request): + enum_member, ser_count, point_count, snippet_name = request.param + chart_type = getattr(XL_CHART_TYPE, enum_member) + chart_data = make_xy_chart_data(ser_count, point_count) + xml_writer = _XyChartXmlWriter(chart_type, chart_data) + expected_xml = snippet_text(snippet_name) + return xml_writer, expected_xml + + +class Describe_BubbleSeriesXmlWriter(object): + def it_knows_its_bubbleSize_XML(self, bubbleSize_fixture): + xml_writer, expected_xml = bubbleSize_fixture + bubbleSize = xml_writer.bubbleSize + assert bubbleSize.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + (None, None, "General"), + (None, 42, "42"), + (24, None, "24"), + (24, 42, "42"), + ] + ) + def bubbleSize_fixture(self, request): + cht_numfmt, ser_numfmt, expected_numfmt = request.param + expected_xml = xml( + 'c:bubbleSize/c:numRef/(c:f"Sheet1!$C$2:$C$1",c:numCache/(c:form' + 'atCode"%s",c:ptCount{val=0}))' % expected_numfmt + ) + chart_number_format = () if cht_numfmt is None else (cht_numfmt,) + series_number_format = () if ser_numfmt is None else (ser_numfmt,) + chart_data = BubbleChartData(*chart_number_format) + series_data = chart_data.add_series(None, *series_number_format) + xml_writer = _BubbleSeriesXmlWriter(series_data) + return xml_writer, expected_xml + + +class Describe_CategorySeriesXmlWriter(object): + def it_knows_its_val_XML(self, val_fixture): + xml_writer, expected_xml = val_fixture + val = xml_writer.val + assert val.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def val_fixture(self, series_data_): + values_ref, number_format = "Sheet1!$B$2:$B$1", "Foobar" + expected_xml = xml( + 'c:val/c:numRef/(c:f"%s",c:numCache/(c:formatCode"%s",c:ptCount{' + "val=0}))" % (values_ref, number_format) + ) + xml_writer = _CategorySeriesXmlWriter(series_data_) + series_data_.values_ref = values_ref + series_data_.number_format = number_format + return xml_writer, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def series_data_(self, request): + return instance_mock(request, CategorySeriesData) + + +class Describe_XySeriesXmlWriter(object): + def it_knows_its_xVal_XML(self, xVal_fixture): + xml_writer, expected_xml = xVal_fixture + xVal = xml_writer.xVal + assert xVal.xml == expected_xml + + def it_knows_its_yVal_XML(self, yVal_fixture): + xml_writer, expected_xml = yVal_fixture + yVal = xml_writer.yVal + assert yVal.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + (None, None, "General"), + (None, 42, "42"), + (24, None, "24"), + (24, 42, "42"), + ] + ) + def xVal_fixture(self, request): + cht_numfmt, ser_numfmt, expected_numfmt = request.param + expected_xml = xml( + 'c:xVal/c:numRef/(c:f"Sheet1!$A$2:$A$1",c:numCache/(c:formatCode' + '"%s",c:ptCount{val=0}))' % expected_numfmt + ) + chart_number_format = () if cht_numfmt is None else (cht_numfmt,) + series_number_format = () if ser_numfmt is None else (ser_numfmt,) + chart_data = XyChartData(*chart_number_format) + series_data = chart_data.add_series(None, *series_number_format) + xml_writer = _XySeriesXmlWriter(series_data) + return xml_writer, expected_xml + + @pytest.fixture( + params=[ + (None, None, "General"), + (None, 42, "42"), + (24, None, "24"), + (24, 42, "42"), + ] + ) + def yVal_fixture(self, request): + cht_numfmt, ser_numfmt, expected_numfmt = request.param + expected_xml = xml( + 'c:yVal/c:numRef/(c:f"Sheet1!$B$2:$B$1",c:numCache/(c:formatCode' + '"%s",c:ptCount{val=0}))' % expected_numfmt + ) + chart_number_format = () if cht_numfmt is None else (cht_numfmt,) + series_number_format = () if ser_numfmt is None else (ser_numfmt,) + chart_data = XyChartData(*chart_number_format) + series_data = chart_data.add_series(None, *series_number_format) + xml_writer = _XySeriesXmlWriter(series_data) + return xml_writer, expected_xml + + +class Describe_BaseSeriesXmlRewriter(object): + def it_can_replace_series_data(self, replace_fixture): + rewriter, chartSpace, plotArea, ser_count, calls = replace_fixture + rewriter.replace_series_data(chartSpace) + rewriter._adjust_ser_count.assert_called_once_with(rewriter, plotArea, ser_count) + assert rewriter._rewrite_ser_data.call_args_list == calls + + def it_adjusts_the_ser_count_to_help(self, adjust_fixture): + rewriter, plotArea, new_ser_count, add_calls, trim_calls, sers = adjust_fixture + rewriter._adjust_ser_count(plotArea, new_ser_count) + assert rewriter._add_cloned_sers.call_args_list == add_calls + assert rewriter._trim_ser_count_by.call_args_list == trim_calls + + def it_adds_cloned_sers_to_help(self, clone_fixture): + rewriter, plotArea, count, expected_xml = clone_fixture + rewriter._add_cloned_sers(plotArea, count) + assert plotArea.xml == expected_xml + + def it_trims_sers_to_help(self, trim_fixture): + rewriter, plotArea, count, expected_xml = trim_fixture + rewriter._trim_ser_count_by(plotArea, count) + assert plotArea.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=[(3, True, False), (2, False, False), (1, False, True)]) + def adjust_fixture(self, request, _add_cloned_sers_, _trim_ser_count_by_): + new_ser_count, add, trim = request.param + rewriter = _BaseSeriesXmlRewriter(None) + plotArea = element( + "c:plotArea/c:barChart/(c:ser/(c:idx{val=3},c:order{val=1}),c:se" + "r/(c:idx{val=1},c:order{val=3}))" + ) + sers = plotArea.sers + add_calls = [call(rewriter, plotArea, 1)] if add else [] + trim_calls = [call(rewriter, plotArea, 1)] if trim else [] + return rewriter, plotArea, new_ser_count, add_calls, trim_calls, sers + + @pytest.fixture( + params=[ + ( + "c:plotArea/c:barChart/c:ser/(c:idx{val=3},c:order{val=1})", + 1, + "c:plotArea/c:barChart/(c:ser/(c:idx{val=3},c:order{val=1}),c:ser/(" + "c:idx{val=4},c:order{val=2}))", + ), + ( + "c:plotArea/(c:barChart/c:ser/(c:idx{val=3},c:order{val=1}),c:lineC" + "hart/(c:ser/(c:idx{val=4},c:order{val=7}),c:ser/(c:idx{val=1},c:or" + "der{val=2})))", + 1, + "c:plotArea/(c:barChart/c:ser/(c:idx{val=3},c:order{val=1}),c:lineC" + "hart/(c:ser/(c:idx{val=4},c:order{val=7}),c:ser/(c:idx{val=5},c:or" + "der{val=8}),c:ser/(c:idx{val=1},c:order{val=2})))", + ), + ] + ) + def clone_fixture(self, request): + plotArea_cxml, count, expected_cxml = request.param + rewriter = _BaseSeriesXmlRewriter(None) + plotArea = element(plotArea_cxml) + expected_xml = xml(expected_cxml) + return rewriter, plotArea, count, expected_xml + + @pytest.fixture + def replace_fixture(self, request, chart_data_, _adjust_ser_count_, _rewrite_ser_data_): + rewriter = _BaseSeriesXmlRewriter(chart_data_) + chartSpace = element( + "c:chartSpace/c:chart/c:plotArea/c:barChart/(c:ser/c:order{val=0" + "},c:ser/c:order{val=1})" + ) + plotArea = chartSpace.xpath("c:chart/c:plotArea")[0] + sers = chartSpace.xpath(".//c:ser") + ser_count = len(sers) + series_datas = [ + instance_mock(request, _BaseSeriesData), + instance_mock(request, _BaseSeriesData), + ] + calls = [ + call(rewriter, sers[0], series_datas[0], False), + call(rewriter, sers[1], series_datas[1], False), + ] + chart_data_.__len__.return_value = len(series_datas) + chart_data_.__iter__.return_value = iter(series_datas) + return rewriter, chartSpace, plotArea, ser_count, calls + + @pytest.fixture( + params=[ + # --single xChart, remove single ser-- + ( + "c:plotArea/c:barChart/(c:ser/(c:idx{val=3},c:order{val=4}),c:ser/(" + "c:idx{val=1},c:order{val=2}))", + 1, + "c:plotArea/c:barChart/(c:ser/(c:idx{val=1},c:order{val=2}))", + ), + # --two xCharts, remove two sers (and emptied second xChart)-- + ( + "c:plotArea/(c:barChart/c:ser/(c:idx{val=3},c:order{val=1}),c:lineC" + "hart/(c:ser/(c:idx{val=4},c:order{val=7}),c:ser/(c:idx{val=1},c:or" + "der{val=2})))", + 2, + "c:plotArea/(c:barChart/c:ser/(c:idx{val=3},c:order{val=1}))", + ), + ] + ) + def trim_fixture(self, request): + plotArea_cxml, count, expected_cxml = request.param + rewriter = _BaseSeriesXmlRewriter(None) + plotArea = element(plotArea_cxml) + expected_xml = xml(expected_cxml) + return rewriter, plotArea, count, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def _add_cloned_sers_(self, request): + return method_mock(request, _BaseSeriesXmlRewriter, "_add_cloned_sers", autospec=True) + + @pytest.fixture + def _adjust_ser_count_(self, request): + return method_mock(request, _BaseSeriesXmlRewriter, "_adjust_ser_count", autospec=True) + + @pytest.fixture + def chart_data_(self, request): + return instance_mock(request, _BaseChartData) + + @pytest.fixture + def _rewrite_ser_data_(self, request): + return method_mock(request, _BaseSeriesXmlRewriter, "_rewrite_ser_data", autospec=True) + + @pytest.fixture + def _trim_ser_count_by_(self, request): + return method_mock(request, _BaseSeriesXmlRewriter, "_trim_ser_count_by", autospec=True) + + +class Describe_BubbleSeriesXmlRewriter(object): + def it_can_rewrite_a_ser_element(self, rewrite_fixture): + rewriter, ser, series_data, expected_xml = rewrite_fixture + rewriter._rewrite_ser_data(ser, series_data, None) + assert ser.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def rewrite_fixture(self): + ser_xml, expected_xml = snippet_seq("rewrite-ser")[4:6] + + chart_data = BubbleChartData() + series_data = chart_data.add_series("Series 1") + series_data.add_data_point(1, 2, 10) + series_data.add_data_point(3, 4, 20) + + rewriter = _BubbleSeriesXmlRewriter(chart_data) + ser = parse_xml(ser_xml) + return rewriter, ser, series_data, expected_xml + + +class Describe_CategorySeriesXmlRewriter(object): + def it_can_rewrite_a_ser_element(self, rewrite_fixture): + rewriter, ser, series_data, expected_xml = rewrite_fixture + rewriter._rewrite_ser_data(ser, series_data, False) + assert ser.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + (0, ("foo", "bar")), + (6, (42, 24)), + (8, (date(2016, 12, 22), date(2016, 12, 23))), + ] + ) + def rewrite_fixture(self, request): + snippet_offset, categories = request.param + chart_data = CategoryChartData() + chart_data.categories = categories + rewriter = _CategorySeriesXmlRewriter(chart_data) + snippets = snippet_seq("rewrite-ser") + ser_xml = snippets[snippet_offset] + ser = parse_xml(ser_xml) + series_data = chart_data.add_series("Series 1", (1, 2)) + expected_xml = snippets[snippet_offset + 1] + return rewriter, ser, series_data, expected_xml + + +class Describe_XySeriesXmlRewriter(object): + def it_can_rewrite_a_ser_element(self, rewrite_fixture): + rewriter, ser, series_data, expected_xml = rewrite_fixture + rewriter._rewrite_ser_data(ser, series_data, None) + assert ser.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def rewrite_fixture(self): + ser_xml, expected_xml = snippet_seq("rewrite-ser")[2:4] + + chart_data = XyChartData() + series_data = chart_data.add_series("Series 1") + series_data.add_data_point(1, 2) + series_data.add_data_point(3, 4) + + rewriter = _XySeriesXmlRewriter(chart_data) + ser = parse_xml(ser_xml) + return rewriter, ser, series_data, expected_xml + + +# helpers ------------------------------------------------------------ + + +def make_bubble_chart_data(ser_count, point_count): + """ + Return an |BubbleChartData| object populated with *ser_count* series, + each having *point_count* data points. + """ + points = ( + (1.1, 11.1, 10.0), + (2.1, 12.1, 20.0), + (3.1, 13.1, 30.0), + (1.2, 11.2, 40.0), + (2.2, 12.2, 50.0), + (3.2, 13.2, 60.0), + ) + chart_data = BubbleChartData() + for i in range(ser_count): + series_label = "Series %d" % (i + 1) + series = chart_data.add_series(series_label) + for j in range(point_count): + point_idx = (i * point_count) + j + x, y, size = points[point_idx] + series.add_data_point(x, y, size) + return chart_data + + +def make_category_chart_data(cat_count, cat_type, ser_count): + """ + Return a |CategoryChartData| instance populated with *cat_count* + categories of type *cat_type* and *ser_count* series. Values are + auto-generated. + """ + category_labels = { + date: (date(2016, 12, 27), date(2016, 12, 28), date(2016, 12, 29)), + float: (1.1, 2.2, 3.3, 4.4, 5.5), + str: ("Foo", "Bar", "Baz", "Boo", "Far", "Faz"), + }[cat_type] + point_values = count(1.1, 1.1) + chart_data = CategoryChartData() + chart_data.categories = category_labels[:cat_count] + for idx in range(ser_count): + series_title = "Series %d" % (idx + 1) + series_values = tuple(islice(point_values, cat_count)) + series_values = [round(x * 10) / 10.0 for x in series_values] + chart_data.add_series(series_title, series_values) + return chart_data + + +def make_xy_chart_data(ser_count, point_count): + """ + Return an |XyChartData| object populated with *ser_count* series each + having *point_count* data points. Values are auto-generated. + """ + points = ( + (1.1, 11.1), + (2.1, 12.1), + (3.1, 13.1), + (1.2, 11.2), + (2.2, 12.2), + (3.2, 13.2), + ) + chart_data = XyChartData() + for i in range(ser_count): + series_label = "Series %d" % (i + 1) + series = chart_data.add_series(series_label) + for j in range(point_count): + point_idx = (i * point_count) + j + x, y = points[point_idx] + series.add_data_point(x, y) + return chart_data diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/dml/__init__.py b/tasks/tasksmith-74f059424102/environment/source/tests/dml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_chtfmt.py b/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_chtfmt.py new file mode 100644 index 0000000000000000000000000000000000000000..f877521802700db8ecdfc5a25e4089cb5263bce4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_chtfmt.py @@ -0,0 +1,87 @@ +"""Unit-test suite for `pptx.dml.chtfmt` module.""" + +from __future__ import annotations + +import pytest + +from pptx.dml.chtfmt import ChartFormat +from pptx.dml.fill import FillFormat +from pptx.dml.line import LineFormat + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, instance_mock + + +class DescribeChartFormat(object): + def it_provides_access_to_its_fill(self, fill_fixture): + chart_format, FillFormat_, fill_, expected_xml = fill_fixture + fill = chart_format.fill + FillFormat_.from_fill_parent.assert_called_once_with( + chart_format._element.xpath("c:spPr")[0] + ) + assert fill is fill_ + assert chart_format._element.xml == expected_xml + + def it_provides_access_to_its_line(self, line_fixture): + chart_format, LineFormat_, line_, expected_xml = line_fixture + line = chart_format.line + LineFormat_.assert_called_once_with(chart_format._element.xpath("c:spPr")[0]) + assert line is line_ + assert chart_format._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("c:catAx", "c:catAx/c:spPr"), + ("c:catAx/c:spPr", "c:catAx/c:spPr"), + ("c:dPt", "c:dPt/c:spPr"), + ("c:dPt/c:spPr", "c:dPt/c:spPr"), + ("c:majorGridlines", "c:majorGridlines/c:spPr"), + ("c:majorGridlines/c:spPr", "c:majorGridlines/c:spPr"), + ("c:valAx", "c:valAx/c:spPr"), + ("c:valAx/c:spPr", "c:valAx/c:spPr"), + ] + ) + def fill_fixture(self, request, FillFormat_, fill_): + dPt_cxml, expected_cxml = request.param + chart_format = ChartFormat(element(dPt_cxml)) + FillFormat_.from_fill_parent.return_value = fill_ + expected_xml = xml(expected_cxml) + return chart_format, FillFormat_, fill_, expected_xml + + @pytest.fixture( + params=[ + ("c:catAx", "c:catAx/c:spPr"), + ("c:catAx/c:spPr", "c:catAx/c:spPr"), + ("c:dPt", "c:dPt/c:spPr"), + ("c:dPt/c:spPr", "c:dPt/c:spPr"), + ("c:majorGridlines", "c:majorGridlines/c:spPr"), + ("c:majorGridlines/c:spPr", "c:majorGridlines/c:spPr"), + ("c:valAx", "c:valAx/c:spPr"), + ("c:valAx/c:spPr", "c:valAx/c:spPr"), + ] + ) + def line_fixture(self, request, LineFormat_, line_): + cxml, expected_cxml = request.param + chart_format = ChartFormat(element(cxml)) + expected_xml = xml(expected_cxml) + return chart_format, LineFormat_, line_, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def FillFormat_(self, request): + return class_mock(request, "pptx.dml.chtfmt.FillFormat") + + @pytest.fixture + def fill_(self, request): + return instance_mock(request, FillFormat) + + @pytest.fixture + def LineFormat_(self, request, line_): + return class_mock(request, "pptx.dml.chtfmt.LineFormat", return_value=line_) + + @pytest.fixture + def line_(self, request): + return instance_mock(request, LineFormat) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_color.py b/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_color.py new file mode 100644 index 0000000000000000000000000000000000000000..95a1f7c5d988e43ca29d64a1a2a6b3e48e3b827f --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_color.py @@ -0,0 +1,280 @@ +"""Unit-test suite for `pptx.text` module.""" + +from __future__ import annotations + +import pytest + +from pptx.dml.color import ColorFormat, RGBColor +from pptx.enum.dml import MSO_COLOR_TYPE, MSO_THEME_COLOR + +from ..oxml.unitdata.dml import ( + a_lumMod, + a_lumOff, + a_prstClr, + a_schemeClr, + a_solidFill, + a_sysClr, + an_hslClr, + an_scrgbClr, + an_srgbClr, +) + + +class DescribeColorFormat(object): + def it_knows_the_type_of_its_color(self, color_type_fixture_): + color_format, color_type = color_type_fixture_ + assert color_format.type == color_type + + def it_knows_the_RGB_value_of_an_RGB_color(self, rgb_color_format): + color_format = rgb_color_format + assert color_format.rgb == RGBColor(0x12, 0x34, 0x56) + + def it_raises_on_rgb_get_for_colors_other_than_rgb(self, rgb_raise_fixture_): + color_format, exception_type = rgb_raise_fixture_ + with pytest.raises(exception_type): + color_format.rgb + + def it_knows_the_theme_color_of_a_theme_color(self, get_theme_color_fixture_): + color_format, theme_color = get_theme_color_fixture_ + assert color_format.theme_color == theme_color + + def it_raises_on_theme_color_get_for_NoneColor(self, _NoneColor_color_format): + with pytest.raises(AttributeError): + _NoneColor_color_format.theme_color + + def it_knows_its_brightness_adjustment(self, color_format_with_brightness): + color_format, expected_brightness = color_format_with_brightness + assert color_format.brightness == expected_brightness + + def it_can_set_itself_to_an_RGB_color(self, set_rgb_fixture_): + color_format, rgb_color, expected_xml = set_rgb_fixture_ + color_format.rgb = rgb_color + assert color_format._xFill.xml == expected_xml + + def it_raises_on_assign_non_RGBColor_type_to_rgb(self, rgb_color_format): + color_format = rgb_color_format + with pytest.raises(ValueError): + color_format.rgb = (0x12, 0x34, 0x56) + + def it_can_set_itself_to_a_theme_color(self, set_theme_color_fixture_): + color_format, theme_color, expected_xml = set_theme_color_fixture_ + color_format.theme_color = theme_color + assert color_format._xFill.xml == expected_xml + + def it_can_set_its_brightness_adjustment(self, set_brightness_fixture_): + color_format, brightness, expected_xml = set_brightness_fixture_ + color_format.brightness = brightness + assert color_format._xFill.xml == expected_xml + + def it_raises_on_attempt_to_set_brightness_out_of_range(self, rgb_color_format): + with pytest.raises(ValueError): + rgb_color_format.brightness = 1.1 + with pytest.raises(ValueError): + rgb_color_format.brightness = -1.1 + + def it_raises_on_attempt_to_set_brightness_on_None_color_type( + self, color_format_having_none_color_type + ): + color_format = color_format_having_none_color_type + with pytest.raises(ValueError): + color_format.brightness = 0.5 + + # fixtures --------------------------------------------- + + @pytest.fixture + def color_format_having_none_color_type(self): + solidFill = a_solidFill().with_nsdecls().element + color_format = ColorFormat.from_colorchoice_parent(solidFill) + return color_format + + @pytest.fixture(params=["hsl", "prst", "scheme", "scrgb", "srgb", "sys"]) + def color_format_with_brightness(self, request): + mapping = { + "hsl": (an_hslClr, 55000, 45000, 0.45), + "prst": (a_prstClr, None, None, 0.0), + "scheme": (a_schemeClr, 15000, None, -0.85), + "scrgb": (an_scrgbClr, 15000, 85000, 0.85), + "srgb": (an_srgbClr, None, None, 0.0), + "sys": (a_sysClr, 23000, None, -0.77), + } + xClr_bldr_fn, lumMod, lumOff, exp_brightness = mapping[request.param] + xClr_bldr = xClr_bldr_fn() + if lumMod is not None: + xClr_bldr.with_child(a_lumMod().with_val(lumMod)) + if lumOff is not None: + xClr_bldr.with_child(a_lumOff().with_val(lumOff)) + solidFill = a_solidFill().with_nsdecls().with_child(xClr_bldr).element + color_format = ColorFormat.from_colorchoice_parent(solidFill) + return color_format, exp_brightness + + @pytest.fixture(params=["none", "hsl", "prst", "scheme", "scrgb", "srgb", "sys"]) + def color_type_fixture_(self, request): + mapping = { + "none": (None, None), + "hsl": (an_hslClr, MSO_COLOR_TYPE.HSL), + "prst": (a_prstClr, MSO_COLOR_TYPE.PRESET), + "srgb": (an_srgbClr, MSO_COLOR_TYPE.RGB), + "scheme": (a_schemeClr, MSO_COLOR_TYPE.SCHEME), + "scrgb": (an_scrgbClr, MSO_COLOR_TYPE.SCRGB), + "sys": (a_sysClr, MSO_COLOR_TYPE.SYSTEM), + } + xClr_bldr_fn, color_type = mapping[request.param] + solidFill_bldr = a_solidFill().with_nsdecls() + if xClr_bldr_fn is not None: + solidFill_bldr.with_child(xClr_bldr_fn()) + solidFill = solidFill_bldr.element + color_format = ColorFormat.from_colorchoice_parent(solidFill) + return color_format, color_type + + @pytest.fixture + def _NoneColor_color_format(self): + solidFill = a_solidFill().with_nsdecls().element + color_format = ColorFormat.from_colorchoice_parent(solidFill) + return color_format + + @pytest.fixture + def rgb_color_format(self): + srgbClr_bldr = an_srgbClr().with_val("123456") + solidFill = a_solidFill().with_nsdecls().with_child(srgbClr_bldr).element + color_format = ColorFormat.from_colorchoice_parent(solidFill) + return color_format + + @pytest.fixture(params=["none", "hsl", "prst", "scheme", "scrgb", "sys"]) + def rgb_raise_fixture_(self, request): + mapping = { + "none": (None, AttributeError), + "hsl": (an_hslClr, AttributeError), + "prst": (a_prstClr, AttributeError), + "scheme": (a_schemeClr, AttributeError), + "scrgb": (an_scrgbClr, AttributeError), + "sys": (a_sysClr, AttributeError), + } + xClr_bldr_fn, exception_type = mapping[request.param] + solidFill_bldr = a_solidFill().with_nsdecls() + if xClr_bldr_fn is not None: + solidFill_bldr.with_child(xClr_bldr_fn()) + solidFill = solidFill_bldr.element + color_format = ColorFormat.from_colorchoice_parent(solidFill) + return color_format, exception_type + + @pytest.fixture( + params=[ + "0 to 0", + "0 to -0.4", + "0.15 to 0.25", + "0.15 to -0.15", + "-0.25 to 0.4", + "-0.3 to -0.4", + "-0.4 to 0", + ] + ) + def set_brightness_fixture_(self, request): + mapping = { + "0 to 0": (an_srgbClr, None, None, 0, None, None), + "0 to -0.4": (an_hslClr, None, None, -0.4, 60000, None), + "0.15 to 0.25": (a_prstClr, 85000, 15000, 0.25, 75000, 25000), + "0.15 to -0.15": (a_schemeClr, 85000, 15000, -0.15, 85000, None), + "-0.25 to 0.4": (an_scrgbClr, 75000, None, 0.4, 60000, 40000), + "-0.3 to -0.4": (an_srgbClr, 70000, None, -0.4, 60000, None), + "-0.4 to 0": (a_sysClr, 60000, None, 0, None, None), + } + xClr_bldr_fn, mod_in, off_in, brightness, mod_out, off_out = mapping[request.param] + + xClr_bldr = xClr_bldr_fn() + if mod_in is not None: + xClr_bldr.with_child(a_lumMod().with_val(mod_in)) + if off_in is not None: + xClr_bldr.with_child(a_lumOff().with_val(off_in)) + solidFill = a_solidFill().with_nsdecls().with_child(xClr_bldr).element + color_format = ColorFormat.from_colorchoice_parent(solidFill) + + xClr_bldr = xClr_bldr_fn() + if mod_out is not None: + xClr_bldr.with_child(a_lumMod().with_val(mod_out)) + if off_out is not None: + xClr_bldr.with_child(a_lumOff().with_val(off_out)) + expected_xml = a_solidFill().with_nsdecls().with_child(xClr_bldr).xml() + + return color_format, brightness, expected_xml + + @pytest.fixture(params=["none", "hsl", "prst", "scheme", "scrgb", "srgb", "sys"]) + def set_rgb_fixture_(self, request): + mapping = { + "none": None, + "hsl": an_hslClr, + "prst": a_prstClr, + "scheme": a_schemeClr, + "scrgb": an_scrgbClr, + "srgb": an_srgbClr, + "sys": a_sysClr, + } + xClr_bldr_fn = mapping[request.param] + solidFill_bldr = a_solidFill().with_nsdecls() + if xClr_bldr_fn is not None: + solidFill_bldr.with_child(xClr_bldr_fn()) + solidFill = solidFill_bldr.element + color_format = ColorFormat.from_colorchoice_parent(solidFill) + rgb_color = RGBColor(0x12, 0x34, 0x56) + expected_xml = ( + a_solidFill().with_nsdecls().with_child(an_srgbClr().with_val("123456")).xml() + ) + return color_format, rgb_color, expected_xml + + @pytest.fixture(params=["none", "hsl", "prst", "scheme", "scrgb", "srgb", "sys"]) + def set_theme_color_fixture_(self, request): + mapping = { + "none": None, + "hsl": an_hslClr, + "prst": a_prstClr, + "scheme": a_schemeClr, + "scrgb": an_scrgbClr, + "srgb": an_srgbClr, + "sys": a_sysClr, + } + xClr_bldr_fn = mapping[request.param] + solidFill_bldr = a_solidFill().with_nsdecls() + if xClr_bldr_fn is not None: + solidFill_bldr.with_child(xClr_bldr_fn()) + solidFill = solidFill_bldr.element + color_format = ColorFormat.from_colorchoice_parent(solidFill) + theme_color = MSO_THEME_COLOR.ACCENT_6 + expected_xml = ( + a_solidFill().with_nsdecls().with_child(a_schemeClr().with_val("accent6")).xml() + ) + return color_format, theme_color, expected_xml + + @pytest.fixture(params=["hsl", "prst", "scheme", "scrgb", "srgb", "sys"]) + def get_theme_color_fixture_(self, request): + mapping = { + "hsl": (an_hslClr, MSO_THEME_COLOR.NOT_THEME_COLOR), + "prst": (a_prstClr, MSO_THEME_COLOR.NOT_THEME_COLOR), + "scheme": (a_schemeClr, MSO_THEME_COLOR.ACCENT_1), + "scrgb": (an_scrgbClr, MSO_THEME_COLOR.NOT_THEME_COLOR), + "srgb": (an_srgbClr, MSO_THEME_COLOR.NOT_THEME_COLOR), + "sys": (a_sysClr, MSO_THEME_COLOR.NOT_THEME_COLOR), + } + xClr_bldr_fn, theme_color = mapping[request.param] + xClr_bldr = xClr_bldr_fn() + if theme_color != MSO_THEME_COLOR.NOT_THEME_COLOR: + xClr_bldr.with_val("accent1") + solidFill = a_solidFill().with_nsdecls().with_child(xClr_bldr).element + color_format = ColorFormat.from_colorchoice_parent(solidFill) + return color_format, theme_color + + +class DescribeRGBColor(object): + def it_is_natively_constructed_using_three_ints_0_to_255(self): + RGBColor(0x12, 0x34, 0x56) + with pytest.raises(ValueError): + RGBColor("12", "34", "56") + with pytest.raises(ValueError): + RGBColor(-1, 34, 56) + with pytest.raises(ValueError): + RGBColor(12, 256, 56) + + def it_can_construct_from_a_hex_string_rgb_value(self): + rgb = RGBColor.from_string("123456") + assert rgb == RGBColor(0x12, 0x34, 0x56) + + def it_can_provide_a_hex_string_rgb_value(self): + assert str(RGBColor(0x12, 0x34, 0x56)) == "123456" diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_effect.py b/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_effect.py new file mode 100644 index 0000000000000000000000000000000000000000..1907e561d1f103153bd680183997bed4f65d1224 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_effect.py @@ -0,0 +1,54 @@ +"""Unit-test suite for `pptx.dml.effect` module.""" + +from __future__ import annotations + +import pytest + +from pptx.dml.effect import ShadowFormat + +from ..unitutil.cxml import element, xml + + +class DescribeShadowFormat(object): + def it_knows_whether_it_inherits(self, inherit_get_fixture): + shadow, expected_value = inherit_get_fixture + inherit = shadow.inherit + assert inherit is expected_value + + def it_can_change_whether_it_inherits(self, inherit_set_fixture): + shadow, value, expected_xml = inherit_set_fixture + shadow.inherit = value + assert shadow._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("p:spPr", True), + ("p:spPr/a:effectLst", False), + ("p:grpSpPr", True), + ("p:grpSpPr/a:effectLst", False), + ] + ) + def inherit_get_fixture(self, request): + cxml, expected_value = request.param + shadow = ShadowFormat(element(cxml)) + return shadow, expected_value + + @pytest.fixture( + params=[ + ("p:spPr{a:b=c}", False, "p:spPr{a:b=c}/a:effectLst"), + ("p:grpSpPr{a:b=c}", False, "p:grpSpPr{a:b=c}/a:effectLst"), + ("p:spPr{a:b=c}/a:effectLst", True, "p:spPr{a:b=c}"), + ("p:grpSpPr{a:b=c}/a:effectLst", True, "p:grpSpPr{a:b=c}"), + ("p:spPr", True, "p:spPr"), + ("p:grpSpPr", True, "p:grpSpPr"), + ("p:spPr/a:effectLst", False, "p:spPr/a:effectLst"), + ("p:grpSpPr/a:effectLst", False, "p:grpSpPr/a:effectLst"), + ] + ) + def inherit_set_fixture(self, request): + cxml, value, expected_cxml = request.param + shadow = ShadowFormat(element(cxml)) + expected_value = xml(expected_cxml) + return shadow, value, expected_value diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_fill.py b/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..defbaf98076b67e32d16493033dccb523615f429 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_fill.py @@ -0,0 +1,737 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.dml.fill` module.""" + +from __future__ import annotations + +import pytest + +from pptx.dml.color import ColorFormat +from pptx.dml.fill import ( + FillFormat, + _BlipFill, + _Fill, + _GradFill, + _GradientStop, + _GradientStops, + _GrpFill, + _NoFill, + _NoneFill, + _PattFill, + _SolidFill, +) +from pptx.enum.dml import MSO_FILL, MSO_PATTERN +from pptx.oxml.dml.fill import CT_GradientStopList + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, instance_mock, method_mock, property_mock + + +class DescribeFillFormat(object): + def it_can_set_the_fill_type_to_no_fill(self, background_fixture): + fill, _NoFill_, expected_xml, no_fill_ = background_fixture + + fill.background() + + assert fill._xPr.xml == expected_xml + _NoFill_.assert_called_once_with(fill._xPr.eg_fillProperties) + assert fill._fill is no_fill_ + + def it_can_set_the_fill_type_to_gradient(self, gradient_fixture): + fill, _GradFill_, expected_xml, grad_fill_ = gradient_fixture + + fill.gradient() + + assert fill._xPr.xml == expected_xml + _GradFill_.assert_called_once_with(fill._xPr.eg_fillProperties) + assert fill._fill is grad_fill_ + + def it_can_set_the_fill_type_to_solid(self, solid_fixture): + fill, _SolidFill_, expected_xml, solid_fill_ = solid_fixture + + fill.solid() + + assert fill._xPr.xml == expected_xml + _SolidFill_.assert_called_once_with(fill._xPr.eg_fillProperties) + assert fill._fill is solid_fill_ + + def it_can_set_the_fill_type_to_patterned(self, patterned_fixture): + fill, _PattFill_, expected_xml, patt_fill_ = patterned_fixture + + fill.patterned() + + assert fill._xPr.xml == expected_xml + _PattFill_.assert_called_once_with(fill._xPr.eg_fillProperties) + assert fill._fill is patt_fill_ + + def it_provides_access_to_its_foreground_color(self, fore_color_fixture): + fill, color_ = fore_color_fixture + color = fill.fore_color + assert color is color_ + + def it_provides_access_to_its_background_color(self, back_color_fixture): + fill, color_ = back_color_fixture + color = fill.back_color + assert color is color_ + + def it_knows_its_fill_type(self, fill_type_fixture): + fill, expected_value = fill_type_fixture + fill_type = fill.type + assert fill_type == expected_value + + def it_knows_the_angle_of_a_linear_gradient(self, grad_fill_, type_prop_): + grad_fill_.gradient_angle = 42.0 + type_prop_.return_value = MSO_FILL.GRADIENT + fill = FillFormat(None, grad_fill_) + + angle = fill.gradient_angle + + assert angle == 42.0 + + def it_can_change_the_angle_of_a_linear_gradient(self, grad_fill_, type_prop_): + type_prop_.return_value = MSO_FILL.GRADIENT + fill = FillFormat(None, grad_fill_) + + fill.gradient_angle = 42.24 + + assert grad_fill_.gradient_angle == 42.24 + + def it_provides_access_to_the_gradient_stops(self, type_prop_, grad_fill_, gradient_stops_): + type_prop_.return_value = MSO_FILL.GRADIENT + grad_fill_.gradient_stops = gradient_stops_ + fill = FillFormat(None, grad_fill_) + + gradient_stops = fill.gradient_stops + + assert gradient_stops is gradient_stops_ + + def it_raises_on_non_gradient_fill(self, grad_fill_, type_prop_): + type_prop_.return_value = None + fill = FillFormat(None, grad_fill_) + with pytest.raises(TypeError): + fill.gradient_angle + with pytest.raises(TypeError): + fill.gradient_angle = 123.4 + with pytest.raises(TypeError): + fill.gradient_stops + + def it_knows_its_pattern(self, pattern_get_fixture): + fill, expected_value = pattern_get_fixture + pattern = fill.pattern + assert pattern == expected_value + + def it_can_change_its_pattern(self, pattern_set_fixture): + fill, pattern = pattern_set_fixture + fill.pattern = pattern + assert fill.pattern is pattern + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def back_color_fixture(self, fill_, color_): + fill_.back_color = color_ + fill_format = FillFormat(None, fill_) + return fill_format, color_ + + @pytest.fixture( + params=[ + ("p:spPr{a:b=c}", "p:spPr{a:b=c}/a:noFill"), + ("a:tcPr/a:blipFill", "a:tcPr/a:noFill"), + ("a:rPr/a:gradFill", "a:rPr/a:noFill"), + ("a:tcPr/a:grpFill", "a:tcPr/a:noFill"), + ("a:defRPr/a:noFill", "a:defRPr/a:noFill"), + ("a:endParaRPr/a:pattFill", "a:endParaRPr/a:noFill"), + ("a:rPr/a:solidFill", "a:rPr/a:noFill"), + ] + ) + def background_fixture(self, request, no_fill_): + cxml, expected_cxml = request.param + + fill = FillFormat.from_fill_parent(element(cxml)) + # --mock must be after FillFormat call to avoid poss. contructor call + _NoFill_ = class_mock( + request, "pptx.dml.fill._NoFill", return_value=no_fill_, autospec=True + ) + expected_xml = xml(expected_cxml) + return fill, _NoFill_, expected_xml, no_fill_ + + @pytest.fixture + def fill_type_fixture(self, fill_): + expected_value = fill_.type = 42 + fill = FillFormat(None, fill_) + return fill, expected_value + + @pytest.fixture + def fore_color_fixture(self, fill_, color_): + fill_.fore_color = color_ + fill_format = FillFormat(None, fill_) + return fill_format, color_ + + @pytest.fixture( + params=[ + ("p:spPr{a:b=c}", "p:spPr{a:b=c}/a:gradFill"), + ("p:bgPr/a:noFill", "p:bgPr/a:gradFill"), + ("a:tcPr/a:blipFill", "a:tcPr/a:gradFill"), + ("a:rPr/a:grpFill", "a:rPr/a:gradFill"), + ("a:tcPr/a:noFill", "a:tcPr/a:gradFill"), + ("a:defRPr/a:solidFill", "a:defRPr/a:gradFill"), + ("a:endParaRPr/a:blipFill", "a:endParaRPr/a:gradFill"), + ] + ) + def gradient_fixture(self, request, grad_fill_): + cxml, expected_cxml = request.param + + fill = FillFormat.from_fill_parent(element(cxml)) + # --mock must be after FillFormat call to avoid poss. contructor call + _GradFill_ = class_mock( + request, "pptx.dml.fill._GradFill", return_value=grad_fill_, autospec=True + ) + expected_xml = xml( + expected_cxml + "{rotWithShape=1}/(a:gsLst/(a:gs{pos=0}/a:scheme" + "Clr{val=accent1}/(a:tint{val=100000},a:shade{val=100000},a:satM" + "od{val=130000}),a:gs{pos=100000}/a:schemeClr{val=accent1}/(a:ti" + "nt{val=50000},a:shade{val=100000},a:satMod{val=350000})),a:lin{" + "scaled=0})" + ) + return fill, _GradFill_, expected_xml, grad_fill_ + + @pytest.fixture + def pattern_get_fixture(self, fill_): + expected_value = fill_.pattern = MSO_PATTERN.WAVE + fill = FillFormat(None, fill_) + return fill, expected_value + + @pytest.fixture + def pattern_set_fixture(self, fill_): + pattern = MSO_PATTERN.DIVOT + fill = FillFormat(None, fill_) + return fill, pattern + + @pytest.fixture( + params=[ + ("p:spPr{a:b=c}", "p:spPr{a:b=c}/a:pattFill"), + ("a:tcPr/a:blipFill", "a:tcPr/a:pattFill"), + ("a:rPr/a:gradFill", "a:rPr/a:pattFill"), + ("a:tcPr/a:grpFill", "a:tcPr/a:pattFill"), + ("a:defRPr/a:noFill", "a:defRPr/a:pattFill"), + ("a:endParaRPr/a:pattFill", "a:endParaRPr/a:pattFill"), + ("a:rPr/a:solidFill", "a:rPr/a:pattFill"), + ] + ) + def patterned_fixture(self, request, patt_fill_): + cxml, expected_cxml = request.param + + fill = FillFormat.from_fill_parent(element(cxml)) + # --mock must be after FillFormat call to avoid poss. contructor call + _PattFill_ = class_mock( + request, "pptx.dml.fill._PattFill", return_value=patt_fill_, autospec=True + ) + expected_xml = xml(expected_cxml) + return fill, _PattFill_, expected_xml, patt_fill_ + + @pytest.fixture( + params=[ + ("p:spPr{a:b=c}", "p:spPr{a:b=c}/a:solidFill"), + ("a:tcPr/a:blipFill", "a:tcPr/a:solidFill"), + ("a:rPr/a:gradFill", "a:rPr/a:solidFill"), + ("a:tcPr/a:grpFill", "a:tcPr/a:solidFill"), + ("a:defRPr/a:noFill", "a:defRPr/a:solidFill"), + ("a:rPr/a:pattFill", "a:rPr/a:solidFill"), + ("a:endParaRPr/a:solidFill", "a:endParaRPr/a:solidFill"), + ] + ) + def solid_fixture(self, request, solid_fill_): + cxml, expected_cxml = request.param + + fill = FillFormat.from_fill_parent(element(cxml)) + # --mock must be after FillFormat call to avoid poss. contructor call + _SolidFill_ = class_mock( + request, "pptx.dml.fill._SolidFill", return_value=solid_fill_, autospec=True + ) + expected_xml = xml(expected_cxml) + return fill, _SolidFill_, expected_xml, solid_fill_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def color_(self, request): + return instance_mock(request, ColorFormat) + + @pytest.fixture + def fill_(self, request): + return instance_mock(request, _Fill) + + @pytest.fixture + def grad_fill_(self, request): + return instance_mock(request, _GradFill) + + @pytest.fixture + def gradient_stops_(self, request): + return instance_mock(request, _GradientStops) + + @pytest.fixture + def no_fill_(self, request): + return instance_mock(request, _NoFill) + + @pytest.fixture + def patt_fill_(self, request): + return instance_mock(request, _PattFill) + + @pytest.fixture + def solid_fill_(self, request): + return instance_mock(request, _SolidFill) + + @pytest.fixture + def type_prop_(self, request): + return property_mock(request, FillFormat, "type") + + +class Describe_Fill(object): + def it_raises_on_fore_color_access(self, fore_raise_fixture): + fill, exception_type = fore_raise_fixture + with pytest.raises(exception_type): + fill.fore_color + + def it_raises_on_back_color_access(self, back_raise_fixture): + fill, exception_type = back_raise_fixture + with pytest.raises(exception_type): + fill.back_color + + def it_raises_on_pattern_access(self, pattern_raise_fixture): + fill, exception_type = pattern_raise_fixture + with pytest.raises(exception_type): + fill.pattern + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def back_raise_fixture(self): + fill = _Fill("foobar") + exception_type = TypeError + return fill, exception_type + + @pytest.fixture + def fore_raise_fixture(self): + fill = _Fill("foobar") + exception_type = TypeError + return fill, exception_type + + @pytest.fixture + def pattern_raise_fixture(self): + fill = _Fill("barfoo") + exception_type = TypeError + return fill, exception_type + + +class Describe_BlipFill(object): + def it_knows_its_fill_type(self, fill_type_fixture): + blip_fill, expected_value = fill_type_fixture + fill_type = blip_fill.type + assert fill_type == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def fill_type_fixture(self): + xFill = element("a:blipFill") + blip_fill = _BlipFill(xFill) + expected_value = MSO_FILL.PICTURE + return blip_fill, expected_value + + +class Describe_GradFill(object): + def it_knows_the_gradient_angle(self, angle_fixture): + grad_fill, expected_value = angle_fixture + angle = grad_fill.gradient_angle + assert angle == expected_value + + def it_can_change_the_gradient_angle(self, angle_set_fixture): + grad_fill, angle, expected_xml = angle_set_fixture + grad_fill.gradient_angle = angle + assert grad_fill._gradFill.xml == expected_xml + + def it_provides_access_to_the_gradient_stops(self, stops_fixture): + grad_fill, _GradientStops_ = stops_fixture[:2] + expected_xml, gradient_stops_ = stops_fixture[2:] + + gradient_stops = grad_fill.gradient_stops + + gradFill = grad_fill._gradFill + _GradientStops_.assert_called_once_with(gradFill[0]) + assert gradFill.xml == expected_xml + assert gradient_stops is gradient_stops_ + + def it_raises_on_non_linear_gradient(self): + gradFill = element("a:gradFill/a:path") + grad_fill = _GradFill(gradFill) + with pytest.raises(ValueError): + grad_fill.gradient_angle + with pytest.raises(ValueError): + grad_fill.gradient_angle = 43.21 + + def it_knows_its_fill_type(self, fill_type_fixture): + grad_fill, expected_value = fill_type_fixture + fill_type = grad_fill.type + assert fill_type == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("a:gradFill", None), + ("a:gradFill/a:lin{ang=0}", 0.0), + ("a:gradFill/a:lin{ang=2730000}", 314.5), + ("a:gradFill/a:lin{ang=16200000}", 90.0), + ] + ) + def angle_fixture(self, request): + cxml, expected_value = request.param + grad_fill = _GradFill(element(cxml)) + return grad_fill, expected_value + + @pytest.fixture( + params=[ + (301.2, "a:gradFill/a:lin{ang=3528000}"), + (31.22, "a:gradFill/a:lin{ang=19726800}"), + (0, "a:gradFill/a:lin{ang=0}"), + (-460.0, "a:gradFill/a:lin{ang=6000000}"), + ] + ) + def angle_set_fixture(self, request): + angle, expected_cxml = request.param + grad_fill = _GradFill(element("a:gradFill/a:lin{ang=0}")) + expected_xml = xml(expected_cxml) + return grad_fill, angle, expected_xml + + @pytest.fixture + def fill_type_fixture(self): + xFill = element("a:gradFill") + grad_fill = _GradFill(xFill) + expected_value = MSO_FILL.GRADIENT + return grad_fill, expected_value + + @pytest.fixture( + params=[ + ("a:gradFill", "a:gradFill", True), + ("a:gradFill/a:gsLst", "a:gradFill/a:gsLst", False), + ] + ) + def stops_fixture(self, request, _GradientStops_, gradient_stops_): + gradFill_cxml, expected_cxml, add_gsLst = request.param + _GradientStops_.return_value = gradient_stops_ + grad_fill = _GradFill(element(gradFill_cxml)) + if add_gsLst: + expected_xml = xml( + expected_cxml + "/a:gsLst/(a:gs{pos=0}/a:schemeClr{val=accen" + "t1}/(a:tint{val=100000},a:shade{val=100000},a:satMod{val=13" + "0000}),a:gs{pos=100000}/a:schemeClr{val=accent1}/(a:tint{va" + "l=50000},a:shade{val=100000},a:satMod{val=350000}))" + ) + else: + expected_xml = xml(expected_cxml) + return grad_fill, _GradientStops_, expected_xml, gradient_stops_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _GradientStops_(self, request): + return class_mock(request, "pptx.dml.fill._GradientStops") + + @pytest.fixture + def gradient_stops_(self, request): + return instance_mock(request, _GradientStops) + + +class Describe_GrpFill(object): + def it_knows_its_fill_type(self, fill_type_fixture): + grp_fill, expected_value = fill_type_fixture + fill_type = grp_fill.type + assert fill_type == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def fill_type_fixture(self): + xFill = element("a:grpFill") + grp_fill = _GrpFill(xFill) + expected_value = MSO_FILL.GROUP + return grp_fill, expected_value + + +class Describe_NoFill(object): + def it_knows_its_fill_type(self, fill_type_fixture): + no_fill, expected_value = fill_type_fixture + fill_type = no_fill.type + assert fill_type == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def fill_type_fixture(self): + xFill = element("a:noFill") + no_fill = _NoFill(xFill) + expected_value = MSO_FILL.BACKGROUND + return no_fill, expected_value + + +class Describe_NoneFill(object): + def it_knows_its_fill_type(self, fill_type_fixture): + none_fill, expected_value = fill_type_fixture + fill_type = none_fill.type + assert fill_type == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def fill_type_fixture(self): + none_fill = _NoneFill(None) + expected_value = None + return none_fill, expected_value + + +class Describe_PattFill(object): + """Unit-test suite for `pptx.dml.fill._PattFill` objects.""" + + def it_knows_its_fill_type(self, fill_type_fixture): + patt_fill, expected_value = fill_type_fixture + fill_type = patt_fill.type + assert fill_type == expected_value + + def it_knows_its_pattern(self, pattern_get_fixture): + patt_fill, expected_value = pattern_get_fixture + pattern = patt_fill.pattern + assert pattern == expected_value + + def it_can_change_its_pattern(self, pattern_set_fixture): + patt_fill, pattern, pattFill, expected_xml = pattern_set_fixture + patt_fill.pattern = pattern + assert pattFill.xml == expected_xml + + def it_provides_access_to_its_foreground_color(self, fore_color_fixture): + patt_fill, pattFill, expected_xml, color_ = fore_color_fixture[:4] + ColorFormat_from_colorchoice_parent_ = fore_color_fixture[4] + + color = patt_fill.fore_color + + assert pattFill.xml == expected_xml + ColorFormat_from_colorchoice_parent_.assert_called_once_with(pattFill.fgClr) + assert color is color_ + + def it_provides_access_to_its_background_color(self, back_color_fixture): + patt_fill, pattFill, expected_xml, color_ = back_color_fixture[:4] + ColorFormat_from_colorchoice_parent_ = back_color_fixture[4] + + color = patt_fill.back_color + + assert pattFill.xml == expected_xml + ColorFormat_from_colorchoice_parent_.assert_called_once_with(pattFill.bgClr) + assert color is color_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("a:pattFill", "a:pattFill/a:bgClr/a:srgbClr{val=FFFFFF}"), + ("a:pattFill/a:bgClr", "a:pattFill/a:bgClr"), + ( + "a:pattFill/a:bgClr/a:schemeClr{val=accent1}", + "a:pattFill/a:bgClr/a:schemeClr{val=accent1}", + ), + ] + ) + def back_color_fixture(self, request, color_, ColorFormat_from_colorchoice_parent_): + pattFill_cxml, expected_cxml = request.param + pattFill = element(pattFill_cxml) + expected_xml = xml(expected_cxml) + ColorFormat_from_colorchoice_parent_.return_value = color_ + + patt_fill = _PattFill(pattFill) + return ( + patt_fill, + pattFill, + expected_xml, + color_, + ColorFormat_from_colorchoice_parent_, + ) + + @pytest.fixture( + params=[ + ("a:pattFill", "a:pattFill/a:fgClr/a:srgbClr{val=000000}"), + ("a:pattFill/a:fgClr", "a:pattFill/a:fgClr"), + ( + "a:pattFill/a:fgClr/a:schemeClr{val=accent2}", + "a:pattFill/a:fgClr/a:schemeClr{val=accent2}", + ), + ] + ) + def fore_color_fixture(self, request, color_, ColorFormat_from_colorchoice_parent_): + pattFill_cxml, expected_cxml = request.param + pattFill = element(pattFill_cxml) + expected_xml = xml(expected_cxml) + ColorFormat_from_colorchoice_parent_.return_value = color_ + + patt_fill = _PattFill(pattFill) + return ( + patt_fill, + pattFill, + expected_xml, + color_, + ColorFormat_from_colorchoice_parent_, + ) + + @pytest.fixture + def fill_type_fixture(self): + patt_fill = _PattFill(element("a:pattFill")) + expected_value = MSO_FILL.PATTERNED + return patt_fill, expected_value + + @pytest.fixture( + params=[ + ("a:pattFill", None), + ("a:pattFill{prst=diagCross}", MSO_PATTERN.DIAGONAL_CROSS), + ("a:pattFill{prst=wave}", MSO_PATTERN.WAVE), + ] + ) + def pattern_get_fixture(self, request): + pattFill_cxml, expected_value = request.param + pattFill = element(pattFill_cxml) + + patt_fill = _PattFill(pattFill) + return patt_fill, expected_value + + @pytest.fixture( + params=[ + ("a:pattFill", MSO_PATTERN.WAVE, "a:pattFill{prst=wave}"), + ("a:pattFill{prst=wave}", MSO_PATTERN.DIVOT, "a:pattFill{prst=divot}"), + ("a:pattFill{prst=divot}", None, "a:pattFill"), + ] + ) + def pattern_set_fixture(self, request): + pattFill_cxml, pattern, expected_cxml = request.param + pattFill = element(pattFill_cxml) + expected_xml = xml(expected_cxml) + + patt_fill = _PattFill(pattFill) + return patt_fill, pattern, pattFill, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def ColorFormat_from_colorchoice_parent_(self, request): + return method_mock(request, ColorFormat, "from_colorchoice_parent", autospec=False) + + @pytest.fixture + def color_(self, request): + return instance_mock(request, ColorFormat) + + +class Describe_SolidFill(object): + def it_knows_its_fill_type(self, fill_type_fixture): + solid_fill, expected_value = fill_type_fixture + fill_type = solid_fill.type + assert fill_type == expected_value + + def it_provides_access_to_its_foreground_color(self, fore_color_fixture): + solid_fill, solidFill, color_ = fore_color_fixture[:3] + ColorFormat_from_colorchoice_parent_ = fore_color_fixture[3] + + color = solid_fill.fore_color + + ColorFormat_from_colorchoice_parent_.assert_called_once_with(solidFill) + assert color is color_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def fill_type_fixture(self): + solid_fill = _SolidFill(element("a:solidFill")) + expected_value = MSO_FILL.SOLID + return solid_fill, expected_value + + @pytest.fixture + def fore_color_fixture(self, ColorFormat_from_colorchoice_parent_, color_): + ColorFormat_from_colorchoice_parent_.return_value = color_ + solidFill = element("a:solidFill") + + solid_fill = _SolidFill(solidFill) + return (solid_fill, solidFill, color_, ColorFormat_from_colorchoice_parent_) + + # fixture components --------------------------------------------- + + @pytest.fixture + def ColorFormat_from_colorchoice_parent_(self, request): + return method_mock(request, ColorFormat, "from_colorchoice_parent", autospec=False) + + @pytest.fixture + def color_(self, request): + return instance_mock(request, ColorFormat) + + +class Describe_GradientStops(object): + def it_provides_access_to_its_stops(self): + stops = _GradientStops(CT_GradientStopList.new_gsLst()) + + assert len(stops) == 2 + for stop in stops: + assert isinstance(stop, _GradientStop) + + +class Describe_GradientStop(object): + def it_provides_access_to_its_color(self, request): + gs = element("a:gs") + ColorFormat_ = class_mock(request, "pptx.dml.fill.ColorFormat") + color_ = instance_mock(request, ColorFormat) + ColorFormat_.from_colorchoice_parent.return_value = color_ + stop = _GradientStop(gs) + + color = stop.color + + ColorFormat_.from_colorchoice_parent.assert_called_once_with(gs) + assert color is color_ + + def it_knows_its_position(self, pos_get_fixture): + stop, expected_value = pos_get_fixture + position = stop.position + assert position == expected_value + + def it_can_change_its_position(self, pos_set_fixture): + stop, new_value, expected_value = pos_set_fixture + stop.position = new_value + assert stop.position == expected_value + + def it_raises_on_position_out_of_range(self, raises_fixture): + stop, out_of_range_value = raises_fixture + with pytest.raises(ValueError): + stop.position = out_of_range_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("a:gs{pos=0}", 0.0), + ("a:gs{pos=42240}", 0.4224), + ("a:gs{pos=100000}", 1.0), + ] + ) + def pos_get_fixture(self, request): + gs_cxml, expected_value = request.param + stop = _GradientStop(element(gs_cxml)) + return stop, expected_value + + @pytest.fixture( + params=[ + ("a:gs{pos=0}", 0.42, 0.42), + ("a:gs{pos=42000}", 1.0, 1.0), + ("a:gs{pos=100000}", 0.0, 0.0), + ] + ) + def pos_set_fixture(self, request): + gs_cxml, new_value, expected_value = request.param + stop = _GradientStop(element(gs_cxml)) + return stop, new_value, expected_value + + @pytest.fixture(params=[-0.42, 1.001]) + def raises_fixture(self, request): + out_of_range_value = request.param + stop = _GradientStop(element("a:gs{pos=50000}")) + return stop, out_of_range_value diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_line.py b/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_line.py new file mode 100644 index 0000000000000000000000000000000000000000..158e55589f78051890b0ea371877d70c00d66909 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/dml/test_line.py @@ -0,0 +1,168 @@ +"""Test suite for `pptx.dml.line` module.""" + +from __future__ import annotations + +import pytest + +from pptx.dml.color import ColorFormat +from pptx.dml.fill import FillFormat +from pptx.dml.line import LineFormat +from pptx.enum.dml import MSO_FILL, MSO_LINE +from pptx.oxml.shapes.shared import CT_LineProperties +from pptx.shapes.autoshape import Shape + +from ..oxml.unitdata.dml import an_ln +from ..unitutil.cxml import element, xml +from ..unitutil.mock import call, class_mock, instance_mock, property_mock + + +class DescribeLineFormat(object): + def it_knows_its_dash_style(self, dash_style_get_fixture): + line, expected_value = dash_style_get_fixture + assert line.dash_style == expected_value + + @pytest.mark.parametrize( + ("spPr_cxml", "dash_style", "expected_cxml"), + [ + ("p:spPr{a:b=c}", MSO_LINE.DASH, "p:spPr{a:b=c}/a:ln/a:prstDash{val=dash}"), + ("p:spPr/a:ln", MSO_LINE.ROUND_DOT, "p:spPr/a:ln/a:prstDash{val=sysDot}"), + ( + "p:spPr/a:ln/a:prstDash", + MSO_LINE.SOLID, + "p:spPr/a:ln/a:prstDash{val=solid}", + ), + ( + "p:spPr/a:ln/a:custDash", + MSO_LINE.DASH_DOT, + "p:spPr/a:ln/a:prstDash{val=dashDot}", + ), + ( + "p:spPr/a:ln/a:prstDash{val=dash}", + MSO_LINE.LONG_DASH, + "p:spPr/a:ln/a:prstDash{val=lgDash}", + ), + ("p:spPr/a:ln/a:prstDash{val=dash}", None, "p:spPr/a:ln"), + ("p:spPr/a:ln/a:custDash", None, "p:spPr/a:ln"), + ], + ) + def it_can_change_its_dash_style( + self, spPr_cxml: str, dash_style: MSO_LINE, expected_cxml: str + ): + spPr = element(spPr_cxml) + line = LineFormat(spPr) + + line.dash_style = dash_style + + assert spPr.xml == xml(expected_cxml) + + def it_knows_its_width(self, width_get_fixture): + line, expected_line_width = width_get_fixture + assert line.width == expected_line_width + + def it_can_change_its_width(self, width_set_fixture): + line, width, expected_xml = width_set_fixture + line.width = width + assert line._ln.xml == expected_xml + + def it_has_a_fill(self, fill_fixture): + line, FillFormat_, ln_, fill_ = fill_fixture + fill = line.fill + FillFormat_.from_fill_parent.assert_called_once_with(ln_) + assert fill is fill_ + + def it_has_a_color(self, color_fixture): + line, fill_, expected_solid_calls, color_ = color_fixture + color = line.color + assert fill_.solid.mock_calls == expected_solid_calls + assert color is color_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=[(MSO_FILL.SOLID, False), (MSO_FILL.BACKGROUND, True), (None, True)]) + def color_fixture(self, request, line, fill_prop_, fill_, color_): + pre_call_fill_type, solid_call_expected = request.param + fill_.type = pre_call_fill_type + expected_solid_calls = [call()] if solid_call_expected else [] + return line, fill_, expected_solid_calls, color_ + + @pytest.fixture( + params=[ + ("p:spPr", None), + ("p:spPr/a:ln", None), + ("p:spPr/a:ln/a:prstDash", None), + ("p:spPr/a:ln/a:prstDash{val=dash}", MSO_LINE.DASH), + ("p:spPr/a:ln/a:prstDash{val=solid}", MSO_LINE.SOLID), + ] + ) + def dash_style_get_fixture(self, request): + spPr_cxml, expected_value = request.param + spPr = element(spPr_cxml) + line = LineFormat(spPr) + return line, expected_value + + @pytest.fixture + def fill_fixture(self, line, FillFormat_, ln_, fill_): + return line, FillFormat_, ln_, fill_ + + @pytest.fixture(params=[(None, 0), (12700, 12700)]) + def width_get_fixture(self, request, shape_): + w, expected_line_width = request.param + shape_.ln = self.ln_bldr(w).element + line = LineFormat(shape_) + return line, expected_line_width + + @pytest.fixture( + params=[ + (None, None), + (None, 12700), + (12700, 12700), + (12700, 25400), + (25400, None), + ] + ) + def width_set_fixture(self, request, shape_): + initial_width, width = request.param + shape_.ln = shape_.get_or_add_ln.return_value = self.ln_bldr(initial_width).element + line = LineFormat(shape_) + expected_xml = self.ln_bldr(width).xml() + return line, width, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def color_(self, request): + return instance_mock(request, ColorFormat) + + @pytest.fixture + def fill_(self, request, color_): + return instance_mock(request, FillFormat, fore_color=color_) + + @pytest.fixture + def fill_prop_(self, request, fill_): + return property_mock(request, LineFormat, "fill", return_value=fill_) + + @pytest.fixture + def FillFormat_(self, request, fill_): + FillFormat_ = class_mock(request, "pptx.dml.line.FillFormat") + FillFormat_.from_fill_parent.return_value = fill_ + return FillFormat_ + + @pytest.fixture + def line(self, shape_): + return LineFormat(shape_) + + @pytest.fixture + def ln_(self, request): + return instance_mock(request, CT_LineProperties) + + def ln_bldr(self, w): + ln_bldr = an_ln().with_nsdecls() + if w is not None: + ln_bldr.with_w(w) + return ln_bldr + + @pytest.fixture + def shape_(self, request, ln_): + shape_ = instance_mock(request, Shape) + shape_.get_or_add_ln.return_value = ln_ + return shape_ diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/enum/__init__.py b/tasks/tasksmith-74f059424102/environment/source/tests/enum/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/enum/test_base.py b/tasks/tasksmith-74f059424102/environment/source/tests/enum/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..3b4e970a7d58812b5e5ebc22c4572d85087c83b5 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/enum/test_base.py @@ -0,0 +1,73 @@ +"""Unit-test suite for `pptx.enum.base`.""" + +from __future__ import annotations + +import pytest + +from pptx.enum.action import PP_ACTION, PP_ACTION_TYPE +from pptx.enum.dml import MSO_LINE_DASH_STYLE + + +class DescribeBaseEnum: + """Unit-test suite for `pptx.enum.base.BaseEnum`.""" + + def it_produces_members_each_equivalent_to_an_integer_value(self): + assert PP_ACTION_TYPE.END_SHOW == 6 + assert PP_ACTION_TYPE.NONE == 0 + + def but_member_reprs_are_a_str_indicating_the_enum_and_member_name(self): + assert repr(PP_ACTION_TYPE.END_SHOW) == "" + assert repr(PP_ACTION_TYPE.RUN_MACRO) == "" + + def and_member_str_values_are_a_str_indicating_the_member_name(self): + assert str(PP_ACTION_TYPE.FIRST_SLIDE) == "FIRST_SLIDE (3)" + assert str(PP_ACTION_TYPE.HYPERLINK) == "HYPERLINK (7)" + + def it_provides_a_docstring_for_each_member(self): + assert PP_ACTION_TYPE.LAST_SLIDE.__doc__ == "Moves to the last slide." + assert PP_ACTION_TYPE.LAST_SLIDE_VIEWED.__doc__ == "Moves to the last slide viewed." + + def it_can_look_up_a_member_by_its_value(self): + assert PP_ACTION_TYPE(10) == PP_ACTION_TYPE.NAMED_SLIDE_SHOW + assert PP_ACTION_TYPE(101) == PP_ACTION_TYPE.NAMED_SLIDE + + def but_it_raises_when_no_member_has_that_value(self): + with pytest.raises(ValueError, match="42 is not a valid PP_ACTION_TYPE"): + PP_ACTION_TYPE(42) + + def it_knows_its_name(self): + assert PP_ACTION_TYPE.NEXT_SLIDE.name == "NEXT_SLIDE" + assert PP_ACTION_TYPE.NONE.name == "NONE" + + def it_can_be_referred_to_by_a_convenience_alias_if_defined(self): + assert PP_ACTION_TYPE.OPEN_FILE is PP_ACTION.OPEN_FILE + + +class DescribeBaseXmlEnum: + """Unit-test suite for `pptx.enum.base.BaseXmlEnum`.""" + + def it_can_look_up_a_member_by_its_corresponding_XML_attribute_value(self): + assert MSO_LINE_DASH_STYLE.from_xml("dash") == MSO_LINE_DASH_STYLE.DASH + assert MSO_LINE_DASH_STYLE.from_xml("dashDot") == MSO_LINE_DASH_STYLE.DASH_DOT + + def but_it_raises_on_an_attribute_value_that_is_not_regitstered(self): + with pytest.raises(ValueError, match="MSO_LINE_DASH_STYLE has no XML mapping for 'wavy'"): + MSO_LINE_DASH_STYLE.from_xml("wavy") + + def and_the_empty_string_never_maps_to_a_member(self): + with pytest.raises(ValueError, match="MSO_LINE_DASH_STYLE has no XML mapping for ''"): + MSO_LINE_DASH_STYLE.from_xml("") + + def it_knows_the_XML_attribute_value_for_each_member_that_has_one(self): + assert MSO_LINE_DASH_STYLE.to_xml(MSO_LINE_DASH_STYLE.SOLID) == "solid" + + def and_it_looks_up_the_member_by_int_value_before_mapping_when_provided_that_way(self): + assert MSO_LINE_DASH_STYLE.to_xml(3) == "sysDot" + + def but_it_raises_when_no_member_has_the_provided_int_value(self): + with pytest.raises(ValueError, match="42 is not a valid MSO_LINE_DASH_STYLE"): + MSO_LINE_DASH_STYLE.to_xml(42) + + def and_it_raises_when_the_member_has_no_XML_value(self): + with pytest.raises(ValueError, match="MSO_LINE_DASH_STYLE.DASH_STYLE_MIXED has no XML r"): + MSO_LINE_DASH_STYLE.to_xml(-2) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/enum/test_shapes.py b/tasks/tasksmith-74f059424102/environment/source/tests/enum/test_shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..5bfac69667b73887baea90937e6428e5f5df0e02 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/enum/test_shapes.py @@ -0,0 +1,46 @@ +"""Unit-test suite for `pptx.enum.shapes`.""" + +from __future__ import annotations + +import pytest + +from pptx.enum.shapes import PROG_ID + + +class DescribeProgId: + """Unit-test suite for `pptx.enum.shapes.ProgId`.""" + + def it_has_members_for_the_OLE_embeddings_known_to_work_on_Windows(self): + assert PROG_ID.DOCX + assert PROG_ID.PPTX + assert PROG_ID.XLSX + + @pytest.mark.parametrize( + ("member", "expected_value"), + [(PROG_ID.DOCX, 609600), (PROG_ID.PPTX, 609600), (PROG_ID.XLSX, 609600)], + ) + def it_knows_its_height(self, member: PROG_ID, expected_value: int): + assert member.height == expected_value + + def it_knows_its_icon_filename(self): + assert PROG_ID.DOCX.icon_filename == "docx-icon.emf" + + def it_knows_its_progId(self): + assert PROG_ID.PPTX.progId == "PowerPoint.Show.12" + + def it_knows_its_width(self): + assert PROG_ID.XLSX.width == 965200 + + @pytest.mark.parametrize( + ("value", "expected_value"), + [ + # -DELETEME--------------------------------------------------------------- + (PROG_ID.DOCX, True), + (PROG_ID.PPTX, True), + (PROG_ID.XLSX, True), + (17, False), + ("XLSX", False), + ], + ) + def it_knows_each_of_its_members_is_an_instance(self, value: object, expected_value: bool): + assert isinstance(value, PROG_ID) is expected_value diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/opc/__init__.py b/tasks/tasksmith-74f059424102/environment/source/tests/opc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_oxml.py b/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_oxml.py new file mode 100644 index 0000000000000000000000000000000000000000..5dee9408bbeac6aa5376a7f579a6550c9ef9dab2 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_oxml.py @@ -0,0 +1,211 @@ +"""Unit-test suite for `pptx.opc.oxml` module.""" + +from __future__ import annotations + +from typing import cast + +import pytest + +from pptx.opc.constants import RELATIONSHIP_TARGET_MODE as RTM +from pptx.opc.oxml import ( + CT_Default, + CT_Override, + CT_Relationship, + CT_Relationships, + CT_Types, + nsmap, + oxml_tostring, + serialize_part_xml, +) +from pptx.opc.packuri import PackURI +from pptx.oxml import parse_xml +from pptx.oxml.xmlchemy import BaseOxmlElement + +from ..unitutil.cxml import element + + +class DescribeCT_Default: + """Unit-test suite for `pptx.opc.oxml.CT_Default` objects.""" + + def it_provides_read_access_to_xml_values(self): + default = cast(CT_Default, element("ct:Default{Extension=xml,ContentType=application/xml}")) + assert default.extension == "xml" + assert default.contentType == "application/xml" + + +class DescribeCT_Override: + """Unit-test suite for `pptx.opc.oxml.CT_Override` objects.""" + + def it_provides_read_access_to_xml_values(self): + override = cast( + CT_Override, element("ct:Override{PartName=/part/name.xml,ContentType=text/plain}") + ) + assert override.partName == "/part/name.xml" + assert override.contentType == "text/plain" + + +class DescribeCT_Relationship: + """Unit-test suite for `pptx.opc.oxml.CT_Relationship` objects.""" + + def it_provides_read_access_to_xml_values(self): + rel = cast( + CT_Relationship, + element("pr:Relationship{Id=rId9,Type=ReLtYpE,Target=docProps/core.xml}"), + ) + assert rel.rId == "rId9" + assert rel.reltype == "ReLtYpE" + assert rel.target_ref == "docProps/core.xml" + assert rel.targetMode == RTM.INTERNAL + + def it_constructs_an_internal_relationship_when_no_target_mode_is_provided(self): + rel = CT_Relationship.new("rId9", "ReLtYpE", "foo/bar.xml") + + assert rel.rId == "rId9" + assert rel.reltype == "ReLtYpE" + assert rel.target_ref == "foo/bar.xml" + assert rel.targetMode == RTM.INTERNAL + assert rel.xml == ( + f'' + ) + + def and_it_constructs_an_internal_relationship_when_target_mode_INTERNAL_is_specified(self): + rel = CT_Relationship.new("rId9", "ReLtYpE", "foo/bar.xml", RTM.INTERNAL) + + assert rel.rId == "rId9" + assert rel.reltype == "ReLtYpE" + assert rel.target_ref == "foo/bar.xml" + assert rel.targetMode == RTM.INTERNAL + assert rel.xml == ( + f'' + ) + + def and_it_constructs_an_external_relationship_when_target_mode_EXTERNAL_is_specified(self): + rel = CT_Relationship.new("rId9", "ReLtYpE", "http://some/link", RTM.EXTERNAL) + + assert rel.rId == "rId9" + assert rel.reltype == "ReLtYpE" + assert rel.target_ref == "http://some/link" + assert rel.targetMode == RTM.EXTERNAL + assert rel.xml == ( + f'' + ) + + +class DescribeCT_Relationships: + """Unit-test suite for `pptx.opc.oxml.CT_Relationships` objects.""" + + def it_can_construct_a_new_relationships_element(self): + rels = CT_Relationships.new() + assert rels.xml == ( + '' + ) + + def it_can_build_rels_element_incrementally(self): + rels = CT_Relationships.new() + + rels.add_rel("rId1", "http://reltype1", "docProps/core.xml") + rels.add_rel("rId2", "http://linktype", "http://some/link", True) + rels.add_rel("rId3", "http://reltype2", "../slides/slide1.xml") + + assert oxml_tostring(rels, encoding="unicode", pretty_print=True) == ( + '\n' + ' \n' + ' \n' + ' \n' + "\n" + ) + + def it_can_generate_rels_file_xml(self): + assert CT_Relationships.new().xml_file_bytes == ( + "\n" + ''.encode("utf-8") + ) + + +class DescribeCT_Types: + """Unit-test suite for `pptx.opc.oxml.CT_Types` objects.""" + + def it_provides_access_to_default_child_elements(self, types: CT_Types): + assert len(types.default_lst) == 2 + for default in types.default_lst: + assert isinstance(default, CT_Default) + + def it_provides_access_to_override_child_elements(self, types: CT_Types): + assert len(types.override_lst) == 3 + for override in types.override_lst: + assert isinstance(override, CT_Override) + + def it_should_have_empty_list_on_no_matching_elements(self): + types = cast(CT_Types, element("ct:Types")) + assert types.default_lst == [] + assert types.override_lst == [] + + def it_can_construct_a_new_types_element(self): + types = CT_Types.new() + assert types.xml == ( + '\n' + ) + + def it_can_build_types_element_incrementally(self): + types = CT_Types.new() + types.add_default("xml", "application/xml") + types.add_default("jpeg", "image/jpeg") + types.add_override(PackURI("/docProps/core.xml"), "app/vnd.type1") + types.add_override(PackURI("/ppt/presentation.xml"), "app/vnd.type2") + types.add_override(PackURI("/docProps/thumbnail.jpeg"), "image/jpeg") + assert types.xml == ( + '\n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + "\n" + ) + + # -- fixtures ---------------------------------------------------- + + @pytest.fixture + def types(self) -> CT_Types: + return cast( + CT_Types, + element( + "ct:Types/(ct:Default{Extension=xml,ContentType=application/xml}" + ",ct:Default{Extension=jpeg,ContentType=image/jpeg}" + ",ct:Override{PartName=/docProps/core.xml,ContentType=app/vnd.type1}" + ",ct:Override{PartName=/ppt/presentation.xml,ContentType=app/vnd.type2}" + ",ct:Override{PartName=/docProps/thunbnail.jpeg,ContentType=image/jpeg})" + ), + ) + + +class Describe_serialize_part_xml: + """Unit-test suite for `pptx.opc.oxml.serialize_part_xml` function.""" + + def it_produces_properly_formatted_xml_for_an_opc_part(self): + """ + Tested aspects: + --------------- + * [X] it generates an XML declaration + * [X] it produces no whitespace between elements + * [X] it preserves unused namespaces + * [X] it returns bytes ready to save to file (not unicode) + """ + part_elm = cast( + BaseOxmlElement, + parse_xml( + '\n fØØ' + "bÅr\n\n" + ), + ) + xml = serialize_part_xml(part_elm) + # xml contains 134 chars, of which 3 are double-byte; it will have + # len of 134 if it's unicode and 137 if it's bytes + assert len(xml) == 137 + assert xml == ( + "\n" + 'fØØbÅr' + ).encode("utf-8") diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_package.py b/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_package.py new file mode 100644 index 0000000000000000000000000000000000000000..8c0e95809925cceec009d7eb92aba54ab2df38a4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_package.py @@ -0,0 +1,1031 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.opc.package` module.""" + +from __future__ import annotations + +import collections +import io +import itertools +from typing import Any + +import pytest + +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.opc.constants import RELATIONSHIP_TARGET_MODE as RTM +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.oxml import CT_Relationship, CT_Relationships +from pptx.opc.package import ( + OpcPackage, + Part, + PartFactory, + XmlPart, + _ContentTypeMap, + _PackageLoader, + _RelatableMixin, + _Relationship, + _Relationships, +) +from pptx.opc.packuri import PACKAGE_URI, PackURI +from pptx.oxml import parse_xml +from pptx.parts.presentation import PresentationPart + +from ..unitutil.cxml import element +from ..unitutil.file import absjoin, snippet_bytes, test_file_dir, testfile_bytes +from ..unitutil.mock import ( + ANY, + FixtureRequest, + Mock, + call, + class_mock, + function_mock, + initializer_mock, + instance_mock, + method_mock, + property_mock, +) + + +class Describe_RelatableMixin: + """Unit-test suite for `pptx.opc.package._RelatableMixin`. + + This mixin is used for both OpcPackage and Part because both a package and a part + can have relationships to target parts. + """ + + def it_can_find_a_part_related_by_reltype(self, _rels_prop_, relationships_, part_): + relationships_.part_with_reltype.return_value = part_ + _rels_prop_.return_value = relationships_ + mixin = _RelatableMixin() + + related_part = mixin.part_related_by(RT.CHART) + + relationships_.part_with_reltype.assert_called_once_with(RT.CHART) + assert related_part is part_ + + def it_can_establish_a_relationship_to_another_part(self, _rels_prop_, relationships_, part_): + relationships_.get_or_add.return_value = "rId42" + _rels_prop_.return_value = relationships_ + mixin = _RelatableMixin() + + rId = mixin.relate_to(part_, RT.SLIDE) + + relationships_.get_or_add.assert_called_once_with(RT.SLIDE, part_) + assert rId == "rId42" + + def and_it_can_establish_a_relationship_to_an_external_link( + self, request, _rels_prop_, relationships_ + ): + relationships_.get_or_add_ext_rel.return_value = "rId24" + _rels_prop_.return_value = relationships_ + mixin = _RelatableMixin() + + rId = mixin.relate_to("http://url", RT.HYPERLINK, is_external=True) + + relationships_.get_or_add_ext_rel.assert_called_once_with(RT.HYPERLINK, "http://url") + assert rId == "rId24" + + def it_can_find_a_related_part_by_rId( + self, request, _rels_prop_, relationships_, relationship_, part_ + ): + _rels_prop_.return_value = relationships_ + relationships_.__getitem__.return_value = relationship_ + relationship_.target_part = part_ + mixin = _RelatableMixin() + + related_part = mixin.related_part("rId17") + + relationships_.__getitem__.assert_called_once_with("rId17") + assert related_part is part_ + + def it_can_find_a_target_ref_URI_by_rId( + self, request, _rels_prop_, relationships_, relationship_ + ): + _rels_prop_.return_value = relationships_ + relationships_.__getitem__.return_value = relationship_ + relationship_.target_ref = "http://url" + mixin = _RelatableMixin() + + target_ref = mixin.target_ref("rId9") + + relationships_.__getitem__.assert_called_once_with("rId9") + assert target_ref == "http://url" + + # fixture components ----------------------------------- + + @pytest.fixture + def part_(self, request): + return instance_mock(request, Part) + + @pytest.fixture + def relationship_(self, request): + return instance_mock(request, _Relationship) + + @pytest.fixture + def relationships_(self, request): + return instance_mock(request, _Relationships) + + @pytest.fixture + def _rels_prop_(self, request): + return property_mock(request, _RelatableMixin, "_rels") + + +class DescribeOpcPackage: + """Unit-test suite for `pptx.opc.package.OpcPackage` objects.""" + + def it_can_open_a_pkg_file(self, request): + package_ = instance_mock(request, OpcPackage) + _init_ = initializer_mock(request, OpcPackage) + _load_ = method_mock(request, OpcPackage, "_load", return_value=package_) + + package = OpcPackage.open("package.pptx") + + _init_.assert_called_once_with(ANY, "package.pptx") + _load_.assert_called_once_with(ANY) + assert package is package_ + + def it_can_drop_a_relationship(self, _rels_prop_, relationships_): + _rels_prop_.return_value = relationships_ + + OpcPackage(None).drop_rel("rId42") + + relationships_.pop.assert_called_once_with("rId42") + + def it_can_iterate_over_its_parts(self, request): + part_, part_2_ = [instance_mock(request, Part, name="part_%d" % i) for i in range(2)] + rels_iter = ( + instance_mock(request, _Relationship, is_external=is_external, target_part=target) + for is_external, target in ( + (True, "http://some/url/"), + (False, part_), + (False, part_), + (False, part_2_), + (False, part_), + (False, part_2_), + ) + ) + method_mock(request, OpcPackage, "iter_rels", return_value=rels_iter) + package = OpcPackage(None) + + assert list(package.iter_parts()) == [part_, part_2_] + + def it_can_iterate_over_its_relationships(self, request, _rels_prop_): + """ + +----------+ +--------+ + | pkg_rels |-- r0 --> | part_0 | + +----------+ +--------+ + | | | ^ + r2 | | r1 r3 | | r4 + | | | | + v | v | + external | +--------+ + +--------> | part_1 | + +--------+ + """ + part_0_, part_1_ = [instance_mock(request, Part, name="part_%d" % i) for i in range(2)] + all_rels = tuple( + instance_mock( + request, + _Relationship, + name="r%d" % i, + is_external=ext, + target_part=part, + ) + for i, (ext, part) in enumerate( + ( + (False, part_0_), + (False, part_1_), + (True, None), + (False, part_1_), + (False, part_0_), + ) + ) + ) + _rels_prop_.return_value = {r.rId: r for r in all_rels[:3]} + part_0_.rels = {r.rId: r for r in all_rels[3:4]} + part_1_.rels = {r.rId: r for r in all_rels[4:]} + package = OpcPackage(None) + + rels = set(package.iter_rels()) + + # -- sequence is not guaranteed, but count (len) and uniqueness are -- + assert rels == set(all_rels) + + def it_provides_access_to_the_main_document_part(self, request): + presentation_part_ = instance_mock(request, PresentationPart) + part_related_by_ = method_mock( + request, OpcPackage, "part_related_by", return_value=presentation_part_ + ) + package = OpcPackage(None) + + presentation_part = package.main_document_part + + part_related_by_.assert_called_once_with(package, RT.OFFICE_DOCUMENT) + assert presentation_part is presentation_part_ + + @pytest.mark.parametrize( + "ns, expected_n", (((), 1), ((1,), 2), ((1, 2), 3), ((2, 4), 3), ((1, 4), 3)) + ) + def it_can_find_the_next_available_partname(self, request, ns, expected_n): + tmpl = "/x%d.xml" + method_mock( + request, + OpcPackage, + "iter_parts", + return_value=(instance_mock(request, Part, partname=tmpl % n) for n in ns), + ) + next_partname = tmpl % expected_n + PackURI_ = class_mock( + request, "pptx.opc.package.PackURI", return_value=PackURI(next_partname) + ) + package = OpcPackage(None) + + partname = package.next_partname(tmpl) + + PackURI_.assert_called_once_with(next_partname) + assert partname == next_partname + + def it_can_save_to_a_pkg_file(self, request, _rels_prop_, relationships_): + _rels_prop_.return_value = relationships_ + parts_ = tuple(instance_mock(request, Part) for _ in range(3)) + method_mock(request, OpcPackage, "iter_parts", return_value=iter(parts_)) + PackageWriter_ = class_mock(request, "pptx.opc.package.PackageWriter") + package = OpcPackage(None) + + package.save("prs.pptx") + + PackageWriter_.write.assert_called_once_with("prs.pptx", relationships_, parts_) + + def it_loads_the_pkg_file_to_help(self, request, _rels_prop_, relationships_): + _PackageLoader_ = class_mock(request, "pptx.opc.package._PackageLoader") + _PackageLoader_.load.return_value = "pkg-rels-xml", {"partname": "part"} + _rels_prop_.return_value = relationships_ + package = OpcPackage("prs.pptx") + + return_value = package._load() + + _PackageLoader_.load.assert_called_once_with("prs.pptx", package) + relationships_.load_from_xml.assert_called_once_with( + PACKAGE_URI, "pkg-rels-xml", {"partname": "part"} + ) + assert return_value is package + + def it_constructs_its_relationships_object_to_help(self, request, relationships_): + _Relationships_ = class_mock( + request, "pptx.opc.package._Relationships", return_value=relationships_ + ) + package = OpcPackage(None) + + rels = package._rels + + _Relationships_.assert_called_once_with(PACKAGE_URI.baseURI) + assert rels is relationships_ + + # fixture components ----------------------------------- + + @pytest.fixture + def relationships_(self, request): + return instance_mock(request, _Relationships) + + @pytest.fixture + def _rels_prop_(self, request): + return property_mock(request, OpcPackage, "_rels") + + +class Describe_PackageLoader: + """Unit-test suite for `pptx.opc.package._PackageLoader` objects.""" + + def it_provides_a_load_interface_classmethod(self, request, package_): + _init_ = initializer_mock(request, _PackageLoader) + pkg_xml_rels_ = element("r:Relationships") + _load_ = method_mock( + request, + _PackageLoader, + "_load", + return_value=(pkg_xml_rels_, {"partname": "part"}), + ) + + pkg_xml_rels, parts = _PackageLoader.load("prs.pptx", package_) + + _init_.assert_called_once_with(ANY, "prs.pptx", package_) + _load_.assert_called_once_with(ANY) + assert pkg_xml_rels is pkg_xml_rels_ + assert parts == {"partname": "part"} + + def it_loads_the_package_to_help(self, request, _xml_rels_prop_): + parts_ = { + "partname_%d" % n: instance_mock(request, Part, partname="partname_%d" % n) + for n in range(1, 4) + } + property_mock(request, _PackageLoader, "_parts", return_value=parts_) + rels_ = dict( + itertools.chain( + (("/", instance_mock(request, _Relationships)),), + (("partname_%d" % n, instance_mock(request, _Relationships)) for n in range(1, 4)), + ) + ) + _xml_rels_prop_.return_value = rels_ + package_loader = _PackageLoader(None, None) + + pkg_xml_rels, parts = package_loader._load() + + for part_ in parts_.values(): + part_.load_rels_from_xml.assert_called_once_with(rels_[part_.partname], parts_) + assert pkg_xml_rels is rels_["/"] + assert parts is parts_ + + def it_loads_the_xml_relationships_from_the_package_to_help(self, request): + pkg_xml_rels = parse_xml(snippet_bytes("package-rels-xml")) + prs_xml_rels = parse_xml(snippet_bytes("presentation-rels-xml")) + slide_xml_rels = CT_Relationships.new() + thumbnail_xml_rels = CT_Relationships.new() + core_xml_rels = CT_Relationships.new() + _xml_rels_for_ = method_mock( + request, + _PackageLoader, + "_xml_rels_for", + side_effect=iter( + ( + pkg_xml_rels, + prs_xml_rels, + slide_xml_rels, + thumbnail_xml_rels, + core_xml_rels, + ) + ), + ) + package_loader = _PackageLoader(None, None) + + xml_rels = package_loader._xml_rels + + # print(f"{_xml_rels_for_.call_args_list=}") + assert _xml_rels_for_.call_args_list == [ + call(package_loader, "/"), + call(package_loader, "/ppt/presentation.xml"), + call(package_loader, "/ppt/slides/slide1.xml"), + call(package_loader, "/docProps/thumbnail.jpeg"), + call(package_loader, "/docProps/core.xml"), + ] + assert xml_rels == { + "/": pkg_xml_rels, + "/ppt/presentation.xml": prs_xml_rels, + "/ppt/slides/slide1.xml": slide_xml_rels, + "/docProps/thumbnail.jpeg": thumbnail_xml_rels, + "/docProps/core.xml": core_xml_rels, + } + + # fixture components ----------------------------------- + + @pytest.fixture + def package_(self, request): + return instance_mock(request, OpcPackage) + + @pytest.fixture + def _xml_rels_prop_(self, request): + return property_mock(request, _PackageLoader, "_xml_rels") + + +class DescribePart: + """Unit-test suite for `pptx.opc.package.Part` objects.""" + + def it_can_be_constructed_by_PartFactory(self, request, package_): + partname_ = instance_mock(request, PackURI) + _init_ = initializer_mock(request, Part) + + part = Part.load(partname_, CT.PML_SLIDE, package_, b"blob") + + _init_.assert_called_once_with(part, partname_, CT.PML_SLIDE, package_, b"blob") + assert isinstance(part, Part) + + def it_uses_the_load_blob_as_its_blob(self): + assert Part(None, None, None, b"blob").blob == b"blob" + + def it_can_change_its_blob(self): + part = Part(None, None, None, b"old-blob") + part.blob = b"new-blob" + assert part.blob == b"new-blob" + + def it_knows_its_content_type(self): + assert Part(None, CT.PML_SLIDE, None).content_type == CT.PML_SLIDE + + def it_knows_the_package_it_belongs_to(self, package_): + assert Part(None, None, package_).package is package_ + + def it_knows_its_partname(self): + assert Part(PackURI("/part/name"), None, None).partname == PackURI("/part/name") + + def it_can_change_its_partname(self): + part = Part(PackURI("/old/part/name"), None, None) + part.partname = PackURI("/new/part/name") + assert part.partname == PackURI("/new/part/name") + + def it_provides_access_to_its_relationships_for_traversal(self, request, relationships_): + property_mock(request, Part, "_rels", return_value=relationships_) + assert Part(None, None, None).rels is relationships_ + + def it_can_load_a_blob_from_a_file_path_to_help(self): + path = absjoin(test_file_dir, "minimal.pptx") + with open(path, "rb") as f: + file_bytes = f.read() + part = Part(None, None, None, None) + + assert part._blob_from_file(path) == file_bytes + + def it_can_load_a_blob_from_a_file_like_object_to_help(self): + part = Part(None, None, None, None) + assert part._blob_from_file(io.BytesIO(b"012345")) == b"012345" + + def it_constructs_its_relationships_object_to_help(self, request, relationships_): + _Relationships_ = class_mock( + request, "pptx.opc.package._Relationships", return_value=relationships_ + ) + part = Part(PackURI("/ppt/slides/slide1.xml"), None, None) + + rels = part._rels + + _Relationships_.assert_called_once_with("/ppt/slides") + assert rels is relationships_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def package_(self, request): + return instance_mock(request, OpcPackage) + + @pytest.fixture + def relationships_(self, request): + return instance_mock(request, _Relationships) + + +class DescribeXmlPart: + """Unit-test suite for `pptx.opc.package.XmlPart` objects.""" + + def it_can_be_constructed_by_PartFactory(self, request): + partname = PackURI("/ppt/slides/slide1.xml") + element_ = element("p:sld") + package_ = instance_mock(request, OpcPackage) + parse_xml_ = function_mock(request, "pptx.opc.package.parse_xml", return_value=element_) + _init_ = initializer_mock(request, XmlPart) + + part = XmlPart.load(partname, CT.PML_SLIDE, package_, b"blob") + + parse_xml_.assert_called_once_with(b"blob") + _init_.assert_called_once_with(part, partname, CT.PML_SLIDE, package_, element_) + assert isinstance(part, XmlPart) + + def it_can_serialize_to_xml(self, request): + element_ = element("p:sld") + serialize_part_xml_ = function_mock(request, "pptx.opc.package.serialize_part_xml") + xml_part = XmlPart(None, None, None, element_) + + blob = xml_part.blob + + serialize_part_xml_.assert_called_once_with(element_) + assert blob is serialize_part_xml_.return_value + + @pytest.mark.parametrize(("ref_count", "calls"), [(2, []), (1, [call("rId42")])]) + def it_can_drop_a_relationship( + self, request: FixtureRequest, relationships_: Mock, ref_count: int, calls: list[Any] + ): + _rel_ref_count_ = method_mock(request, XmlPart, "_rel_ref_count", return_value=ref_count) + property_mock(request, XmlPart, "_rels", return_value=relationships_) + part = XmlPart(None, None, None, None) + + part.drop_rel("rId42") + + _rel_ref_count_.assert_called_once_with(part, "rId42") + assert relationships_.pop.call_args_list == calls + + def it_knows_it_is_the_part_for_its_child_objects(self): + xml_part = XmlPart(None, None, None, None) + assert xml_part.part is xml_part + + # -- fixtures ---------------------------------------------------- + + @pytest.fixture + def relationships_(self, request): + return instance_mock(request, _Relationships) + + +class DescribePartFactory: + """Unit-test suite for `pptx.opc.package.PartFactory` objects.""" + + def it_constructs_custom_part_type_for_registered_content_types(self, request, package_, part_): + SlidePart_ = class_mock(request, "pptx.opc.package.XmlPart") + SlidePart_.load.return_value = part_ + partname = PackURI("/ppt/slides/slide7.xml") + PartFactory.part_type_for[CT.PML_SLIDE] = SlidePart_ + + part = PartFactory(partname, CT.PML_SLIDE, package_, b"blob") + + SlidePart_.load.assert_called_once_with(partname, CT.PML_SLIDE, package_, b"blob") + assert part is part_ + + def it_constructs_part_using_default_class_when_no_custom_registered( + self, request, package_, part_ + ): + Part_ = class_mock(request, "pptx.opc.package.Part") + Part_.load.return_value = part_ + partname = PackURI("/bar/foo.xml") + + part = PartFactory(partname, CT.OFC_VML_DRAWING, package_, b"blob") + + Part_.load.assert_called_once_with(partname, CT.OFC_VML_DRAWING, package_, b"blob") + assert part is part_ + + # fixtures components ---------------------------------- + + @pytest.fixture + def package_(self, request): + return instance_mock(request, OpcPackage) + + @pytest.fixture + def part_(self, request): + return instance_mock(request, Part) + + +class Describe_ContentTypeMap: + """Unit-test suite for `pptx.opc.package._ContentTypeMap` objects.""" + + def it_can_construct_from_content_types_xml(self, request): + _init_ = initializer_mock(request, _ContentTypeMap) + content_types_xml = ( + '\n' + ' \n' + ' \n' + ' \n" + "\n" + ) + + ct_map = _ContentTypeMap.from_xml(content_types_xml) + + _init_.assert_called_once_with( + ct_map, + {"/ppt/presentation.xml": CT.PML_PRESENTATION_MAIN}, + {"png": CT.PNG, "xml": CT.XML}, + ) + + @pytest.mark.parametrize( + "partname, expected_value", + ( + ("/docProps/core.xml", CT.OPC_CORE_PROPERTIES), + ("/ppt/presentation.xml", CT.PML_PRESENTATION_MAIN), + ("/PPT/Presentation.XML", CT.PML_PRESENTATION_MAIN), + ("/ppt/viewprops.xml", CT.PML_VIEW_PROPS), + ), + ) + def it_matches_an_override_on_case_insensitive_partname( + self, content_type_map, partname, expected_value + ): + assert content_type_map[PackURI(partname)] == expected_value + + @pytest.mark.parametrize( + "partname, expected_value", + ( + ("/foo/bar.xml", CT.XML), + ("/FOO/BAR.Rels", CT.OPC_RELATIONSHIPS), + ("/foo/bar.jpeg", CT.JPEG), + ), + ) + def it_falls_back_to_case_insensitive_extension_default_match( + self, content_type_map, partname, expected_value + ): + assert content_type_map[PackURI(partname)] == expected_value + + def it_raises_KeyError_on_partname_not_found(self, content_type_map): + with pytest.raises(KeyError) as e: + content_type_map[PackURI("/!blat/rhumba.1x&")] + assert str(e.value) == ( + "\"no content-type for partname '/!blat/rhumba.1x&' " 'in [Content_Types].xml"' + ) + + def it_raises_TypeError_on_key_not_instance_of_PackURI(self, content_type_map): + with pytest.raises(TypeError) as e: + content_type_map["/part/name1.xml"] + assert str(e.value) == "_ContentTypeMap key must be , got str" + + # fixtures --------------------------------------------- + + @pytest.fixture(scope="class") + def content_type_map(self): + return _ContentTypeMap.from_xml(testfile_bytes("expanded_pptx", "[Content_Types].xml")) + + +class Describe_Relationships: + """Unit-test suite for `pptx.opc.package._Relationships` objects.""" + + @pytest.mark.parametrize("rId, expected_value", (("rId1", True), ("rId2", False))) + def it_knows_whether_it_contains_a_relationship_with_rId( + self, _rels_prop_, rId, expected_value + ): + _rels_prop_.return_value = {"rId1": None} + assert (rId in _Relationships(None)) is expected_value + + def it_has_dict_style_lookup_of_rel_by_rId(self, _rels_prop_, relationship_): + _rels_prop_.return_value = {"rId17": relationship_} + assert _Relationships(None)["rId17"] is relationship_ + + def but_it_raises_KeyError_when_no_relationship_has_rId(self, _rels_prop_): + _rels_prop_.return_value = {} + with pytest.raises(KeyError) as e: + _Relationships(None)["rId6"] + assert str(e.value) == "\"no relationship with key 'rId6'\"" + + def it_can_iterate_the_rIds_of_the_relationships_it_contains(self, request, _rels_prop_): + rels_ = set(instance_mock(request, _Relationship) for n in range(5)) + _rels_prop_.return_value = {"rId%d" % (i + 1): r for i, r in enumerate(rels_)} + relationships = _Relationships(None) + + for rId in relationships: + rels_.remove(relationships[rId]) + + assert len(rels_) == 0 + + def it_has_a_len(self, _rels_prop_): + _rels_prop_.return_value = {"a": 0, "b": 1} + assert len(_Relationships(None)) == 2 + + def it_can_add_a_relationship_to_a_target_part(self, part_, _get_matching_, _add_relationship_): + _get_matching_.return_value = None + _add_relationship_.return_value = "rId7" + relationships = _Relationships(None) + + rId = relationships.get_or_add(RT.IMAGE, part_) + + _get_matching_.assert_called_once_with(relationships, RT.IMAGE, part_) + _add_relationship_.assert_called_once_with(relationships, RT.IMAGE, part_) + assert rId == "rId7" + + def but_it_returns_an_existing_relationship_if_it_matches(self, part_, _get_matching_): + _get_matching_.return_value = "rId3" + relationships = _Relationships(None) + + rId = relationships.get_or_add(RT.IMAGE, part_) + + _get_matching_.assert_called_once_with(relationships, RT.IMAGE, part_) + assert rId == "rId3" + + def it_can_add_an_external_relationship_to_a_URI(self, _get_matching_, _add_relationship_): + _get_matching_.return_value = None + _add_relationship_.return_value = "rId2" + relationships = _Relationships(None) + + rId = relationships.get_or_add_ext_rel(RT.HYPERLINK, "http://url") + + _get_matching_.assert_called_once_with( + relationships, RT.HYPERLINK, "http://url", is_external=True + ) + _add_relationship_.assert_called_once_with( + relationships, RT.HYPERLINK, "http://url", is_external=True + ) + assert rId == "rId2" + + def but_it_returns_an_existing_external_relationship_if_it_matches(self, part_, _get_matching_): + _get_matching_.return_value = "rId10" + relationships = _Relationships(None) + + rId = relationships.get_or_add_ext_rel(RT.HYPERLINK, "http://url") + + _get_matching_.assert_called_once_with( + relationships, RT.HYPERLINK, "http://url", is_external=True + ) + assert rId == "rId10" + + def it_can_load_from_the_xml_in_a_rels_part(self, request, _Relationship_, part_): + rels_ = tuple( + instance_mock(request, _Relationship, rId="rId%d" % (i + 1)) for i in range(5) + ) + _Relationship_.from_xml.side_effect = iter(rels_) + parts = {"/ppt/slideLayouts/slideLayout1.xml": part_} + xml_rels = parse_xml(snippet_bytes("rels-load-from-xml")) + relationships = _Relationships(None) + + relationships.load_from_xml("/ppt/slides", xml_rels, parts) + + assert _Relationship_.from_xml.call_args_list == [ + call("/ppt/slides", xml_rels[0], parts), + call("/ppt/slides", xml_rels[1], parts), + ] + assert relationships._rels == {"rId1": rels_[0], "rId2": rels_[1]} + + def it_can_find_a_part_with_reltype(self, _rels_by_reltype_prop_, relationship_, part_): + relationship_.target_part = part_ + _rels_by_reltype_prop_.return_value = collections.defaultdict( + list, ((RT.SLIDE_LAYOUT, [relationship_]),) + ) + relationships = _Relationships(None) + + assert relationships.part_with_reltype(RT.SLIDE_LAYOUT) is part_ + + def but_it_raises_KeyError_when_there_is_no_such_part(self, _rels_by_reltype_prop_): + _rels_by_reltype_prop_.return_value = collections.defaultdict(list) + relationships = _Relationships(None) + + with pytest.raises(KeyError) as e: + relationships.part_with_reltype(RT.SLIDE_LAYOUT) + assert str(e.value) == ( + "\"no relationship of type 'http://schemas.openxmlformats.org/" + "officeDocument/2006/relationships/slideLayout' in collection\"" + ) + + def and_it_raises_ValueError_when_there_is_more_than_one_part_with_reltype( + self, _rels_by_reltype_prop_, relationship_, part_ + ): + relationship_.target_part = part_ + _rels_by_reltype_prop_.return_value = collections.defaultdict( + list, ((RT.SLIDE_LAYOUT, [relationship_, relationship_]),) + ) + relationships = _Relationships(None) + + with pytest.raises(ValueError) as e: + relationships.part_with_reltype(RT.SLIDE_LAYOUT) + assert str(e.value) == ( + "multiple relationships of type 'http://schemas.openxmlformats.org/" + "officeDocument/2006/relationships/slideLayout' in collection" + ) + + def it_can_pop_a_relationship_to_remove_it_from_the_collection( + self, _rels_prop_, relationship_ + ): + _rels_prop_.return_value = {"rId22": relationship_} + relationships = _Relationships(None) + + relationships.pop("rId22") + + assert relationships._rels == {} + + def it_can_serialize_itself_to_XML(self, request, _rels_prop_): + _rels_prop_.return_value = { + "rId11": instance_mock( + request, + _Relationship, + rId="rId11", + reltype=RT.SLIDE, + target_ref="../slides/slide1.xml", + is_external=False, + ), + "rId2": instance_mock( + request, + _Relationship, + rId="rId2", + reltype=RT.HYPERLINK, + target_ref="http://url", + is_external=True, + ), + "foo7W": instance_mock( + request, + _Relationship, + rId="foo7W", + reltype=RT.IMAGE, + target_ref="../media/image1.png", + is_external=False, + ), + } + relationships = _Relationships(None) + + assert relationships.xml == snippet_bytes("relationships") + + def it_can_add_a_relationship_to_a_part_to_help( + self, + request, + _next_rId_prop_, + _Relationship_, + relationship_, + _rels_prop_, + part_, + ): + _next_rId_prop_.return_value = "rId8" + _Relationship_.return_value = relationship_ + _rels_prop_.return_value = {} + relationships = _Relationships("/ppt") + + rId = relationships._add_relationship(RT.SLIDE, part_) + + _Relationship_.assert_called_once_with( + "/ppt", "rId8", RT.SLIDE, target_mode=RTM.INTERNAL, target=part_ + ) + assert relationships._rels == {"rId8": relationship_} + assert rId == "rId8" + + def and_it_can_add_an_external_relationship_to_help( + self, request, _next_rId_prop_, _rels_prop_, _Relationship_, relationship_ + ): + _next_rId_prop_.return_value = "rId9" + _Relationship_.return_value = relationship_ + _rels_prop_.return_value = {} + relationships = _Relationships("/ppt") + + rId = relationships._add_relationship(RT.HYPERLINK, "http://url", is_external=True) + + _Relationship_.assert_called_once_with( + "/ppt", "rId9", RT.HYPERLINK, target_mode=RTM.EXTERNAL, target="http://url" + ) + assert relationships._rels == {"rId9": relationship_} + assert rId == "rId9" + + @pytest.mark.parametrize( + "target_ref, is_external, expected_value", + ( + ("http://url", True, "rId1"), + ("part_1", False, "rId2"), + ("http://foo", True, "rId3"), + ("part_2", False, "rId4"), + ("http://bar", True, None), + ), + ) + def it_can_get_a_matching_relationship_to_help( + self, request, _rels_by_reltype_prop_, target_ref, is_external, expected_value + ): + part_1, part_2 = (instance_mock(request, Part) for _ in range(2)) + _rels_by_reltype_prop_.return_value = { + RT.SLIDE: [ + instance_mock( + request, + _Relationship, + rId=rId, + target_part=target_part, + target_ref=ref, + is_external=external, + ) + for rId, target_part, ref, external in ( + ("rId1", None, "http://url", True), + ("rId2", part_1, "/ppt/foo.bar", False), + ("rId3", None, "http://foo", True), + ("rId4", part_2, "/ppt/bar.foo", False), + ) + ] + } + target = target_ref if is_external else part_1 if target_ref == "part_1" else part_2 + relationships = _Relationships(None) + + matching = relationships._get_matching(RT.SLIDE, target, is_external) + + assert matching == expected_value + + def but_it_returns_None_when_there_is_no_matching_relationship(self, _rels_by_reltype_prop_): + _rels_by_reltype_prop_.return_value = collections.defaultdict(list) + relationships = _Relationships(None) + + assert relationships._get_matching(RT.HYPERLINK, "http://url", True) is None + + @pytest.mark.parametrize( + "rIds, expected_value", + ( + ((), "rId1"), + (("rId1",), "rId2"), + (("rId1", "rId2"), "rId3"), + (("rId1", "rId4"), "rId3"), + (("rId1", "rId4", "rId6"), "rId3"), + (("rId1", "rId2", "rId6"), "rId4"), + ), + ) + def it_finds_the_next_rId_to_help(self, _rels_prop_, rIds, expected_value): + _rels_prop_.return_value = {rId: None for rId in rIds} + relationships = _Relationships(None) + + assert relationships._next_rId == expected_value + + def it_collects_relationships_by_reltype_to_help(self, request, _rels_prop_): + rels = { + "rId%d" % (i + 1): instance_mock(request, _Relationship, reltype=reltype) + for i, reltype in enumerate((RT.SLIDE, RT.IMAGE, RT.SLIDE, RT.HYPERLINK)) + } + _rels_prop_.return_value = rels + relationships = _Relationships(None) + + rels_by_reltype = relationships._rels_by_reltype + + assert rels["rId1"] in rels_by_reltype[RT.SLIDE] + assert rels["rId2"] in rels_by_reltype[RT.IMAGE] + assert rels["rId3"] in rels_by_reltype[RT.SLIDE] + assert rels["rId4"] in rels_by_reltype[RT.HYPERLINK] + assert rels_by_reltype[RT.CHART] == [] + + # fixture components ----------------------------------- + + @pytest.fixture + def _add_relationship_(self, request): + return method_mock(request, _Relationships, "_add_relationship") + + @pytest.fixture + def _get_matching_(self, request): + return method_mock(request, _Relationships, "_get_matching") + + @pytest.fixture + def _next_rId_prop_(self, request): + return property_mock(request, _Relationships, "_next_rId") + + @pytest.fixture + def part_(self, request): + return instance_mock(request, Part) + + @pytest.fixture + def _Relationship_(self, request): + return class_mock(request, "pptx.opc.package._Relationship") + + @pytest.fixture + def relationship_(self, request): + return instance_mock(request, _Relationship) + + @pytest.fixture + def _rels_by_reltype_prop_(self, request): + return property_mock(request, _Relationships, "_rels_by_reltype") + + @pytest.fixture + def _rels_prop_(self, request): + return property_mock(request, _Relationships, "_rels") + + +class Describe_Relationship: + """Unit-test suite for `pptx.opc.package._Relationship` objects.""" + + def it_can_construct_from_xml(self, request, part_): + _init_ = initializer_mock(request, _Relationship) + rel_elm = instance_mock( + request, + CT_Relationship, + rId="rId42", + reltype=RT.SLIDE, + targetMode=RTM.INTERNAL, + target_ref="slides/slide7.xml", + ) + parts = {"/ppt/slides/slide7.xml": part_} + + relationship = _Relationship.from_xml("/ppt", rel_elm, parts) + + _init_.assert_called_once_with(relationship, "/ppt", "rId42", RT.SLIDE, RTM.INTERNAL, part_) + assert isinstance(relationship, _Relationship) + + @pytest.mark.parametrize( + "target_mode, expected_value", + ((RTM.INTERNAL, False), (RTM.EXTERNAL, True), (None, False)), + ) + def it_knows_whether_it_is_external(self, target_mode, expected_value): + relationship = _Relationship(None, None, None, target_mode, None) + assert relationship.is_external == expected_value + + def it_knows_its_relationship_type(self): + relationship = _Relationship(None, None, RT.SLIDE, None, None) + assert relationship.reltype == RT.SLIDE + + def it_knows_its_rId(self): + relationship = _Relationship(None, "rId42", None, None, None) + assert relationship.rId == "rId42" + + def it_provides_access_to_its_target_part(self, part_): + relationship = _Relationship(None, None, None, RTM.INTERNAL, part_) + assert relationship.target_part is part_ + + def but_it_raises_ValueError_on_target_part_for_external_rel(self): + relationship = _Relationship(None, None, None, RTM.EXTERNAL, None) + with pytest.raises(ValueError) as e: + relationship.target_part + assert str(e.value) == ( + "`.target_part` property on _Relationship is undefined when " "target-mode is external" + ) + + def it_knows_its_target_partname(self, part_): + part_.partname = PackURI("/ppt/slideLayouts/slideLayout4.xml") + relationship = _Relationship(None, None, None, RTM.INTERNAL, part_) + + assert relationship.target_partname == "/ppt/slideLayouts/slideLayout4.xml" + + def but_it_raises_ValueError_on_target_partname_for_external_rel(self): + relationship = _Relationship(None, None, None, RTM.EXTERNAL, None) + + with pytest.raises(ValueError) as e: + relationship.target_partname + + assert str(e.value) == ( + "`.target_partname` property on _Relationship is undefined when " + "target-mode is external" + ) + + def it_knows_the_target_uri_for_an_external_rel(self): + relationship = _Relationship(None, None, None, RTM.EXTERNAL, "http://url") + assert relationship.target_ref == "http://url" + + def and_it_knows_the_relative_partname_for_an_internal_rel(self, request): + """Internal relationships have a relative reference for `.target_ref`. + + A relative reference looks like "../slideLayouts/slideLayout1.xml". This form + is suitable for writing to a .rels file. + """ + property_mock( + request, + _Relationship, + "target_partname", + return_value=PackURI("/ppt/media/image1.png"), + ) + relationship = _Relationship("/ppt/slides", None, None, None, None) + + assert relationship.target_ref == "../media/image1.png" + + # --- fixture components ------------------------------- + + @pytest.fixture + def part_(self, request): + return instance_mock(request, Part) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_packuri.py b/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_packuri.py new file mode 100644 index 0000000000000000000000000000000000000000..5b7e64a2fca8434ba639243f0c8345813431c8d3 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_packuri.py @@ -0,0 +1,94 @@ +"""Unit-test suite for the `pptx.opc.packuri` module.""" + +from __future__ import annotations + +import pytest + +from pptx.opc.packuri import PackURI + + +class DescribePackURI(object): + """Unit-test suite for the `pptx.opc.packuri.PackURI` objects.""" + + def it_can_construct_from_relative_ref(self): + pack_uri = PackURI.from_rel_ref("/ppt/slides", "../slideLayouts/slideLayout1.xml") + assert pack_uri == "/ppt/slideLayouts/slideLayout1.xml" + + def it_should_raise_on_construct_with_bad_pack_uri_str(self): + with pytest.raises(ValueError): + PackURI("foobar") + + @pytest.mark.parametrize( + ("uri", "expected_value"), + [ + ("/", "/"), + ("/ppt/presentation.xml", "/ppt"), + ("/ppt/slides/slide1.xml", "/ppt/slides"), + ], + ) + def it_knows_its_base_URI(self, uri: str, expected_value: str): + assert PackURI(uri).baseURI == expected_value + + @pytest.mark.parametrize( + ("uri", "expected_value"), + [ + ("/", ""), + ("/ppt/presentation.xml", "xml"), + ("/ppt/media/image.PnG", "PnG"), + ], + ) + def it_knows_its_extension(self, uri: str, expected_value: str): + assert PackURI(uri).ext == expected_value + + @pytest.mark.parametrize( + ("uri", "expected_value"), + [ + ("/", ""), + ("/ppt/presentation.xml", "presentation.xml"), + ("/ppt/media/image.png", "image.png"), + ], + ) + def it_knows_its_filename(self, uri: str, expected_value: str): + assert PackURI(uri).filename == expected_value + + @pytest.mark.parametrize( + ("uri", "expected_value"), + [ + ("/", None), + ("/ppt/presentation.xml", None), + ("/ppt/,foo,grob!.xml", None), + ("/ppt/media/image42.png", 42), + ], + ) + def it_knows_the_filename_index(self, uri: str, expected_value: str): + assert PackURI(uri).idx == expected_value + + @pytest.mark.parametrize( + ("uri", "base_uri", "expected_value"), + [ + ("/ppt/presentation.xml", "/", "ppt/presentation.xml"), + ( + "/ppt/slideMasters/slideMaster1.xml", + "/ppt", + "slideMasters/slideMaster1.xml", + ), + ( + "/ppt/slideLayouts/slideLayout1.xml", + "/ppt/slides", + "../slideLayouts/slideLayout1.xml", + ), + ], + ) + def it_can_compute_its_relative_reference(self, uri: str, base_uri: str, expected_value: str): + assert PackURI(uri).relative_ref(base_uri) == expected_value + + @pytest.mark.parametrize( + ("uri", "expected_value"), + [ + ("/", "/_rels/.rels"), + ("/ppt/presentation.xml", "/ppt/_rels/presentation.xml.rels"), + ("/ppt/slides/slide42.xml", "/ppt/slides/_rels/slide42.xml.rels"), + ], + ) + def it_knows_the_uri_of_its_rels_part(self, uri: str, expected_value: str): + assert PackURI(uri).rels_uri == expected_value diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_serialized.py b/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_serialized.py new file mode 100644 index 0000000000000000000000000000000000000000..d5b867c4ea629d057ee7f9cf8c75cba5a98820ab --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/opc/test_serialized.py @@ -0,0 +1,408 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.opc.serialized` module.""" + +from __future__ import annotations + +import hashlib +import io +import zipfile + +import pytest + +from pptx.exc import PackageNotFoundError +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.opc.package import Part, _Relationships +from pptx.opc.packuri import CONTENT_TYPES_URI, PackURI +from pptx.opc.serialized import ( + PackageReader, + PackageWriter, + _ContentTypesItem, + _DirPkgReader, + _PhysPkgReader, + _PhysPkgWriter, + _ZipPkgReader, + _ZipPkgWriter, +) + +from ..unitutil.file import absjoin, snippet_text, test_file_dir +from ..unitutil.mock import ( + ANY, + FixtureRequest, + Mock, + call, + class_mock, + function_mock, + initializer_mock, + instance_mock, + method_mock, + property_mock, +) + +test_pptx_path = absjoin(test_file_dir, "test.pptx") +dir_pkg_path = absjoin(test_file_dir, "expanded_pptx") +zip_pkg_path = test_pptx_path + + +class DescribePackageReader: + """Unit-test suite for `pptx.opc.serialized.PackageReader` objects.""" + + def it_knows_whether_it_contains_a_partname(self, _blob_reader_prop_: Mock): + _blob_reader_prop_.return_value = {"/ppt", "/docProps"} + package_reader = PackageReader("") + + assert "/ppt" in package_reader + assert "/xyz" not in package_reader + + def it_can_get_a_blob_by_partname(self, _blob_reader_prop_: Mock): + _blob_reader_prop_.return_value = {"/ppt/slides/slide1.xml": b"blob"} + package_reader = PackageReader("") + + assert package_reader[PackURI("/ppt/slides/slide1.xml")] == b"blob" + + def it_can_get_the_rels_xml_for_a_partname(self, _blob_reader_prop_: Mock): + _blob_reader_prop_.return_value = {"/ppt/_rels/presentation.xml.rels": b"blob"} + package_reader = PackageReader("") + + assert package_reader.rels_xml_for(PackURI("/ppt/presentation.xml")) == b"blob" + + def but_it_returns_None_when_the_part_has_no_rels(self, _blob_reader_prop_: Mock): + _blob_reader_prop_.return_value = {"/ppt/_rels/presentation.xml.rels": b"blob"} + package_reader = PackageReader("") + + assert package_reader.rels_xml_for(PackURI("/ppt/slides.slide1.xml")) is None + + def it_constructs_its_blob_reader_to_help(self, request: FixtureRequest): + phys_pkg_reader_ = instance_mock(request, _PhysPkgReader) + _PhysPkgReader_ = class_mock(request, "pptx.opc.serialized._PhysPkgReader") + _PhysPkgReader_.factory.return_value = phys_pkg_reader_ + package_reader = PackageReader("prs.pptx") + + blob_reader = package_reader._blob_reader + + _PhysPkgReader_.factory.assert_called_once_with("prs.pptx") + assert blob_reader is phys_pkg_reader_ + + # fixture components ----------------------------------- + + @pytest.fixture + def _blob_reader_prop_(self, request: FixtureRequest): + return property_mock(request, PackageReader, "_blob_reader") + + +class DescribePackageWriter: + """Unit-test suite for `pptx.opc.serialized.PackageWriter` objects.""" + + def it_provides_a_write_interface_classmethod( + self, request: FixtureRequest, relationships_: Mock, part_: Mock + ): + _init_ = initializer_mock(request, PackageWriter) + _write_ = method_mock(request, PackageWriter, "_write") + + PackageWriter.write("prs.pptx", relationships_, (part_, part_)) + + _init_.assert_called_once_with(ANY, "prs.pptx", relationships_, (part_, part_)) + _write_.assert_called_once_with(ANY) + + def it_can_write_a_package( + self, request: FixtureRequest, phys_writer_: Mock, relationships_: Mock + ): + _PhysPkgWriter_ = class_mock(request, "pptx.opc.serialized._PhysPkgWriter") + phys_writer_.__enter__.return_value = phys_writer_ + _PhysPkgWriter_.factory.return_value = phys_writer_ + _write_content_types_stream_ = method_mock( + request, PackageWriter, "_write_content_types_stream" + ) + _write_pkg_rels_ = method_mock(request, PackageWriter, "_write_pkg_rels") + _write_parts_ = method_mock(request, PackageWriter, "_write_parts") + package_writer = PackageWriter("prs.pptx", relationships_, []) + + package_writer._write() + + _PhysPkgWriter_.factory.assert_called_once_with("prs.pptx") + _write_content_types_stream_.assert_called_once_with(package_writer, phys_writer_) + _write_pkg_rels_.assert_called_once_with(package_writer, phys_writer_) + _write_parts_.assert_called_once_with(package_writer, phys_writer_) + + def it_can_write_a_content_types_stream( + self, request: FixtureRequest, phys_writer_: Mock, relationships_: Mock, part_: Mock + ): + _ContentTypesItem_ = class_mock(request, "pptx.opc.serialized._ContentTypesItem") + _ContentTypesItem_.xml_for.return_value = "part_xml" + serialize_part_xml_ = function_mock( + request, "pptx.opc.serialized.serialize_part_xml", return_value=b"xml" + ) + package_writer = PackageWriter("", relationships_, (part_, part_)) + + package_writer._write_content_types_stream(phys_writer_) + + _ContentTypesItem_.xml_for.assert_called_once_with((part_, part_)) + serialize_part_xml_.assert_called_once_with("part_xml") + phys_writer_.write.assert_called_once_with(CONTENT_TYPES_URI, b"xml") + + def it_can_write_a_sequence_of_parts( + self, request: FixtureRequest, relationships_: Mock, phys_writer_: Mock + ): + parts_ = [ + instance_mock( + request, + Part, + partname=PackURI("/ppt/%s.xml" % x), + blob="blob_%s" % x, + rels=instance_mock(request, _Relationships, xml="rels_xml_%s" % x), + ) + for x in ("a", "b", "c") + ] + package_writer = PackageWriter("", relationships_, parts_) + + package_writer._write_parts(phys_writer_) + + assert phys_writer_.write.call_args_list == [ + call("/ppt/a.xml", "blob_a"), + call("/ppt/_rels/a.xml.rels", "rels_xml_a"), + call("/ppt/b.xml", "blob_b"), + call("/ppt/_rels/b.xml.rels", "rels_xml_b"), + call("/ppt/c.xml", "blob_c"), + call("/ppt/_rels/c.xml.rels", "rels_xml_c"), + ] + + def it_can_write_a_pkg_rels_item(self, phys_writer_: Mock, relationships_: Mock): + relationships_.xml = b"pkg-rels-xml" + package_writer = PackageWriter("", relationships_, []) + + package_writer._write_pkg_rels(phys_writer_) + + phys_writer_.write.assert_called_once_with("/_rels/.rels", b"pkg-rels-xml") + + # -- fixtures ---------------------------------------------------- + + @pytest.fixture + def part_(self, request: FixtureRequest): + return instance_mock(request, Part) + + @pytest.fixture + def phys_writer_(self, request: FixtureRequest): + return instance_mock(request, _ZipPkgWriter) + + @pytest.fixture + def relationships_(self, request: FixtureRequest): + return instance_mock(request, _Relationships) + + +class Describe_PhysPkgReader: + """Unit-test suite for `pptx.opc.serialized._PhysPkgReader` objects.""" + + def it_constructs_ZipPkgReader_when_pkg_is_file_like( + self, _ZipPkgReader_: Mock, zip_pkg_reader_: Mock + ): + _ZipPkgReader_.return_value = zip_pkg_reader_ + file_like_pkg = io.BytesIO(b"pkg-bytes") + + phys_reader = _PhysPkgReader.factory(file_like_pkg) + + _ZipPkgReader_.assert_called_once_with(file_like_pkg) + assert phys_reader is zip_pkg_reader_ + + def and_it_constructs_DirPkgReader_when_pkg_is_a_dir(self, request: FixtureRequest): + dir_pkg_reader_ = instance_mock(request, _DirPkgReader) + _DirPkgReader_ = class_mock( + request, "pptx.opc.serialized._DirPkgReader", return_value=dir_pkg_reader_ + ) + + phys_reader = _PhysPkgReader.factory(dir_pkg_path) + + _DirPkgReader_.assert_called_once_with(dir_pkg_path) + assert phys_reader is dir_pkg_reader_ + + def and_it_constructs_ZipPkgReader_when_pkg_is_a_zip_file_path( + self, _ZipPkgReader_: Mock, zip_pkg_reader_: Mock + ): + _ZipPkgReader_.return_value = zip_pkg_reader_ + pkg_file_path = test_pptx_path + + phys_reader = _PhysPkgReader.factory(pkg_file_path) + + _ZipPkgReader_.assert_called_once_with(pkg_file_path) + assert phys_reader is zip_pkg_reader_ + + def but_it_raises_when_pkg_path_is_not_a_package(self): + with pytest.raises(PackageNotFoundError) as e: + _PhysPkgReader.factory("foobar") + assert str(e.value) == "Package not found at 'foobar'" + + # --- fixture components ------------------------------- + + @pytest.fixture + def zip_pkg_reader_(self, request: FixtureRequest): + return instance_mock(request, _ZipPkgReader) + + @pytest.fixture + def _ZipPkgReader_(self, request: FixtureRequest): + return class_mock(request, "pptx.opc.serialized._ZipPkgReader") + + +class Describe_DirPkgReader: + """Unit-test suite for `pptx.opc.serialized._DirPkgReader` objects.""" + + def it_knows_whether_it_contains_a_partname(self, dir_pkg_reader: _DirPkgReader): + assert PackURI("/ppt/presentation.xml") in dir_pkg_reader + assert PackURI("/ppt/foobar.xml") not in dir_pkg_reader + + def it_can_retrieve_the_blob_for_a_pack_uri(self, dir_pkg_reader: _DirPkgReader): + blob = dir_pkg_reader[PackURI("/ppt/presentation.xml")] + assert hashlib.sha1(blob).hexdigest() == "51b78f4dabc0af2419d4e044ab73028c4bef53aa" + + def but_it_raises_KeyError_when_requested_member_is_not_present( + self, dir_pkg_reader: _DirPkgReader + ): + with pytest.raises(KeyError) as e: + dir_pkg_reader[PackURI("/ppt/foobar.xml")] + assert str(e.value) == "\"no member '/ppt/foobar.xml' in package\"" + + # --- fixture components ------------------------------- + + @pytest.fixture(scope="class") + def dir_pkg_reader(self): + return _DirPkgReader(dir_pkg_path) + + +class Describe_ZipPkgReader: + """Unit-test suite for `pptx.opc.serialized._ZipPkgReader` objects.""" + + def it_knows_whether_it_contains_a_partname(self, zip_pkg_reader: _ZipPkgReader): + assert PackURI("/ppt/presentation.xml") in zip_pkg_reader + assert PackURI("/ppt/foobar.xml") not in zip_pkg_reader + + def it_can_get_a_blob_by_partname(self, zip_pkg_reader: _ZipPkgReader): + blob = zip_pkg_reader[PackURI("/ppt/presentation.xml")] + assert hashlib.sha1(blob).hexdigest() == ("efa7bee0ac72464903a67a6744c1169035d52a54") + + def but_it_raises_KeyError_when_requested_member_is_not_present( + self, zip_pkg_reader: _ZipPkgReader + ): + with pytest.raises(KeyError) as e: + zip_pkg_reader[PackURI("/ppt/foobar.xml")] + assert str(e.value) == "\"no member '/ppt/foobar.xml' in package\"" + + def it_loads_the_package_blobs_on_first_access_to_help(self, zip_pkg_reader: _ZipPkgReader): + blobs = zip_pkg_reader._blobs + assert len(blobs) == 38 + assert "/ppt/presentation.xml" in blobs + assert "/ppt/_rels/presentation.xml.rels" in blobs + + # --- fixture components ------------------------------- + + @pytest.fixture(scope="class") + def zip_pkg_reader(self): + return _ZipPkgReader(zip_pkg_path) + + +class Describe_PhysPkgWriter: + """Unit-test suite for `pptx.opc.serialized._PhysPkgWriter` objects.""" + + def it_constructs_ZipPkgWriter_unconditionally(self, request: FixtureRequest): + zip_pkg_writer_ = instance_mock(request, _ZipPkgWriter) + _ZipPkgWriter_ = class_mock( + request, "pptx.opc.serialized._ZipPkgWriter", return_value=zip_pkg_writer_ + ) + + phys_writer = _PhysPkgWriter.factory("prs.pptx") + + _ZipPkgWriter_.assert_called_once_with("prs.pptx") + assert phys_writer is zip_pkg_writer_ + + +class Describe_ZipPkgWriter: + """Unit-test suite for `pptx.opc.serialized._ZipPkgWriter` objects.""" + + def it_has_an__enter__method_for_context_management(self): + pkg_writer = _ZipPkgWriter("") + assert pkg_writer.__enter__() is pkg_writer + + def and_it_closes_the_zip_archive_on_context__exit__(self, _zipf_prop_: Mock): + _ZipPkgWriter("").__exit__() + _zipf_prop_.return_value.close.assert_called_once_with() + + def it_can_write_a_blob(self, _zipf_prop_: Mock): + """Integrates with zipfile.ZipFile.""" + pack_uri = PackURI("/part/name.xml") + _zipf_prop_.return_value = zipf = zipfile.ZipFile(io.BytesIO(), "w") + pkg_writer = _ZipPkgWriter("") + + pkg_writer.write(pack_uri, b"blob") + + members = {PackURI("/%s" % name): zipf.read(name) for name in zipf.namelist()} + assert len(members) == 1 + assert members[pack_uri] == b"blob" + + def it_provides_access_to_the_open_zip_file_to_help(self, request: FixtureRequest): + ZipFile_ = class_mock(request, "pptx.opc.serialized.zipfile.ZipFile") + pkg_writer = _ZipPkgWriter("prs.pptx") + + zipf = pkg_writer._zipf + + ZipFile_.assert_called_once_with("prs.pptx", "w", compression=zipfile.ZIP_DEFLATED) + assert zipf is ZipFile_.return_value + + # fixtures --------------------------------------------- + + @pytest.fixture + def _zipf_prop_(self, request: FixtureRequest): + return property_mock(request, _ZipPkgWriter, "_zipf") + + +class Describe_ContentTypesItem: + """Unit-test suite for `pptx.opc.serialized._ContentTypesItem` objects.""" + + def it_provides_an_interface_classmethod(self, request: FixtureRequest, part_: Mock): + _init_ = initializer_mock(request, _ContentTypesItem) + property_mock(request, _ContentTypesItem, "_xml", return_value=b"xml") + + xml = _ContentTypesItem.xml_for((part_, part_)) + + _init_.assert_called_once_with(ANY, (part_, part_)) + assert xml == b"xml" + + def it_can_compose_content_types_xml(self, request: FixtureRequest): + defaults = {"png": CT.PNG, "xml": CT.XML, "rels": CT.OPC_RELATIONSHIPS} + overrides = { + "/docProps/core.xml": "app/vnd.core", + "/ppt/slides/slide1.xml": "app/vnd.ct_sld", + "/zebra/foo.bar": "app/vnd.foobar", + } + property_mock( + request, + _ContentTypesItem, + "_defaults_and_overrides", + return_value=(defaults, overrides), + ) + + content_types = _ContentTypesItem([])._xml + + assert content_types.xml == snippet_text("content-types-xml").strip() + + def it_computes_defaults_and_overrides_to_help(self, request: FixtureRequest): + parts = [ + instance_mock(request, Part, partname=PackURI(partname), content_type=content_type) + for partname, content_type in ( + ("/media/image1.png", CT.PNG), + ("/ppt/slides/slide1.xml", CT.PML_SLIDE), + ("/foo/bar.xml", CT.XML), + ("/docProps/core.xml", CT.OPC_CORE_PROPERTIES), + ) + ] + content_types = _ContentTypesItem(parts) + + defaults, overrides = content_types._defaults_and_overrides + + assert defaults == {"png": CT.PNG, "rels": CT.OPC_RELATIONSHIPS, "xml": CT.XML} + assert overrides == { + "/ppt/slides/slide1.xml": CT.PML_SLIDE, + "/docProps/core.xml": CT.OPC_CORE_PROPERTIES, + } + + # -- fixtures ---------------------------------------------------- + + @pytest.fixture + def part_(self, request: FixtureRequest): + return instance_mock(request, Part) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/parts/__init__.py b/tasks/tasksmith-74f059424102/environment/source/tests/parts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_chart.py b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_chart.py new file mode 100644 index 0000000000000000000000000000000000000000..b0a41f5811db2f103ad6e85228680f10b0bf1761 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_chart.py @@ -0,0 +1,152 @@ +"""Unit-test suite for `pptx.parts.chart` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.chart import Chart +from pptx.chart.data import ChartData +from pptx.enum.chart import XL_CHART_TYPE as XCT +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.package import OpcPackage +from pptx.opc.packuri import PackURI +from pptx.oxml.chart.chart import CT_ChartSpace +from pptx.parts.chart import ChartPart, ChartWorkbook +from pptx.parts.embeddedpackage import EmbeddedXlsxPart + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, instance_mock, method_mock, property_mock + + +class DescribeChartPart(object): + """Unit-test suite for `pptx.parts.chart.ChartPart` objects.""" + + def it_can_construct_from_chart_type_and_data(self, request): + chart_data_ = instance_mock(request, ChartData, xlsx_blob=b"xlsx-blob") + chart_data_.xml_bytes.return_value = b"chart-blob" + package_ = instance_mock(request, OpcPackage) + package_.next_partname.return_value = PackURI("/ppt/charts/chart42.xml") + chart_part_ = instance_mock(request, ChartPart) + # --- load() must have autospec turned off to work in Python 2.7 mock --- + load_ = method_mock(request, ChartPart, "load", autospec=False, return_value=chart_part_) + + chart_part = ChartPart.new(XCT.RADAR, chart_data_, package_) + + package_.next_partname.assert_called_once_with("/ppt/charts/chart%d.xml") + chart_data_.xml_bytes.assert_called_once_with(XCT.RADAR) + load_.assert_called_once_with( + "/ppt/charts/chart42.xml", CT.DML_CHART, package_, b"chart-blob" + ) + chart_part_.chart_workbook.update_from_xlsx_blob.assert_called_once_with(b"xlsx-blob") + assert chart_part is chart_part_ + + def it_provides_access_to_the_chart_object(self, request, chartSpace_): + chart_ = instance_mock(request, Chart) + Chart_ = class_mock(request, "pptx.parts.chart.Chart", return_value=chart_) + chart_part = ChartPart(None, None, None, chartSpace_) + + chart = chart_part.chart + + Chart_.assert_called_once_with(chart_part._element, chart_part) + assert chart is chart_ + + def it_provides_access_to_the_chart_workbook(self, request, chartSpace_): + chart_workbook_ = instance_mock(request, ChartWorkbook) + ChartWorkbook_ = class_mock( + request, "pptx.parts.chart.ChartWorkbook", return_value=chart_workbook_ + ) + chart_part = ChartPart(None, None, None, chartSpace_) + + chart_workbook = chart_part.chart_workbook + + ChartWorkbook_.assert_called_once_with(chartSpace_, chart_part) + assert chart_workbook is chart_workbook_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def chartSpace_(self, request): + return instance_mock(request, CT_ChartSpace) + + +class DescribeChartWorkbook(object): + """Unit-test suite for `pptx.parts.chart.ChartWorkbook` objects.""" + + def it_can_get_the_chart_xlsx_part(self, chart_part_, xlsx_part_): + chart_part_.related_part.return_value = xlsx_part_ + chart_workbook = ChartWorkbook( + element("c:chartSpace/c:externalData{r:id=rId42}"), chart_part_ + ) + + xlsx_part = chart_workbook.xlsx_part + + chart_part_.related_part.assert_called_once_with("rId42") + assert xlsx_part is xlsx_part_ + + def but_it_returns_None_when_the_chart_has_no_xlsx_part(self): + chart_workbook = ChartWorkbook(element("c:chartSpace"), None) + assert chart_workbook.xlsx_part is None + + @pytest.mark.parametrize( + "chartSpace_cxml, expected_cxml", + ( + ( + "c:chartSpace{r:a=b}", + "c:chartSpace{r:a=b}/c:externalData{r:id=rId" "42}/c:autoUpdate{val=0}", + ), + ( + "c:chartSpace/c:externalData{r:id=rId66}", + "c:chartSpace/c:externalData{r:id=rId42}", + ), + ), + ) + def it_can_change_the_chart_xlsx_part( + self, chart_part_, xlsx_part_, chartSpace_cxml, expected_cxml + ): + chart_part_.relate_to.return_value = "rId42" + chart_data = ChartWorkbook(element(chartSpace_cxml), chart_part_) + + chart_data.xlsx_part = xlsx_part_ + + chart_part_.relate_to.assert_called_once_with(xlsx_part_, RT.PACKAGE) + assert chart_data._chartSpace.xml == xml(expected_cxml) + + def it_adds_an_xlsx_part_on_update_if_needed( + self, request, chart_part_, package_, xlsx_part_, xlsx_part_prop_ + ): + EmbeddedXlsxPart_ = class_mock(request, "pptx.parts.chart.EmbeddedXlsxPart") + EmbeddedXlsxPart_.new.return_value = xlsx_part_ + chart_part_.package = package_ + xlsx_part_prop_.return_value = None + chart_data = ChartWorkbook(element("c:chartSpace"), chart_part_) + + chart_data.update_from_xlsx_blob(b"xlsx-blob") + + EmbeddedXlsxPart_.new.assert_called_once_with(b"xlsx-blob", package_) + xlsx_part_prop_.assert_called_with(xlsx_part_) + + def but_it_replaces_the_xlsx_blob_when_the_part_exists(self, xlsx_part_prop_, xlsx_part_): + xlsx_part_prop_.return_value = xlsx_part_ + chart_data = ChartWorkbook(None, None) + chart_data.update_from_xlsx_blob(b"xlsx-blob") + + assert chart_data.xlsx_part.blob == b"xlsx-blob" + + # fixture components --------------------------------------------- + + @pytest.fixture + def chart_part_(self, request, package_, xlsx_part_): + return instance_mock(request, ChartPart) + + @pytest.fixture + def package_(self, request): + return instance_mock(request, OpcPackage) + + @pytest.fixture + def xlsx_part_(self, request): + return instance_mock(request, EmbeddedXlsxPart) + + @pytest.fixture + def xlsx_part_prop_(self, request): + return property_mock(request, ChartWorkbook, "xlsx_part") diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_coreprops.py b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_coreprops.py new file mode 100644 index 0000000000000000000000000000000000000000..0983218e4b232b24b6225f080cd2ddf2440774fd --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_coreprops.py @@ -0,0 +1,198 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.parts.coreprops` module.""" + +from __future__ import annotations + +import datetime as dt + +import pytest + +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.oxml.coreprops import CT_CoreProperties +from pptx.parts.coreprops import CorePropertiesPart + + +class DescribeCorePropertiesPart(object): + """Unit-test suite for `pptx.parts.coreprops.CorePropertiesPart` objects.""" + + @pytest.mark.parametrize( + ("prop_name", "expected_value"), + [ + ("author", "python-pptx"), + ("category", ""), + ("comments", ""), + ("content_status", "DRAFT"), + ("identifier", "GXS 10.2.1ab"), + ("keywords", "foo bar baz"), + ("language", "US-EN"), + ("last_modified_by", "Steve Canny"), + ("subject", "Spam"), + ("title", "Presentation"), + ("version", "1.2.88"), + ], + ) + def it_knows_the_string_property_values( + self, core_properties: CorePropertiesPart, prop_name: str, expected_value: str + ): + assert getattr(core_properties, prop_name) == expected_value + + @pytest.mark.parametrize( + ("prop_name", "tagname", "value"), + [ + ("author", "dc:creator", "scanny"), + ("category", "cp:category", "silly stories"), + ("comments", "dc:description", "Bar foo to you"), + ("content_status", "cp:contentStatus", "FINAL"), + ("identifier", "dc:identifier", "GT 5.2.xab"), + ("keywords", "cp:keywords", "dog cat moo"), + ("language", "dc:language", "GB-EN"), + ("last_modified_by", "cp:lastModifiedBy", "Billy Bob"), + ("subject", "dc:subject", "Eggs"), + ("title", "dc:title", "Dissertation"), + ("version", "cp:version", "81.2.8"), + ], + ) + def it_can_change_the_string_property_values(self, prop_name: str, tagname: str, value: str): + coreProperties = self.coreProperties_xml(None, None) + core_properties = CorePropertiesPart.load(None, None, None, coreProperties) # type: ignore + + setattr(core_properties, prop_name, value) + + assert core_properties._element.xml == self.coreProperties_xml(tagname, value) + + @pytest.mark.parametrize( + ("prop_name", "expected_value"), + [ + ("created", dt.datetime(2012, 11, 17, 16, 37, 40)), + ("last_printed", dt.datetime(2014, 6, 4, 4, 28)), + ("modified", None), + ], + ) + def it_knows_the_date_property_values( + self, + core_properties: CorePropertiesPart, + prop_name: str, + expected_value: dt.datetime | None, + ): + actual_datetime = getattr(core_properties, prop_name) + assert actual_datetime == expected_value + + @pytest.mark.parametrize( + ("prop_name", "tagname", "value", "str_val", "attrs"), + [ + ( + "created", + "dcterms:created", + dt.datetime(2001, 2, 3, 4, 5), + "2001-02-03T04:05:00Z", + ' xsi:type="dcterms:W3CDTF"', + ), + ( + "last_printed", + "cp:lastPrinted", + dt.datetime(2014, 6, 4, 4), + "2014-06-04T04:00:00Z", + "", + ), + ( + "modified", + "dcterms:modified", + dt.datetime(2005, 4, 3, 2, 1), + "2005-04-03T02:01:00Z", + ' xsi:type="dcterms:W3CDTF"', + ), + ], + ) + def it_can_change_the_date_property_values( + self, prop_name: str, tagname: str, value: dt.datetime, str_val: str, attrs: str + ): + coreProperties = self.coreProperties_xml(None, None) + core_properties = CorePropertiesPart.load(None, None, None, coreProperties) # type: ignore + + setattr(core_properties, prop_name, value) + + assert core_properties._element.xml == self.coreProperties_xml(tagname, str_val, attrs) + + @pytest.mark.parametrize( + ("str_val", "expected_value"), + [("42", 42), (None, 0), ("foobar", 0), ("-17", 0), ("32.7", 0)], + ) + def it_knows_the_revision_number(self, str_val: str | None, expected_value: int): + tagname = "" if str_val is None else "cp:revision" + coreProperties = self.coreProperties_xml(tagname, str_val) + core_properties = CorePropertiesPart.load(None, None, None, coreProperties) # type: ignore + + assert core_properties.revision == expected_value + + def it_can_change_the_revision_number(self): + coreProperties = self.coreProperties_xml(None, None) + core_properties = CorePropertiesPart.load(None, None, None, coreProperties) # type: ignore + + core_properties.revision = 42 + + assert core_properties._element.xml == self.coreProperties_xml("cp:revision", "42") + + def it_can_construct_a_default_core_props(self): + core_props = CorePropertiesPart.default(None) # type: ignore + # verify ----------------------- + assert isinstance(core_props, CorePropertiesPart) + assert core_props.content_type is CT.OPC_CORE_PROPERTIES + assert core_props.partname == "/docProps/core.xml" + assert isinstance(core_props._element, CT_CoreProperties) + assert core_props.title == "PowerPoint Presentation" + assert core_props.last_modified_by == "python-pptx" + assert core_props.revision == 1 + assert core_props.modified is not None + # core_props.modified only stores time with seconds resolution, so + # comparison needs to be a little loose (within two seconds) + modified_timedelta = ( + dt.datetime.now(dt.timezone.utc).replace(tzinfo=None) - core_props.modified + ) + max_expected_timedelta = dt.timedelta(seconds=2) + assert modified_timedelta < max_expected_timedelta + + # -- fixtures ---------------------------------------------------- + + def coreProperties_xml(self, tagname: str | None, str_val: str | None, attrs: str = "") -> str: + tmpl = ( + '%s\n' + ) + if not tagname: + child_element = "" + elif not str_val: + child_element = "\n <%s%s/>\n" % (tagname, attrs) # pragma: no cover + else: + child_element = "\n <%s%s>%s\n" % (tagname, attrs, str_val, tagname) + return tmpl % child_element + + @pytest.fixture + def core_properties(self): + xml = ( + b"" + b'\n\n' + b" DRAFT\n" + b" python-pptx\n" + b' 2012-11-17T11:07:' + b"40-05:30\n" + b" \n" + b" GXS 10.2.1ab\n" + b" US-EN\n" + b" 2014-06-04T04:28:00Z\n" + b" foo bar baz\n" + b" Steve Canny\n" + b" 4\n" + b" Spam\n" + b" Presentation\n" + b" 1.2.88\n" + b"\n" + ) + return CorePropertiesPart.load(None, None, None, xml) # type: ignore diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_embeddedpackage.py b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_embeddedpackage.py new file mode 100644 index 0000000000000000000000000000000000000000..ae2aca82f050c688013aa8b9f4b7f9dc2015968e --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_embeddedpackage.py @@ -0,0 +1,74 @@ +"""Unit-test suite for `pptx.parts.embeddedpackage` module.""" + +from __future__ import annotations + +import pytest + +from pptx.enum.shapes import PROG_ID +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.opc.package import OpcPackage, PackURI +from pptx.parts.embeddedpackage import ( + EmbeddedDocxPart, + EmbeddedPackagePart, + EmbeddedPptxPart, + EmbeddedXlsxPart, +) + +from ..unitutil.mock import ANY, FixtureRequest, class_mock, initializer_mock, instance_mock + + +class DescribeEmbeddedPackagePart(object): + """Unit-test suite for `pptx.parts.embeddedpackage.EmbeddedPackagePart` objects.""" + + @pytest.mark.parametrize( + ("prog_id", "EmbeddedPartCls"), + [ + (PROG_ID.DOCX, EmbeddedDocxPart), + (PROG_ID.PPTX, EmbeddedPptxPart), + (PROG_ID.XLSX, EmbeddedXlsxPart), + ], + ) + def it_provides_a_factory_that_creates_a_package_part_for_MS_Office_files( + self, request: FixtureRequest, prog_id: PROG_ID, EmbeddedPartCls: type + ): + object_blob_ = b"0123456789" + package_ = instance_mock(request, OpcPackage) + embedded_object_part_ = instance_mock(request, EmbeddedPartCls) + EmbeddedPartCls_ = class_mock( + request, "pptx.parts.embeddedpackage.%s" % EmbeddedPartCls.__name__ + ) + EmbeddedPartCls_.new.return_value = embedded_object_part_ + + ole_object_part = EmbeddedPackagePart.factory(prog_id, object_blob_, package_) + + EmbeddedPartCls_.new.assert_called_once_with(object_blob_, package_) + assert ole_object_part is embedded_object_part_ + + def but_it_creates_a_generic_object_part_for_non_MS_Office_files(self, request: FixtureRequest): + progId = "Foo.Bar.42" + object_blob_ = b"0123456789" + package_ = instance_mock(request, OpcPackage) + _init_ = initializer_mock(request, EmbeddedPackagePart, autospec=True) + partname_ = instance_mock(request, PackURI) + package_.next_partname.return_value = partname_ + + ole_object_part = EmbeddedPackagePart.factory(progId, object_blob_, package_) + + package_.next_partname.assert_called_once_with("/ppt/embeddings/oleObject%d.bin") + _init_.assert_called_once_with(ANY, partname_, CT.OFC_OLE_OBJECT, package_, object_blob_) + assert isinstance(ole_object_part, EmbeddedPackagePart) + + def it_provides_a_contructor_classmethod_for_subclasses(self, request: FixtureRequest): + blob_ = b"0123456789" + package_ = instance_mock(request, OpcPackage) + _init_ = initializer_mock(request, EmbeddedXlsxPart, autospec=True) + partname_ = instance_mock(request, PackURI) + package_.next_partname.return_value = partname_ + + xlsx_part = EmbeddedXlsxPart.new(blob_, package_) + + package_.next_partname.assert_called_once_with(EmbeddedXlsxPart.partname_template) + _init_.assert_called_once_with( + xlsx_part, partname_, EmbeddedXlsxPart.content_type, package_, blob_ + ) + assert isinstance(xlsx_part, EmbeddedXlsxPart) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_image.py b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_image.py new file mode 100644 index 0000000000000000000000000000000000000000..386e3fce97125916e44c9bd8b9b5f5edf4b5124e --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_image.py @@ -0,0 +1,246 @@ +"""Unit-test suite for `pptx.parts.image` module.""" + +from __future__ import annotations + +import io + +import pytest + +from pptx.package import Package +from pptx.parts.image import Image, ImagePart +from pptx.util import Emu + +from ..unitutil.file import absjoin, test_file_dir +from ..unitutil.mock import ( + class_mock, + initializer_mock, + instance_mock, + method_mock, + property_mock, +) + +images_pptx_path = absjoin(test_file_dir, "with_images.pptx") + +test_image_path = absjoin(test_file_dir, "python-icon.jpeg") +test_eps_path = absjoin(test_file_dir, "cdw-logo.eps") +new_image_path = absjoin(test_file_dir, "monty-truth.png") + + +class DescribeImagePart(object): + """Unit-test suite for `pptx.parts.image.ImagePart` objects.""" + + def it_can_construct_from_an_image_object(self, request, image_): + package_ = instance_mock(request, Package) + _init_ = initializer_mock(request, ImagePart) + partname_ = package_.next_image_partname.return_value + + image_part = ImagePart.new(package_, image_) + + package_.next_image_partname.assert_called_once_with(image_.ext) + _init_.assert_called_once_with( + image_part, + partname_, + image_.content_type, + package_, + image_.blob, + image_.filename, + ) + assert isinstance(image_part, ImagePart) + + def it_provides_access_to_its_image(self, request, image_): + Image_ = class_mock(request, "pptx.parts.image.Image") + Image_.return_value = image_ + property_mock(request, ImagePart, "desc", return_value="foobar.png") + image_part = ImagePart(None, None, None, b"blob", None) + + image = image_part.image + + Image_.assert_called_once_with(b"blob", "foobar.png") + assert image is image_ + + @pytest.mark.parametrize( + "width, height, expected_width, expected_height", + ( + (None, None, Emu(2590800), Emu(2590800)), + (1000, None, 1000, 1000), + (None, 3000, 3000, 3000), + (3337, 9999, 3337, 9999), + ), + ) + def it_can_scale_its_dimensions(self, width, height, expected_width, expected_height): + with open(test_image_path, "rb") as f: + blob = f.read() + image_part = ImagePart(None, None, None, blob) + + assert image_part.scale(width, height) == (expected_width, expected_height) + + def it_knows_its_pixel_dimensions_to_help(self): + with open(test_image_path, "rb") as f: + blob = f.read() + image_part = ImagePart(None, None, None, blob) + + assert image_part._px_size == (204, 204) + + # fixture components --------------------------------------------- + + @pytest.fixture + def image_(self, request): + return instance_mock(request, Image) + + +class DescribeImage(object): + """Unit-test suite for `pptx.parts.image.Image` objects.""" + + def it_can_construct_from_a_path(self, from_blob_, image_): + with open(test_image_path, "rb") as f: + blob = f.read() + from_blob_.return_value = image_ + + image = Image.from_file(test_image_path) + + Image.from_blob.assert_called_once_with(blob, "python-icon.jpeg") + assert image is image_ + + def it_can_construct_from_a_stream(self, from_stream_fixture): + image_file, blob, image_ = from_stream_fixture + image = Image.from_file(image_file) + Image.from_blob.assert_called_once_with(blob, None) + assert image is image_ + + def it_can_construct_from_a_blob(self, _init_): + image = Image.from_blob(b"blob", "foo.png") + + _init_.assert_called_once_with(image, b"blob", "foo.png") + assert isinstance(image, Image) + + def it_knows_its_blob(self, blob_fixture): + image, expected_value = blob_fixture + assert image.blob == expected_value + + def it_knows_its_content_type(self, content_type_fixture): + image, expected_value = content_type_fixture + assert image.content_type == expected_value + + def it_knows_its_canonical_filename_extension(self, ext_fixture): + image, expected_value = ext_fixture + assert image.ext == expected_value + + def it_knows_its_dpi(self, dpi_fixture): + image, expected_value = dpi_fixture + assert image.dpi == expected_value + + def it_knows_its_filename(self, filename_fixture): + image, expected_value = filename_fixture + assert image.filename == expected_value + + def it_knows_its_sha1_hash(self): + image = Image(b"foobar", None) + assert image.sha1 == "8843d7f92416211de9ebb963ff4ce28125932878" + + def it_knows_its_PIL_properties_to_help(self, pil_fixture): + image, size, format, dpi = pil_fixture + assert image.size == size + assert image._format == format + assert image.dpi == dpi + assert image._pil_props == (format, size, None) + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def blob_fixture(self): + blob = b"foobar" + image = Image(blob, None) + return image, blob + + @pytest.fixture( + params=[ + ("BMP", "image/bmp"), + ("GIF", "image/gif"), + ("JPEG", "image/jpeg"), + ("PNG", "image/png"), + ("TIFF", "image/tiff"), + ("WMF", "image/x-wmf"), + ] + ) + def content_type_fixture(self, request, _format_): + format, expected_value = request.param + image = Image(None, None) + _format_.return_value = format + return image, expected_value + + @pytest.fixture( + params=[ + ((42, 24), (42, 24)), + ((42.1, 23.6), (42, 24)), + (None, (72, 72)), + ((3047, 2388), (72, 72)), + ("foobar", (72, 72)), + ] + ) + def dpi_fixture(self, request, _pil_props_): + raw_dpi, expected_dpi = request.param + image = Image(None, None) + _pil_props_.return_value = (None, None, raw_dpi) + return image, expected_dpi + + @pytest.fixture( + params=[ + ("BMP", "bmp"), + ("GIF", "gif"), + ("JPEG", "jpg"), + ("PNG", "png"), + ("TIFF", "tiff"), + ("WMF", "wmf"), + ] + ) + def ext_fixture(self, request, _format_): + format, expected_value = request.param + image = Image(None, None) + _format_.return_value = format + return image, expected_value + + @pytest.fixture(params=["foo.bar", None]) + def filename_fixture(self, request): + filename = request.param + image = Image(None, filename) + return image, filename + + @pytest.fixture + def from_stream_fixture(self, from_blob_, image_): + with open(test_image_path, "rb") as f: + blob = f.read() + image_file = io.BytesIO(blob) + from_blob_.return_value = image_ + return image_file, blob, image_ + + @pytest.fixture + def pil_fixture(self): + with open(test_image_path, "rb") as f: + blob = f.read() + image = Image(blob, None) + size = (204, 204) + format = "JPEG" + dpi = (72, 72) + return image, size, format, dpi + + # fixture components --------------------------------------------- + + @pytest.fixture + def _format_(self, request): + return property_mock(request, Image, "_format") + + @pytest.fixture + def from_blob_(self, request): + return method_mock(request, Image, "from_blob", autospec=False) + + @pytest.fixture + def image_(self, request): + return instance_mock(request, Image) + + @pytest.fixture + def _init_(self, request): + return initializer_mock(request, Image) + + @pytest.fixture + def _pil_props_(self, request): + return property_mock(request, Image, "_pil_props") diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_media.py b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_media.py new file mode 100644 index 0000000000000000000000000000000000000000..f7095f35d6b05ba4382d9e3ba4c1a87db1c977e6 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_media.py @@ -0,0 +1,33 @@ +"""Unit test suite for `pptx.parts.media` module.""" + +from __future__ import annotations + +from pptx.media import Video +from pptx.package import Package +from pptx.parts.media import MediaPart + +from ..unitutil.mock import initializer_mock, instance_mock + + +class DescribeMediaPart(object): + """Unit-test suite for `pptx.parts.media.MediaPart` objects.""" + + def it_can_construct_from_a_media_object(self, request): + media_ = instance_mock(request, Video) + _init_ = initializer_mock(request, MediaPart) + package_ = instance_mock(request, Package) + package_.next_media_partname.return_value = "media42.mp4" + media_.blob, media_.content_type = b"blob-bytes", "video/mp4" + + media_part = MediaPart.new(package_, media_) + + package_.next_media_partname.assert_called_once_with(media_.ext) + _init_.assert_called_once_with( + media_part, "media42.mp4", media_.content_type, package_, media_.blob + ) + assert isinstance(media_part, MediaPart) + + def it_knows_the_sha1_hash_of_the_media(self): + assert MediaPart(None, None, None, b"blobish-bytes").sha1 == ( + "61efc464c21e54cfc1382fb5b6ef7512e141ceae" + ) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_presentation.py b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_presentation.py new file mode 100644 index 0000000000000000000000000000000000000000..edde4c44c422ce18500bfa55b2f70a3f4398f572 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_presentation.py @@ -0,0 +1,225 @@ +"""Unit-test suite for `pptx.parts.presentation` module.""" + +from __future__ import annotations + +import pytest + +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.packuri import PackURI +from pptx.package import Package +from pptx.parts.coreprops import CorePropertiesPart +from pptx.parts.presentation import PresentationPart +from pptx.parts.slide import NotesMasterPart, SlideMasterPart, SlidePart +from pptx.presentation import Presentation +from pptx.slide import NotesMaster, Slide, SlideLayout, SlideMaster + +from ..unitutil.cxml import element +from ..unitutil.mock import call, class_mock, instance_mock, method_mock, property_mock + + +class DescribePresentationPart(object): + """Unit-test suite for `pptx.parts.presentation.PresentationPart` objects.""" + + def it_provides_access_to_its_presentation(self, request): + prs_ = instance_mock(request, Presentation) + Presentation_ = class_mock( + request, "pptx.parts.presentation.Presentation", return_value=prs_ + ) + prs_elm = element("p:presentation") + prs_part = PresentationPart(None, None, None, prs_elm) + + prs = prs_part.presentation + + Presentation_.assert_called_once_with(prs_elm, prs_part) + assert prs is prs_ + + def it_provides_access_to_its_core_properties(self, request, package_): + core_properties_ = instance_mock(request, CorePropertiesPart) + package_.core_properties = core_properties_ + prs_part = PresentationPart(None, None, package_, None) + + assert prs_part.core_properties is core_properties_ + + def it_provides_access_to_an_existing_notes_master_part( + self, notes_master_part_, part_related_by_ + ): + """This is the first of a two-part test to cover the existing notes master case. + + The notes master not-present case follows. + """ + prs_part = PresentationPart(None, None, None, None) + part_related_by_.return_value = notes_master_part_ + + notes_master_part = prs_part.notes_master_part + + prs_part.part_related_by.assert_called_once_with(prs_part, RT.NOTES_MASTER) + assert notes_master_part is notes_master_part_ + + def but_it_adds_a_notes_master_part_when_needed( + self, request, package_, notes_master_part_, part_related_by_, relate_to_ + ): + """This is the second of a two-part test to cover notes-master-not-present case. + + The notes master present case is just above. + """ + NotesMasterPart_ = class_mock(request, "pptx.parts.presentation.NotesMasterPart") + NotesMasterPart_.create_default.return_value = notes_master_part_ + part_related_by_.side_effect = KeyError + prs_part = PresentationPart(None, None, package_, None) + + notes_master_part = prs_part.notes_master_part + + NotesMasterPart_.create_default.assert_called_once_with(package_) + relate_to_.assert_called_once_with(prs_part, notes_master_part_, RT.NOTES_MASTER) + assert notes_master_part is notes_master_part_ + + def it_provides_access_to_its_notes_master(self, request, notes_master_part_): + notes_master_ = instance_mock(request, NotesMaster) + property_mock( + request, + PresentationPart, + "notes_master_part", + return_value=notes_master_part_, + ) + notes_master_part_.notes_master = notes_master_ + prs_part = PresentationPart(None, None, None, None) + + assert prs_part.notes_master is notes_master_ + + def it_provides_access_to_a_related_slide(self, request, slide_, related_part_): + slide_part_ = instance_mock(request, SlidePart, slide=slide_) + related_part_.return_value = slide_part_ + prs_part = PresentationPart(None, None, None, None) + + slide = prs_part.related_slide("rId42") + + related_part_.assert_called_once_with(prs_part, "rId42") + assert slide is slide_ + + def it_provides_access_to_a_related_master(self, request, slide_master_, related_part_): + slide_master_part_ = instance_mock(request, SlideMasterPart, slide_master=slide_master_) + related_part_.return_value = slide_master_part_ + prs_part = PresentationPart(None, None, None, None) + + slide_master = prs_part.related_slide_master("rId42") + + related_part_.assert_called_once_with(prs_part, "rId42") + assert slide_master is slide_master_ + + def it_can_rename_related_slide_parts(self, request, related_part_): + rIds = tuple("rId%d" % n for n in range(5, 0, -1)) + slide_parts = tuple(instance_mock(request, SlidePart) for _ in range(5)) + related_part_.side_effect = iter(slide_parts) + prs_part = PresentationPart(None, None, None, None) + + prs_part.rename_slide_parts(rIds) + + assert related_part_.call_args_list == [call(prs_part, rId) for rId in rIds] + assert [s.partname for s in slide_parts] == [ + PackURI("/ppt/slides/slide%d.xml" % (i + 1)) for i in range(len(rIds)) + ] + + def it_can_save_the_package_to_a_file(self, package_): + PresentationPart(None, None, package_, None).save("prs.pptx") + package_.save.assert_called_once_with("prs.pptx") + + def it_can_add_a_new_slide(self, request, package_, slide_part_, slide_, relate_to_): + slide_layout_ = instance_mock(request, SlideLayout) + partname = PackURI("/ppt/slides/slide9.xml") + property_mock(request, PresentationPart, "_next_slide_partname", return_value=partname) + SlidePart_ = class_mock(request, "pptx.parts.presentation.SlidePart") + SlidePart_.new.return_value = slide_part_ + relate_to_.return_value = "rId42" + slide_layout_part_ = slide_layout_.part + slide_part_.slide = slide_ + prs_part = PresentationPart(None, None, package_, None) + + rId, slide = prs_part.add_slide(slide_layout_) + + SlidePart_.new.assert_called_once_with(partname, package_, slide_layout_part_) + prs_part.relate_to.assert_called_once_with(prs_part, slide_part_, RT.SLIDE) + assert rId == "rId42" + assert slide is slide_ + + def it_finds_the_slide_id_of_a_slide_part(self, slide_part_, related_part_): + prs_elm = element( + "p:presentation/p:sldIdLst/(p:sldId{r:id=a,id=256},p:sldId{r:id=" + "b,id=257},p:sldId{r:id=c,id=258})" + ) + related_part_.side_effect = iter((None, slide_part_, None)) + prs_part = PresentationPart(None, None, None, prs_elm) + + _slide_id = prs_part.slide_id(slide_part_) + + assert related_part_.call_args_list == [ + call(prs_part, "a"), + call(prs_part, "b"), + ] + assert _slide_id == 257 + + def it_raises_on_slide_id_not_found(self, slide_part_, related_part_): + prs_elm = element( + "p:presentation/p:sldIdLst/(p:sldId{r:id=a,id=256},p:sldId{r:id=" + "b,id=257},p:sldId{r:id=c,id=258})" + ) + related_part_.return_value = "not the slide you're looking for" + prs_part = PresentationPart(None, None, None, prs_elm) + + with pytest.raises(ValueError): + prs_part.slide_id(slide_part_) + + @pytest.mark.parametrize("is_present", (True, False)) + def it_finds_a_slide_by_slide_id(self, is_present, slide_, slide_part_, related_part_): + prs_elm = element( + "p:presentation/p:sldIdLst/(p:sldId{r:id=a,id=256},p:sldId{r:id=" + "b,id=257},p:sldId{r:id=c,id=258})" + ) + slide_id = 257 if is_present else 666 + expected_value = slide_ if is_present else None + related_part_.return_value = slide_part_ + slide_part_.slide = slide_ + prs_part = PresentationPart(None, None, None, prs_elm) + + slide = prs_part.get_slide(slide_id) + + assert slide == expected_value + + def it_knows_the_next_slide_partname_to_help(self): + prs_elm = element("p:presentation/p:sldIdLst/(p:sldId,p:sldId)") + prs_part = PresentationPart(None, None, None, prs_elm) + + assert prs_part._next_slide_partname == PackURI("/ppt/slides/slide3.xml") + + # fixture components --------------------------------------------- + + @pytest.fixture + def notes_master_part_(self, request): + return instance_mock(request, NotesMasterPart) + + @pytest.fixture + def package_(self, request): + return instance_mock(request, Package) + + @pytest.fixture + def part_related_by_(self, request): + return method_mock(request, PresentationPart, "part_related_by") + + @pytest.fixture + def relate_to_(self, request): + return method_mock(request, PresentationPart, "relate_to") + + @pytest.fixture + def related_part_(self, request): + return method_mock(request, PresentationPart, "related_part") + + @pytest.fixture + def slide_(self, request): + return instance_mock(request, Slide) + + @pytest.fixture + def slide_master_(self, request): + return instance_mock(request, SlideMaster) + + @pytest.fixture + def slide_part_(self, request): + return instance_mock(request, SlidePart) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_slide.py b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb2f11b045c438c15fa1fbf1f2b51a7fb3d8482 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/parts/test_slide.py @@ -0,0 +1,587 @@ +"""Unit-test suite for `pptx.parts.slide` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.data import ChartData +from pptx.enum.chart import XL_CHART_TYPE as XCT +from pptx.enum.shapes import PROG_ID +from pptx.media import Video +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.package import Part +from pptx.opc.packuri import PackURI +from pptx.oxml.slide import CT_NotesMaster, CT_NotesSlide, CT_Slide +from pptx.oxml.theme import CT_OfficeStyleSheet +from pptx.package import Package +from pptx.parts.chart import ChartPart +from pptx.parts.embeddedpackage import EmbeddedPackagePart +from pptx.parts.image import Image, ImagePart +from pptx.parts.media import MediaPart +from pptx.parts.presentation import PresentationPart +from pptx.parts.slide import ( + BaseSlidePart, + NotesMasterPart, + NotesSlidePart, + SlideLayoutPart, + SlideMasterPart, + SlidePart, +) +from pptx.slide import NotesMaster, NotesSlide, Slide, SlideLayout, SlideMaster + +from ..unitutil.cxml import element +from ..unitutil.file import absjoin, test_file_dir +from ..unitutil.mock import ( + call, + class_mock, + initializer_mock, + instance_mock, + method_mock, +) + + +class DescribeBaseSlidePart(object): + """Unit-test suite for `pptx.parts.slide.BaseSlidePart` objects.""" + + def it_knows_its_name(self): + slide_part = BaseSlidePart(None, None, None, element("p:sld/p:cSld{name=Foobar}")) + assert slide_part.name == "Foobar" + + def it_can_get_a_related_image_by_rId(self, request, image_part_): + image_ = instance_mock(request, Image) + image_part_.image = image_ + related_part_ = method_mock( + request, BaseSlidePart, "related_part", return_value=image_part_ + ) + slide_part = BaseSlidePart(None, None, None, None) + + image = slide_part.get_image("rId42") + + related_part_.assert_called_once_with(slide_part, "rId42") + assert image is image_ + + def it_can_add_an_image_part(self, request, image_part_): + package_ = instance_mock(request, Package) + package_.get_or_add_image_part.return_value = image_part_ + relate_to_ = method_mock(request, BaseSlidePart, "relate_to", return_value="rId6") + slide_part = BaseSlidePart(None, None, package_, None) + + image_part, rId = slide_part.get_or_add_image_part("foobar.png") + + package_.get_or_add_image_part.assert_called_once_with("foobar.png") + relate_to_.assert_called_once_with(slide_part, image_part_, RT.IMAGE) + assert image_part is image_part_ + assert rId == "rId6" + + # fixture components --------------------------------------------- + + @pytest.fixture + def image_part_(self, request): + return instance_mock(request, ImagePart) + + +class DescribeNotesMasterPart(object): + """Unit-test suite for `pptx.parts.slide.NotesMasterPart` objects.""" + + def it_can_create_a_notes_master_part(self, request, package_, notes_master_part_, theme_part_): + method_mock( + request, + NotesMasterPart, + "_new", + autospec=False, + return_value=notes_master_part_, + ) + method_mock( + request, + NotesMasterPart, + "_new_theme_part", + autospec=False, + return_value=theme_part_, + ) + notes_master_part = NotesMasterPart.create_default(package_) + + NotesMasterPart._new.assert_called_once_with(package_) + NotesMasterPart._new_theme_part.assert_called_once_with(package_) + notes_master_part.relate_to.assert_called_once_with(theme_part_, RT.THEME) + assert notes_master_part is notes_master_part_ + + def it_provides_access_to_its_notes_master(self, request): + notes_master_ = instance_mock(request, NotesMaster) + NotesMaster_ = class_mock( + request, "pptx.parts.slide.NotesMaster", return_value=notes_master_ + ) + notesMaster = element("p:notesMaster") + notes_master_part = NotesMasterPart(None, None, None, notesMaster) + + notes_master = notes_master_part.notes_master + + NotesMaster_.assert_called_once_with(notesMaster, notes_master_part) + assert notes_master is notes_master_ + + def it_creates_a_new_notes_master_part_to_help(self, request, package_, notes_master_part_): + NotesMasterPart_ = class_mock( + request, "pptx.parts.slide.NotesMasterPart", return_value=notes_master_part_ + ) + notesMaster = element("p:notesMaster") + method_mock( + request, + CT_NotesMaster, + "new_default", + autospec=False, + return_value=notesMaster, + ) + + notes_master_part = NotesMasterPart._new(package_) + + CT_NotesMaster.new_default.assert_called_once_with() + NotesMasterPart_.assert_called_once_with( + PackURI("/ppt/notesMasters/notesMaster1.xml"), + CT.PML_NOTES_MASTER, + package_, + notesMaster, + ) + assert notes_master_part is notes_master_part_ + + def it_creates_a_new_theme_part_to_help(self, request, package_, theme_part_): + XmlPart_ = class_mock(request, "pptx.parts.slide.XmlPart", return_value=theme_part_) + theme_elm = element("p:theme") + method_mock( + request, + CT_OfficeStyleSheet, + "new_default", + autospec=False, + return_value=theme_elm, + ) + pn_tmpl = "/ppt/theme/theme%d.xml" + partname = PackURI("/ppt/theme/theme2.xml") + package_.next_partname.return_value = partname + + theme_part = NotesMasterPart._new_theme_part(package_) + + package_.next_partname.assert_called_once_with(pn_tmpl) + CT_OfficeStyleSheet.new_default.assert_called_once_with() + XmlPart_.assert_called_once_with(partname, CT.OFC_THEME, package_, theme_elm) + assert theme_part is theme_part_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def notes_master_part_(self, request): + return instance_mock(request, NotesMasterPart) + + @pytest.fixture + def package_(self, request): + return instance_mock(request, Package) + + @pytest.fixture + def theme_part_(self, request): + return instance_mock(request, Part) + + +class DescribeNotesSlidePart(object): + """Unit-test suite for `pptx.parts.slide.NotesSlidePart` objects.""" + + def it_can_create_a_notes_slide_part( + self, + request, + package_, + slide_part_, + notes_master_part_, + notes_slide_, + notes_master_, + notes_slide_part_, + ): + presentation_part_ = instance_mock(request, PresentationPart) + package_.presentation_part = presentation_part_ + presentation_part_.notes_master_part = notes_master_part_ + _add_notes_slide_part_ = method_mock( + request, + NotesSlidePart, + "_add_notes_slide_part", + autospec=False, + return_value=notes_slide_part_, + ) + notes_slide_part_.notes_slide = notes_slide_ + notes_master_part_.notes_master = notes_master_ + + notes_slide_part = NotesSlidePart.new(package_, slide_part_) + + _add_notes_slide_part_.assert_called_once_with(package_, slide_part_, notes_master_part_) + notes_slide_.clone_master_placeholders.assert_called_once_with(notes_master_) + assert notes_slide_part is notes_slide_part_ + + def it_provides_access_to_the_notes_master(self, request, notes_master_, notes_master_part_): + part_related_by_ = method_mock( + request, NotesSlidePart, "part_related_by", return_value=notes_master_part_ + ) + notes_slide_part = NotesSlidePart(None, None, None, None) + notes_master_part_.notes_master = notes_master_ + + notes_master = notes_slide_part.notes_master + + part_related_by_.assert_called_once_with(notes_slide_part, RT.NOTES_MASTER) + assert notes_master is notes_master_ + + def it_provides_access_to_its_notes_slide(self, request, notes_slide_): + NotesSlide_ = class_mock(request, "pptx.parts.slide.NotesSlide", return_value=notes_slide_) + notes = element("p:notes") + notes_slide_part = NotesSlidePart(None, None, None, notes) + + notes_slide = notes_slide_part.notes_slide + + NotesSlide_.assert_called_once_with(notes, notes_slide_part) + assert notes_slide is notes_slide_ + + def it_adds_a_notes_slide_part_to_help( + self, request, package_, slide_part_, notes_master_part_, notes_slide_part_ + ): + NotesSlidePart_ = class_mock( + request, "pptx.parts.slide.NotesSlidePart", return_value=notes_slide_part_ + ) + notes = element("p:notes") + new_ = method_mock(request, CT_NotesSlide, "new", autospec=False, return_value=notes) + package_.next_partname.return_value = PackURI("/ppt/notesSlides/notesSlide42.xml") + + notes_slide_part = NotesSlidePart._add_notes_slide_part( + package_, slide_part_, notes_master_part_ + ) + + package_.next_partname.assert_called_once_with("/ppt/notesSlides/notesSlide%d.xml") + new_.assert_called_once_with() + NotesSlidePart_.assert_called_once_with( + PackURI("/ppt/notesSlides/notesSlide42.xml"), + CT.PML_NOTES_SLIDE, + package_, + notes, + ) + assert notes_slide_part_.relate_to.call_args_list == [ + call(notes_master_part_, RT.NOTES_MASTER), + call(slide_part_, RT.SLIDE), + ] + assert notes_slide_part is notes_slide_part_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def notes_master_(self, request): + return instance_mock(request, NotesMaster) + + @pytest.fixture + def notes_master_part_(self, request): + return instance_mock(request, NotesMasterPart) + + @pytest.fixture + def notes_slide_(self, request): + return instance_mock(request, NotesSlide) + + @pytest.fixture + def notes_slide_part_(self, request): + return instance_mock(request, NotesSlidePart) + + @pytest.fixture + def package_(self, request): + return instance_mock(request, Package) + + @pytest.fixture + def slide_part_(self, request): + return instance_mock(request, SlidePart) + + +class DescribeSlidePart(object): + """Unit-test suite for `pptx.parts.slide.SlidePart` objects.""" + + def it_knows_its_slide_id(self, slide_id_fixture): + slide_part, presentation_part_, slide_id = slide_id_fixture + _slide_id = slide_part.slide_id + presentation_part_.slide_id.assert_called_once_with(slide_part) + assert _slide_id is slide_id + + def it_knows_whether_it_has_a_notes_slide(self, has_notes_slide_fixture): + slide_part, expected_value = has_notes_slide_fixture + value = slide_part.has_notes_slide + slide_part.part_related_by.assert_called_once_with(slide_part, RT.NOTES_SLIDE) + assert value is expected_value + + def it_can_add_a_chart_part(self, request, package_, relate_to_): + chart_data_ = instance_mock(request, ChartData) + chart_part_ = instance_mock(request, ChartPart) + ChartPart_ = class_mock(request, "pptx.parts.slide.ChartPart") + ChartPart_.new.return_value = chart_part_ + relate_to_.return_value = "rId42" + slide_part = SlidePart(None, None, package_, None) + + rId = slide_part.add_chart_part(XCT.RADAR, chart_data_) + + ChartPart_.new.assert_called_once_with(XCT.RADAR, chart_data_, package_) + relate_to_.assert_called_once_with(slide_part, chart_part_, RT.CHART) + assert rId == "rId42" + + @pytest.mark.parametrize( + "prog_id, rel_type", + ( + (PROG_ID.DOCX, RT.PACKAGE), + (PROG_ID.PPTX, RT.PACKAGE), + (PROG_ID.XLSX, RT.PACKAGE), + ("Foo.Bar.18", RT.OLE_OBJECT), + ), + ) + def it_can_add_an_embedded_ole_object_part( + self, request, package_, relate_to_, prog_id, rel_type + ): + _blob_from_file_ = method_mock( + request, SlidePart, "_blob_from_file", return_value=b"012345" + ) + embedded_package_part_ = instance_mock(request, EmbeddedPackagePart) + EmbeddedPackagePart_ = class_mock(request, "pptx.parts.slide.EmbeddedPackagePart") + EmbeddedPackagePart_.factory.return_value = embedded_package_part_ + relate_to_.return_value = "rId9" + slide_part = SlidePart(None, None, package_, None) + + _rId = slide_part.add_embedded_ole_object_part(prog_id, "workbook.xlsx") + + _blob_from_file_.assert_called_once_with(slide_part, "workbook.xlsx") + EmbeddedPackagePart_.factory.assert_called_once_with(prog_id, b"012345", package_) + relate_to_.assert_called_once_with(slide_part, embedded_package_part_, rel_type) + assert _rId == "rId9" + + def it_can_get_or_add_a_video_part(self, package_, video_, relate_to_, media_part_): + media_rId, video_rId = "rId1", "rId2" + package_.get_or_add_media_part.return_value = media_part_ + relate_to_.side_effect = [media_rId, video_rId] + slide_part = SlidePart(None, None, package_, None) + + result = slide_part.get_or_add_video_media_part(video_) + + package_.get_or_add_media_part.assert_called_once_with(video_) + assert relate_to_.call_args_list == [ + call(slide_part, media_part_, RT.MEDIA), + call(slide_part, media_part_, RT.VIDEO), + ] + assert result == (media_rId, video_rId) + + def it_can_create_a_new_slide_part(self, request, package_, relate_to_): + partname = PackURI("/foobar.xml") + _init_ = initializer_mock(request, SlidePart) + slide_layout_part_ = instance_mock(request, SlideLayoutPart) + CT_Slide_ = class_mock(request, "pptx.parts.slide.CT_Slide") + CT_Slide_.new.return_value = sld = element("c:sld") + + slide_part = SlidePart.new(partname, package_, slide_layout_part_) + + _init_.assert_called_once_with(slide_part, partname, CT.PML_SLIDE, package_, sld) + slide_part.relate_to.assert_called_once_with( + slide_part, slide_layout_part_, RT.SLIDE_LAYOUT + ) + assert isinstance(slide_part, SlidePart) + + def it_provides_access_to_its_slide(self, slide_fixture): + slide_part, Slide_, sld, slide_ = slide_fixture + slide = slide_part.slide + Slide_.assert_called_once_with(sld, slide_part) + assert slide is slide_ + + def it_provides_access_to_the_slide_layout(self, layout_fixture): + slide_part, slide_layout_ = layout_fixture + slide_layout = slide_part.slide_layout + slide_part.part_related_by.assert_called_once_with(slide_part, RT.SLIDE_LAYOUT) + assert slide_layout is slide_layout_ + + def it_knows_the_minimal_element_xml_for_a_slide(self): + path = absjoin(test_file_dir, "minimal_slide.xml") + sld = CT_Slide.new() + with open(path, "r") as f: + expected_xml = f.read() + assert sld.xml == expected_xml + + def it_gets_its_notes_slide_to_help(self, notes_slide_fixture): + slide_part, calls, notes_slide_ = notes_slide_fixture + + notes_slide = slide_part.notes_slide + + slide_part.part_related_by.assert_called_once_with(slide_part, RT.NOTES_SLIDE) + assert slide_part._add_notes_slide_part.call_args_list == calls + assert notes_slide is notes_slide_ + + def it_adds_a_notes_slide_part_to_help( + self, package_, NotesSlidePart_, notes_slide_part_, relate_to_ + ): + NotesSlidePart_.new.return_value = notes_slide_part_ + slide_part = SlidePart(None, None, package_, None) + + notes_slide_part = slide_part._add_notes_slide_part() + + assert notes_slide_part is notes_slide_part_ + NotesSlidePart_.new.assert_called_once_with(package_, slide_part) + relate_to_.assert_called_once_with(slide_part, notes_slide_part, RT.NOTES_SLIDE) + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=[True, False]) + def has_notes_slide_fixture(self, request, part_related_by_): + has_notes_slide = request.param + slide_part = SlidePart(None, None, None, None) + part_related_by_.side_effect = None if has_notes_slide else KeyError + expected_value = has_notes_slide + return slide_part, expected_value + + @pytest.fixture + def layout_fixture(self, slide_layout_, part_related_by_): + slide_part = SlidePart(None, None, None, None) + part_related_by_.return_value.slide_layout = slide_layout_ + return slide_part, slide_layout_ + + @pytest.fixture(params=[True, False]) + def notes_slide_fixture( + self, + request, + notes_slide_, + part_related_by_, + _add_notes_slide_part_, + notes_slide_part_, + ): + has_notes_slide = request.param + slide_part = SlidePart(None, None, None, None) + part_related_by_.return_value = notes_slide_part_ + add_calls = [] + if not has_notes_slide: + part_related_by_.side_effect = KeyError + add_calls.append(call(slide_part)) + notes_slide_part_.notes_slide = notes_slide_ + return slide_part, add_calls, notes_slide_ + + @pytest.fixture + def slide_fixture(self, Slide_, slide_): + sld = element("p:sld") + slide_part = SlidePart(None, None, None, sld) + return slide_part, Slide_, sld, slide_ + + @pytest.fixture + def slide_id_fixture(self, package_, presentation_part_): + slide_part = SlidePart(None, None, package_, None) + slide_id = 256 + package_.presentation_part = presentation_part_ + presentation_part_.slide_id.return_value = slide_id + return slide_part, presentation_part_, slide_id + + # fixture components --------------------------------------------- + + @pytest.fixture + def _add_notes_slide_part_(self, request, notes_slide_part_): + return method_mock( + request, + SlidePart, + "_add_notes_slide_part", + return_value=notes_slide_part_, + autospec=True, + ) + + @pytest.fixture + def media_part_(self, request): + return instance_mock(request, MediaPart) + + @pytest.fixture + def notes_slide_(self, request): + return instance_mock(request, NotesSlide) + + @pytest.fixture + def NotesSlidePart_(self, request, notes_slide_part_): + return class_mock( + request, "pptx.parts.slide.NotesSlidePart", return_value=notes_slide_part_ + ) + + @pytest.fixture + def notes_slide_part_(self, request): + return instance_mock(request, NotesSlidePart) + + @pytest.fixture + def package_(self, request): + return instance_mock(request, Package) + + @pytest.fixture + def part_related_by_(self, request): + return method_mock(request, SlidePart, "part_related_by", autospec=True) + + @pytest.fixture + def presentation_part_(self, request): + return instance_mock(request, PresentationPart) + + @pytest.fixture + def relate_to_(self, request): + return method_mock(request, SlidePart, "relate_to", autospec=True) + + @pytest.fixture + def Slide_(self, request, slide_): + return class_mock(request, "pptx.parts.slide.Slide", return_value=slide_) + + @pytest.fixture + def slide_(self, request): + return instance_mock(request, Slide) + + @pytest.fixture + def slide_layout_(self, request): + return instance_mock(request, SlideLayout) + + @pytest.fixture + def video_(self, request): + return instance_mock(request, Video) + + +class DescribeSlideLayoutPart(object): + """Unit-test suite for `pptx.parts.slide.SlideLayoutPart` objects.""" + + def it_provides_access_to_its_slide_master(self, request): + slide_master_ = instance_mock(request, SlideMaster) + slide_master_part_ = instance_mock(request, SlideMasterPart, slide_master=slide_master_) + part_related_by_ = method_mock( + request, SlideLayoutPart, "part_related_by", return_value=slide_master_part_ + ) + slide_layout_part = SlideLayoutPart(None, None, None, None) + + slide_master = slide_layout_part.slide_master + + part_related_by_.assert_called_once_with(slide_layout_part, RT.SLIDE_MASTER) + assert slide_master is slide_master_ + + def it_provides_access_to_its_slide_layout(self, request): + slide_layout_ = instance_mock(request, SlideLayout) + SlideLayout_ = class_mock( + request, "pptx.parts.slide.SlideLayout", return_value=slide_layout_ + ) + sldLayout = element("p:sldLayout") + slide_layout_part = SlideLayoutPart(None, None, None, sldLayout) + + slide_layout = slide_layout_part.slide_layout + + SlideLayout_.assert_called_once_with(sldLayout, slide_layout_part) + assert slide_layout is slide_layout_ + + +class DescribeSlideMasterPart(object): + """Unit-test suite for `pptx.parts.slide.SlideMasterPart` objects.""" + + def it_provides_access_to_its_slide_master(self, request): + slide_master_ = instance_mock(request, SlideMaster) + SlideMaster_ = class_mock( + request, "pptx.parts.slide.SlideMaster", return_value=slide_master_ + ) + sldMaster = element("p:sldMaster") + slide_master_part = SlideMasterPart(None, None, None, sldMaster) + + slide_master = slide_master_part.slide_master + + SlideMaster_.assert_called_once_with(sldMaster, slide_master_part) + assert slide_master is slide_master_ + + def it_provides_access_to_a_related_slide_layout(self, request): + slide_layout_ = instance_mock(request, SlideLayout) + slide_layout_part_ = instance_mock(request, SlideLayoutPart, slide_layout=slide_layout_) + related_part_ = method_mock( + request, SlideMasterPart, "related_part", return_value=slide_layout_part_ + ) + slide_master_part = SlideMasterPart(None, None, None, None) + + slide_layout = slide_master_part.related_slide_layout("rId42") + + related_part_.assert_called_once_with(slide_master_part, "rId42") + assert slide_layout is slide_layout_ diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/shapes/__init__.py b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_autoshape.py b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_autoshape.py new file mode 100644 index 0000000000000000000000000000000000000000..efb38e6b97ef30192451086b5b98ecbe9d16177d --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_autoshape.py @@ -0,0 +1,491 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.shapes.autoshape` module.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +import pytest + +from pptx.dml.fill import FillFormat +from pptx.dml.line import LineFormat +from pptx.enum.shapes import MSO_SHAPE, MSO_SHAPE_TYPE +from pptx.oxml import parse_xml +from pptx.oxml.shapes.autoshape import CT_PresetGeometry2D, CT_Shape +from pptx.shapes.autoshape import Adjustment, AdjustmentCollection, AutoShapeType, Shape +from pptx.text.text import TextFrame + +from ..oxml.unitdata.shape import ( + a_cNvSpPr, + a_gd, + a_prstGeom, + an_avLst, + an_nvSpPr, + an_sp, + an_spPr, +) +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, instance_mock, property_mock + +if TYPE_CHECKING: + from pptx.spec import AdjustmentValue + + +class DescribeAdjustment(object): + """Unit-test suite for `pptx.shapes.autoshape.Adjustment`.""" + + @pytest.mark.parametrize( + ("def_val", "actual", "expected_value"), + [ + # -- no actual, effective should be determined by default value -- + (50000, None, 0.5), + # -- actual matches default -- + (50000, 50000, 0.5), + # -- actual is different than default -- + (50000, 12500, 0.125), + # -- actual is zero -- + (50000, 0, 0.0), + # -- negative default -- + (-20833, None, -0.20833), + # -- negative actual -- + (-20833, -5678901, -56.78901), + ], + ) + def it_knows_its_effective_value(self, def_val: int, actual: int | None, expected_value: float): + assert Adjustment("foobar", def_val, actual).effective_value == expected_value + + +class DescribeAdjustmentCollection(object): + """Unit-test suite for `pptx.shapes.autoshape.AdjustmentCollection`.""" + + @pytest.mark.parametrize( + ("prst", "expected_values"), + [ + # -- rect has no adjustments -- + ("rect", ()), + # -- chevron has one simple one + ("chevron", (("adj", 50000),)), + # -- one with several and some negative -- + ( + "accentBorderCallout1", + (("adj1", 18750), ("adj2", -8333), ("adj3", 112500), ("adj4", -38333)), + ), + # -- another one with some negative -- + ( + "wedgeRoundRectCallout", + (("adj1", -20833), ("adj2", 62500), ("adj3", 16667)), + ), + # -- one with values outside normal range -- + ( + "circularArrow", + ( + ("adj1", 12500), + ("adj2", 1142319), + ("adj3", 20457681), + ("adj4", 10800000), + ("adj5", 12500), + ), + ), + ], + ) + def it_should_load_default_adjustment_values( + self, prst: str, expected_values: tuple[str, tuple[tuple[str, int], ...]] + ): + prstGeom = cast(CT_PresetGeometry2D, element(f"a:prstGeom{{prst={prst}}}/a:avLst")) + + adjustments = AdjustmentCollection(prstGeom)._adjustments + + actuals = tuple([(adj.name, adj.def_val) for adj in adjustments]) + assert actuals == expected_values + + def it_should_load_adj_val_actuals_from_xml(self, load_adj_actuals_fixture_): + prstGeom, expected_actuals, prstGeom_xml = load_adj_actuals_fixture_ + adjustments = AdjustmentCollection(prstGeom)._adjustments + actual_actuals = dict([(a.name, a.actual) for a in adjustments]) + assert actual_actuals == expected_actuals + + def it_provides_normalized_effective_value_on_indexed_access(self, indexed_access_fixture_): + prstGeom, prst, expected_values = indexed_access_fixture_ + adjustments = AdjustmentCollection(prstGeom) + actual_values = [adjustments[idx] for idx in range(len(adjustments))] + assert actual_values == expected_values + + def it_should_update_actual_value_on_indexed_assignment(self, indexed_assignment_fixture_): + """ + Assignment to AdjustmentCollection[n] updates nth actual + """ + adjs, idx, new_val, expected = indexed_assignment_fixture_ + adjs[idx] = new_val + assert adjs._adjustments[idx].actual == expected + + def it_should_round_trip_indexed_assignment(self, adjustments): + new_value = 0.375 + assert adjustments[0] != new_value + # exercise --------------------- + adjustments[0] = new_value + # verify ----------------------- + assert adjustments[0] == new_value + + def it_should_raise_on_bad_index(self, adjustments): + with pytest.raises(IndexError): + adjustments[-6] + with pytest.raises(IndexError): + adjustments[6] + with pytest.raises(TypeError): + adjustments[0.0] + with pytest.raises(TypeError): + adjustments["0"] + with pytest.raises(IndexError): + adjustments[-6] = 1.0 + with pytest.raises(IndexError): + adjustments[6] = 1.0 + with pytest.raises(TypeError): + adjustments[0.0] = 1.0 + with pytest.raises(TypeError): + adjustments["0"] = 1.0 + + def it_should_raise_on_assigned_bad_value(self, adjustments): + """ + AdjustmentCollection[n] = val raises on val is not number + """ + with pytest.raises(ValueError): + adjustments[0] = "1.0" + + def it_writes_adj_vals_to_xml_on_assignment(self, adjustments_with_prstGeom_): + adjs, guides = adjustments_with_prstGeom_ + adjs[0] = 0.999 + adjs._prstGeom.rewrite_guides.assert_called_once_with(guides) + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def adjustments(self): + prstGeom = a_prstGeom().with_nsdecls().with_prst("chevron").element + return AdjustmentCollection(prstGeom) + + @pytest.fixture + def adjustments_with_prstGeom_(self, request): + prstGeom = a_prstGeom().with_nsdecls().with_prst("chevron").element + adjustments = AdjustmentCollection(prstGeom) + prstGeom_ = instance_mock(request, CT_PresetGeometry2D, name="prstGeom_") + adjustments._prstGeom = prstGeom_ + guides = [("adj", 99900)] + return adjustments, guides + + def _adj_actuals_cases(): + gd_bldr = a_gd().with_name("adj2").with_fmla("val 25000") + avLst_bldr = an_avLst().with_child(gd_bldr) + mathDivide_bldr = a_prstGeom().with_nsdecls().with_prst("mathDivide").with_child(avLst_bldr) + + gd_bldr = a_gd().with_name("adj").with_fmla("val 25000") + avLst_bldr = an_avLst().with_child(gd_bldr) + rect_bldr = a_prstGeom().with_nsdecls().with_prst("rect").with_child(avLst_bldr) + + gd_bldr_1 = a_gd().with_name("adj1").with_fmla("val 111") + gd_bldr_2 = a_gd().with_name("adj2").with_fmla("val 222") + gd_bldr_3 = a_gd().with_name("adj3").with_fmla("val 333") + avLst_bldr = an_avLst().with_child(gd_bldr_1).with_child(gd_bldr_2).with_child(gd_bldr_3) + wedgeRoundRectCallout_bldr = ( + a_prstGeom().with_nsdecls().with_prst("wedgeRoundRectCallout").with_child(avLst_bldr) + ) + + return [ + # no adjustment values in xml or spec + (a_prstGeom().with_nsdecls().with_prst("rect").with_child(an_avLst()), ()), + # no adjustment values in xml, but some in spec + ( + a_prstGeom().with_nsdecls().with_prst("circularArrow"), + ( + ("adj1", None), + ("adj2", None), + ("adj3", None), + ("adj4", None), + ("adj5", None), + ), + ), + # adjustment value in xml but none in spec + (rect_bldr, ()), + # middle adjustment value in xml + (mathDivide_bldr, (("adj1", None), ("adj2", 25000), ("adj3", None))), + # all adjustment values in xml + (wedgeRoundRectCallout_bldr, (("adj1", 111), ("adj2", 222), ("adj3", 333))), + ] + + @pytest.fixture(params=_adj_actuals_cases()) + def load_adj_actuals_fixture_(self, request): + prstGeom_bldr, adj_vals = request.param + prstGeom = prstGeom_bldr.element + expected = dict(adj_vals) + prstGeom_xml = prstGeom_bldr.xml + return prstGeom, expected, prstGeom_xml + + def _effective_val_cases(): + return [ + ("rect", ()), + ("chevron", (0.5,)), + ("circularArrow", (0.125, 11.42319, 204.57681, 108.0, 0.125)), + ] + + @pytest.fixture(params=_effective_val_cases()) + def indexed_access_fixture_(self, request): + prst, effective_values = request.param + prstGeom = a_prstGeom().with_nsdecls().with_prst(prst).element + return prstGeom, prst, list(effective_values) + + def _indexed_assignment_cases(): + return [("chevron", 0, 0.5, 50000), ("circularArrow", 4, 99.99, 9999000)] + + @pytest.fixture(params=_indexed_assignment_cases()) + def indexed_assignment_fixture_(self, request): + prst, idx, new_val, expected = request.param + prstGeom = a_prstGeom().with_nsdecls().with_prst(prst).element + adjustments = AdjustmentCollection(prstGeom) + return adjustments, idx, new_val, expected + + +class DescribeAutoShapeType(object): + """Unit-test suite for `pptx.shapes.autoshape.AutoShapeType`""" + + def it_knows_the_details_of_the_auto_shape_type_it_represents(self): + autoshape_type = AutoShapeType(MSO_SHAPE.ROUNDED_RECTANGLE) + assert autoshape_type.autoshape_type_id == MSO_SHAPE.ROUNDED_RECTANGLE + assert autoshape_type.prst == "roundRect" + assert autoshape_type.basename == "Rounded Rectangle" + + def it_xml_escapes_the_basename_when_the_name_contains_special_characters(self): + autoshape_type = AutoShapeType(MSO_SHAPE.NO_SYMBOL) + assert autoshape_type.autoshape_type_id == MSO_SHAPE.NO_SYMBOL + assert autoshape_type.prst == "noSmoking" + assert autoshape_type.basename == ""No" Symbol" + + @pytest.mark.parametrize( + ("prst", "default_adj_vals"), + [ + (MSO_SHAPE.RECTANGLE, ()), + (MSO_SHAPE.CHEVRON, (("adj", 50000),)), + ( + MSO_SHAPE.LEFT_CIRCULAR_ARROW, + ( + ("adj1", 12500), + ("adj2", -1142319), + ("adj3", 1142319), + ("adj4", 10800000), + ("adj5", 12500), + ), + ), + ], + ) + def it_knows_the_default_adj_vals_for_its_autoshape_type( + self, prst: MSO_SHAPE, default_adj_vals: tuple[AdjustmentValue, ...] + ): + _default_adj_vals = AutoShapeType.default_adjustment_values(prst) + assert _default_adj_vals == default_adj_vals + + def it_knows_the_autoshape_type_id_for_each_prst_key(self): + assert AutoShapeType.id_from_prst("rect") == MSO_SHAPE.RECTANGLE + + def it_raises_when_asked_for_autoshape_type_id_with_a_bad_prst(self): + with pytest.raises(ValueError, match="MSO_AUTO_SHAPE_TYPE has no XML mapping for 'badPr"): + AutoShapeType.id_from_prst("badPrst") + + def it_caches_autoshape_type_lookups(self): + autoshape_type_id = MSO_SHAPE.ROUNDED_RECTANGLE + autoshape_type_1 = AutoShapeType(autoshape_type_id) + autoshape_type_2 = AutoShapeType(autoshape_type_id) + assert autoshape_type_2 is autoshape_type_1 + + def it_raises_on_construction_with_bad_autoshape_type_id(self): + with pytest.raises(KeyError): + AutoShapeType(9999) + + +class DescribeShape(object): + """Unit-test suite for `pptx.shapes.autoshape.Shape` object.""" + + def it_initializes_adjustments_on_first_ref(self, init_adjs_fixture_): + shape, adjs_, AdjustmentCollection_, sp_ = init_adjs_fixture_ + assert shape.adjustments is adjs_ + AdjustmentCollection_.assert_called_once_with(sp_.prstGeom) + + def it_knows_its_autoshape_type(self, autoshape_type_fixture_): + shape, expected_value = autoshape_type_fixture_ + auto_shape_type = shape.auto_shape_type + assert auto_shape_type == expected_value + + def but_it_raises_when_auto_shape_type_called_on_non_autoshape(self, non_autoshape_shape_): + with pytest.raises(ValueError): + non_autoshape_shape_.auto_shape_type + + def it_has_a_fill(self, shape): + assert isinstance(shape.fill, FillFormat) + + def it_knows_it_has_a_text_frame(self): + shape = Shape(None, None) + assert shape.has_text_frame is True + + def it_has_a_line(self, shape): + assert isinstance(shape.line, LineFormat) + + def it_knows_its_shape_type_when_its_a_placeholder(self, placeholder_shape_): + assert placeholder_shape_.shape_type == MSO_SHAPE_TYPE.PLACEHOLDER + + def and_it_knows_its_shape_type_when_its_not_a_placeholder(self, non_placeholder_shapes_): + autoshape_shape_, textbox_shape_, freeform_ = non_placeholder_shapes_ + assert autoshape_shape_.shape_type == MSO_SHAPE_TYPE.AUTO_SHAPE + assert textbox_shape_.shape_type == MSO_SHAPE_TYPE.TEXT_BOX + assert freeform_.shape_type == MSO_SHAPE_TYPE.FREEFORM + + def but_it_raises_when_shape_type_called_on_unrecognized_shape(self): + xml_ = ( + '" + ) + sp = parse_xml(xml_) + shape = Shape(sp, None) + # verify ----------------------- + with pytest.raises(NotImplementedError): + shape.shape_type + + def it_knows_what_text_it_contains(self, text_frame_prop_, text_frame_): + text_frame_prop_.return_value = text_frame_ + text_frame_.text = "foobar" + shape = Shape(None, None) + + text = shape.text + + assert text == "foobar" + + def it_can_change_its_text(self, text_frame_prop_, text_frame_): + text_frame_prop_.return_value = text_frame_ + shape = Shape(None, None) + + shape.text = "føøbår" + + assert text_frame_.text == "føøbår" + + def it_provides_access_to_its_text_frame(self, text_frame_fixture): + shape, text_frame_, TextFrame_, txBody = text_frame_fixture + text_frame = shape.text_frame + TextFrame_.assert_called_once_with(txBody, shape) + assert text_frame is text_frame_ + + def and_it_creates_a_txBody_if_needed(self, txBody_fixture): + shape, expected_xml = txBody_fixture + text_frame = shape.text_frame + assert text_frame._txBody.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def autoshape_type_fixture_(self, shape, prst): + sp = ( + an_sp() + .with_nsdecls() + .with_child(an_nvSpPr().with_child(a_cNvSpPr())) + .with_child(an_spPr().with_child(a_prstGeom().with_prst("chevron"))) + ).element + shape = Shape(sp, None) + return shape, MSO_SHAPE.CHEVRON + + @pytest.fixture + def init_adjs_fixture_(self, request, shape, sp_, adjustments_, AdjustmentCollection_): + return shape, adjustments_, AdjustmentCollection_, sp_ + + @pytest.fixture + def text_frame_fixture(self, TextFrame_, text_frame_): + sp = element("p:sp/p:txBody") + txBody = sp[0] + shape = Shape(sp, None) + return shape, text_frame_, TextFrame_, txBody + + @pytest.fixture + def txBody_fixture(self, request): + sp_cxml = "p:sp" + expected_cxml = "p:txBody/(a:bodyPr,a:p)" + shape = Shape(element(sp_cxml), None) + expected_xml = xml(expected_cxml) + return shape, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def AdjustmentCollection_(self, request, adjustments_): + return class_mock( + request, + "pptx.shapes.autoshape.AdjustmentCollection", + return_value=adjustments_, + ) + + @pytest.fixture + def adjustments_(self, request): + return instance_mock(request, AdjustmentCollection) + + @pytest.fixture + def non_autoshape_shape_(self, request, sp_): + sp_.is_autoshape = False + return Shape(sp_, None) + + @pytest.fixture + def non_placeholder_shapes_(self, request): + autoshape_sp_ = instance_mock( + request, + CT_Shape, + name="autoshape_sp_", + is_autoshape=True, + is_textbox=False, + has_custom_geometry=False, + ) + autoshape_shape_ = Shape(autoshape_sp_, None) + textbox_sp_ = instance_mock( + request, + CT_Shape, + name="textbox_sp_", + is_autoshape=False, + is_textbox=True, + has_custom_geometry=False, + ) + textbox_shape_ = Shape(textbox_sp_, None) + freeform_sp_ = instance_mock( + request, + CT_Shape, + name="freeform_sp_", + is_autoshape=True, + is_textbox=False, + has_custom_geometry=True, + ) + freeform_ = Shape(freeform_sp_, None) + property_mock(request, Shape, "is_placeholder", return_value=False) + return autoshape_shape_, textbox_shape_, freeform_ + + @pytest.fixture + def placeholder_shape_(self, request, sp_): + placeholder_shape_ = Shape(sp_, None) + property_mock(request, Shape, "is_placeholder", return_value=True) + return placeholder_shape_ + + @pytest.fixture + def prst(self): + return MSO_SHAPE.CHEVRON + + @pytest.fixture + def shape(self, request, sp_): + return Shape(sp_, None) + + @pytest.fixture + def sp_(self, request, prst): + return instance_mock(request, CT_Shape, prst=prst, is_autoshape=True) + + @pytest.fixture + def TextFrame_(self, request, text_frame_): + return class_mock(request, "pptx.shapes.autoshape.TextFrame", return_value=text_frame_) + + @pytest.fixture + def text_frame_(self, request): + return instance_mock(request, TextFrame) + + @pytest.fixture + def text_frame_prop_(self, request): + return property_mock(request, Shape, "text_frame") diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_base.py b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..89632ca80097630ee17e810ae8a2171426273977 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_base.py @@ -0,0 +1,619 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.shapes.base` module.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +import pytest + +from pptx.action import ActionSetting +from pptx.dml.effect import ShadowFormat +from pptx.enum.shapes import PP_PLACEHOLDER +from pptx.oxml.shapes.shared import BaseShapeElement +from pptx.oxml.text import CT_TextBody +from pptx.shapes import Subshape +from pptx.shapes.autoshape import Shape +from pptx.shapes.base import BaseShape, _PlaceholderFormat +from pptx.shapes.graphfrm import GraphicFrame +from pptx.shapes.picture import Picture +from pptx.shapes.shapetree import BaseShapeFactory, SlideShapes + +from ..oxml.unitdata.shape import ( + a_cNvPr, + a_cxnSp, + a_graphicFrame, + a_grpSp, + a_grpSpPr, + a_p_xfrm, + a_pic, + an_ext, + an_nvSpPr, + an_off, + an_sp, + an_spPr, + an_xfrm, +) +from ..unitutil.cxml import element, xml +from ..unitutil.mock import class_mock, instance_mock, loose_mock + +if TYPE_CHECKING: + from pptx.opc.package import XmlPart + from pptx.oxml.shapes import ShapeElement + from pptx.types import ProvidesPart + + +class DescribeBaseShape(object): + """Unit-test suite for `pptx.shapes.base.BaseShape` objects.""" + + def it_provides_access_to_its_click_action(self, click_action_fixture): + shape, ActionSetting_, cNvPr, click_action_ = click_action_fixture + click_action = shape.click_action + ActionSetting_.assert_called_once_with(cNvPr, shape) + assert click_action is click_action_ + + def it_knows_its_shape_id(self, id_fixture): + shape, expected_value = id_fixture + assert shape.shape_id == expected_value + + def it_knows_its_name(self, name_get_fixture): + shape, name = name_get_fixture + assert shape.name == name + + def it_can_change_its_name(self, name_set_fixture): + shape, new_value, expected_xml = name_set_fixture + shape.name = new_value + assert shape._element.xml == expected_xml + + @pytest.mark.parametrize( + ("shape_cxml", "expected_x", "expected_y"), + [ + ("p:cxnSp/p:spPr", None, None), + ("p:cxnSp/p:spPr/a:xfrm", None, None), + ("p:cxnSp/p:spPr/a:xfrm/a:off{x=123,y=456}", 123, 456), + ("p:graphicFrame/p:xfrm", None, None), + ("p:graphicFrame/p:xfrm/a:off{x=123,y=456}", 123, 456), + ("p:grpSp/p:grpSpPr", None, None), + ("p:grpSp/p:grpSpPr/a:xfrm/a:off{x=123,y=456}", 123, 456), + ("p:pic/p:spPr", None, None), + ("p:pic/p:spPr/a:xfrm", None, None), + ("p:pic/p:spPr/a:xfrm/a:off{x=123,y=456}", 123, 456), + ("p:sp/p:spPr", None, None), + ("p:sp/p:spPr/a:xfrm", None, None), + ("p:sp/p:spPr/a:xfrm/a:off{x=123,y=456}", 123, 456), + ], + ) + def it_has_a_position( + self, + shape_cxml: str, + expected_x: int | None, + expected_y: int | None, + provides_part: ProvidesPart, + ): + shape_elm = cast("ShapeElement", element(shape_cxml)) + + shape = BaseShape(shape_elm, provides_part) + + assert shape.left == expected_x + assert shape.top == expected_y + + @pytest.fixture + def provides_part(self) -> ProvidesPart: + + class FakeProvidesPart: + @property + def part(self) -> XmlPart: + raise NotImplementedError + + return FakeProvidesPart() + + def it_can_change_its_position(self, position_set_fixture): + shape, left, top, expected_xml = position_set_fixture + shape.left = left + shape.top = top + assert shape._element.xml == expected_xml + + def it_has_dimensions(self, dimensions_get_fixture): + shape, expected_width, expected_height = dimensions_get_fixture + assert shape.width == expected_width + assert shape.height == expected_height + + def it_can_change_its_dimensions(self, dimensions_set_fixture): + shape, width, height, expected_xml = dimensions_set_fixture + shape.width = width + shape.height = height + assert shape._element.xml == expected_xml + + def it_knows_its_rotation_angle(self, rotation_get_fixture): + shape, expected_value = rotation_get_fixture + assert shape.rotation == expected_value + + def it_can_change_its_rotation_angle(self, rotation_set_fixture): + shape, new_value, expected_xml = rotation_set_fixture + shape.rotation = new_value + assert shape._element.xml == expected_xml + + def it_provides_access_to_its_shadow(self, shadow_fixture): + shape, ShadowFormat_, spPr, shadow_ = shadow_fixture + + shadow = shape.shadow + + ShadowFormat_.assert_called_once_with(spPr) + assert shadow is shadow_ + + def it_knows_the_part_it_belongs_to(self, part_fixture): + shape, parent_ = part_fixture + part = shape.part + assert part is parent_.part + + def it_knows_it_doesnt_have_a_text_frame(self): + shape = BaseShape(None, None) + assert shape.has_text_frame is False + + def it_knows_whether_it_is_a_placeholder(self, is_placeholder_fixture): + shape, is_placeholder = is_placeholder_fixture + assert shape.is_placeholder is is_placeholder + + def it_provides_access_to_its_placeholder_format(self, phfmt_fixture): + shape, _PlaceholderFormat_, placeholder_format_, ph = phfmt_fixture + placeholder_format = shape.placeholder_format + _PlaceholderFormat_.assert_called_once_with(ph) + assert placeholder_format is placeholder_format_ + + def it_raises_when_shape_is_not_a_placeholder(self, phfmt_raise_fixture): + shape = phfmt_raise_fixture + with pytest.raises(ValueError): + shape.placeholder_format + + def it_knows_it_doesnt_contain_a_chart(self): + shape = BaseShape(None, None) + assert shape.has_chart is False + + def it_knows_it_doesnt_contain_a_table(self): + shape = BaseShape(None, None) + assert shape.has_table is False + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + "p:sp/p:nvSpPr/p:cNvPr", + "p:grpSp/p:nvGrpSpPr/p:cNvPr", + "p:graphicFrame/p:nvGraphicFramePr/p:cNvPr", + "p:cxnSp/p:nvCxnSpPr/p:cNvPr", + "p:pic/p:nvPicPr/p:cNvPr", + ] + ) + def click_action_fixture(self, request, ActionSetting_, action_setting_): + sp_cxml = request.param + sp = element(sp_cxml) + cNvPr = sp.xpath("//p:cNvPr")[0] + shape = BaseShape(sp, None) + return shape, ActionSetting_, cNvPr, action_setting_ + + @pytest.fixture( + params=[ + ("sp", False), + ("sp_with_ext", True), + ("pic", False), + ("pic_with_ext", True), + ("graphicFrame", False), + ("graphicFrame_with_ext", True), + ("grpSp", False), + ("grpSp_with_ext", True), + ("cxnSp", False), + ("cxnSp_with_ext", True), + ] + ) + def dimensions_get_fixture(self, request, width, height): + shape_elm_fixt_name, expect_values = request.param + shape_elm = request.getfixturevalue(shape_elm_fixt_name) + shape = BaseShape(shape_elm, None) + if not expect_values: + width = height = None + return shape, width, height + + @pytest.fixture( + params=[ + ("sp", "sp_with_ext"), + ("pic", "pic_with_ext"), + ("graphicFrame", "graphicFrame_with_ext"), + ("grpSp", "grpSp_with_ext"), + ("cxnSp", "cxnSp_with_ext"), + ] + ) + def dimensions_set_fixture(self, request, width, height): + start_elm_fixt_name, expected_elm_fixt_name = request.param + start_elm = request.getfixturevalue(start_elm_fixt_name) + shape = BaseShape(start_elm, None) + expected_xml = request.getfixturevalue(expected_elm_fixt_name).xml + return shape, width, height, expected_xml + + @pytest.fixture( + params=[ + ("p:sp/p:nvSpPr/p:cNvPr{id=1}", 1), + ("p:cxnSp/p:nvCxnSpPr/p:cNvPr{id=2}", 2), + ("p:graphicFrame/p:nvGraphicFramePr/p:cNvPr{id=3}", 3), + ("p:grpSp/p:nvGrpSpPr/p:cNvPr{id=4}", 4), + ("p:pic/p:nvPicPr/p:cNvPr{id=5}", 5), + ] + ) + def id_fixture(self, request): + xSp_cxml, expected_value = request.param + shape = BaseShape(element(xSp_cxml), None) + return shape, expected_value + + @pytest.fixture(params=[True, False]) + def is_placeholder_fixture(self, request, shape_elm_, txBody_): + is_placeholder = request.param + shape_elm_.has_ph_elm = is_placeholder + shape = BaseShape(shape_elm_, None) + return shape, is_placeholder + + @pytest.fixture + def name_get_fixture(self, shape_name): + shape_elm = ( + an_sp() + .with_nsdecls() + .with_child(an_nvSpPr().with_child(a_cNvPr().with_name(shape_name))) + ).element + shape = BaseShape(shape_elm, None) + return shape, shape_name + + @pytest.fixture( + params=[ + ( + "p:sp/p:nvSpPr/p:cNvPr{id=1,name=foo}", + Shape, + "Shape1", + "p:sp/p:nvSpPr/p:cNvPr{id=1,name=Shape1}", + ), + ( + "p:grpSp/p:nvGrpSpPr/p:cNvPr{id=2,name=bar}", + BaseShape, + "Shape2", + "p:grpSp/p:nvGrpSpPr/p:cNvPr{id=2,name=Shape2}", + ), + ( + "p:graphicFrame/p:nvGraphicFramePr/p:cNvPr{id=3,name=baz}", + GraphicFrame, + "Shape3", + "p:graphicFrame/p:nvGraphicFramePr/p:cNvPr{id=3,name=Shape3}", + ), + ( + "p:cxnSp/p:nvCxnSpPr/p:cNvPr{id=4,name=boo}", + BaseShape, + "Shape4", + "p:cxnSp/p:nvCxnSpPr/p:cNvPr{id=4,name=Shape4}", + ), + ( + "p:pic/p:nvPicPr/p:cNvPr{id=5,name=far}", + Picture, + "Shape5", + "p:pic/p:nvPicPr/p:cNvPr{id=5,name=Shape5}", + ), + ] + ) + def name_set_fixture(self, request): + xSp_cxml, ShapeCls, new_value, expected_xSp_cxml = request.param + shape = ShapeCls(element(xSp_cxml), None) + expected_xml = xml(expected_xSp_cxml) + return shape, new_value, expected_xml + + @pytest.fixture + def part_fixture(self, shapes_): + parent_ = shapes_ + shape = BaseShape(None, parent_) + return shape, parent_ + + @pytest.fixture + def phfmt_fixture(self, _PlaceholderFormat_, placeholder_format_): + sp = element("p:sp/p:nvSpPr/p:nvPr/p:ph") + ph = sp.xpath("//p:ph")[0] + shape = BaseShape(sp, None) + return shape, _PlaceholderFormat_, placeholder_format_, ph + + @pytest.fixture + def phfmt_raise_fixture(self): + return BaseShape(element("p:sp/p:nvSpPr/p:nvPr"), None) + + @pytest.fixture( + params=[ + ("sp", "sp_with_off"), + ("pic", "pic_with_off"), + ("graphicFrame", "graphicFrame_with_off"), + ("grpSp", "grpSp_with_off"), + ("cxnSp", "cxnSp_with_off"), + ] + ) + def position_set_fixture(self, request, left, top): + start_elm_fixt_name, expected_elm_fixt_name = request.param + start_elm = request.getfixturevalue(start_elm_fixt_name) + shape = BaseShape(start_elm, None) + expected_xml = request.getfixturevalue(expected_elm_fixt_name).xml + return shape, left, top, expected_xml + + @pytest.fixture( + params=[ + ("p:sp/p:spPr", 0.0), + ("p:sp/p:spPr/a:xfrm{rot=60000}", 1.0), + ("p:sp/p:spPr/a:xfrm{rot=2545200}", 42.42), + ("p:sp/p:spPr/a:xfrm{rot=-60000}", 359.0), + ("p:grpSp/p:grpSpPr/a:xfrm{rot=2545200}", 42.42), + ] + ) + def rotation_get_fixture(self, request): + xSp_cxml, expected_value = request.param + shape = BaseShapeFactory(element(xSp_cxml), None) + return shape, expected_value + + @pytest.fixture( + params=[ + ("p:sp/p:spPr/a:xfrm", 1.0, "p:sp/p:spPr/a:xfrm{rot=60000}"), + ("p:sp/p:spPr/a:xfrm{rot=60000}", 0.0, "p:sp/p:spPr/a:xfrm"), + ( + "p:sp/p:spPr/a:xfrm{rot=60000}", + -420.0, + "p:sp/p:spPr/a:xfrm{rot=18000000}", + ), + ("p:grpSp/p:grpSpPr/a:xfrm", 1.0, "p:grpSp/p:grpSpPr/a:xfrm{rot=60000}"), + ] + ) + def rotation_set_fixture(self, request): + xSp_cxml, new_value, expected_xSp_cxml = request.param + shape = BaseShapeFactory(element(xSp_cxml), None) + expected_xml = xml(expected_xSp_cxml) + return shape, new_value, expected_xml + + @pytest.fixture( + params=[ + "p:sp/p:spPr", + "p:cxnSp/p:spPr", + "p:pic/p:spPr", + # ---group and graphic frame shapes override this property--- + ] + ) + def shadow_fixture(self, request, ShadowFormat_, shadow_): + sp_cxml = request.param + sp = element(sp_cxml) + spPr = sp.xpath("//p:spPr")[0] + ShadowFormat_.return_value = shadow_ + + shape = BaseShape(sp, None) + return shape, ShadowFormat_, spPr, shadow_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def ActionSetting_(self, request, action_setting_): + return class_mock(request, "pptx.shapes.base.ActionSetting", return_value=action_setting_) + + @pytest.fixture + def action_setting_(self, request): + return instance_mock(request, ActionSetting) + + @pytest.fixture + def cxnSp(self): + return a_cxnSp().with_nsdecls().with_child(an_spPr()).element + + @pytest.fixture + def cxnSp_with_ext(self, width, height): + return ( + a_cxnSp() + .with_nsdecls() + .with_child( + an_spPr().with_child(an_xfrm().with_child(an_ext().with_cx(width).with_cy(height))) + ) + ).element + + @pytest.fixture + def cxnSp_with_off(self, left, top): + return ( + a_cxnSp() + .with_nsdecls() + .with_child( + an_spPr().with_child(an_xfrm().with_child(an_off().with_x(left).with_y(top))) + ) + ).element + + @pytest.fixture + def graphicFrame(self): + # Note that element is required on graphicFrame + return a_graphicFrame().with_nsdecls().with_child(a_p_xfrm()).element + + @pytest.fixture + def graphicFrame_with_ext(self, width, height): + return ( + a_graphicFrame() + .with_nsdecls() + .with_child(a_p_xfrm().with_child(an_ext().with_cx(width).with_cy(height))) + ).element + + @pytest.fixture + def graphicFrame_with_off(self, left, top): + return ( + a_graphicFrame() + .with_nsdecls() + .with_child(a_p_xfrm().with_child(an_off().with_x(left).with_y(top))) + ).element + + @pytest.fixture + def grpSp(self): + return (a_grpSp().with_nsdecls("p", "a").with_child(a_grpSpPr())).element + + @pytest.fixture + def grpSp_with_ext(self, width, height): + return ( + a_grpSp() + .with_nsdecls("p", "a") + .with_child( + a_grpSpPr().with_child( + an_xfrm().with_child(an_ext().with_cx(width).with_cy(height)) + ) + ) + ).element + + @pytest.fixture + def grpSp_with_off(self, left, top): + return ( + a_grpSp() + .with_nsdecls("p", "a") + .with_child( + a_grpSpPr().with_child(an_xfrm().with_child(an_off().with_x(left).with_y(top))) + ) + ).element + + @pytest.fixture + def height(self): + return 654 + + @pytest.fixture + def left(self): + return 123 + + @pytest.fixture + def pic(self): + return a_pic().with_nsdecls().with_child(an_spPr()).element + + @pytest.fixture + def pic_with_off(self, left, top): + return ( + a_pic() + .with_nsdecls() + .with_child( + an_spPr().with_child(an_xfrm().with_child(an_off().with_x(left).with_y(top))) + ) + ).element + + @pytest.fixture + def pic_with_ext(self, width, height): + return ( + a_pic() + .with_nsdecls() + .with_child( + an_spPr().with_child(an_xfrm().with_child(an_ext().with_cx(width).with_cy(height))) + ) + ).element + + @pytest.fixture + def _PlaceholderFormat_(self, request, placeholder_format_): + return class_mock( + request, + "pptx.shapes.base._PlaceholderFormat", + return_value=placeholder_format_, + ) + + @pytest.fixture + def placeholder_format_(self, request): + return instance_mock(request, _PlaceholderFormat) + + @pytest.fixture + def shadow_(self, request): + return instance_mock(request, ShadowFormat) + + @pytest.fixture + def ShadowFormat_(self, request): + return class_mock(request, "pptx.shapes.base.ShadowFormat") + + @pytest.fixture + def shape_elm_(self, request, shape_id, shape_name, txBody_): + return instance_mock( + request, + BaseShapeElement, + shape_id=shape_id, + shape_name=shape_name, + txBody=txBody_, + ) + + @pytest.fixture + def shape_id(self): + return 42 + + @pytest.fixture + def shape_name(self): + return "Foobar 41" + + @pytest.fixture + def shapes_(self, request): + return instance_mock(request, SlideShapes) + + @pytest.fixture + def sp(self): + return an_sp().with_nsdecls().with_child(an_spPr()).element + + @pytest.fixture + def sp_with_ext(self, width, height): + return ( + an_sp() + .with_nsdecls() + .with_child( + an_spPr().with_child(an_xfrm().with_child(an_ext().with_cx(width).with_cy(height))) + ) + ).element + + @pytest.fixture + def sp_with_off(self, left, top): + return ( + an_sp() + .with_nsdecls() + .with_child( + an_spPr().with_child(an_xfrm().with_child(an_off().with_x(left).with_y(top))) + ) + ).element + + @pytest.fixture + def top(self): + return 456 + + @pytest.fixture + def txBody_(self, request): + return instance_mock(request, CT_TextBody) + + @pytest.fixture + def width(self): + return 321 + + +class DescribeSubshape(object): + def it_knows_the_part_it_belongs_to(self, subshape_with_parent_): + subshape, parent_ = subshape_with_parent_ + part = subshape.part + assert part is parent_.part + + # fixtures --------------------------------------------- + + @pytest.fixture + def subshape_with_parent_(self, request): + parent_ = loose_mock(request, name="parent_") + subshape = Subshape(parent_) + return subshape, parent_ + + +class Describe_PlaceholderFormat(object): + def it_knows_its_idx(self, idx_get_fixture): + placeholder_format, expected_value = idx_get_fixture + assert placeholder_format.idx == expected_value + + def it_knows_its_type(self, type_get_fixture): + placeholder_format, expected_value = type_get_fixture + assert placeholder_format.type == expected_value + + # fixtures --------------------------------------------- + + @pytest.fixture(params=[("p:ph", 0), ("p:ph{idx=42}", 42)]) + def idx_get_fixture(self, request): + ph_cxml, expected_value = request.param + placeholder_format = _PlaceholderFormat(element(ph_cxml)) + return placeholder_format, expected_value + + @pytest.fixture( + params=[ + ("p:ph", PP_PLACEHOLDER.OBJECT), + ("p:ph{type=pic}", PP_PLACEHOLDER.PICTURE), + ] + ) + def type_get_fixture(self, request): + ph_cxml, expected_value = request.param + placeholder_format = _PlaceholderFormat(element(ph_cxml)) + return placeholder_format, expected_value diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_connector.py b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..f61f0a0297467e3a30e4309141dd4f6a7ba1d8e9 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_connector.py @@ -0,0 +1,427 @@ +"""Unit test suite for pptx.shapes.connector module.""" + +from __future__ import annotations + +import pytest + +from pptx.dml.line import LineFormat +from pptx.enum.shapes import MSO_SHAPE_TYPE +from pptx.shapes.base import BaseShape +from pptx.shapes.connector import Connector +from pptx.util import Emu + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import instance_mock, method_mock + + +class DescribeConnector(object): + """Unit-test suite for `pptx.shapes.connector.Connector`.""" + + def it_knows_its_begin_point_x_location(self, begin_x_get_fixture): + connector, expected_value = begin_x_get_fixture + begin_x = connector.begin_x + assert isinstance(begin_x, Emu) + assert connector.begin_x == expected_value + + def it_can_change_its_begin_point_x_location(self, begin_x_set_fixture): + connector, new_x, expected_xml = begin_x_set_fixture + connector.begin_x = new_x + assert connector._element.xml == expected_xml + + def it_knows_its_begin_point_y_location(self, begin_y_get_fixture): + connector, expected_value = begin_y_get_fixture + begin_y = connector.begin_y + assert isinstance(begin_y, Emu) + assert connector.begin_y == expected_value + + def it_can_change_its_begin_point_y_location(self, begin_y_set_fixture): + connector, new_y, expected_xml = begin_y_set_fixture + connector.begin_y = new_y + assert connector._element.xml == expected_xml + + def it_knows_its_end_point_x_location(self, end_x_get_fixture): + connector, expected_value = end_x_get_fixture + end_x = connector.end_x + assert isinstance(end_x, Emu) + assert connector.end_x == expected_value + + def it_can_change_its_end_point_x_location(self, end_x_set_fixture): + connector, new_x, expected_xml = end_x_set_fixture + connector.end_x = new_x + assert connector._element.xml == expected_xml + + def it_knows_its_end_point_y_location(self, end_y_get_fixture): + connector, expected_value = end_y_get_fixture + end_y = connector.end_y + assert isinstance(end_y, Emu) + assert connector.end_y == expected_value + + def it_can_change_its_end_point_y_location(self, end_y_set_fixture): + connector, new_y, expected_xml = end_y_set_fixture + connector.end_y = new_y + assert connector._element.xml == expected_xml + + def it_can_connect_its_begin_point_to_a_shape(self, begin_conn_fixture): + connector, shape, cxn_idx = begin_conn_fixture + + connector.begin_connect(shape, cxn_idx) + + connector._connect_begin_to.assert_called_once_with(connector, shape, cxn_idx) + connector._move_begin_to_cxn.assert_called_once_with(connector, shape, cxn_idx) + + def it_can_connect_its_end_point_to_a_shape(self, end_conn_fixture): + connector, shape, cxn_idx = end_conn_fixture + + connector.end_connect(shape, cxn_idx) + + connector._connect_end_to.assert_called_once_with(connector, shape, cxn_idx) + connector._move_end_to_cxn.assert_called_once_with(connector, shape, cxn_idx) + + def it_provides_access_to_its_line_format(self): + connector = Connector(element("p:cxnSp/p:spPr"), None) + + line = connector.line + + assert isinstance(line, LineFormat) + # exercise line to test parent interface, .ln and .get_or_add_ln() + line.width = 91440 + assert line.width == 91440 + + def it_knows_its_shape_type(self): + assert Connector(None, None).shape_type == MSO_SHAPE_TYPE.LINE + + def it_connects_its_begin_point_to_help(self, connect_begin_fixture): + connector, shape, cxn_idx, expected_xml = connect_begin_fixture + connector._connect_begin_to(shape, cxn_idx) + assert connector._element.xml == expected_xml + + def it_connects_its_end_point_to_help(self, connect_end_fixture): + connector, shape, cxn_idx, expected_xml = connect_end_fixture + connector._connect_end_to(shape, cxn_idx) + assert connector._element.xml == expected_xml + + def it_moves_its_begin_point_to_help(self, move_begin_fixture): + connector, shape, cxn_idx, expected_xml = move_begin_fixture + connector._move_begin_to_cxn(shape, cxn_idx) + assert connector._element.xml == expected_xml + + def it_moves_its_end_point_to_help(self, move_end_fixture): + connector, shape, cxn_idx, expected_xml = move_end_fixture + connector._move_end_to_cxn(shape, cxn_idx) + assert connector._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def begin_conn_fixture(self, _connect_begin_to_, _move_begin_to_cxn_): + connector = Connector(None, None) + shape, cxn_idx = 42, 24 + return connector, shape, cxn_idx + + @pytest.fixture(params=[(42, 24, False, 42), (24, 42, True, 66)]) + def begin_x_get_fixture(self, request): + x, cx, flipH, expected_value = request.param + cxnSp = element( + "p:cxnSp/p:spPr/a:xfrm{flipH=%d}/(a:off{x=%d,y=6},a:ext{cx=%d,cy" + "=32})" % (flipH, x, cx) + ) + connector = Connector(cxnSp, None) + return connector, expected_value + + @pytest.fixture( + params=[ + ( + "a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 5, + "a:xfrm/(a:off{x=5,y=1},a:ext{cx=15,cy=1})", + ), + ( + "a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 15, + "a:xfrm/(a:off{x=15,y=1},a:ext{cx=5,cy=1})", + ), + ( + "a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 25, + "a:xfrm{flipH=1}/(a:off{x=20,y=1},a:ext{cx=5,cy=1})", + ), + ( + "a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 25, + "a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=15,cy=1})", + ), + ( + "a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 15, + "a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=5,cy=1})", + ), + ( + "a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 5, + "a:xfrm/(a:off{x=5,y=1},a:ext{cx=5,cy=1})", + ), + ] + ) + def begin_x_set_fixture(self, request): + xfrm_cxml, new_x, expected_cxml = request.param + tmpl = "p:cxnSp/p:spPr/%s" + cxnSp = element(tmpl % xfrm_cxml) + expected_xml = xml(tmpl % expected_cxml) + connector = Connector(cxnSp, None) + return connector, new_x, expected_xml + + @pytest.fixture(params=[(40, 60, False, 40), (50, 42, True, 92)]) + def begin_y_get_fixture(self, request): + y, cy, flipV, expected_value = request.param + cxnSp = element( + "p:cxnSp/p:spPr/a:xfrm{flipV=%d}/(a:off{x=6,y=%d},a:ext{cx=32,cy" + "=%d})" % (flipV, y, cy) + ) + connector = Connector(cxnSp, None) + return connector, expected_value + + @pytest.fixture( + params=[ + ( + "a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 5, + "a:xfrm/(a:off{x=1,y=5},a:ext{cx=1,cy=15})", + ), + ( + "a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 15, + "a:xfrm/(a:off{x=1,y=15},a:ext{cx=1,cy=5})", + ), + ( + "a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 25, + "a:xfrm{flipV=1}/(a:off{x=1,y=20},a:ext{cx=1,cy=5})", + ), + ( + "a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 30, + "a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=20})", + ), + ( + "a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 15, + "a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=5})", + ), + ( + "a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 5, + "a:xfrm/(a:off{x=1,y=5},a:ext{cx=1,cy=5})", + ), + ] + ) + def begin_y_set_fixture(self, request): + xfrm_cxml, new_y, expected_cxml = request.param + tmpl = "p:cxnSp/p:spPr/%s" + cxnSp = element(tmpl % xfrm_cxml) + expected_xml = xml(tmpl % expected_cxml) + connector = Connector(cxnSp, None) + return connector, new_y, expected_xml + + @pytest.fixture( + params=[ + ( + "p:cxnSp{a:b=c}/p:nvCxnSpPr/p:cNvCxnSpPr", + "p:cxnSp{a:b=c}/p:nvCxnSpPr/p:cNvCxnSpPr/a:stCxn{id=42,idx=3}", + ), + ( + "p:cxnSp/p:nvCxnSpPr/p:cNvCxnSpPr/a:stCxn{id=66,idx=6}", + "p:cxnSp/p:nvCxnSpPr/p:cNvCxnSpPr/a:stCxn{id=42,idx=3}", + ), + ] + ) + def connect_begin_fixture(self, request, shape_): + cxnSp_cxml, expected_cxml = request.param + cxnSp = element(cxnSp_cxml) + connector = Connector(cxnSp, None) + shape_.shape_id, cxn_idx = 42, 3 + expected_xml = xml(expected_cxml) + return connector, shape_, cxn_idx, expected_xml + + @pytest.fixture( + params=[ + ( + "p:cxnSp{a:b=c}/p:nvCxnSpPr/p:cNvCxnSpPr", + "p:cxnSp{a:b=c}/p:nvCxnSpPr/p:cNvCxnSpPr/a:endCxn{id=24,idx=2}", + ), + ( + "p:cxnSp/p:nvCxnSpPr/p:cNvCxnSpPr/a:endCxn{id=66,idx=6}", + "p:cxnSp/p:nvCxnSpPr/p:cNvCxnSpPr/a:endCxn{id=24,idx=2}", + ), + ] + ) + def connect_end_fixture(self, request, shape_): + cxnSp_cxml, expected_cxml = request.param + cxnSp = element(cxnSp_cxml) + connector = Connector(cxnSp, None) + shape_.shape_id, cxn_idx = 24, 2 + expected_xml = xml(expected_cxml) + return connector, shape_, cxn_idx, expected_xml + + @pytest.fixture + def end_conn_fixture(self, _connect_end_to_, _move_end_to_cxn_): + connector = Connector(None, None) + shape, cxn_idx = 42, 24 + return connector, shape, cxn_idx + + @pytest.fixture(params=[(21, 32, False, 53), (43, 54, True, 43)]) + def end_x_get_fixture(self, request): + x, cx, flipH, expected_value = request.param + cxnSp = element( + "p:cxnSp/p:spPr/a:xfrm{flipH=%d}/(a:off{x=%d,y=6},a:ext{cx=%d,cy" + "=60})" % (flipH, x, cx) + ) + connector = Connector(cxnSp, None) + return connector, expected_value + + @pytest.fixture( + params=[ + ( + "a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 32, + "a:xfrm/(a:off{x=10,y=1},a:ext{cx=22,cy=1})", + ), + ( + "a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 15, + "a:xfrm/(a:off{x=10,y=1},a:ext{cx=5,cy=1})", + ), + ( + "a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 5, + "a:xfrm{flipH=1}/(a:off{x=5,y=1},a:ext{cx=5,cy=1})", + ), + ( + "a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 5, + "a:xfrm{flipH=1}/(a:off{x=5,y=1},a:ext{cx=15,cy=1})", + ), + ( + "a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 15, + "a:xfrm{flipH=1}/(a:off{x=15,y=1},a:ext{cx=5,cy=1})", + ), + ( + "a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})", + 28, + "a:xfrm/(a:off{x=20,y=1},a:ext{cx=8,cy=1})", + ), + ] + ) + def end_x_set_fixture(self, request): + xfrm_cxml, new_x, expected_cxml = request.param + tmpl = "p:cxnSp/p:spPr/%s" + cxnSp = element(tmpl % xfrm_cxml) + expected_xml = xml(tmpl % expected_cxml) + connector = Connector(cxnSp, None) + return connector, new_x, expected_xml + + @pytest.fixture(params=[(31, 42, False, 73), (53, 14, True, 53)]) + def end_y_get_fixture(self, request): + y, cy, flipV, expected_value = request.param + cxnSp = element( + "p:cxnSp/p:spPr/a:xfrm{flipV=%d}/(a:off{x=6,y=%d},a:ext{cx=32,cy" + "=%d})" % (flipV, y, cy) + ) + connector = Connector(cxnSp, None) + return connector, expected_value + + @pytest.fixture( + params=[ + ( + "a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 28, + "a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=18})", + ), + ( + "a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 13, + "a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=3})", + ), + ( + "a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 4, + "a:xfrm{flipV=1}/(a:off{x=1,y=4},a:ext{cx=1,cy=6})", + ), + ( + "a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 6, + "a:xfrm{flipV=1}/(a:off{x=1,y=6},a:ext{cx=1,cy=14})", + ), + ( + "a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 12, + "a:xfrm{flipV=1}/(a:off{x=1,y=12},a:ext{cx=1,cy=8})", + ), + ( + "a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})", + 27, + "a:xfrm/(a:off{x=1,y=20},a:ext{cx=1,cy=7})", + ), + ] + ) + def end_y_set_fixture(self, request): + xfrm_cxml, new_y, expected_cxml = request.param + tmpl = "p:cxnSp/p:spPr/%s" + cxnSp = element(tmpl % xfrm_cxml) + expected_xml = xml(tmpl % expected_cxml) + connector = Connector(cxnSp, None) + return connector, new_y, expected_xml + + @pytest.fixture( + params=[ + (0, "p:cxnSp/p:spPr/a:xfrm/(a:off{x=25,y=15},a:ext{cx=74,cy=123})"), + (1, "p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=33},a:ext{cx=89,cy=105})"), + (2, "p:cxnSp/p:spPr/a:xfrm/(a:off{x=25,y=51},a:ext{cx=74,cy=87})"), + (3, "p:cxnSp/p:spPr/a:xfrm/(a:off{x=40,y=33},a:ext{cx=59,cy=105})"), + ] + ) + def move_begin_fixture(self, request, shape_): + cxn_idx, expected_cxml = request.param + cxnSp = element("p:cxnSp/p:spPr/a:xfrm/(a:off{x=66,y=99},a:ext{cx=33,cy=39})") + connector = Connector(cxnSp, None) + shape_.left, shape_.top, shape_.width, shape_.height = 10, 15, 30, 36 + expected_xml = xml(expected_cxml) + return connector, shape_, cxn_idx, expected_xml + + @pytest.fixture( + params=[ + (0, "p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=15},a:ext{cx=50,cy=10})"), + (1, "p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=15},a:ext{cx=40,cy=19})"), + (2, "p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=15},a:ext{cx=50,cy=28})"), + (3, "p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=15},a:ext{cx=60,cy=19})"), + ] + ) + def move_end_fixture(self, request, shape_): + cxn_idx, expected_cxml = request.param + cxnSp = element("p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=15},a:ext{cx=10,cy=5})") + connector = Connector(cxnSp, None) + shape_.left, shape_.top, shape_.width, shape_.height = 50, 25, 20, 18 + expected_xml = xml(expected_cxml) + return connector, shape_, cxn_idx, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def _connect_begin_to_(self, request): + return method_mock(request, Connector, "_connect_begin_to", autospec=True) + + @pytest.fixture + def _connect_end_to_(self, request): + return method_mock(request, Connector, "_connect_end_to", autospec=True) + + @pytest.fixture + def _move_begin_to_cxn_(self, request): + return method_mock(request, Connector, "_move_begin_to_cxn", autospec=True) + + @pytest.fixture + def _move_end_to_cxn_(self, request): + return method_mock(request, Connector, "_move_end_to_cxn", autospec=True) + + @pytest.fixture + def shape_(self, request): + return instance_mock(request, BaseShape) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_freeform.py b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_freeform.py new file mode 100644 index 0000000000000000000000000000000000000000..dd5f53f0d3bb4daf794a596cef92f210d10ef8cf --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_freeform.py @@ -0,0 +1,565 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.shapes.freeform` module""" + +from __future__ import annotations + +import pytest + +from pptx.shapes.autoshape import Shape +from pptx.shapes.freeform import ( + FreeformBuilder, + _BaseDrawingOperation, + _Close, + _LineSegment, + _MoveTo, +) +from pptx.shapes.shapetree import SlideShapes +from pptx.util import Emu, Mm + +from ..unitutil.cxml import element, xml +from ..unitutil.file import snippet_seq +from ..unitutil.mock import ( + FixtureRequest, + Mock, + call, + initializer_mock, + instance_mock, + method_mock, + property_mock, +) + + +class DescribeFreeformBuilder(object): + """Unit-test suite for `pptx.shapes.freeform.FreeformBuilder` objects.""" + + def it_provides_a_constructor(self, shapes_: Mock, _init_: Mock): + start_x, start_y, x_scale, y_scale = 99.56, 200.49, 4.2, 2.4 + start_x_int, start_y_int = 100, 200 + + builder = FreeformBuilder.new(shapes_, start_x, start_y, x_scale, y_scale) + + _init_.assert_called_once_with(builder, shapes_, start_x_int, start_y_int, x_scale, y_scale) + assert isinstance(builder, FreeformBuilder) + + @pytest.mark.parametrize("close", [True, False]) + def it_can_add_straight_line_segments(self, request: FixtureRequest, close: bool): + _add_line_segment_ = method_mock(request, FreeformBuilder, "_add_line_segment") + _add_close_ = method_mock(request, FreeformBuilder, "_add_close") + builder = FreeformBuilder(None, None, None, None, None) # type: ignore + + return_value = builder.add_line_segments(((1, 2), (3, 4), (5, 6)), close) + + assert _add_line_segment_.call_args_list == [ + call(builder, 1, 2), + call(builder, 3, 4), + call(builder, 5, 6), + ] + assert _add_close_.call_args_list == ([call(builder)] if close else []) + assert return_value is builder + + def it_can_move_the_pen_location(self, _MoveTo_new_: Mock, move_to_: Mock): + x, y = 42, 24 + _MoveTo_new_.return_value = move_to_ + builder = FreeformBuilder(None, None, None, None, None) # type: ignore + + return_value = builder.move_to(x, y) + + _MoveTo_new_.assert_called_once_with(builder, x, y) + assert builder._drawing_operations[-1] is move_to_ + assert return_value is builder + + def it_can_build_the_specified_freeform_shape( + self, + shapes_: Mock, + apply_operation_to_: Mock, + _add_freeform_sp_: Mock, + _start_path_: Mock, + shape_: Mock, + ): + origin_x, origin_y = Mm(42), Mm(24) + sp, path = element("p:sp"), element("a:path") + drawing_ops = ( + _LineSegment(None, None, None), # type: ignore + _LineSegment(None, None, None), # type: ignore + ) + shapes_._shape_factory.return_value = shape_ + _add_freeform_sp_.return_value = sp + _start_path_.return_value = path + builder = FreeformBuilder(shapes_, None, None, None, None) # type: ignore + builder._drawing_operations.extend(drawing_ops) + calls = [call(drawing_ops[0], path), call(drawing_ops[1], path)] + + shape = builder.convert_to_shape(origin_x, origin_y) + + _add_freeform_sp_.assert_called_once_with(builder, origin_x, origin_y) + _start_path_.assert_called_once_with(builder, sp) + assert apply_operation_to_.call_args_list == calls + shapes_._shape_factory.assert_called_once_with(sp) + assert shape is shape_ + + @pytest.mark.parametrize( + ("start_x", "xs", "expected_value"), + [ + (Mm(0), (1, None, 2, 3), Mm(0)), + (Mm(6), (1, None, 2, 3), Mm(1)), + (Mm(50), (150, -5, None, 100), Mm(-5)), + ], + ) + def it_knows_the_shape_x_offset( + self, start_x: int, xs: tuple[int | None, ...], expected_value: int + ): + builder = FreeformBuilder(None, start_x, None, None, None) # type: ignore + drawing_ops = [_Close() if x is None else _LineSegment(builder, Mm(x), Mm(0)) for x in xs] + builder._drawing_operations.extend(drawing_ops) + + assert builder.shape_offset_x == expected_value + + @pytest.mark.parametrize( + ("start_y", "ys", "expected_value"), + [ + (Mm(0), (2, None, 6, 8), Mm(0)), + (Mm(4), (2, None, 6, 8), Mm(2)), + (Mm(19), (213, -22, None, 100), Mm(-22)), + ], + ) + def it_knows_the_shape_y_offset( + self, start_y: int, ys: tuple[int | None, ...], expected_value: int + ): + builder = FreeformBuilder(None, None, start_y, None, None) # type: ignore + drawing_ops = [_Close() if y is None else _LineSegment(builder, Mm(0), Mm(y)) for y in ys] + builder._drawing_operations.extend(drawing_ops) + + assert builder.shape_offset_y == expected_value + + def it_adds_a_freeform_sp_to_help( + self, _left_prop_: Mock, _top_prop_: Mock, _width_prop_: Mock, _height_prop_: Mock + ): + origin_x, origin_y = Emu(42), Emu(24) + spTree = element("p:spTree") + shapes = SlideShapes(spTree, None) # type: ignore + _left_prop_.return_value, _top_prop_.return_value = Emu(12), Emu(34) + _width_prop_.return_value, _height_prop_.return_value = 56, 78 + builder = FreeformBuilder(shapes, None, None, None, None) # type: ignore + expected_xml = snippet_seq("freeform")[0] + + sp = builder._add_freeform_sp(origin_x, origin_y) + + assert spTree.xml == expected_xml + assert sp is spTree.xpath("p:sp")[0] + + def it_adds_a_line_segment_to_help(self, _LineSegment_new_: Mock, line_segment_: Mock): + x, y = 4, 2 + _LineSegment_new_.return_value = line_segment_ + + builder = FreeformBuilder(None, None, None, None, None) # type: ignore + + builder._add_line_segment(x, y) + + _LineSegment_new_.assert_called_once_with(builder, x, y) + assert builder._drawing_operations == [line_segment_] + + def it_closes_a_contour_to_help(self, _Close_new_: Mock, close_: Mock): + _Close_new_.return_value = close_ + builder = FreeformBuilder(None, None, None, None, None) # type: ignore + + builder._add_close() + + _Close_new_.assert_called_once_with() + assert builder._drawing_operations == [close_] + + def it_knows_the_freeform_left_extent_to_help(self, left_fixture): + builder, expected_value = left_fixture + left = builder._left + assert left == expected_value + + def it_knows_the_freeform_top_extent_to_help(self, top_fixture): + builder, expected_value = top_fixture + top = builder._top + assert top == expected_value + + def it_knows_the_freeform_width_to_help(self, width_fixture): + builder, expected_value = width_fixture + width = builder._width + assert width == expected_value + + @pytest.mark.parametrize( + ("dy", "y_scale", "expected_value"), + [(0, 2.0, 0), (24, 10.0, 240), (914400, 314.1, 287213040)], + ) + def it_knows_the_freeform_height_to_help( + self, dy: int, y_scale: float, expected_value: int, _dy_prop_: Mock + ): + _dy_prop_.return_value = dy + builder = FreeformBuilder(None, None, None, None, y_scale) # type: ignore + height = builder._height + assert height == expected_value + + def it_knows_the_local_coordinate_width_to_help(self, dx_fixture): + builder, expected_value = dx_fixture + dx = builder._dx + assert dx == expected_value + + def it_knows_the_local_coordinate_height_to_help(self, dy_fixture): + builder, expected_value = dy_fixture + dy = builder._dy + assert dy == expected_value + + def it_can_start_a_new_path_to_help( + self, request: FixtureRequest, _dx_prop_: Mock, _dy_prop_: Mock + ): + _local_to_shape_ = method_mock( + request, FreeformBuilder, "_local_to_shape", return_value=(101, 202) + ) + sp = element("p:sp/p:spPr/a:custGeom") + start_x, start_y = 42, 24 + _dx_prop_.return_value, _dy_prop_.return_value = 1001, 2002 + builder = FreeformBuilder(None, start_x, start_y, None, None) + + path = builder._start_path(sp) + + _local_to_shape_.assert_called_once_with(builder, start_x, start_y) + assert sp.xml == xml( + "p:sp/p:spPr/a:custGeom/a:pathLst/a:path{w=1001,h=2002}/a:moveTo" "/a:pt{x=101,y=202}" + ) + assert path is sp.xpath(".//a:path")[-1] + + def it_translates_local_to_shape_coordinates_to_help(self, local_fixture): + builder, local_x, local_y, expected_value = local_fixture + shape_x_y = builder._local_to_shape(local_x, local_y) + assert shape_x_y == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + (0, (1, None, 2, 3), 3), + (6, (1, None, 2, 3), 5), + (50, (150, -5, None, 100), 155), + ] + ) + def dx_fixture(self, request: FixtureRequest): + start_x, xs, expected_value = request.param + drawing_ops = [] + for x in xs: + if x is None: + drawing_ops.append(_Close()) + else: + drawing_ops.append(_BaseDrawingOperation(None, x, None)) + + builder = FreeformBuilder(None, start_x, None, None, None) + builder._drawing_operations.extend(drawing_ops) + return builder, expected_value + + @pytest.fixture( + params=[ + (0, (1, None, 2, 3), 3), + (2, (1, None, 2, 3), 2), + (32, (160, -8, None, 101), 168), + ] + ) + def dy_fixture(self, request: FixtureRequest): + start_y, ys, expected_value = request.param + drawing_ops = [] + for y in ys: + if y is None: + drawing_ops.append(_Close()) + else: + drawing_ops.append(_BaseDrawingOperation(None, None, y)) + + builder = FreeformBuilder(None, None, start_y, None, None) + builder._drawing_operations.extend(drawing_ops) + return builder, expected_value + + @pytest.fixture(params=[(0, 1.0, 0), (4, 10.0, 40), (914400, 914.3, 836035920)]) + def left_fixture(self, request: FixtureRequest, shape_offset_x_prop_: Mock): + offset_x, x_scale, expected_value = request.param + shape_offset_x_prop_.return_value = offset_x + + builder = FreeformBuilder(None, None, None, x_scale, None) + return builder, expected_value + + @pytest.fixture + def local_fixture(self, shape_offset_x_prop_: Mock, shape_offset_y_prop_: Mock): + local_x, local_y = 123, 456 + shape_offset_x_prop_.return_value = 23 + shape_offset_y_prop_.return_value = 156 + + builder = FreeformBuilder(None, None, None, None, None) + expected_value = (100, 300) + return builder, local_x, local_y, expected_value + + @pytest.fixture + def sp_fixture( + self, _left_prop_: Mock, _top_prop_: Mock, _width_prop_: Mock, _height_prop_: Mock + ): + origin_x, origin_y = 42, 24 + spTree = element("p:spTree") + shapes = SlideShapes(spTree, None) + _left_prop_.return_value, _top_prop_.return_value = 12, 34 + _width_prop_.return_value, _height_prop_.return_value = 56, 78 + + builder = FreeformBuilder(shapes, None, None, None, None) + expected_xml = snippet_seq("freeform")[0] + return builder, origin_x, origin_y, spTree, expected_xml + + @pytest.fixture(params=[(0, 11.0, 0), (100, 10.36, 1036), (914242, 943.1, 862221630)]) + def top_fixture(self, request: FixtureRequest, shape_offset_y_prop_: Mock): + offset_y, y_scale, expected_value = request.param + shape_offset_y_prop_.return_value = offset_y + + builder = FreeformBuilder(None, None, None, None, y_scale) + return builder, expected_value + + @pytest.fixture(params=[(0, 1.0, 0), (42, 10.0, 420), (914400, 914.4, 836127360)]) + def width_fixture(self, request: FixtureRequest, _dx_prop_: Mock): + dx, x_scale, expected_value = request.param + _dx_prop_.return_value = dx + + builder = FreeformBuilder(None, None, None, x_scale, None) + return builder, expected_value + + # fixture components ----------------------------------- + + @pytest.fixture + def _add_freeform_sp_(self, request: FixtureRequest): + return method_mock(request, FreeformBuilder, "_add_freeform_sp", autospec=True) + + @pytest.fixture + def apply_operation_to_(self, request: FixtureRequest): + return method_mock(request, _LineSegment, "apply_operation_to", autospec=True) + + @pytest.fixture + def close_(self, request: FixtureRequest): + return instance_mock(request, _Close) + + @pytest.fixture + def _Close_new_(self, request: FixtureRequest): + return method_mock(request, _Close, "new", autospec=False) + + @pytest.fixture + def _dx_prop_(self, request: FixtureRequest): + return property_mock(request, FreeformBuilder, "_dx") + + @pytest.fixture + def _dy_prop_(self, request: FixtureRequest): + return property_mock(request, FreeformBuilder, "_dy") + + @pytest.fixture + def _height_prop_(self, request: FixtureRequest): + return property_mock(request, FreeformBuilder, "_height") + + @pytest.fixture + def _init_(self, request: FixtureRequest): + return initializer_mock(request, FreeformBuilder, autospec=True) + + @pytest.fixture + def _left_prop_(self, request: FixtureRequest): + return property_mock(request, FreeformBuilder, "_left") + + @pytest.fixture + def line_segment_(self, request: FixtureRequest): + return instance_mock(request, _LineSegment) + + @pytest.fixture + def _LineSegment_new_(self, request: FixtureRequest): + return method_mock(request, _LineSegment, "new", autospec=False) + + @pytest.fixture + def move_to_(self, request: FixtureRequest): + return instance_mock(request, _MoveTo) + + @pytest.fixture + def _MoveTo_new_(self, request: FixtureRequest): + return method_mock(request, _MoveTo, "new", autospec=False) + + @pytest.fixture + def shape_(self, request: FixtureRequest): + return instance_mock(request, Shape) + + @pytest.fixture + def shape_offset_x_prop_(self, request: FixtureRequest): + return property_mock(request, FreeformBuilder, "shape_offset_x") + + @pytest.fixture + def shape_offset_y_prop_(self, request: FixtureRequest): + return property_mock(request, FreeformBuilder, "shape_offset_y") + + @pytest.fixture + def shapes_(self, request: FixtureRequest): + return instance_mock(request, SlideShapes) + + @pytest.fixture + def _start_path_(self, request: FixtureRequest): + return method_mock(request, FreeformBuilder, "_start_path", autospec=True) + + @pytest.fixture + def _top_prop_(self, request: FixtureRequest): + return property_mock(request, FreeformBuilder, "_top") + + @pytest.fixture + def _width_prop_(self, request: FixtureRequest): + return property_mock(request, FreeformBuilder, "_width") + + +class Describe_BaseDrawingOperation(object): + """Unit-test suite for `pptx.shapes.freeform.BaseDrawingOperation` objects.""" + + def it_knows_its_x_coordinate(self, x_fixture): + drawing_operation, expected_value = x_fixture + x = drawing_operation.x + assert x == expected_value + + def it_knows_its_y_coordinate(self, y_fixture): + drawing_operation, expected_value = y_fixture + y = drawing_operation.y + assert y == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def x_fixture(self): + x = 42 + drawing_operation = _BaseDrawingOperation(None, x, None) + expected_value = x + return drawing_operation, expected_value + + @pytest.fixture + def y_fixture(self): + y = 24 + drawing_operation = _BaseDrawingOperation(None, None, y) + expected_value = y + return drawing_operation, expected_value + + +class Describe_Close(object): + """Unit-test suite for `pptx.shapes.freeform._Close` objects.""" + + def it_provides_a_constructor(self, new_fixture): + _init_ = new_fixture + + close = _Close.new() + + _init_.assert_called_once_with() + assert isinstance(close, _Close) + + def it_can_add_close_a_contour(self, apply_fixture): + close, path, expected_xml = apply_fixture + + close_elm = close.apply_operation_to(path) + + assert path.xml == expected_xml + assert close_elm is path.xpath("a:close")[-1] + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def new_fixture(self, _init_): + return _init_ + + # fixture components ----------------------------------- + + @pytest.fixture + def apply_fixture(self): + path = element("a:path") + close = _Close() + expected_xml = xml("a:path/a:close") + return close, path, expected_xml + + @pytest.fixture + def _init_(self, request: FixtureRequest): + return initializer_mock(request, _Close, autospec=True) + + +class Describe_LineSegment(object): + """Unit-test suite for `pptx.shapes.freeform._LineSegment` objects.""" + + def it_provides_a_constructor(self, new_fixture): + builder_, x, y, _init_, x_int, y_int = new_fixture + + line_segment = _LineSegment.new(builder_, x, y) + + _init_.assert_called_once_with(line_segment, builder_, x_int, y_int) + assert isinstance(line_segment, _LineSegment) + + def it_can_add_its_line_segment_to_a_path(self, apply_fixture): + line_segment, path, expected_xml = apply_fixture + + lnTo = line_segment.apply_operation_to(path) + + assert path.xml == expected_xml + assert lnTo is path.xpath("a:lnTo")[-1] + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def apply_fixture(self, builder_): + x, y = 420, 240 + path = element("a:path") + builder_.shape_offset_x, builder_.shape_offset_y = 100, 200 + + line_segment = _LineSegment(builder_, x, y) + expected_xml = xml("a:path/a:lnTo/a:pt{x=320,y=40}") + return line_segment, path, expected_xml + + @pytest.fixture + def new_fixture(self, builder_, _init_): + x, y, x_int, y_int = 99.51, 200.49, 100, 200 + return builder_, x, y, _init_, x_int, y_int + + # fixture components ----------------------------------- + + @pytest.fixture + def builder_(self, request: FixtureRequest): + return instance_mock(request, FreeformBuilder) + + @pytest.fixture + def _init_(self, request: FixtureRequest): + return initializer_mock(request, _LineSegment, autospec=True) + + +class Describe_MoveTo(object): + """Unit-test suite for `pptx.shapes.freeform._MoveTo` objects.""" + + def it_provides_a_constructor(self, new_fixture): + builder_, x, y, _init_, x_int, y_int = new_fixture + + move_to = _MoveTo.new(builder_, x, y) + + _init_.assert_called_once_with(move_to, builder_, x_int, y_int) + assert isinstance(move_to, _MoveTo) + + def it_can_add_its_move_to_a_path(self, apply_fixture): + move_to, path, expected_xml = apply_fixture + + moveTo = move_to.apply_operation_to(path) + + assert path.xml == expected_xml + assert moveTo is path.xpath("a:moveTo")[-1] + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def apply_fixture(self, builder_): + x, y = 120, 340 + path = element("a:path") + builder_.shape_offset_x, builder_.shape_offset_y = 100, 200 + + move_to = _MoveTo(builder_, x, y) + expected_xml = xml("a:path/a:moveTo/a:pt{x=20,y=140}") + return move_to, path, expected_xml + + @pytest.fixture + def new_fixture(self, builder_, _init_): + x, y, x_int, y_int = 99.51, 200.49, 100, 200 + return builder_, x, y, _init_, x_int, y_int + + # fixture components ----------------------------------- + + @pytest.fixture + def builder_(self, request: FixtureRequest): + return instance_mock(request, FreeformBuilder) + + @pytest.fixture + def _init_(self, request: FixtureRequest): + return initializer_mock(request, _MoveTo, autospec=True) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_graphfrm.py b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_graphfrm.py new file mode 100644 index 0000000000000000000000000000000000000000..3324fcfe09a459b3ebdce053e5e087c4842b7de4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_graphfrm.py @@ -0,0 +1,168 @@ +"""Unit-test suite for pptx.shapes.graphfrm module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.chart import Chart +from pptx.enum.shapes import MSO_SHAPE_TYPE +from pptx.parts.chart import ChartPart +from pptx.parts.embeddedpackage import EmbeddedPackagePart +from pptx.parts.slide import SlidePart +from pptx.shapes.graphfrm import GraphicFrame, _OleFormat +from pptx.shapes.shapetree import SlideShapes +from pptx.spec import ( + GRAPHIC_DATA_URI_CHART, + GRAPHIC_DATA_URI_OLEOBJ, + GRAPHIC_DATA_URI_TABLE, +) + +from ..unitutil.cxml import element +from ..unitutil.mock import class_mock, instance_mock, property_mock + + +class DescribeGraphicFrame(object): + """Unit-test suite for `pptx.shapes.graphfrm.GraphicFrame` object.""" + + def it_provides_access_to_the_chart_it_contains( + self, request, has_chart_prop_, chart_part_, chart_ + ): + has_chart_prop_.return_value = True + property_mock(request, GraphicFrame, "chart_part", return_value=chart_part_) + chart_part_.chart = chart_ + + assert GraphicFrame(None, None).chart is chart_ + + def but_it_raises_on_chart_if_there_isnt_one(self, has_chart_prop_): + has_chart_prop_.return_value = False + + with pytest.raises(ValueError) as e: + GraphicFrame(None, None).chart + assert str(e.value) == "shape does not contain a chart" + + def it_provides_access_to_its_chart_part(self, request, chart_part_): + slide_part_ = instance_mock(request, SlidePart) + slide_part_.related_part.return_value = chart_part_ + property_mock(request, GraphicFrame, "part", return_value=slide_part_) + graphic_frame = GraphicFrame( + element("p:graphicFrame/a:graphic/a:graphicData/c:chart{r:id=rId42}"), None + ) + + chart_part = graphic_frame.chart_part + + slide_part_.related_part.assert_called_once_with("rId42") + assert chart_part is chart_part_ + + @pytest.mark.parametrize( + "graphicData_uri, expected_value", + ( + (GRAPHIC_DATA_URI_CHART, True), + (GRAPHIC_DATA_URI_OLEOBJ, False), + (GRAPHIC_DATA_URI_TABLE, False), + ), + ) + def it_knows_whether_it_contains_a_chart(self, graphicData_uri, expected_value): + graphicFrame = element("p:graphicFrame/a:graphic/a:graphicData{uri=%s}" % graphicData_uri) + assert GraphicFrame(graphicFrame, None).has_chart is expected_value + + @pytest.mark.parametrize( + "graphicData_uri, expected_value", + ( + (GRAPHIC_DATA_URI_CHART, False), + (GRAPHIC_DATA_URI_OLEOBJ, False), + (GRAPHIC_DATA_URI_TABLE, True), + ), + ) + def it_knows_whether_it_contains_a_table(self, graphicData_uri, expected_value): + graphicFrame = element("p:graphicFrame/a:graphic/a:graphicData{uri=%s}" % graphicData_uri) + assert GraphicFrame(graphicFrame, None).has_table is expected_value + + def it_provides_access_to_the_OleFormat_object(self, request): + ole_format_ = instance_mock(request, _OleFormat) + _OleFormat_ = class_mock( + request, "pptx.shapes.graphfrm._OleFormat", return_value=ole_format_ + ) + graphicFrame = element( + "p:graphicFrame/a:graphic/a:graphicData{uri=http://schemas.openxmlformats" + ".org/presentationml/2006/ole}" + ) + parent_ = instance_mock(request, SlideShapes) + graphic_frame = GraphicFrame(graphicFrame, parent_) + + ole_format = graphic_frame.ole_format + + _OleFormat_.assert_called_once_with(graphicFrame.graphicData, parent_) + assert ole_format is ole_format_ + + def but_it_raises_on_ole_format_when_this_is_not_an_OLE_object(self): + graphic_frame = GraphicFrame( + element( + "p:graphicFrame/a:graphic/a:graphicData{uri=http://schemas.openxmlfor" + "mats.org/drawingml/2006/table}" + ), + None, + ) + with pytest.raises(ValueError) as e: + graphic_frame.ole_format + assert str(e.value) == "not an OLE-object shape" + + def it_raises_on_shadow(self): + graphic_frame = GraphicFrame(None, None) + with pytest.raises(NotImplementedError): + graphic_frame.shadow + + @pytest.mark.parametrize( + "uri, oleObj_child, expected_value", + ( + (GRAPHIC_DATA_URI_CHART, None, MSO_SHAPE_TYPE.CHART), + (GRAPHIC_DATA_URI_OLEOBJ, "embed", MSO_SHAPE_TYPE.EMBEDDED_OLE_OBJECT), + (GRAPHIC_DATA_URI_OLEOBJ, "link", MSO_SHAPE_TYPE.LINKED_OLE_OBJECT), + (GRAPHIC_DATA_URI_TABLE, None, MSO_SHAPE_TYPE.TABLE), + ("foobar", None, None), + ), + ) + def it_knows_its_shape_type(self, uri, oleObj_child, expected_value): + graphicFrame = element( + ("p:graphicFrame/a:graphic/a:graphicData{uri=%s}/p:oleObj/p:%s" % (uri, oleObj_child)) + if oleObj_child + else "p:graphicFrame/a:graphic/a:graphicData{uri=%s}" % uri + ) + assert GraphicFrame(graphicFrame, None).shape_type is expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def chart_(self, request): + return instance_mock(request, Chart) + + @pytest.fixture + def chart_part_(self, request, chart_): + return instance_mock(request, ChartPart, chart=chart_) + + @pytest.fixture + def has_chart_prop_(self, request): + return property_mock(request, GraphicFrame, "has_chart") + + +class Describe_OleFormat(object): + """Unit-test suite for `pptx.shapes.graphfrm._OleFormat` object.""" + + def it_provides_access_to_the_OLE_object_blob(self, request): + ole_obj_part_ = instance_mock(request, EmbeddedPackagePart, blob=b"0123456789") + slide_part_ = instance_mock(request, SlidePart) + slide_part_.related_part.return_value = ole_obj_part_ + property_mock(request, _OleFormat, "part", return_value=slide_part_) + ole_format = _OleFormat(element("a:graphicData/p:oleObj{r:id=rId7}"), None) + + blob = ole_format.blob + + slide_part_.related_part.assert_called_once_with("rId7") + assert blob == b"0123456789" + + def it_knows_the_OLE_object_prog_id(self): + graphicData = element("a:graphicData/p:oleObj{progId=Excel.Sheet.12}") + assert _OleFormat(graphicData, None).prog_id == "Excel.Sheet.12" + + def it_knows_whether_to_show_the_OLE_object_as_an_icon(self): + graphicData = element("a:graphicData/p:oleObj{showAsIcon=1}") + assert _OleFormat(graphicData, None).show_as_icon is True diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_group.py b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_group.py new file mode 100644 index 0000000000000000000000000000000000000000..93c06d029d49320f64cc0e39a71d82f47191adbf --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_group.py @@ -0,0 +1,73 @@ +"""Test suite for pptx.shapes.group module.""" + +from __future__ import annotations + +import pytest + +from pptx.dml.effect import ShadowFormat +from pptx.enum.shapes import MSO_SHAPE_TYPE +from pptx.shapes.group import GroupShape +from pptx.shapes.shapetree import GroupShapes + +from ..unitutil.cxml import element +from ..unitutil.mock import class_mock, initializer_mock, instance_mock + + +class DescribeGroupShape(object): + def it_raises_on_access_click_action(self, click_action_fixture): + group = click_action_fixture + with pytest.raises(TypeError): + group.click_action + + def it_provides_access_to_its_shadow(self, ShadowFormat_, shadow_): + grpSp = element("p:grpSp/p:grpSpPr") + grpSpPr = grpSp.xpath("//p:grpSpPr")[0] + ShadowFormat_.return_value = shadow_ + group_shape = GroupShape(grpSp, None) + + shadow = group_shape.shadow + + ShadowFormat_.assert_called_once_with(grpSpPr) + assert shadow is shadow_ + + def it_knows_its_shape_type(self, shape_type_fixture): + group = shape_type_fixture + assert group.shape_type == MSO_SHAPE_TYPE.GROUP + + def it_provides_access_to_its_sub_shapes(self, shapes_fixture): + group, GroupShapes_init_, grpSp = shapes_fixture + + shapes = group.shapes + + GroupShapes_init_.assert_called_once_with(shapes, grpSp, group) + assert isinstance(shapes, GroupShapes) + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def click_action_fixture(self): + return GroupShape(None, None) + + @pytest.fixture + def shape_type_fixture(self): + return GroupShape(None, None) + + @pytest.fixture + def shapes_fixture(self, GroupShapes_init_): + grpSp = element("p:grpSp") + group = GroupShape(grpSp, None) + return group, GroupShapes_init_, grpSp + + # fixture components --------------------------------------------- + + @pytest.fixture + def GroupShapes_init_(self, request): + return initializer_mock(request, GroupShapes, autospec=True) + + @pytest.fixture + def shadow_(self, request): + return instance_mock(request, ShadowFormat) + + @pytest.fixture + def ShadowFormat_(self, request): + return class_mock(request, "pptx.shapes.group.ShadowFormat") diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_picture.py b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_picture.py new file mode 100644 index 0000000000000000000000000000000000000000..75728da21172f18d9b10d5c038cbaab0862e8352 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_picture.py @@ -0,0 +1,306 @@ +"""Test suite for pptx.shapes.picture module.""" + +from __future__ import annotations + +import pytest + +from pptx.dml.line import LineFormat +from pptx.enum.shapes import MSO_SHAPE, MSO_SHAPE_TYPE, PP_MEDIA_TYPE +from pptx.parts.image import Image +from pptx.parts.slide import SlidePart +from pptx.shapes.picture import Movie, Picture, _BasePicture, _MediaFormat +from pptx.util import Pt + +from ..unitutil.cxml import element, xml +from ..unitutil.mock import call, class_mock, instance_mock, property_mock + + +class Describe_BasePicture(object): + def it_knows_its_cropping(self, crop_get_fixture): + picture, prop_name, expected_value = crop_get_fixture + crop = getattr(picture, prop_name) + assert abs(crop - expected_value) < 0.000001 + + def it_can_change_its_cropping(self, crop_set_fixture): + picture, prop_name, value, expected_xml = crop_set_fixture + setattr(picture, prop_name, value) + assert picture._element.xml == expected_xml + + def it_provides_access_to_its_outline(self, line_fixture): + picture = line_fixture + line = picture.line + assert isinstance(line, LineFormat) + # exercise line to test has_line interface, .ln and .get_or_add_ln() + picture.line.width = Pt(1) + assert picture.line.width == Pt(1) + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("p:pic/p:blipFill", "left", 0.0), + ("p:pic/p:blipFill/a:srcRect", "top", 0.0), + ("p:pic/p:blipFill/a:srcRect{l=99999}", "bottom", 0.0), + ("p:pic/p:blipFill/a:srcRect{l=42424}", "left", 0.42424), + ("p:pic/p:blipFill/a:srcRect{t=-10000}", "top", -0.1), + ("p:pic/p:blipFill/a:srcRect{r=250000}", "right", 2.5), + ("p:pic/p:blipFill/a:srcRect{b=33333}", "bottom", 0.33333), + ] + ) + def crop_get_fixture(self, request): + pic_cxml, side, expected_value = request.param + picture = Picture(element(pic_cxml), None) + prop_name = "crop_%s" % side + return picture, prop_name, expected_value + + @pytest.fixture( + params=[ + ( + "p:pic{a:b=c}/p:blipFill", + "left", + 0.11, + "p:pic{a:b=c}/p:blipFill/a:srcRect{l=11000}", + ), + ( + "p:pic{a:b=c}/p:blipFill", + "top", + 0.21, + "p:pic{a:b=c}/p:blipFill/a:srcRect{t=21000}", + ), + ( + "p:pic{a:b=c}/p:blipFill", + "right", + 0.31, + "p:pic{a:b=c}/p:blipFill/a:srcRect{r=31000}", + ), + ( + "p:pic{a:b=c}/p:blipFill", + "bottom", + 0.41, + "p:pic{a:b=c}/p:blipFill/a:srcRect{b=41000}", + ), + ( + "p:pic{a:b=c}/p:blipFill/a:srcRect{l=80000}", + "left", + 0.21, + "p:pic{a:b=c}/p:blipFill/a:srcRect{l=21000}", + ), + ( + "p:pic{a:b=c}/p:blipFill/a:srcRect{t=70000}", + "top", + 0.22, + "p:pic{a:b=c}/p:blipFill/a:srcRect{t=22000}", + ), + ( + "p:pic{a:b=c}/p:blipFill/a:srcRect{r=60000}", + "right", + 0.23, + "p:pic{a:b=c}/p:blipFill/a:srcRect{r=23000}", + ), + ( + "p:pic{a:b=c}/p:blipFill/a:srcRect{b=50000}", + "bottom", + 0.24, + "p:pic{a:b=c}/p:blipFill/a:srcRect{b=24000}", + ), + ( + "p:pic{a:b=c}/p:blipFill/a:srcRect{l=90000}", + "left", + 0, + "p:pic{a:b=c}/p:blipFill/a:srcRect", + ), + ( + "p:pic{a:b=c}/p:blipFill/a:srcRect{t=91000}", + "top", + 0.0, + "p:pic{a:b=c}/p:blipFill/a:srcRect", + ), + ( + "p:pic{a:b=c}/p:blipFill/a:srcRect{r=92000}", + "right", + 0, + "p:pic{a:b=c}/p:blipFill/a:srcRect", + ), + ( + "p:pic{a:b=c}/p:blipFill/a:srcRect{b=93000}", + "bottom", + 0.0, + "p:pic{a:b=c}/p:blipFill/a:srcRect", + ), + ] + ) + def crop_set_fixture(self, request): + pic_cxml, side, value, expected_cxml = request.param + pic = element(pic_cxml) + picture = Picture(pic, None) + prop_name = "crop_%s" % side + expected_xml = xml(expected_cxml) + return picture, prop_name, value, expected_xml + + @pytest.fixture + def line_fixture(self): + return _BasePicture(element("p:pic/p:spPr"), None) + + +class DescribeMovie(object): + def it_knows_its_shape_type(self, shape_type_fixture): + movie = shape_type_fixture + assert movie.shape_type == MSO_SHAPE_TYPE.MEDIA + + def it_knows_its_media_type(self, media_type_fixture): + movie = media_type_fixture + assert movie.media_type == PP_MEDIA_TYPE.MOVIE + + def it_provides_access_to_its_media_format(self, format_fixture): + movie, MediaFormat_, pic, parent, media_format_ = format_fixture + media_format = movie.media_format + MediaFormat_.assert_called_once_with(pic, parent) + assert media_format is media_format_ + + def it_provides_access_to_its_poster_frame_image(self, pfrm_fixture): + movie, slide_part_, calls, expected_value = pfrm_fixture + poster_frame = movie.poster_frame + assert slide_part_.get_image.call_args_list == calls + assert poster_frame == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def format_fixture(self, _MediaFormat_, media_format_): + pic = element("p:pic") + parent = movie = Movie(pic, None) + return movie, _MediaFormat_, pic, parent, media_format_ + + @pytest.fixture + def media_type_fixture(self): + return Movie(None, None) + + @pytest.fixture( + params=[ + ("p:pic/p:blipFill/a:blip{r:embed=rId42}", True), + ("p:pic/p:blipFill/a:blip", False), + ] + ) + def pfrm_fixture(self, request, slide_part_, image_, part_prop_): + cxml, is_present = request.param + movie = Movie(element(cxml), None) + calls, expected_value = [], None + part_prop_.return_value = slide_part_ + slide_part_.get_image.return_value = image_ + if is_present: + calls.append(call("rId42")) + expected_value = image_ + return movie, slide_part_, calls, expected_value + + @pytest.fixture + def shape_type_fixture(self): + return Movie(None, None) + + # fixture components --------------------------------------------- + + @pytest.fixture + def image_(self, request): + return instance_mock(request, Image) + + @pytest.fixture + def _MediaFormat_(self, request, media_format_): + return class_mock(request, "pptx.shapes.picture._MediaFormat", return_value=media_format_) + + @pytest.fixture + def media_format_(self, request): + return instance_mock(request, _MediaFormat) + + @pytest.fixture + def part_prop_(self, request): + return property_mock(request, Movie, "part") + + @pytest.fixture + def slide_part_(self, request): + return instance_mock(request, SlidePart) + + +class DescribePicture(object): + def it_knows_its_masking_shape(self, autoshape_get_fixture): + picture, expected_value = autoshape_get_fixture + auto_shape_type = picture.auto_shape_type + assert auto_shape_type == expected_value + + def it_can_change_its_masking_shape(self, autoshape_set_fixture): + picture, new_value, expected_xml = autoshape_set_fixture + picture.auto_shape_type = new_value + assert picture._element.xml == expected_xml + + def it_knows_its_shape_type(self, shape_type_fixture): + picture = shape_type_fixture + assert picture.shape_type == MSO_SHAPE_TYPE.PICTURE + + def it_provides_access_to_its_image(self, image_fixture): + picture, slide_part_, rId, image_ = image_fixture + image = picture.image + slide_part_.get_image.assert_called_once_with(rId) + assert image is image_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("", None), + ("/a:prstGeom{prst=rect}", MSO_SHAPE.RECTANGLE), + ("/a:prstGeom{prst=hexagon}", MSO_SHAPE.HEXAGON), + ] + ) + def autoshape_get_fixture(self, request): + prstGeom_cxml, expected_value = request.param + pic_cxml = "p:pic/p:spPr%s" % prstGeom_cxml + picture = Picture(element(pic_cxml), None) + return picture, expected_value + + @pytest.fixture( + params=[ + ( + "p:pic/p:spPr/a:custGeom", + MSO_SHAPE.RECTANGLE, + "p:pic/p:spPr/a:prstGeom{prst=rect}", + ), + ( + "p:pic/p:spPr/a:prstGeom{prst=rect}", + MSO_SHAPE.OVAL, + "p:pic/p:spPr/a:prstGeom{prst=ellipse}", + ), + ( + "p:pic/p:spPr/a:prstGeom{prst=ellipse}", + MSO_SHAPE.PIE, + "p:pic/p:spPr/a:prstGeom{prst=pie}", + ), + ] + ) + def autoshape_set_fixture(self, request): + pic_cxml, new_value, expected_cxml = request.param + picture = Picture(element(pic_cxml), None) + expected_xml = xml(expected_cxml) + return picture, new_value, expected_xml + + @pytest.fixture + def image_fixture(self, part_prop_, slide_part_, image_): + pic_cxml, rId = "p:pic/p:blipFill/a:blip{r:embed=rId42}", "rId42" + picture = Picture(element(pic_cxml), None) + slide_part_.get_image.return_value = image_ + return picture, slide_part_, rId, image_ + + @pytest.fixture + def shape_type_fixture(self): + return Picture(None, None) + + # fixture components --------------------------------------------- + + @pytest.fixture + def image_(self, request): + return instance_mock(request, Image) + + @pytest.fixture + def part_prop_(self, request, slide_part_): + return property_mock(request, Picture, "part", return_value=slide_part_) + + @pytest.fixture + def slide_part_(self, request): + return instance_mock(request, SlidePart) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_placeholder.py b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_placeholder.py new file mode 100644 index 0000000000000000000000000000000000000000..4d9b26ea0b2020be925ce65e5cd67612c8abfbac --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_placeholder.py @@ -0,0 +1,564 @@ +"""Unit-test suite for `pptx.shapes.placeholder` module.""" + +from __future__ import annotations + +import pytest + +from pptx.chart.data import ChartData +from pptx.enum.chart import XL_CHART_TYPE as XCT +from pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDER +from pptx.oxml.shapes.shared import ST_Direction, ST_PlaceholderSize +from pptx.parts.image import ImagePart +from pptx.parts.slide import NotesSlidePart, SlidePart +from pptx.shapes.placeholder import ( + BasePlaceholder, + ChartPlaceholder, + LayoutPlaceholder, + MasterPlaceholder, + NotesSlidePlaceholder, + PicturePlaceholder, + PlaceholderGraphicFrame, + PlaceholderPicture, + TablePlaceholder, + _BaseSlidePlaceholder, + _InheritsDimensions, +) +from pptx.shapes.shapetree import NotesSlidePlaceholders +from pptx.slide import NotesMaster, SlideLayout, SlideMaster + +from ..oxml.unitdata.shape import ( + a_graphicFrame, + a_ph, + an_nvGraphicFramePr, + an_nvPicPr, + an_nvPr, + an_nvSpPr, + an_sp, +) +from ..unitutil.cxml import element, xml +from ..unitutil.file import snippet_seq +from ..unitutil.mock import class_mock, instance_mock, method_mock, property_mock + + +class Describe_BaseSlidePlaceholder(object): + """Unit-test suite for `pptx.shapes.placeholder._BaseSlidePlaceholder` object.""" + + def it_knows_its_shape_type(self): + placeholder = _BaseSlidePlaceholder(None, None) + assert placeholder.shape_type == MSO_SHAPE_TYPE.PLACEHOLDER + + def it_provides_override_dimensions_when_present(self, override_fixture): + placeholder, prop_name, expected_value = override_fixture + assert getattr(placeholder, prop_name) == expected_value + + @pytest.mark.parametrize("prop_name", ("left", "top", "width", "height")) + def it_provides_inherited_dims_when_no_override(self, request, prop_name): + method_mock(request, _BaseSlidePlaceholder, "_inherited_value", return_value=42) + placeholder = _BaseSlidePlaceholder(element("p:sp/p:spPr"), None) + + value = getattr(placeholder, prop_name) + + placeholder._inherited_value.assert_called_once_with(placeholder, prop_name) + assert value == 42 + + def it_gets_an_inherited_dim_value_to_help(self, base_val_fixture): + placeholder, attr_name, expected_value = base_val_fixture + value = placeholder._inherited_value(attr_name) + assert value == expected_value + + def it_finds_its_base_placeholder_to_help(self, base_ph_fixture): + placeholder, layout_, idx, layout_placeholder_ = base_ph_fixture + base_placeholder = placeholder._base_placeholder + layout_.placeholders.get.assert_called_once_with(idx=idx) + assert base_placeholder is layout_placeholder_ + + def it_can_override_inherited_dimensions(self, dim_set_fixture): + placeholder, prop_name, value, expected_xml = dim_set_fixture + setattr(placeholder, prop_name, value) + assert placeholder._element.xml == expected_xml + + def it_replaces_a_placeholder_element_to_help(self, replace_fixture): + placeholder, element, spTree, expected_xml = replace_fixture + placeholder._replace_placeholder_with(element) + assert spTree.xml == expected_xml + assert placeholder._element is None + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def base_ph_fixture(self, request, part_prop_, slide_layout_, layout_placeholder_): + sp_cxml = "p:sp/p:nvSpPr/p:nvPr/p:ph{type=pic,idx=1}" + placeholder = _BaseSlidePlaceholder(element(sp_cxml), None) + part_prop_.return_value.slide_layout = slide_layout_ + slide_layout_.placeholders.get.return_value = layout_placeholder_ + return placeholder, slide_layout_, 1, layout_placeholder_ + + @pytest.fixture(params=[(True, 42), (False, None)]) + def base_val_fixture(self, request, _base_placeholder_prop_, layout_placeholder_): + has_base_placeholder, expected_value = request.param + placeholder = _BaseSlidePlaceholder(None, None) + if has_base_placeholder: + layout_placeholder_.width = expected_value + _base_placeholder_prop_.return_value = layout_placeholder_ + else: + _base_placeholder_prop_.return_value = None + return placeholder, "width", expected_value + + @pytest.fixture( + params=[ + ("p:sp/p:spPr/a:xfrm", "left", 1, "p:sp/p:spPr/a:xfrm/a:off{x=1,y=0}"), + ("p:sp/p:spPr/a:xfrm", "top", 2, "p:sp/p:spPr/a:xfrm/a:off{x=0,y=2}"), + ("p:sp/p:spPr/a:xfrm", "width", 3, "p:sp/p:spPr/a:xfrm/a:ext{cx=3,cy=0}"), + ("p:sp/p:spPr/a:xfrm", "height", 4, "p:sp/p:spPr/a:xfrm/a:ext{cx=0,cy=4}"), + ] + ) + def dim_set_fixture(self, request): + sp_cxml, prop_name, value, expected_cxml = request.param + placeholder = _BaseSlidePlaceholder(element(sp_cxml), None) + expected_xml = xml(expected_cxml) + return placeholder, prop_name, value, expected_xml + + @pytest.fixture( + params=[ + ("left", "p:sp/p:spPr/a:xfrm/a:off{x=12}", 12), + ("top", "p:sp/p:spPr/a:xfrm/a:off{y=34}", 34), + ("width", "p:sp/p:spPr/a:xfrm/a:ext{cx=56}", 56), + ("height", "p:sp/p:spPr/a:xfrm/a:ext{cy=78}", 78), + ] + ) + def override_fixture(self, request): + prop_name, sp_cxml, value = request.param + slide_placeholder = _BaseSlidePlaceholder(element(sp_cxml), None) + return slide_placeholder, prop_name, value + + @pytest.fixture + def replace_fixture(self): + spTree = element("p:spTree/p:sp/p:nvSpPr/p:nvPr/p:ph{type=pic,idx=10}") + pic = element("p:pic/p:nvPicPr/p:nvPr") + placeholder = _BaseSlidePlaceholder(spTree[0], None) + expected_xml = xml("p:spTree/p:pic/p:nvPicPr/p:nvPr/p:ph{type=pic,idx=10}") + return placeholder, pic, spTree, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def _base_placeholder_prop_(self, request): + return property_mock(request, _BaseSlidePlaceholder, "_base_placeholder") + + @pytest.fixture + def layout_placeholder_(self, request): + return instance_mock(request, LayoutPlaceholder) + + @pytest.fixture + def part_prop_(self, request, slide_part_): + return property_mock(request, _BaseSlidePlaceholder, "part", return_value=slide_part_) + + @pytest.fixture + def slide_layout_(self, request): + return instance_mock(request, SlideLayout) + + @pytest.fixture + def slide_part_(self, request): + return instance_mock(request, SlidePart) + + +class DescribeBasePlaceholder(object): + """Unit-test suite for `pptx.shapes.placeholder.BasePlaceholder` object.""" + + def it_knows_its_idx_value(self, idx_fixture): + placeholder, idx = idx_fixture + assert placeholder.idx == idx + + def it_knows_its_orient_value(self, orient_fixture): + placeholder, orient = orient_fixture + assert placeholder.orient == orient + + def it_raises_on_ph_orient_when_not_a_placeholder(self, orient_raise_fixture): + shape = orient_raise_fixture + with pytest.raises(ValueError): + shape.orient + + def it_knows_its_sz_value(self, sz_fixture): + placeholder, sz = sz_fixture + assert placeholder.sz == sz + + def it_knows_its_placeholder_type(self, type_fixture): + placeholder, ph_type = type_fixture + assert placeholder.ph_type == ph_type + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("sp", None, "title", 0), + ("sp", 0, "title", 0), + ("sp", 3, "body", 3), + ("pic", 6, "pic", 6), + ("graphicFrame", 9, "tbl", 9), + ] + ) + def idx_fixture(self, request): + tagname, idx, ph_type, expected_idx = request.param + shape_elm = self.shape_elm_factory(tagname, ph_type, idx) + placeholder = BasePlaceholder(shape_elm, None) + return placeholder, expected_idx + + @pytest.fixture(params=[(None, ST_Direction.HORZ), (ST_Direction.VERT, ST_Direction.VERT)]) + def orient_fixture(self, request): + orient, expected_orient = request.param + ph_bldr = a_ph() + if orient is not None: + ph_bldr.with_orient(orient) + shape_elm = ( + an_sp() + .with_nsdecls("p") + .with_child(an_nvSpPr().with_child(an_nvPr().with_child(ph_bldr))) + ).element + placeholder = BasePlaceholder(shape_elm, None) + return placeholder, expected_orient + + @pytest.fixture + def orient_raise_fixture(self): + shape_elm = ( + an_sp().with_nsdecls("p").with_child(an_nvSpPr().with_child(an_nvPr())) + ).element + shape = BasePlaceholder(shape_elm, None) + return shape + + @pytest.fixture( + params=[ + (None, ST_PlaceholderSize.FULL), + (ST_PlaceholderSize.HALF, ST_PlaceholderSize.HALF), + ] + ) + def sz_fixture(self, request): + sz, expected_sz = request.param + ph_bldr = a_ph() + if sz is not None: + ph_bldr.with_sz(sz) + shape_elm = ( + an_sp() + .with_nsdecls("p") + .with_child(an_nvSpPr().with_child(an_nvPr().with_child(ph_bldr))) + ).element + placeholder = BasePlaceholder(shape_elm, None) + return placeholder, expected_sz + + @pytest.fixture( + params=[ + ("sp", None, 1, PP_PLACEHOLDER.OBJECT), + ("sp", "title", 0, PP_PLACEHOLDER.TITLE), + ("pic", "pic", 6, PP_PLACEHOLDER.PICTURE), + ("graphicFrame", "tbl", 9, PP_PLACEHOLDER.TABLE), + ] + ) + def type_fixture(self, request): + tagname, ph_type, idx, expected_ph_type = request.param + shape_elm = self.shape_elm_factory(tagname, ph_type, idx) + placeholder = BasePlaceholder(shape_elm, None) + return placeholder, expected_ph_type + + # fixture components --------------------------------------------- + + @staticmethod + def shape_elm_factory(tagname, ph_type, idx): + root_bldr, nvXxPr_bldr = { + "sp": (an_sp().with_nsdecls("p"), an_nvSpPr()), + "pic": (an_sp().with_nsdecls("p"), an_nvPicPr()), + "graphicFrame": (a_graphicFrame().with_nsdecls("p"), an_nvGraphicFramePr()), + }[tagname] + ph_bldr = { + None: a_ph().with_idx(idx), + "obj": a_ph().with_idx(idx), + "title": a_ph().with_type("title"), + "body": a_ph().with_type("body").with_idx(idx), + "pic": a_ph().with_type("pic").with_idx(idx), + "tbl": a_ph().with_type("tbl").with_idx(idx), + }[ph_type] + return (root_bldr.with_child(nvXxPr_bldr.with_child(an_nvPr().with_child(ph_bldr)))).element + + +class DescribeChartPlaceholder(object): + """Unit-test suite for `pptx.shapes.placeholder.ChartPlaceholder` object.""" + + def it_can_insert_a_chart_into_itself(self, request, part_prop_): + slide_part_ = instance_mock(request, SlidePart) + slide_part_.add_chart_part.return_value = "rId6" + part_prop_.return_value = slide_part_ + graphicFrame = element("p:graphicFrame") + _new_chart_graphicFrame_ = method_mock( + request, + ChartPlaceholder, + "_new_chart_graphicFrame", + return_value=graphicFrame, + ) + _replace_placeholder_with_ = method_mock( + request, ChartPlaceholder, "_replace_placeholder_with" + ) + placeholder_graphic_frame_ = instance_mock(request, PlaceholderGraphicFrame) + PlaceholderGraphicFrame_ = class_mock( + request, + "pptx.shapes.placeholder.PlaceholderGraphicFrame", + return_value=placeholder_graphic_frame_, + ) + chart_data_ = instance_mock(request, ChartData) + chart_ph = ChartPlaceholder( + element("p:sp/p:spPr/a:xfrm/(a:off{x=1,y=2},a:ext{cx=3,cy=4})"), "parent" + ) + + ph_graphic_frame = chart_ph.insert_chart(XCT.PIE, chart_data_) + + slide_part_.add_chart_part.assert_called_once_with(XCT.PIE, chart_data_) + _new_chart_graphicFrame_.assert_called_once_with(chart_ph, "rId6", 1, 2, 3, 4) + _replace_placeholder_with_.assert_called_once_with(chart_ph, graphicFrame) + PlaceholderGraphicFrame_.assert_called_once_with(graphicFrame, chart_ph._parent) + assert ph_graphic_frame is placeholder_graphic_frame_ + + def it_creates_a_graphicFrame_element_to_help(self, new_fixture): + chart_ph, rId, x, y, cx, cy, expected_xml = new_fixture + graphicFrame = chart_ph._new_chart_graphicFrame(rId, x, y, cx, cy) + assert graphicFrame.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def new_fixture(self): + sp_cxml = "p:sp/p:nvSpPr/p:cNvPr{id=4,name=bar}" + chart_ph = ChartPlaceholder(element(sp_cxml), None) + rId, x, y, cx, cy = "rId42", 1, 2, 3, 4 + expected_xml = snippet_seq("placeholders")[1] + return chart_ph, rId, x, y, cx, cy, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def part_prop_(self, request, slide_): + return property_mock(request, ChartPlaceholder, "part", return_value=slide_) + + @pytest.fixture + def slide_(self, request): + return instance_mock(request, SlidePart) + + +class DescribeLayoutPlaceholder(object): + """Unit-test suite for `pptx.shapes.placeholder.LayoutPlaceholder` object.""" + + def it_uses_InheritsDimensions_mixin(self): + layout_placeholder = LayoutPlaceholder(None, None) + assert isinstance(layout_placeholder, _InheritsDimensions) + + def it_finds_its_base_placeholder_to_help(self, base_ph_fixture): + layout_placeholder, master_, mstr_ph_type, master_placeholder_ = base_ph_fixture + master_placeholder = layout_placeholder._base_placeholder + master_.placeholders.get.assert_called_once_with(mstr_ph_type, None) + assert master_placeholder is master_placeholder_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("p:sp/p:nvSpPr/p:nvPr/p:ph{type=body}", PP_PLACEHOLDER.BODY), + ("p:sp/p:nvSpPr/p:nvPr/p:ph{type=tbl}", PP_PLACEHOLDER.BODY), + ("p:sp/p:nvSpPr/p:nvPr/p:ph{type=title}", PP_PLACEHOLDER.TITLE), + ] + ) + def base_ph_fixture(self, request, slide_master_, master_placeholder_, part_prop_): + sp_cxml, mstr_ph_type = request.param + sp = element(sp_cxml) + layout_placeholder = LayoutPlaceholder(sp, None) + part_prop_.return_value.slide_master = slide_master_ + slide_master_.placeholders.get.return_value = master_placeholder_ + return (layout_placeholder, slide_master_, mstr_ph_type, master_placeholder_) + + # fixture components --------------------------------------------- + + @pytest.fixture + def master_placeholder_(self, request): + return instance_mock(request, MasterPlaceholder) + + @pytest.fixture + def part_prop_(self, request): + return property_mock(request, LayoutPlaceholder, "part") + + @pytest.fixture + def slide_master_(self, request): + return instance_mock(request, SlideMaster) + + +class DescribeNotesSlidePlaceholder(object): + """Unit-test suite for `pptx.shapes.placeholder.NotesSlidePlaceholder` object.""" + + def it_finds_its_base_placeholder_to_help(self, base_ph_fixture): + placeholder, notes_master_, ph_type, master_placeholder_ = base_ph_fixture + base_placeholder = placeholder._base_placeholder + notes_master_.placeholders.get.assert_called_once_with(ph_type=ph_type) + assert base_placeholder is master_placeholder_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def base_ph_fixture( + self, + request, + notes_master_, + master_placeholder_, + part_prop_, + notes_slide_part_, + notes_slide_placeholders_, + ): + sp_cxml = "p:sp/p:nvSpPr/p:nvPr/p:ph{type=body}" + placeholder = NotesSlidePlaceholder(element(sp_cxml), None) + notes_slide_part_.notes_master = notes_master_ + notes_master_.placeholders = notes_slide_placeholders_ + notes_slide_placeholders_.get.return_value = master_placeholder_ + return (placeholder, notes_master_, PP_PLACEHOLDER.BODY, master_placeholder_) + + # fixture components --------------------------------------------- + + @pytest.fixture + def notes_slide_placeholders_(self, request): + return instance_mock(request, NotesSlidePlaceholders) + + @pytest.fixture + def master_placeholder_(self, request): + return instance_mock(request, MasterPlaceholder) + + @pytest.fixture + def notes_master_(self, request): + return instance_mock(request, NotesMaster) + + @pytest.fixture + def notes_slide_part_(self, request): + return instance_mock(request, NotesSlidePart) + + @pytest.fixture + def part_prop_(self, request, notes_slide_part_): + return property_mock(request, NotesSlidePlaceholder, "part", return_value=notes_slide_part_) + + +class DescribePicturePlaceholder(object): + """Unit-test suite for `pptx.shapes.placeholder.PicturePlaceholder` object.""" + + def it_can_insert_a_picture_into_itself(self, request): + pic = element("p:pic") + _new_placeholder_pic_ = method_mock( + request, PicturePlaceholder, "_new_placeholder_pic", return_value=pic + ) + _replace_placeholder_with_ = method_mock( + request, PicturePlaceholder, "_replace_placeholder_with" + ) + placeholder_picture_ = instance_mock(request, PlaceholderPicture) + PlaceholderPicture_ = class_mock( + request, + "pptx.shapes.placeholder.PlaceholderPicture", + return_value=placeholder_picture_, + ) + picture_ph = PicturePlaceholder(None, "parent") + + placeholder_picture = picture_ph.insert_picture("foobar.png") + + _new_placeholder_pic_.assert_called_once_with(picture_ph, "foobar.png") + _replace_placeholder_with_.assert_called_once_with(picture_ph, pic) + PlaceholderPicture_.assert_called_once_with(pic, picture_ph._parent) + assert placeholder_picture is placeholder_picture_ + + @pytest.mark.parametrize( + "image_size, crop_attr_names", + (((444, 333), ("l", "r")), ((333, 444), ("t", "b"))), + ) + def it_creates_a_pic_element_to_help(self, request, image_size, crop_attr_names): + _get_or_add_image_ = method_mock( + request, + PicturePlaceholder, + "_get_or_add_image", + return_value=(42, "bar", image_size), + ) + picture_ph = PicturePlaceholder( + element("p:sp/(p:nvSpPr/p:cNvPr{id=2,name=foo},p:spPr/a:xfrm/a:ext{cx=99" ",cy=99})"), + None, + ) + + pic = picture_ph._new_placeholder_pic("foobar.png") + + _get_or_add_image_.assert_called_once_with(picture_ph, "foobar.png") + assert pic.xml == xml( + "p:pic/(p:nvPicPr/(p:cNvPr{id=2,name=foo,descr=bar},p:cNvPicPr/a" + ":picLocks{noGrp=1,noChangeAspect=1},p:nvPr),p:blipFill/(a:blip{" + "r:embed=42},a:srcRect{%s=12500,%s=12500},a:stretch/a:fillRect)," + "p:spPr)" % crop_attr_names + ) + + def it_adds_an_image_to_help(self, get_or_add_fixture): + placeholder, image_file, expected_value = get_or_add_fixture + + value = placeholder._get_or_add_image(image_file) + + placeholder.part.get_or_add_image_part.assert_called_once_with(image_file) + assert value == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def get_or_add_fixture(self, part_prop_, image_part_): + placeholder = PicturePlaceholder(None, None) + image_file, rId, desc, image_size = "f.png", "rId6", "desc", (42, 24) + part_prop_.return_value.get_or_add_image_part.return_value = (image_part_, rId) + image_part_.desc, image_part_._px_size = desc, image_size + expected_value = rId, desc, image_size + return placeholder, image_file, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def image_part_(self, request): + return instance_mock(request, ImagePart) + + @pytest.fixture + def part_prop_(self, request, slide_): + return property_mock(request, PicturePlaceholder, "part", return_value=slide_) + + @pytest.fixture + def slide_(self, request): + return instance_mock(request, SlidePart) + + +class DescribeTablePlaceholder(object): + """Unit-test suite for `pptx.shapes.placeholder.TablePlaceholder` object.""" + + def it_can_insert_a_table_into_itself(self, request): + graphicFrame = element("p:graphicFrame") + _new_placeholder_table_ = method_mock( + request, + TablePlaceholder, + "_new_placeholder_table", + return_value=graphicFrame, + ) + _replace_placeholder_with_ = method_mock( + request, TablePlaceholder, "_replace_placeholder_with" + ) + placeholder_graphic_frame_ = instance_mock(request, PlaceholderGraphicFrame) + PlaceholderGraphicFrame_ = class_mock( + request, + "pptx.shapes.placeholder.PlaceholderGraphicFrame", + return_value=placeholder_graphic_frame_, + ) + table_ph = TablePlaceholder(None, "parent") + + ph_graphic_frame = table_ph.insert_table(4, 2) + + _new_placeholder_table_.assert_called_once_with(table_ph, 4, 2) + _replace_placeholder_with_.assert_called_once_with(table_ph, graphicFrame) + PlaceholderGraphicFrame_.assert_called_once_with(graphicFrame, table_ph._parent) + assert ph_graphic_frame is placeholder_graphic_frame_ + + def it_creates_a_graphicFrame_element_to_help(self): + table_ph = TablePlaceholder( + element( + "p:sp/(p:nvSpPr/p:cNvPr{id=2,name=foo},p:spPr/a:xfrm/(a:off{x=1,y=2}," + "a:ext{cx=3,cy=4}))" + ), + None, + ) + graphicFrame = table_ph._new_placeholder_table(1, 1) + + assert graphicFrame.xml == snippet_seq("placeholders")[0] diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_shapetree.py b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_shapetree.py new file mode 100644 index 0000000000000000000000000000000000000000..3cf1ab22589c844a23a05ed56ddfffd159898669 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/shapes/test_shapetree.py @@ -0,0 +1,2365 @@ +# pyright: reportPrivateUsage=false + +"""Unit test suite for pptx.shapes.shapetree module""" + +from __future__ import annotations + +import io + +import pytest + +from pptx.chart.data import ChartData +from pptx.enum.chart import XL_CHART_TYPE +from pptx.enum.shapes import MSO_AUTO_SHAPE_TYPE, MSO_CONNECTOR, PP_PLACEHOLDER, PROG_ID +from pptx.media import SPEAKER_IMAGE_BYTES, Video +from pptx.oxml import parse_xml +from pptx.oxml.shapes.groupshape import CT_GroupShape +from pptx.oxml.shapes.picture import CT_Picture +from pptx.oxml.shapes.shared import BaseShapeElement, ST_Direction +from pptx.parts.image import ImagePart +from pptx.parts.slide import SlidePart +from pptx.shapes.autoshape import AutoShapeType, Shape +from pptx.shapes.base import BaseShape +from pptx.shapes.connector import Connector +from pptx.shapes.freeform import FreeformBuilder +from pptx.shapes.graphfrm import GraphicFrame +from pptx.shapes.group import GroupShape +from pptx.shapes.picture import Movie, Picture +from pptx.shapes.placeholder import ( + LayoutPlaceholder, + MasterPlaceholder, + NotesSlidePlaceholder, + _BaseSlidePlaceholder, +) +from pptx.shapes.shapetree import ( + BasePlaceholders, + BaseShapeFactory, + GroupShapes, + LayoutPlaceholders, + LayoutShapes, + MasterPlaceholders, + MasterShapes, + NotesSlidePlaceholders, + NotesSlideShapes, + SlidePlaceholders, + SlideShapeFactory, + SlideShapes, + _BaseGroupShapes, + _BaseShapes, + _LayoutShapeFactory, + _MasterShapeFactory, + _MoviePicElementCreator, + _NotesSlideShapeFactory, + _OleObjectElementCreator, + _SlidePlaceholderFactory, +) +from pptx.slide import SlideLayout, SlideMaster +from pptx.table import Table +from pptx.util import Emu, Inches + +from ..oxml.unitdata.shape import a_ph, a_pic, an_nvPr, an_nvSpPr, an_sp +from ..unitutil.cxml import element, xml +from ..unitutil.file import snippet_seq +from ..unitutil.mock import ( + ANY, + call, + class_mock, + function_mock, + initializer_mock, + instance_mock, + method_mock, + property_mock, +) + + +class DescribeBaseShapeFactory(object): + def it_constructs_the_right_shape_for_an_element(self, factory_fixture): + shape_elm, parent_, ShapeClass_, shape_ = factory_fixture + shape = BaseShapeFactory(shape_elm, parent_) + ShapeClass_.assert_called_once_with(shape_elm, parent_) + assert shape is shape_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("p:sp", Shape), + ("p:pic", Picture), + ("p:pic/p:nvPicPr/p:nvPr/a:videoFile", Movie), + ("p:graphicFrame", GraphicFrame), + ("p:grpSp", GroupShape), + ("p:cxnSp", Connector), + ] + ) + def factory_fixture(self, request, parent_): + shape_cxml, ShapeCls = request.param + shape_elm = element(shape_cxml) + shape_mock = instance_mock(request, ShapeCls) + ShapeClass_ = class_mock( + request, + "pptx.shapes.shapetree.%s" % ShapeCls.__name__, + return_value=shape_mock, + ) + return shape_elm, parent_, ShapeClass_, shape_mock + + # fixture components ----------------------------------- + + @pytest.fixture + def parent_(self, request): + return instance_mock(request, SlideShapes) + + +class Describe_BaseShapes(object): + """Unit-test suite for `pptx.shapes.shapetree._BaseShapes` objects.""" + + def it_knows_how_many_shapes_it_contains(self, len_fixture): + shapes, expected_count = len_fixture + assert len(shapes) == expected_count + + def it_can_iterate_over_the_shapes_it_contains(self, iter_fixture): + shapes, expected_shapes, BaseShapeFactory_, calls = iter_fixture + assert [s for s in shapes] == expected_shapes + assert BaseShapeFactory_.call_args_list == calls + + def it_iterates_shape_elements_to_help__iter__(self, iter_elms_fixture): + shapes, expected_elms = iter_elms_fixture + assert [e for e in shapes._iter_member_elms()] == expected_elms + + def it_supports_indexed_access(self, getitem_fixture): + shapes, idx, BaseShapeFactory_, sp, shape_ = getitem_fixture + shape = shapes[idx] + BaseShapeFactory_.assert_called_once_with(sp, shapes) + assert shape is shape_ + + def it_raises_on_shape_index_out_of_range(self, getitem_raises_fixture): + shapes = getitem_raises_fixture + with pytest.raises(IndexError): + shapes[2] + + def it_can_clone_a_placeholder(self, clone_ph_fixture): + shapes, placeholder_, expected_xml = clone_ph_fixture + shapes.clone_placeholder(placeholder_) + assert shapes._element.xml == expected_xml + + def it_knows_if_turbo_add_is_enabled(self, turbo_fixture): + shapes, expected_value = turbo_fixture + turbo_add_enabled = shapes.turbo_add_enabled + assert turbo_add_enabled == expected_value + + def it_can_change_turbo_add_enabled(self, turbo_set_fixture): + shapes, value, expected_value = turbo_set_fixture + shapes.turbo_add_enabled = value + assert shapes.turbo_add_enabled == expected_value + + def it_finds_the_next_shape_id_to_help(self, next_id_fixture): + shapes, expected_value = next_id_fixture + assert shapes._next_shape_id == expected_value + + def it_finds_the_next_placeholder_name_to_help(self, ph_name_fixture): + shapes, ph_type, sp_id, orient, expected_value = ph_name_fixture + assert shapes._next_ph_name(ph_type, sp_id, orient) == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def clone_ph_fixture(self, placeholder_): + shapes = SlideShapes(element("p:spTree{a:b=c}"), None) + expected_xml = xml( + "p:spTree{a:b=c}/p:sp/(p:nvSpPr/(p:cNvPr{id=1,name=Vertical Char" + "t Placeholder 0},p:cNvSpPr/a:spLocks{noGrp=1},p:nvPr/p:ph{type=" + "chart,idx=42,orient=vert,sz=half}),p:spPr)" + ) + placeholder_.element = element( + "p:sp/p:nvSpPr/p:nvPr/p:ph{type=chart,idx=42,orient=vert,sz=half" "}" + ) + return shapes, placeholder_, expected_xml + + @pytest.fixture + def getitem_fixture(self, BaseShapeFactory_, shape_): + spTree = element("p:spTree/(p:sp,p:sp)") + shapes = _BaseShapes(spTree, None) + idx = 1 + sp = spTree.xpath("p:sp")[idx] + return shapes, idx, BaseShapeFactory_, sp, shape_ + + @pytest.fixture + def getitem_raises_fixture(self): + spTree = element("p:spTree/(p:sp,p:sp)") + shapes = _BaseShapes(spTree, None) + return shapes + + @pytest.fixture + def iter_fixture(self, BaseShapeFactory_): + spTree = element("p:spTree/(p:sp,p:sp)") + sps = spTree.xpath("p:sp") + shapes = _BaseShapes(spTree, None) + expected_shapes = [Shape(None, None), Shape(None, None)] + calls = [call(sps[0], shapes), call(sps[1], shapes)] + BaseShapeFactory_.side_effect = iter(expected_shapes) + return shapes, expected_shapes, BaseShapeFactory_, calls + + @pytest.fixture + def iter_elms_fixture(self): + spTree = element("p:spTree/(p:sp,p:sp)") + sps = spTree.xpath("p:sp") + shapes = _BaseShapes(spTree, None) + return shapes, sps + + @pytest.fixture + def len_fixture(self): + shapes = _BaseShapes(element("p:spTree/(p:spPr,p:sp,p:sp)"), None) + expected_count = 2 + return shapes, expected_count + + @pytest.fixture( + params=[ + ("p:spTree/p:nvSpPr", 1), + ("p:spTree/p:nvSpPr/p:cNvPr{id=0}", 1), + ("p:spTree/p:nvSpPr/p:cNvPr{id=1}", 2), + ("p:spTree/p:nvSpPr/p:cNvPr{id=2}", 3), + ("p:spTree/p:nvSpPr/(p:cNvPr{id=1},p:cNvPr{id=3})", 4), + ("p:spTree/p:nvSpPr/(p:cNvPr{id=foo},p:cNvPr{id=2})", 3), + ("p:spTree/p:nvSpPr/(p:cNvPr{id=1fo},p:cNvPr{id=2})", 3), + ( + "p:spTree/p:nvSpPr/(p:cNvPr{id=1},p:cNvPr{id=1},p:" "cNvPr{id=1},p:cNvPr{id=4})", + 5, + ), + ] + ) + def next_id_fixture(self, request): + spTree_cxml, expected_value = request.param + shapes = _BaseShapes(element(spTree_cxml), None) + return shapes, expected_value + + @pytest.fixture( + params=[ + (PP_PLACEHOLDER.OBJECT, 3, ST_Direction.HORZ, "Content Placeholder 2"), + (PP_PLACEHOLDER.TABLE, 4, ST_Direction.HORZ, "Table Placeholder 4"), + ( + PP_PLACEHOLDER.TABLE, + 7, + ST_Direction.VERT, + "Vertical Table Placeholder 6", + ), + (PP_PLACEHOLDER.TITLE, 2, ST_Direction.HORZ, "Title 2"), + ] + ) + def ph_name_fixture(self, request): + ph_type, sp_id, orient, expected_name = request.param + spTree = element("p:spTree/(p:cNvPr{name=Title 1},p:cNvPr{name=Table Placeholder " "3})") + shapes = SlideShapes(spTree, None) + return shapes, ph_type, sp_id, orient, expected_name + + @pytest.fixture(params=[(None, False), (42, True)]) + def turbo_fixture(self, request): + cached_max_shape_id, expected_value = request.param + shapes = _BaseShapes(None, None) + if cached_max_shape_id: + shapes._cached_max_shape_id = cached_max_shape_id + return shapes, expected_value + + @pytest.fixture( + params=[ + ("p:spTree/p:nvSpPr", True), + ("p:spTree/p:nvSpPr/p:cNvPr{id=2}", True), + ("p:spTree/p:nvSpPr/(p:cNvPr{id=1},p:cNvPr{id=3})", False), + ( + "p:spTree/p:nvSpPr/(p:cNvPr{id=1},p:cNvPr{id=1},p:" "cNvPr{id=1},p:cNvPr{id=4})", + True, + ), + ] + ) + def turbo_set_fixture(self, request): + spTree_cxml, value = request.param + shapes = _BaseShapes(element(spTree_cxml), None) + expected_value = value + return shapes, value, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def BaseShapeFactory_(self, request, shape_): + return function_mock( + request, + "pptx.shapes.shapetree.BaseShapeFactory", + return_value=shape_, + autospec=True, + ) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, Shape) + + @pytest.fixture + def shape_(self, request): + return instance_mock(request, BaseShape) + + +class Describe_BaseGroupShapes(object): + """Unit-test suite for `pptx.shapes.shapetree._BaseGroupShapes`.""" + + def it_can_add_a_chart( + self, + chart_data_, + part_prop_, + slide_part_, + graphic_frame_, + _add_chart_graphicFrame_, + _recalculate_extents_, + _shape_factory_, + ): + x, y, cx, cy = 1, 2, 3, 4 + part_prop_.return_value = slide_part_ + slide_part_.add_chart_part.return_value = "rId42" + graphicFrame = element("p:graphicFrame") + _add_chart_graphicFrame_.return_value = graphicFrame + _shape_factory_.return_value = graphic_frame_ + shapes = _BaseGroupShapes(None, None) + + graphic_frame = shapes.add_chart(XL_CHART_TYPE.PIE, x, y, cx, cy, chart_data_) + + shapes.part.add_chart_part.assert_called_once_with(XL_CHART_TYPE.PIE, chart_data_) + _add_chart_graphicFrame_.assert_called_once_with(shapes, "rId42", x, y, cx, cy) + _recalculate_extents_.assert_called_once_with(shapes) + _shape_factory_.assert_called_once_with(shapes, graphicFrame) + assert graphic_frame is graphic_frame_ + + def it_can_add_a_connector_shape(self, connector_fixture): + shapes, connector_type, begin_x, begin_y = connector_fixture[:4] + end_x, end_y, cxnSp_, connector_ = connector_fixture[4:] + + connector = shapes.add_connector(connector_type, begin_x, begin_y, end_x, end_y) + + shapes._add_cxnSp.assert_called_once_with( + shapes, connector_type, begin_x, begin_y, end_x, end_y + ) + shapes._recalculate_extents.assert_called_once_with(shapes) + shapes._shape_factory.assert_called_once_with(shapes, cxnSp_) + assert connector is connector_ + + def it_can_provide_a_freeform_builder(self, freeform_fixture): + shapes, start_x, start_y, scale = freeform_fixture[:4] + FreeformBuilder_new_, x_scale, y_scale = freeform_fixture[4:7] + builder_ = freeform_fixture[7] + + builder = shapes.build_freeform(start_x, start_y, scale) + + FreeformBuilder_new_.assert_called_once_with(shapes, start_x, start_y, x_scale, y_scale) + assert builder is builder_ + + def it_can_add_a_group_shape(self, group_fixture): + shapes, spTree, grpSp, group_shape_ = group_fixture + + group_shape = shapes.add_group_shape() + + spTree.add_grpSp.assert_called_once_with(spTree) + shapes._shape_factory.assert_called_once_with(shapes, grpSp) + assert group_shape is group_shape_ + + def it_can_add_an_ole_object( + self, request, _next_shape_id_prop_, _recalculate_extents_, _shape_factory_ + ): + _next_shape_id_prop_.return_value = 42 + graphicFrame = element("p:graphicFrame") + _OleObjectElementCreator_ = class_mock( + request, "pptx.shapes.shapetree._OleObjectElementCreator" + ) + _OleObjectElementCreator_.graphicFrame.return_value = graphicFrame + ole_object_shape_ = instance_mock(request, GraphicFrame) + _shape_factory_.return_value = ole_object_shape_ + x, y, cx, cy = 1, 2, 3, 4 + shapes = _BaseGroupShapes(element("p:spTree"), None) + + shape = shapes.add_ole_object( + "worksheet.xlsx", + PROG_ID.XLSX, + x, + y, + cx, + cy, + "test.xlsx", + Inches(0.5), + Inches(0.75), + ) + + _OleObjectElementCreator_.graphicFrame.assert_called_once_with( + shapes, + 42, + "worksheet.xlsx", + PROG_ID.XLSX, + x, + y, + cx, + cy, + "test.xlsx", + Inches(0.5), + Inches(0.75), + ) + assert shapes._spTree[-1] is graphicFrame + _recalculate_extents_.assert_called_once_with(shapes) + _shape_factory_.assert_called_once_with(shapes, graphicFrame) + assert shape is ole_object_shape_ + + def it_can_add_a_picture(self, picture_fixture): + shapes, image_file, x, y, cx, cy = picture_fixture[:6] + image_part_, rId, pic, picture_ = picture_fixture[6:] + + picture = shapes.add_picture(image_file, x, y, cx, cy) + + shapes.part.get_or_add_image_part.assert_called_once_with(image_file) + shapes._add_pic_from_image_part.assert_called_once_with( + shapes, image_part_, rId, x, y, cx, cy + ) + shapes._recalculate_extents.assert_called_once_with(shapes) + shapes._shape_factory.assert_called_once_with(shapes, pic) + assert picture is picture_ + + def it_can_add_a_shape(self, shape_fixture): + shapes, autoshape_type_id, x, y, cx, cy = shape_fixture[:6] + AutoShapeType_, autoshape_type_, sp, shape_ = shape_fixture[6:] + + shape = shapes.add_shape(autoshape_type_id, x, y, cx, cy) + + AutoShapeType_.assert_called_once_with(autoshape_type_id) + shapes._add_sp.assert_called_once_with(shapes, autoshape_type_, x, y, cx, cy) + shapes._recalculate_extents.assert_called_once_with(shapes) + shapes._shape_factory.assert_called_once_with(shapes, sp) + assert shape is shape_ + + def it_can_add_a_textbox(self, textbox_fixture): + shapes, x, y, cx, cy, sp, shape_ = textbox_fixture + + shape = shapes.add_textbox(x, y, cx, cy) + + shapes._add_textbox_sp.assert_called_once_with(shapes, x, y, cx, cy) + shapes._recalculate_extents.assert_called_once_with(shapes) + shapes._shape_factory.assert_called_once_with(shapes, sp) + assert shape is shape_ + + def it_knows_the_index_of_each_of_its_shapes(self, index_fixture): + shapes, shape_, expected_value = index_fixture + assert shapes.index(shape_) == expected_value + + def it_raises_on_index_where_shape_not_found(self, index_raises_fixture): + shapes, shape_ = index_raises_fixture + with pytest.raises(ValueError): + shapes.index(shape_) + + def it_adds_a_chart_graphicFrame_to_help(self, add_cht_gr_frm_fixture): + shapes, rId, x, y, cx, cy, expected_xml = add_cht_gr_frm_fixture + + graphicFrame = shapes._add_chart_graphicFrame(rId, x, y, cx, cy) + + assert shapes._element.xml == expected_xml + assert graphicFrame is shapes._element.xpath("p:graphicFrame")[0] + + def it_adds_a_cxnSp_to_help(self, add_cxnSp_fixture): + shapes, connector_type, begin_x, begin_y = add_cxnSp_fixture[:4] + end_x, end_y, expected_xml = add_cxnSp_fixture[4:] + + cxnSp = shapes._add_cxnSp(connector_type, begin_x, begin_y, end_x, end_y) + + assert cxnSp is shapes._element.xpath("p:cxnSp")[0] + assert cxnSp.xml == expected_xml + + def it_adds_a_pic_element_to_help(self, add_pic_fixture): + shapes, image_part_, rId, x, y, cx, cy = add_pic_fixture[:7] + expected_xml = add_pic_fixture[7] + + pic = shapes._add_pic_from_image_part(image_part_, rId, x, y, cx, cy) + + image_part_.scale.assert_called_once_with(cx, cy) + assert shapes._element.xml == expected_xml + assert pic is shapes._element.xpath("p:pic")[0] + + def it_adds_an_sp_element_to_help(self, add_sp_fixture): + shapes, autoshape_type_, x, y, cx, cy, expected_xml = add_sp_fixture + + sp = shapes._add_sp(autoshape_type_, x, y, cx, cy) + + assert shapes._element.xml == expected_xml + assert sp is shapes._element.xpath("p:sp")[0] + + def it_adds_a_textbox_sp_element_to_help(self, add_textbox_sp_fixture): + shapes, x, y, cx, cy, expected_xml = add_textbox_sp_fixture + + sp = shapes._add_textbox_sp(x, y, cx, cy) + + assert shapes._element.xml == expected_xml + assert sp is shapes._element.xpath("p:sp")[0] + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def add_cht_gr_frm_fixture(self): + shapes = _BaseGroupShapes(element("p:spTree"), None) + rId, x, y, cx, cy = "rId42", 1, 2, 3, 4 + expected_xml = ( + '\n \n ' + '\n \n \n \n \n \n \n " + ' \n \n \n \n \n \n ' + ' \n \n \n \n" + ) + return shapes, rId, x, y, cx, cy, expected_xml + + @pytest.fixture( + params=[ + (1, 2, 3, 5, "p:spPr/(a:xfrm/(a:off{x=1,y=2},a:ext{cx=2,cy=3})"), + (8, 3, 4, 9, "p:spPr/(a:xfrm{flipH=1}/(a:off{x=4,y=3},a:ext{cx=4,cy=6})"), + (1, 6, 5, 2, "p:spPr/(a:xfrm{flipV=1}/(a:off{x=1,y=2},a:ext{cx=4,cy=4})"), + ( + 9, + 8, + 2, + 3, + "p:spPr/(a:xfrm{flipH=1,flipV=1}/(a:off{x=2,y=3},a:ext{cx=7,cy=5})", + ), + ] + ) + def add_cxnSp_fixture(self, request): + begin_x, begin_y, end_x, end_y, spPr_cxml = request.param + shapes = _BaseGroupShapes(element("p:spTree"), None) + connector_type = MSO_CONNECTOR.STRAIGHT + tmpl_cxml = ( + "p:cxnSp/(p:nvCxnSpPr/(p:cNvPr{id=1,name=Connector 0},p:cNvCxnSp" + "Pr,p:nvPr),%s,a:prstGeom{prst=line}/a:avLst),p:style/(a:lnRef{i" + "dx=2}/a:schemeClr{val=accent1},a:fillRef{idx=0}/a:schemeClr{val" + "=accent1},a:effectRef{idx=1}/a:schemeClr{val=accent1},a:fontRef" + "{idx=minor}/a:schemeClr{val=tx1}))" + ) + expected_xml = xml(tmpl_cxml % spPr_cxml) + return (shapes, connector_type, begin_x, begin_y, end_x, end_y, expected_xml) + + @pytest.fixture + def add_pic_fixture(self, image_part_, _next_shape_id_prop_): + shapes = _BaseGroupShapes(element("p:spTree"), None) + rId, x, y, cx, cy = "rId24", 10, 11, 12, 13 + + _next_shape_id_prop_.return_value = 42 + image_part_.scale.return_value = (101, 102) + image_part_.desc = "sprocket.jpg" + expected_xml = ( + '\n \n \n ' + ' ' + '\n \n ' + "\n \n \n \n <" + 'p:blipFill>\n \n ' + "\n \n \n " + '\n \n \n ' + '\n \n \n \n \n ' + "\n \n \n" + ) + return shapes, image_part_, rId, x, y, cx, cy, expected_xml + + @pytest.fixture + def add_sp_fixture(self, autoshape_type_, _next_shape_id_prop_): + shapes = _BaseGroupShapes(element("p:spTree"), None) + x, y, cx, cy = 8, 7, 6, 5 + + _next_shape_id_prop_.return_value = 7 + autoshape_type_.basename = "Rounded Rectangle" + autoshape_type_.prst = "roundRect" + + expected_xml = ( + '\n \n \n \n \n \n \n \n \n " + '\n \n \n \n ' + "\n \n \n \n \n \n \n \n \n \n \n ' + ' \n \n <' + 'a:fontRef idx="minor">\n \n ' + " \n \n \n \n \n \n ' + ' \n \n \n \n" + ) + return shapes, autoshape_type_, x, y, cx, cy, expected_xml + + @pytest.fixture + def add_textbox_sp_fixture(self, _next_shape_id_prop_): + shapes = _BaseGroupShapes(element("p:spTree"), None) + x, y, cx, cy = 1, 2, 3, 4 + + _next_shape_id_prop_.return_value = 6 + + expected_xml = ( + '\n \n \n \n \n \n \n \n \n " + '\n \n \n \n \n ' + " \n \n \n \n \n \n ' + " \n \n \n \n \n" + ) + return shapes, x, y, cx, cy, expected_xml + + @pytest.fixture + def connector_fixture(self, _add_cxnSp_, _shape_factory_, _recalculate_extents_, connector_): + shapes = _BaseGroupShapes(element("p:spTree"), None) + connector_type = MSO_CONNECTOR.STRAIGHT + begin_x, begin_y, end_x, end_y = 1, 2, 3, 4 + cxnSp = element("p:cxnSp") + + _add_cxnSp_.return_value = cxnSp + _shape_factory_.return_value = connector_ + + return ( + shapes, + connector_type, + begin_x, + begin_y, + end_x, + end_y, + cxnSp, + connector_, + ) + + @pytest.fixture( + params=[ + (0, 0, 1.0, 1.0, 1.0), + (100, 200, 2.0, 2.0, 2.0), + (100, 200, (4.2, 2.4), 4.2, 2.4), + ] + ) + def freeform_fixture(self, request, FreeformBuilder_new_, builder_): + start_x, start_y, scale, x_scale, y_scale = request.param + shapes = _BaseGroupShapes(None, None) + FreeformBuilder_new_.return_value = builder_ + return ( + shapes, + start_x, + start_y, + scale, + FreeformBuilder_new_, + x_scale, + y_scale, + builder_, + ) + + @pytest.fixture + def group_fixture(self, CT_GroupShape_add_grpSp_, _shape_factory_, group_shape_): + spTree = element("p:spTree{id=2e838acdc755e83113ed03904d2fe081f}") + grpSp = element("p:grpSp{id=052874e154b48f9bec4266f80913cae38f}") + shapes = _BaseGroupShapes(spTree, None) + + CT_GroupShape_add_grpSp_.return_value = grpSp + _shape_factory_.return_value = group_shape_ + + return shapes, spTree, grpSp, group_shape_ + + @pytest.fixture( + params=[ + ("p:spTree/(p:sp,p:sp,p:sp)", SlideShapes, 0), + ("p:spTree/(p:sp,p:sp,p:sp)", SlideShapes, 1), + ("p:spTree/(p:sp,p:sp,p:sp)", SlideShapes, 2), + ("p:grpSp/(p:sp,p:sp,p:sp)", GroupShapes, 0), + ("p:grpSp/(p:sp,p:sp,p:sp)", GroupShapes, 1), + ("p:grpSp/(p:sp,p:sp,p:sp)", GroupShapes, 2), + ] + ) + def index_fixture(self, request, shape_): + grpSp_cxml, ShapesCls, idx = request.param + grpSp = element(grpSp_cxml) + sps = grpSp.xpath("p:sp") + shapes = ShapesCls(grpSp, None) + shape_.element = sps[idx] + expected_value = idx + return shapes, shape_, expected_value + + @pytest.fixture( + params=[ + ("p:spTree/(p:sp,p:sp,p:sp)", SlideShapes), + ("p:grpSp/(p:sp,p:sp,p:sp)", GroupShapes), + ] + ) + def index_raises_fixture(self, request, shape_): + grpSp_cxml, ShapesCls = request.param + shapes = SlideShapes(element(grpSp_cxml), None) + shape_.element = element("p:sp") + return shapes, shape_ + + @pytest.fixture + def _next_shape_id_prop_(self, request): + return property_mock(request, _BaseGroupShapes, "_next_shape_id") + + @pytest.fixture + def picture_fixture( + self, + part_prop_, + slide_part_, + image_part_, + _add_pic_from_image_part_, + _recalculate_extents_, + _shape_factory_, + picture_, + ): + shapes = _BaseGroupShapes(None, None) + image_file, x, y, cx, cy, rId = "foobar.png", 1, 2, 3, 4, "rId42" + pic = element("p:pic") + + part_prop_.return_value = slide_part_ + slide_part_.get_or_add_image_part.return_value = image_part_, rId + _add_pic_from_image_part_.return_value = pic + _shape_factory_.return_value = picture_ + return (shapes, image_file, x, y, cx, cy, image_part_, rId, pic, picture_) + + @pytest.fixture + def shape_fixture( + self, + AutoShapeType_, + autoshape_type_, + _add_sp_, + _recalculate_extents_, + _shape_factory_, + shape_, + ): + shapes = _BaseGroupShapes(None, None) + autoshape_type_id = MSO_AUTO_SHAPE_TYPE.ROUNDED_RECTANGLE + x, y, cx, cy = 21, 22, 23, 24 + sp = element("p:sp") + + AutoShapeType_.return_value = autoshape_type_ + _add_sp_.return_value = sp + _shape_factory_.return_value = shape_ + + return ( + shapes, + autoshape_type_id, + x, + y, + cx, + cy, + AutoShapeType_, + autoshape_type_, + sp, + shape_, + ) + + @pytest.fixture + def textbox_fixture(self, _add_textbox_sp_, _recalculate_extents_, _shape_factory_, shape_): + shapes = _BaseGroupShapes(None, None) + x, y, cx, cy = 31, 32, 33, 34 + sp = element("p:sp") + + _add_textbox_sp_.return_value = sp + _shape_factory_.return_value = shape_ + + return shapes, x, y, cx, cy, sp, shape_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _add_chart_graphicFrame_(self, request): + return method_mock(request, _BaseGroupShapes, "_add_chart_graphicFrame", autospec=True) + + @pytest.fixture + def _add_cxnSp_(self, request): + return method_mock(request, _BaseGroupShapes, "_add_cxnSp", autospec=True) + + @pytest.fixture + def _add_pic_from_image_part_(self, request): + return method_mock(request, _BaseGroupShapes, "_add_pic_from_image_part", autospec=True) + + @pytest.fixture + def _add_sp_(self, request): + return method_mock(request, _BaseGroupShapes, "_add_sp", autospec=True) + + @pytest.fixture + def _add_textbox_sp_(self, request): + return method_mock(request, _BaseGroupShapes, "_add_textbox_sp", autospec=True) + + @pytest.fixture + def autoshape_type_(self, request): + return instance_mock(request, AutoShapeType) + + @pytest.fixture + def AutoShapeType_(self, request): + return class_mock(request, "pptx.shapes.shapetree.AutoShapeType") + + @pytest.fixture + def builder_(self, request): + return instance_mock(request, FreeformBuilder) + + @pytest.fixture + def chart_data_(self, request): + return instance_mock(request, ChartData) + + @pytest.fixture + def connector_(self, request): + return instance_mock(request, Connector) + + @pytest.fixture + def CT_GroupShape_add_grpSp_(self, request): + return method_mock(request, CT_GroupShape, "add_grpSp", autospec=True) + + @pytest.fixture + def FreeformBuilder_new_(self, request): + return method_mock(request, FreeformBuilder, "new", autospec=False) + + @pytest.fixture + def graphic_frame_(self, request): + return instance_mock(request, GraphicFrame) + + @pytest.fixture + def group_shape_(self, request): + return instance_mock(request, GroupShape) + + @pytest.fixture + def image_part_(self, request): + return instance_mock(request, ImagePart) + + @pytest.fixture + def part_prop_(self, request): + return property_mock(request, _BaseGroupShapes, "part") + + @pytest.fixture + def picture_(self, request): + return instance_mock(request, Picture) + + @pytest.fixture + def _recalculate_extents_(self, request): + return method_mock(request, _BaseGroupShapes, "_recalculate_extents", autospec=True) + + @pytest.fixture + def shape_(self, request): + return instance_mock(request, Shape) + + @pytest.fixture + def _shape_factory_(self, request): + return method_mock(request, _BaseGroupShapes, "_shape_factory", autospec=True) + + @pytest.fixture + def slide_part_(self, request): + return instance_mock(request, SlidePart) + + +class DescribeGroupShapes(object): + def it_recalculates_its_extents_to_help(self, recalc_fixture): + shapes = recalc_fixture + shapes._recalculate_extents() + shapes._grpSp.recalculate_extents.assert_called_once_with() + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def recalc_fixture(self, grpSp_): + return GroupShapes(grpSp_, None) + + # fixture components --------------------------------------------- + + @pytest.fixture + def grpSp_(self, request): + return instance_mock(request, CT_GroupShape) + + +class DescribeBasePlaceholders(object): + def it_contains_only_placeholder_shapes(self, member_fixture): + shape_elm_, is_ph_shape = member_fixture + _is_ph_shape = BasePlaceholders._is_member_elm(shape_elm_) + assert _is_ph_shape == is_ph_shape + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=[True, False]) + def member_fixture(self, request, shape_elm_): + is_ph_shape = request.param + shape_elm_.has_ph_elm = is_ph_shape + return shape_elm_, is_ph_shape + + # fixture components --------------------------------------------- + + @pytest.fixture + def shape_elm_(self, request): + return instance_mock(request, BaseShapeElement) + + +class DescribeNotesSlidePlaceholders(object): + def it_brokers_access_to_its_shape_factory(self, factory_fixture): + placeholders, sp, _NotesSlideShapeFactory_, placeholder_ = factory_fixture + placeholder = placeholders._shape_factory(sp) + _NotesSlideShapeFactory_.assert_called_once_with(sp, placeholders) + assert placeholder is placeholder_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def factory_fixture(self, _NotesSlideShapeFactory_, placeholder_): + placeholders = NotesSlidePlaceholders(None, None) + sp = element("p:sp") + return placeholders, sp, _NotesSlideShapeFactory_, placeholder_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _NotesSlideShapeFactory_(self, request, placeholder_): + return function_mock( + request, + "pptx.shapes.shapetree._NotesSlideShapeFactory", + return_value=placeholder_, + autospec=True, + ) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, NotesSlidePlaceholder) + + +class DescribeNotesSlideShapes(object): + def it_knows_notes_slide_placeholder_basenames(self, basename_fixture): + notes_slide_shapes, ph_type, expected_value = basename_fixture + assert notes_slide_shapes.ph_basename(ph_type) == expected_value + + def it_brokers_access_to_its_shape_factory(self, factory_fixture): + shapes, sp, _NotesSlideShapeFactory_, shape_ = factory_fixture + shape = shapes._shape_factory(sp) + _NotesSlideShapeFactory_.assert_called_once_with(sp, shapes) + assert shape is shape_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + (PP_PLACEHOLDER.BODY, "Notes Placeholder"), + (PP_PLACEHOLDER.HEADER, "Header Placeholder"), + ] + ) + def basename_fixture(self, request): + ph_type, expected_value = request.param + notes_slide_shapes = NotesSlideShapes(None, None) + return notes_slide_shapes, ph_type, expected_value + + @pytest.fixture + def factory_fixture(self, _NotesSlideShapeFactory_, shape_): + shapes = NotesSlideShapes(None, None) + sp = element("p:sp") + return shapes, sp, _NotesSlideShapeFactory_, shape_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _NotesSlideShapeFactory_(self, request, shape_): + return function_mock( + request, + "pptx.shapes.shapetree._NotesSlideShapeFactory", + return_value=shape_, + autospec=True, + ) + + @pytest.fixture + def shape_(self, request): + return instance_mock(request, Shape) + + +class DescribeSlidePlaceholders(object): + def it_can_get_a_placeholder_by_idx(self, getitem_fixture): + placeholders, idx, SlideShapeFactory_ = getitem_fixture[:3] + shape_elm, placeholder_ = getitem_fixture[3:] + + placeholder = placeholders[idx] + + SlideShapeFactory_.assert_called_once_with(shape_elm, placeholders) + assert placeholder is placeholder_ + + def it_can_iterate_over_its_placeholders(self, iter_fixture): + placeholders, SlideShapeFactory_ = iter_fixture[:2] + expected_calls, expected_values = iter_fixture[2:] + + ps = [p for p in placeholders] + + assert SlideShapeFactory_.call_args_list == expected_calls + assert ps == expected_values + + def it_knows_how_many_placeholders_it_contains(self, len_fixture): + placeholders, expected_value = len_fixture + assert len(placeholders) == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("p:spTree/p:sp/p:nvSpPr/p:nvPr/p:ph{type=pic,idx=1}", 1, 0), + ("p:spTree/p:pic/p:nvPicPr/p:nvPr/p:ph{type=pic,idx=1}", 1, 0), + ("p:spTree/(p:sp,p:sp/p:nvSpPr/p:nvPr/p:ph{type=title})", 0, 1), + ("p:spTree/(p:sp,p:pic/p:nvPicPr/p:nvPr/p:ph{type=pic,idx=1})", 1, 1), + ( + "p:spTree/(p:sp/p:nvSpPr/p:nvPr/p:ph{type=title}," + "p:sp/p:nvSpPr/p:nvPr/p:ph{type=pic,idx=3})", + 3, + 1, + ), + ] + ) + def getitem_fixture(self, request, SlideShapeFactory_, placeholder_): + spTree_cxml, idx, offset = request.param + spTree = element(spTree_cxml) + placeholders = SlidePlaceholders(spTree, None) + shape_elm = spTree[offset] + SlideShapeFactory_.return_value = placeholder_ + return placeholders, idx, SlideShapeFactory_, shape_elm, placeholder_ + + @pytest.fixture( + params=[ + ( + "p:spTree/(" + "p:sp/p:nvSpPr/p:nvPr/p:ph{type=body,idx=1}," + "p:sp/p:nvSpPr/p:nvPr/p:ph{type=title}," + "p:pic/p:nvPicPr/p:nvPr/p:ph{type=pic,idx=3})", + (1, 0, 2), + ) + ] + ) + def iter_fixture(self, request, SlideShapeFactory_, placeholder_): + spTree_cxml, sequence = request.param + spTree = element(spTree_cxml) + placeholders = SlidePlaceholders(spTree, None) + SlideShapeFactory_.return_value = placeholder_ + calls = [call(spTree[i], placeholders) for i in sequence] + values = [placeholder_] * len(sequence) + return placeholders, SlideShapeFactory_, calls, values + + @pytest.fixture( + params=[ + ("p:spTree", 0), + ("p:spTree/(p:sp,p:pic,p:sp)", 0), + ("p:spTree/(p:sp,p:sp/p:nvSpPr/p:nvPr/p:ph{type=title},p:pic)", 1), + ( + "p:spTree/(" + "p:sp/p:nvSpPr/p:nvPr/p:ph{type=body,idx=1}," + "p:sp/p:nvSpPr/p:nvPr/p:ph{type=title}," + "p:pic/p:nvPicPr/p:nvPr/p:ph{type=pic,idx=3})", + 3, + ), + ] + ) + def len_fixture(self, request): + spTree_cxml, length = request.param + placeholders = SlidePlaceholders(element(spTree_cxml), None) + return placeholders, length + + # fixture components --------------------------------------------- + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, _BaseSlidePlaceholder) + + @pytest.fixture + def SlideShapeFactory_(self, request, placeholder_): + return function_mock( + request, + "pptx.shapes.shapetree.SlideShapeFactory", + return_value=placeholder_, + ) + + +class Describe_SlidePlaceholderFactory(object): + def it_constructs_the_right_type_of_placeholder(self, factory_fixture): + element, parent_, Constructor_, placeholder_ = factory_fixture + placeholder = _SlidePlaceholderFactory(element, parent_) + Constructor_.assert_called_once_with(element, parent_) + assert placeholder is placeholder_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("p:sp/p:nvSpPr/p:nvPr/p:ph{type=title}", "sp"), + ("p:sp/p:nvSpPr/p:nvPr/p:ph{type=pic,idx=1}", "pph"), + ("p:sp/p:nvSpPr/p:nvPr/p:ph{type=clipArt,idx=1}", "pph"), + ("p:sp/p:nvSpPr/p:nvPr/p:ph{type=tbl,idx=1}", "tph"), + ("p:sp/p:nvSpPr/p:nvPr/p:ph{type=chart,idx=10}", "cph"), + ("p:pic/p:nvPicPr/p:nvPr/p:ph{type=pic,idx=1}", "php"), + ("p:graphicFrame/p:nvSpPr/p:nvPr/p:ph{type=tbl,idx=2}", "phgf"), + ("p:graphicFrame/p:nvSpPr/p:nvPr/p:ph{type=chart,idx=2}", "phgf"), + ("p:graphicFrame/p:nvSpPr/p:nvPr/p:ph{type=dgm,idx=2}", "phgf"), + ] + ) + def factory_fixture( + self, + request, + SlidePlaceholder_, + ChartPlaceholder_, + PicturePlaceholder_, + TablePlaceholder_, + PlaceholderGraphicFrame_, + PlaceholderPicture_, + placeholder_, + ): + shape_cxml, constructor_key = request.param + shape_elm = element(shape_cxml) + Constructor_, shape_ = { + "sp": (SlidePlaceholder_, placeholder_), + "cph": (ChartPlaceholder_, placeholder_), + "pph": (PicturePlaceholder_, placeholder_), + "tph": (TablePlaceholder_, placeholder_), + "phgf": (PlaceholderGraphicFrame_, placeholder_), + "php": (PlaceholderPicture_, placeholder_), + }[constructor_key] + return shape_elm, 42, Constructor_, shape_ + + # fixture components ----------------------------------- + + @pytest.fixture + def ChartPlaceholder_(self, request, placeholder_): + return class_mock( + request, "pptx.shapes.shapetree.ChartPlaceholder", return_value=placeholder_ + ) + + @pytest.fixture + def PicturePlaceholder_(self, request, placeholder_): + return class_mock( + request, + "pptx.shapes.shapetree.PicturePlaceholder", + return_value=placeholder_, + ) + + @pytest.fixture + def PlaceholderGraphicFrame_(self, request, placeholder_): + return class_mock( + request, + "pptx.shapes.shapetree.PlaceholderGraphicFrame", + return_value=placeholder_, + ) + + @pytest.fixture + def PlaceholderPicture_(self, request, placeholder_): + return class_mock( + request, + "pptx.shapes.shapetree.PlaceholderPicture", + return_value=placeholder_, + ) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, _BaseSlidePlaceholder) + + @pytest.fixture + def SlidePlaceholder_(self, request, placeholder_): + return class_mock( + request, "pptx.shapes.shapetree.SlidePlaceholder", return_value=placeholder_ + ) + + @pytest.fixture + def TablePlaceholder_(self, request, placeholder_): + return class_mock( + request, "pptx.shapes.shapetree.TablePlaceholder", return_value=placeholder_ + ) + + +class DescribeSlideShapeFactory(object): + def it_constructs_the_right_type_of_shape(self, factory_fixture): + element, parent_, Constructor_, shape_ = factory_fixture + shape = SlideShapeFactory(element, parent_) + Constructor_.assert_called_once_with(element, parent_) + assert shape is shape_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("p:sp/p:nvSpPr/p:nvPr/p:ph{type=title}", "spf"), + ("p:pic/p:nvSpPr/p:nvPr/p:ph{type=pic,idx=1}", "spf"), + ("p:sp", "bsf"), + ("p:pic", "bsf"), + ] + ) + def factory_fixture( + self, + request, + _SlidePlaceholderFactory_, + placeholder_, + BaseShapeFactory_, + base_shape_, + ): + shape_cxml, shape_type = request.param + shape_elm = element(shape_cxml) + Constructor_, shape_ = { + "spf": (_SlidePlaceholderFactory_, placeholder_), + "bsf": (BaseShapeFactory_, base_shape_), + }[shape_type] + return shape_elm, 42, Constructor_, shape_ + + # fixture components ----------------------------------- + + @pytest.fixture + def BaseShapeFactory_(self, request, base_shape_): + return function_mock( + request, "pptx.shapes.shapetree.BaseShapeFactory", return_value=base_shape_ + ) + + @pytest.fixture + def base_shape_(self, request): + return instance_mock(request, BaseShape) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, _BaseSlidePlaceholder) + + @pytest.fixture + def _SlidePlaceholderFactory_(self, request, placeholder_): + return function_mock( + request, + "pptx.shapes.shapetree._SlidePlaceholderFactory", + return_value=placeholder_, + ) + + +class DescribeSlideShapes(object): + def it_provides_access_to_its_shape_factory(self, factory_fixture): + shapes, sp, SlideShapeFactory_, shape_ = factory_fixture + shape = shapes._shape_factory(sp) + SlideShapeFactory_.assert_called_once_with(sp, shapes) + assert shape is shape_ + + def it_can_find_the_title_placeholder(self, title_fixture): + shapes, _shape_factory_, calls, shape_ = title_fixture + title_placeholder = shapes.title + assert _shape_factory_.call_args_list == calls + assert title_placeholder is shape_ + + def it_can_add_a_movie(self, movie_fixture): + shapes, movie_file, x, y, cx, cy = movie_fixture[:6] + poster_frame_image, mime_type, shape_id_ = movie_fixture[6:9] + _MoviePicElementCreator_, movie_pic = movie_fixture[9:11] + _add_video_timing_, _shape_factory_, movie_ = movie_fixture[11:] + + movie = shapes.add_movie(movie_file, x, y, cx, cy, poster_frame_image, mime_type) + + _MoviePicElementCreator_.new_movie_pic.assert_called_once_with( + shapes, shape_id_, movie_file, x, y, cx, cy, poster_frame_image, mime_type + ) + assert shapes._spTree[-1] is movie_pic + _add_video_timing_.assert_called_once_with(shapes, movie_pic) + _shape_factory_.assert_called_once_with(shapes, movie_pic) + assert movie is movie_ + + def it_can_add_a_table(self, table_fixture): + shapes, rows, cols, x, y, cx, cy, table_, expected_xml = table_fixture + + table = shapes.add_table(rows, cols, x, y, cx, cy) + + graphicFrame = shapes._element.xpath("p:graphicFrame")[0] + shapes._shape_factory.assert_called_once_with(shapes, graphicFrame) + assert table is table_ + assert shapes._element.xml == expected_xml + + def it_can_clone_placeholder_shapes_from_a_layout(self, clone_fixture): + shapes, slide_layout_, calls = clone_fixture + shapes.clone_layout_placeholders(slide_layout_) + assert shapes.clone_placeholder.call_args_list == calls + + def it_adds_a_video_timing_to_help(self, add_timing_fixture): + shapes, pic, sld, expected_xml = add_timing_fixture + shapes._add_video_timing(pic) + assert sld.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + (0, 1), # no timing gets timing with one video + (1, 2), # timing with one video gets a second video + (3, 1), # timing without p:childTnLst parent gets replaced + ] + ) + def add_timing_fixture(self, request): + before_idx, after_idx = request.param + snippets = snippet_seq("timing") + sld = parse_xml(snippets[before_idx]) + spTree = sld.xpath(".//p:spTree")[0] + shapes = SlideShapes(spTree, None) + pic = element("p:pic/p:nvPicPr/p:cNvPr{id=42}") + expected_xml = snippets[after_idx] + return shapes, pic, sld, expected_xml + + @pytest.fixture + def clone_fixture(self, slide_layout_, clone_placeholder_, placeholder_): + shapes = SlideShapes(None, None) + calls = [call(shapes, placeholder_)] + slide_layout_.iter_cloneable_placeholders.return_value = iter([placeholder_]) + return shapes, slide_layout_, calls + + @pytest.fixture + def factory_fixture(self, SlideShapeFactory_, shape_): + shapes = SlideShapes(None, None) + sp = element("p:sp") + return shapes, sp, SlideShapeFactory_, shape_ + + @pytest.fixture + def movie_fixture( + self, + _MoviePicElementCreator_, + _add_video_timing_, + _shape_factory_, + movie_, + _next_shape_id_prop_, + ): + shapes = SlideShapes(element("p:spTree"), None) + movie_file, x, y, cx, cy = "foobar.mp4", 1, 2, 3, 4 + poster_frame_image, mime_type = "foobar.png", "video/mp4" + movie_pic = element("p:pic") + _MoviePicElementCreator_.new_movie_pic.return_value = movie_pic + _shape_factory_.return_value = movie_ + shape_id_ = _next_shape_id_prop_.return_value + return ( + shapes, + movie_file, + x, + y, + cx, + cy, + poster_frame_image, + mime_type, + shape_id_, + _MoviePicElementCreator_, + movie_pic, + _add_video_timing_, + _shape_factory_, + movie_, + ) + + @pytest.fixture + def table_fixture(self, table_, _shape_factory_): + shapes = SlideShapes(element("p:spTree"), None) + rows, cols, x, y, cx, cy = 1, 2, 10, 11, 12, 13 + _shape_factory_.return_value = table_ + expected_xml = ( + '\n \n ' + '\n \n \n \n \n \n \n " + ' \n \n \n \n \n ' + '\n \n ' + "\n {5C22544A-7EE6-4342-B048-85BDC9FD" + "1C3A}\n \n \n \n \n \n \n ' + " \n \n \n \n \n " + " \n \n \n \n \n " + " \n \n " + " \n \n \n" + " \n \n \n " + " \n \n \n" + ) + return shapes, rows, cols, x, y, cx, cy, table_, expected_xml + + @pytest.fixture( + params=[ + ("p:spTree/(p:sp,p:sp/p:nvSpPr/p:nvPr/p:ph{idx=0})", True), + ("p:spTree/(p:sp,p:sp)", False), + ] + ) + def title_fixture(self, request, _shape_factory_, shape_): + spTree_cxml, found = request.param + spTree = element(spTree_cxml) + shapes = SlideShapes(spTree, None) + calls = [call(shapes, spTree.xpath("p:sp")[1])] if found else [] + _shape_ = shape_ if found else None + return shapes, _shape_factory_, calls, _shape_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _add_video_timing_(self, request): + return method_mock(request, SlideShapes, "_add_video_timing", autospec=True) + + @pytest.fixture + def clone_placeholder_(self, request): + return method_mock(request, SlideShapes, "clone_placeholder", autospec=True) + + @pytest.fixture + def movie_(self, request): + return instance_mock(request, Movie) + + @pytest.fixture + def _MoviePicElementCreator_(self, request): + return class_mock(request, "pptx.shapes.shapetree._MoviePicElementCreator", autospec=True) + + @pytest.fixture + def _next_shape_id_prop_(self, request, shape_id_): + return property_mock(request, SlideShapes, "_next_shape_id", return_value=shape_id_) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, Shape) + + @pytest.fixture + def shape_(self, request): + return instance_mock(request, Shape) + + @pytest.fixture + def shape_id_(self): + return 42 + + @pytest.fixture + def _shape_factory_(self, request, shape_): + return method_mock( + request, SlideShapes, "_shape_factory", return_value=shape_, autospec=True + ) + + @pytest.fixture + def slide_layout_(self, request): + return instance_mock(request, SlideLayout) + + @pytest.fixture + def SlideShapeFactory_(self, request, shape_): + return function_mock( + request, + "pptx.shapes.shapetree.SlideShapeFactory", + return_value=shape_, + autospec=True, + ) + + @pytest.fixture + def table_(self, request): + return instance_mock(request, Table) + + +class DescribeLayoutShapes(object): + def it_provides_access_to_its_shape_factory(self, factory_fixture): + shapes, sp, _LayoutShapeFactory_, placeholder_ = factory_fixture + placeholder = shapes._shape_factory(sp) + _LayoutShapeFactory_.assert_called_once_with(sp, shapes) + assert placeholder is placeholder_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def factory_fixture(self, _LayoutShapeFactory_, placeholder_): + shapes = LayoutShapes(None, None) + sp = element("p:sp") + return shapes, sp, _LayoutShapeFactory_, placeholder_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _LayoutShapeFactory_(self, request, placeholder_): + return function_mock( + request, + "pptx.shapes.shapetree._LayoutShapeFactory", + return_value=placeholder_, + autospec=True, + ) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, LayoutPlaceholder) + + +class Describe_LayoutShapeFactory(object): + def it_constructs_the_right_shape_for_an_element(self, factory_fixture): + shape_elm, parent_, ShapeConstructor_, shape_ = factory_fixture + shape = _LayoutShapeFactory(shape_elm, parent_) + ShapeConstructor_.assert_called_once_with(shape_elm, parent_) + assert shape is shape_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=["ph", "sp", "pic"]) + def factory_fixture( + self, + request, + ph_bldr, + parent_, + _LayoutPlaceholder_, + layout_placeholder_, + BaseShapeFactory_, + base_shape_, + ): + shape_bldr, ShapeConstructor_, shape_mock = { + "ph": (ph_bldr, _LayoutPlaceholder_, layout_placeholder_), + "sp": (an_sp(), BaseShapeFactory_, base_shape_), + "pic": (a_pic(), BaseShapeFactory_, base_shape_), + }[request.param] + shape_elm = shape_bldr.with_nsdecls().element + return shape_elm, parent_, ShapeConstructor_, shape_mock + + # fixture components --------------------------------------------- + + @pytest.fixture + def BaseShapeFactory_(self, request, base_shape_): + return function_mock( + request, "pptx.shapes.shapetree.BaseShapeFactory", return_value=base_shape_ + ) + + @pytest.fixture + def base_shape_(self, request): + return instance_mock(request, BaseShape) + + @pytest.fixture + def _LayoutPlaceholder_(self, request, layout_placeholder_): + return class_mock( + request, + "pptx.shapes.shapetree.LayoutPlaceholder", + return_value=layout_placeholder_, + ) + + @pytest.fixture + def layout_placeholder_(self, request): + return instance_mock(request, LayoutPlaceholder) + + @pytest.fixture + def parent_(self, request): + return instance_mock(request, BasePlaceholders) + + @pytest.fixture + def ph_bldr(self): + return an_sp().with_child(an_nvSpPr().with_child(an_nvPr().with_child(a_ph().with_idx(1)))) + + +class DescribeLayoutPlaceholders(object): + def it_provides_access_to_its_shape_factory(self, factory_fixture): + placeholders, sp, _LayoutShapeFactory_, placeholder_ = factory_fixture + placeholder = placeholders._shape_factory(sp) + _LayoutShapeFactory_.assert_called_once_with(sp, placeholders) + assert placeholder is placeholder_ + + def it_can_find_a_placeholder_by_idx_value(self, get_fixture): + placeholders, idx, placeholder_ = get_fixture + assert placeholders.get(idx) is placeholder_ + + def it_returns_default_on_ph_idx_not_found(self, default_fixture): + placeholders, default = default_fixture + assert placeholders.get(42, default) is default + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def default_fixture(self, _iter_): + placeholders = LayoutPlaceholders(None, None) + default = "barfoo" + return placeholders, default + + @pytest.fixture + def factory_fixture(self, _LayoutShapeFactory_, placeholder_): + placeholders = LayoutPlaceholders(None, None) + sp = element("p:sp") + return placeholders, sp, _LayoutShapeFactory_, placeholder_ + + @pytest.fixture(params=[0, 1]) + def get_fixture(self, request, _iter_, placeholder_, placeholder_2_): + idx = request.param + layout_placeholders = LayoutPlaceholders(None, None) + _placeholder_ = (placeholder_, placeholder_2_)[idx] + placeholder_.element.ph_idx, placeholder_2_.element.ph_idx = 0, 1 + return layout_placeholders, idx, _placeholder_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _iter_(self, request, placeholder_, placeholder_2_): + return method_mock( + request, + LayoutPlaceholders, + "__iter__", + return_value=iter([placeholder_, placeholder_2_]), + ) + + @pytest.fixture + def _LayoutShapeFactory_(self, request, placeholder_): + return function_mock( + request, + "pptx.shapes.shapetree._LayoutShapeFactory", + return_value=placeholder_, + autospec=True, + ) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, LayoutPlaceholder) + + @pytest.fixture + def placeholder_2_(self, request): + return instance_mock(request, LayoutPlaceholder) + + +class Describe_MasterShapeFactory(object): + def it_constructs_a_master_placeholder_for_a_shape_element(self, factory_fixture): + shape_elm, parent_, ShapeConstructor_, shape_ = factory_fixture + shape = _MasterShapeFactory(shape_elm, parent_) + ShapeConstructor_.assert_called_once_with(shape_elm, parent_) + assert shape is shape_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=["ph", "sp", "pic"]) + def factory_fixture( + self, + request, + ph_bldr, + slide_master_, + _MasterPlaceholder_, + master_placeholder_, + BaseShapeFactory_, + base_shape_, + ): + shape_bldr, ShapeConstructor_, shape_mock = { + "ph": (ph_bldr, _MasterPlaceholder_, master_placeholder_), + "sp": (an_sp(), BaseShapeFactory_, base_shape_), + "pic": (a_pic(), BaseShapeFactory_, base_shape_), + }[request.param] + shape_elm = shape_bldr.with_nsdecls().element + return shape_elm, slide_master_, ShapeConstructor_, shape_mock + + # fixture components ----------------------------------- + + @pytest.fixture + def BaseShapeFactory_(self, request, base_shape_): + return function_mock( + request, "pptx.shapes.shapetree.BaseShapeFactory", return_value=base_shape_ + ) + + @pytest.fixture + def base_shape_(self, request): + return instance_mock(request, BaseShape) + + @pytest.fixture + def _MasterPlaceholder_(self, request, master_placeholder_): + return class_mock( + request, + "pptx.shapes.shapetree.MasterPlaceholder", + return_value=master_placeholder_, + ) + + @pytest.fixture + def master_placeholder_(self, request): + return instance_mock(request, MasterPlaceholder) + + @pytest.fixture + def ph_bldr(self): + return an_sp().with_child(an_nvSpPr().with_child(an_nvPr().with_child(a_ph().with_idx(1)))) + + @pytest.fixture + def slide_master_(self, request): + return instance_mock(request, SlideMaster) + + +class DescribeMasterShapes(object): + def it_provides_access_to_its_shape_factory(self, factory_fixture): + shapes, sp, _MasterShapeFactory_, placeholder_ = factory_fixture + placeholder = shapes._shape_factory(sp) + _MasterShapeFactory_.assert_called_once_with(sp, shapes) + assert placeholder is placeholder_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def factory_fixture(self, _MasterShapeFactory_, placeholder_): + shapes = MasterShapes(None, None) + sp = element("p:sp") + return shapes, sp, _MasterShapeFactory_, placeholder_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _MasterShapeFactory_(self, request, placeholder_): + return function_mock( + request, + "pptx.shapes.shapetree._MasterShapeFactory", + return_value=placeholder_, + autospec=True, + ) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, MasterPlaceholder) + + +class DescribeMasterPlaceholders(object): + def it_provides_access_to_its_shape_factory(self, factory_fixture): + placeholders, sp, _MasterShapeFactory_, placeholder_ = factory_fixture + placeholder = placeholders._shape_factory(sp) + _MasterShapeFactory_.assert_called_once_with(sp, placeholders) + assert placeholder is placeholder_ + + def it_can_find_a_placeholder_by_type(self, get_fixture): + placeholders, ph_type, placeholder_ = get_fixture + assert placeholders.get(ph_type) is placeholder_ + + def it_returns_default_on_ph_type_not_found(self, default_fixture): + placeholders, default = default_fixture + assert placeholders.get(42, default) is default + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def default_fixture(self, _iter_): + placeholders = MasterPlaceholders(None, None) + default = "barfoo" + return placeholders, default + + @pytest.fixture + def factory_fixture(self, _MasterShapeFactory_, placeholder_): + placeholders = MasterPlaceholders(None, None) + sp = element("p:sp") + return placeholders, sp, _MasterShapeFactory_, placeholder_ + + @pytest.fixture(params=["title", "body"]) + def get_fixture(self, request, _iter_, placeholder_, placeholder_2_): + ph_type = request.param + placeholders = MasterPlaceholders(None, None) + _placeholder_ = {"title": placeholder_, "body": placeholder_2_}[ph_type] + return placeholders, ph_type, _placeholder_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _iter_(self, request, placeholder_, placeholder_2_): + return method_mock( + request, + MasterPlaceholders, + "__iter__", + return_value=iter([placeholder_, placeholder_2_]), + ) + + @pytest.fixture + def _MasterShapeFactory_(self, request, placeholder_): + return function_mock( + request, + "pptx.shapes.shapetree._MasterShapeFactory", + return_value=placeholder_, + autospec=True, + ) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, MasterPlaceholder, ph_type="title") + + @pytest.fixture + def placeholder_2_(self, request): + return instance_mock(request, MasterPlaceholder, ph_type="body") + + +class Describe_MoviePicElementCreator(object): + def it_creates_a_new_movie_pic_element(self, movie_pic_fixture): + shapes_, shape_id, movie_file, x, y, cx, cy = movie_pic_fixture[:7] + poster_frame_image, mime_type = movie_pic_fixture[7:9] + _MoviePicElementCreator_init_, _pic_prop_ = movie_pic_fixture[9:11] + pic_ = movie_pic_fixture[11] + + pic = _MoviePicElementCreator.new_movie_pic( + shapes_, shape_id, movie_file, x, y, cx, cy, poster_frame_image, mime_type + ) + + _MoviePicElementCreator_init_.assert_called_once_with( + ANY, + shapes_, + shape_id, + movie_file, + x, + y, + cx, + cy, + poster_frame_image, + mime_type, + ) + _pic_prop_.assert_called_once_with() + assert pic is pic_ + + def it_creates_a_pic_element(self, pic_fixture): + movie_pic_element_creator, new_video_pic_, shape_id = pic_fixture[:3] + shape_name, video_rId, media_rId, poster_frame_rId = pic_fixture[3:7] + x, y, cx, cy, pic_ = pic_fixture[7:] + + pic = movie_pic_element_creator._pic + + new_video_pic_.assert_called_once_with( + shape_id, shape_name, video_rId, media_rId, poster_frame_rId, x, y, cx, cy + ) + assert pic is pic_ + + def it_knows_the_shape_name_to_help(self, shape_name_fixture): + movie_pic_element_creator, filename = shape_name_fixture + shape_name = movie_pic_element_creator._shape_name + assert shape_name == filename + + def it_constructs_the_video_to_help(self, video_fixture): + movie_pic_element_creator, movie_file = video_fixture[:2] + mime_type, video_ = video_fixture[2:] + video = movie_pic_element_creator._video + Video.from_path_or_file_like.assert_called_once_with(movie_file, mime_type) + assert video is video_ + + def it_knows_the_media_rId_to_help(self, media_rId_fixture): + movie_pic_element_creator, expected_value = media_rId_fixture + assert movie_pic_element_creator._media_rId == expected_value + + def it_knows_the_video_rId_to_help(self, video_rId_fixture): + movie_pic_element_creator, expected_value = video_rId_fixture + assert movie_pic_element_creator._video_rId == expected_value + + def it_adds_the_poster_frame_image_to_help(self, pfrm_rId_fixture): + movie_pic_element_creator, slide_part_ = pfrm_rId_fixture[:2] + poster_frame_image_file, expected_value = pfrm_rId_fixture[2:] + + poster_frame_rId = movie_pic_element_creator._poster_frame_rId + + slide_part_.get_or_add_image_part.assert_called_once_with(poster_frame_image_file) + assert poster_frame_rId == expected_value + + def it_gets_the_poster_frame_image_from_the_specified_path_to_help( + self, request: pytest.FixtureRequest + ): + BytesIO_ = class_mock(request, "pptx.shapes.shapetree.io.BytesIO") + movie_pic_element_creator = _MoviePicElementCreator( + None, None, None, None, None, None, None, "image.png", None # type: ignore + ) + + image_file = movie_pic_element_creator._poster_frame_image_file + + BytesIO_.assert_not_called() + assert image_file == "image.png" + + def but_it_gets_the_poster_frame_image_from_the_default_bytes_when_None_specified( + self, request: pytest.FixtureRequest + ): + stream_ = instance_mock(request, io.BytesIO) + BytesIO_ = class_mock(request, "pptx.shapes.shapetree.io.BytesIO", return_value=stream_) + movie_pic_element_creator = _MoviePicElementCreator( + None, None, None, None, None, None, None, None, None # type: ignore + ) + + image_file = movie_pic_element_creator._poster_frame_image_file + + BytesIO_.assert_called_once_with(SPEAKER_IMAGE_BYTES) + assert image_file == stream_ + + def it_gets_the_video_part_rIds_to_help(self, part_rIds_fixture): + movie_pic_element_creator, slide_part_ = part_rIds_fixture[:2] + video_, media_rId, video_rId = part_rIds_fixture[2:] + + result = movie_pic_element_creator._video_part_rIds + + slide_part_.get_or_add_video_media_part.assert_called_once_with(video_) + assert result == (media_rId, video_rId) + + def it_gets_the_slide_part_to_help(self, slide_part_fixture): + movie_pic_element_creator, slide_part_ = slide_part_fixture + slide_part = movie_pic_element_creator._slide_part + assert slide_part is slide_part_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def media_rId_fixture(self, _video_part_rIds_prop_): + movie_pic_element_creator = _MoviePicElementCreator( + None, None, None, None, None, None, None, None, None + ) + expected_value = "rId24" + _video_part_rIds_prop_.return_value = (expected_value, "rId666") + return movie_pic_element_creator, expected_value + + @pytest.fixture + def movie_pic_fixture(self, shapes_, _MoviePicElementCreator_init_, _pic_prop_, pic_): + shape_id, movie_file, x, y, cx, cy = 42, "movie.mp4", 1, 2, 3, 4 + poster_frame_image, mime_type = "image.png", "video/mp4" + return ( + shapes_, + shape_id, + movie_file, + x, + y, + cx, + cy, + poster_frame_image, + mime_type, + _MoviePicElementCreator_init_, + _pic_prop_, + pic_, + ) + + @pytest.fixture + def part_rIds_fixture(self, slide_part_, video_, _slide_part_prop_, _video_prop_): + movie_pic_element_creator = _MoviePicElementCreator( + None, None, None, None, None, None, None, None, None + ) + media_rId, video_rId = "rId42", "rId24" + _slide_part_prop_.return_value = slide_part_ + slide_part_.get_or_add_video_media_part.return_value = (media_rId, video_rId) + _video_prop_.return_value = video_ + return (movie_pic_element_creator, slide_part_, video_, media_rId, video_rId) + + @pytest.fixture + def pfrm_rId_fixture(self, _slide_part_prop_, slide_part_, _poster_frame_image_file_prop_): + movie_pic_element_creator = _MoviePicElementCreator( + None, None, None, None, None, None, None, None, None + ) + poster_frame_image_file, expected_value = "image.png", "rId42" + _slide_part_prop_.return_value = slide_part_ + _poster_frame_image_file_prop_.return_value = poster_frame_image_file + slide_part_.get_or_add_image_part.return_value = (None, expected_value) + return ( + movie_pic_element_creator, + slide_part_, + poster_frame_image_file, + expected_value, + ) + + @pytest.fixture + def pic_fixture( + self, + new_video_pic_, + pic_, + _shape_name_prop_, + _video_rId_prop_, + _media_rId_prop_, + _poster_frame_rId_prop_, + ): + shape_id, x, y, cx, cy = 42, 1, 2, 3, 4 + movie_pic_element_creator = _MoviePicElementCreator( + None, shape_id, None, x, y, cx, cy, None, None + ) + _shape_name_prop_.return_value = shape_name = "movie.mp4" + _video_rId_prop_.return_value = video_rId = "rId1" + _media_rId_prop_.return_value = media_rId = ("rId2",) + _poster_frame_rId_prop_.return_value = poster_frame_rId = "rId3" + new_video_pic_.return_value = pic_ + return ( + movie_pic_element_creator, + new_video_pic_, + shape_id, + shape_name, + video_rId, + media_rId, + poster_frame_rId, + x, + y, + cx, + cy, + pic_, + ) + + @pytest.fixture + def shape_name_fixture(self, _video_prop_, video_): + movie_pic_element_creator = _MoviePicElementCreator( + None, None, None, None, None, None, None, None, None + ) + _video_prop_.return_value = video_ + video_.filename = filename = "movie.mp4" + return movie_pic_element_creator, filename + + @pytest.fixture + def slide_part_fixture(self, shapes_, slide_part_): + movie_pic_element_creator = _MoviePicElementCreator( + shapes_, None, None, None, None, None, None, None, None + ) + shapes_.part = slide_part_ + return movie_pic_element_creator, slide_part_ + + @pytest.fixture + def video_rId_fixture(self, _video_part_rIds_prop_): + movie_pic_element_creator = _MoviePicElementCreator( + None, None, None, None, None, None, None, None, None + ) + expected_value = "rId42" + _video_part_rIds_prop_.return_value = ("rId666", expected_value) + return movie_pic_element_creator, expected_value + + @pytest.fixture + def video_fixture(self, video_, from_path_or_file_like_): + movie_file, mime_type = "movie.mp4", "video/mp4" + movie_pic_element_creator = _MoviePicElementCreator( + None, None, movie_file, None, None, None, None, None, mime_type + ) + from_path_or_file_like_.return_value = video_ + return movie_pic_element_creator, movie_file, mime_type, video_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def from_path_or_file_like_(self, request): + return method_mock(request, Video, "from_path_or_file_like", autospec=False) + + @pytest.fixture + def _media_rId_prop_(self, request): + return property_mock(request, _MoviePicElementCreator, "_media_rId") + + @pytest.fixture + def _MoviePicElementCreator_init_(self, request): + return initializer_mock(request, _MoviePicElementCreator, autospec=True) + + @pytest.fixture + def new_video_pic_(self, request): + return method_mock(request, CT_Picture, "new_video_pic", autospec=False) + + @pytest.fixture + def pic_(self): + return element("p:pic") + + @pytest.fixture + def _pic_prop_(self, request, pic_): + return property_mock(request, _MoviePicElementCreator, "_pic", return_value=pic_) + + @pytest.fixture + def _poster_frame_image_file_prop_(self, request): + return property_mock(request, _MoviePicElementCreator, "_poster_frame_image_file") + + @pytest.fixture + def _poster_frame_rId_prop_(self, request): + return property_mock(request, _MoviePicElementCreator, "_poster_frame_rId") + + @pytest.fixture + def _shape_name_prop_(self, request): + return property_mock(request, _MoviePicElementCreator, "_shape_name") + + @pytest.fixture + def shapes_(self, request): + return instance_mock(request, _BaseShapes) + + @pytest.fixture + def slide_part_(self, request): + return instance_mock(request, SlidePart) + + @pytest.fixture + def _slide_part_prop_(self, request): + return property_mock(request, _MoviePicElementCreator, "_slide_part") + + @pytest.fixture + def video_(self, request): + return instance_mock(request, Video) + + @pytest.fixture + def _video_prop_(self, request): + return property_mock(request, _MoviePicElementCreator, "_video") + + @pytest.fixture + def _video_rId_prop_(self, request): + return property_mock(request, _MoviePicElementCreator, "_video_rId") + + @pytest.fixture + def _video_part_rIds_prop_(self, request): + return property_mock(request, _MoviePicElementCreator, "_video_part_rIds") + + +class Describe_OleObjectElementCreator(object): + """Unit-test suite for `pptx.shapes.shapetree._OleObjectElementCreator` objects.""" + + def it_provides_a_graphicFrame_interface_method(self, request, shapes_): + shape_id, x, y, cx, cy = 42, 1, 2, 3, 4 + _init_ = initializer_mock(request, _OleObjectElementCreator, autospec=True) + graphicFrame_ = element("p:graphicFrame") + _graphicFrame_prop_ = property_mock( + request, + _OleObjectElementCreator, + "_graphicFrame", + return_value=graphicFrame_, + ) + + graphicFrame = _OleObjectElementCreator.graphicFrame( + shapes_, + shape_id, + "sheet.xlsx", + PROG_ID.XLSX, + x, + y, + cx, + cy, + "icon.png", + Inches(0.5), + Inches(0.75), + ) + + _init_.assert_called_once_with( + ANY, + shapes_, + shape_id, + "sheet.xlsx", + PROG_ID.XLSX, + x, + y, + cx, + cy, + "icon.png", + Inches(0.5), + Inches(0.75), + ) + _graphicFrame_prop_.assert_called_once_with() + assert graphicFrame is graphicFrame_ + + def it_creates_the_graphicFrame_element(self, request): + shape_id, x, y, cx, cy = 7, 1, 2, 3, 4 + property_mock(request, _OleObjectElementCreator, "_shape_name", return_value="Object 42") + property_mock(request, _OleObjectElementCreator, "_ole_object_rId", return_value="rId42") + property_mock(request, _OleObjectElementCreator, "_progId", return_value="Excel.Sheet.42") + property_mock(request, _OleObjectElementCreator, "_icon_rId", return_value="rId24") + property_mock(request, _OleObjectElementCreator, "_cx", return_value=cx) + property_mock(request, _OleObjectElementCreator, "_cy", return_value=cy) + element_creator = _OleObjectElementCreator( + None, shape_id, None, None, x, y, cx, cy, None, Inches(0.5), Inches(0.75) + ) + + assert element_creator._graphicFrame.xml == ( + "\n' + " \n" + ' \n' + " \n" + ' \n' + " \n" + " \n" + " \n" + " \n" + ' \n' + ' \n' + " \n" + " \n" + " \n' + ' \n' + " \n" + " \n" + " \n" + ' \n' + " \n" + " \n" + " \n" + " \n" + ' \n' + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + ' \n' + ' \n' + " \n" + ' \n' + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + '"\n' + ) + + @pytest.mark.parametrize( + "cx_arg, prog_id, expected_value", + ( + (Emu(999999), None, Emu(999999)), + (None, PROG_ID.DOCX, Emu(965200)), + (None, PROG_ID.PPTX, Emu(965200)), + (None, PROG_ID.XLSX, Emu(965200)), + (None, "Foo.Bar.6", Emu(965200)), + ), + ) + def it_determines_the_shape_width_to_help(self, cx_arg, prog_id, expected_value): + element_creator = _OleObjectElementCreator( + None, None, None, prog_id, None, None, cx_arg, None, None, None, None + ) + assert element_creator._cx == expected_value + + @pytest.mark.parametrize( + "cy_arg, prog_id, expected_value", + ( + (Emu(666666), None, Emu(666666)), + (None, PROG_ID.DOCX, Emu(609600)), + (None, PROG_ID.PPTX, Emu(609600)), + (None, PROG_ID.XLSX, Emu(609600)), + (None, "Foo.Bar.6", Emu(609600)), + ), + ) + def it_determines_the_shape_height_to_help(self, cy_arg, prog_id, expected_value): + element_creator = _OleObjectElementCreator( + None, None, None, prog_id, None, None, None, cy_arg, None, None, None + ) + assert element_creator._cy == expected_value + + @pytest.mark.parametrize( + "icon_height_arg, expected_value", + ( + (Emu(666666), Emu(666666)), + (None, Emu(609600)), + ), + ) + def it_determines_the_icon_height_to_help(self, icon_height_arg, expected_value): + element_creator = _OleObjectElementCreator( + None, None, None, None, None, None, None, None, None, None, icon_height_arg + ) + assert element_creator._icon_height == expected_value + + @pytest.mark.parametrize( + "icon_file_arg, prog_id, expected_value", + ( + ("user-icon.png", PROG_ID.XLSX, "user-icon.png"), + (None, "Foo.Bar.18", "generic-icon.emf"), + (None, PROG_ID.DOCX, "docx-icon.emf"), + (None, PROG_ID.PPTX, "pptx-icon.emf"), + (None, PROG_ID.XLSX, "xlsx-icon.emf"), + ), + ) + def it_resolves_the_icon_image_file_to_help(self, icon_file_arg, prog_id, expected_value): + element_creator = _OleObjectElementCreator( + None, None, None, prog_id, None, None, None, None, icon_file_arg, None, None + ) + assert element_creator._icon_image_file.endswith(expected_value) + + def it_adds_and_relates_the_icon_image_part_to_help( + self, request, _slide_part_prop_, slide_part_ + ): + property_mock( + request, + _OleObjectElementCreator, + "_icon_image_file", + return_value="obj-icon.emf", + ) + slide_part_.get_or_add_image_part.return_value = None, "rId16" + _slide_part_prop_.return_value = slide_part_ + element_creator = _OleObjectElementCreator( + None, None, None, None, None, None, None, None, None, None, None + ) + + rId = element_creator._icon_rId + + slide_part_.get_or_add_image_part.assert_called_once_with("obj-icon.emf") + assert rId == "rId16" + + @pytest.mark.parametrize( + "icon_width_arg, expected_value", + ((Emu(666666), Emu(666666)), (None, Emu(965200))), + ) + def it_determines_the_icon_width_to_help(self, icon_width_arg, expected_value): + element_creator = _OleObjectElementCreator( + None, None, None, None, None, None, None, None, None, icon_width_arg, None + ) + assert element_creator._icon_width == expected_value + + def it_adds_and_relates_the_ole_object_part_to_help( + self, request, _slide_part_prop_, slide_part_ + ): + ole_object_file = "workbook.xlsx" + slide_part_.add_embedded_ole_object_part.return_value = "rId14" + _slide_part_prop_.return_value = slide_part_ + element_creator = _OleObjectElementCreator( + None, + None, + ole_object_file, + PROG_ID.DOCX, + None, + None, + None, + None, + None, + None, + None, + ) + + rId = element_creator._ole_object_rId + + slide_part_.add_embedded_ole_object_part.assert_called_once_with( + PROG_ID.DOCX, ole_object_file + ) + assert rId == "rId14" + + @pytest.mark.parametrize( + "prog_id_arg, expected_value", + ( + (PROG_ID.DOCX, "Word.Document.12"), + (PROG_ID.PPTX, "PowerPoint.Show.12"), + (PROG_ID.XLSX, "Excel.Sheet.12"), + ("Something.Else.42", "Something.Else.42"), + ), + ) + def it_resolves_the_progId_str_to_help(self, prog_id_arg, expected_value): + element_creator = _OleObjectElementCreator( + None, None, None, prog_id_arg, None, None, None, None, None, None, None + ) + assert element_creator._progId == expected_value + + def it_computes_the_shape_name_to_help(self): + shape_id = 42 + element_creator = _OleObjectElementCreator( + None, shape_id, None, None, None, None, None, None, None, None, None + ) + assert element_creator._shape_name == "Object 41" + + def it_provides_access_to_the_slide_part_to_help(self, shapes_, slide_part_): + shapes_.part = slide_part_ + element_creator = _OleObjectElementCreator( + shapes_, None, None, None, None, None, None, None, None, None, None + ) + + assert element_creator._slide_part is slide_part_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def shapes_(self, request): + return instance_mock(request, _BaseGroupShapes) + + @pytest.fixture + def slide_part_(self, request): + return instance_mock(request, SlidePart) + + @pytest.fixture + def _slide_part_prop_(self, request): + return property_mock(request, _OleObjectElementCreator, "_slide_part") + + +class Describe_NotesSlideShapeFactory(object): + def it_constructs_the_right_shape_for_an_element(self, factory_fixture): + shape_elm, parent_, ShapeConstructor_, shape_ = factory_fixture + shape = _NotesSlideShapeFactory(shape_elm, parent_) + ShapeConstructor_.assert_called_once_with(shape_elm, parent_) + assert shape is shape_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("p:sp", "BaseShapeFactory"), + ("p:sp/p:nvSpPr/p:nvPr/p:ph", "NotesSlidePlaceholder"), + ] + ) + def factory_fixture(self, request, shapes_, shape_): + sp_cxml, shape_cls_name = request.param + shape_elm = element(sp_cxml) + ShapeConstructor_ = class_mock( + request, "pptx.shapes.shapetree.%s" % shape_cls_name, return_value=shape_ + ) + return shape_elm, shapes_, ShapeConstructor_, shape_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def shape_(self, request): + return instance_mock(request, BaseShape) + + @pytest.fixture + def shapes_(self, request): + return instance_mock(request, _BaseShapes) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_action.py b/tasks/tasksmith-74f059424102/environment/source/tests/test_action.py new file mode 100644 index 0000000000000000000000000000000000000000..dd0193ca6856e01c0424b1a9a41821fd2bdfca6c --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_action.py @@ -0,0 +1,373 @@ +"""Unit-test suite for `pptx.action` module.""" + +from __future__ import annotations + +import pytest + +from pptx.action import ActionSetting, Hyperlink +from pptx.enum.action import PP_ACTION +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.package import XmlPart +from pptx.parts.slide import SlidePart +from pptx.slide import Slide + +from .unitutil.cxml import element, xml +from .unitutil.mock import call, class_mock, instance_mock, method_mock, property_mock + + +class DescribeActionSetting(object): + """Unit-test suite for `pptx.action.ActionSetting` objects.""" + + def it_knows_its_action_type(self, action_fixture): + action_setting, expected_action = action_fixture + action = action_setting.action + assert action is expected_action + + def it_provides_access_to_its_hyperlink(self, hyperlink_fixture): + action_setting, hyperlink_, Hyperlink_ = hyperlink_fixture[:3] + xPr, parent = hyperlink_fixture[3:] + hyperlink = action_setting.hyperlink + Hyperlink_.assert_called_once_with(xPr, parent, False) + assert hyperlink is hyperlink_ + + def it_can_find_its_slide_jump_target(self, target_get_fixture): + action_setting, expected_value = target_get_fixture + target_slide = action_setting.target_slide + assert target_slide == expected_value + + def it_can_change_its_slide_jump_target( + self, request, _clear_click_action_, slide_, part_prop_, part_ + ): + part_prop_.return_value = part_ + part_.relate_to.return_value = "rId42" + slide_part_ = instance_mock(request, SlidePart) + slide_.part = slide_part_ + action_setting = ActionSetting(element("p:cNvPr{a:b=c,r:s=t}"), None) + + action_setting.target_slide = slide_ + + _clear_click_action_.assert_called_once_with(action_setting) + part_.relate_to.assert_called_once_with(slide_part_, RT.SLIDE) + assert action_setting._element.xml == xml( + "p:cNvPr{a:b=c,r:s=t}/a:hlinkClick{action=ppaction://hlinksldjump,r:id=rI" "d42}", + ) + + def but_it_clears_the_target_slide_if_None_is_assigned(self, _clear_click_action_): + action_setting = ActionSetting(element("p:cNvPr{a:b=c,r:s=t}"), None) + + action_setting.target_slide = None + + _clear_click_action_.assert_called_once_with(action_setting) + assert action_setting._element.xml == xml("p:cNvPr{a:b=c,r:s=t}") + + def it_raises_on_no_next_prev_slide(self, target_raise_fixture): + action_setting = target_raise_fixture + with pytest.raises(ValueError): + action_setting.target_slide + + def it_knows_its_slide_index_to_help(self, _slide_index_fixture): + action_setting, slides, slide, expected_value = _slide_index_fixture + slide_index = action_setting._slide_index + slides.index.assert_called_once_with(slide) + assert slide_index == expected_value + + def it_clears_the_click_action_to_help(self, clear_fixture): + action_setting, calls, expected_xml = clear_fixture + + action_setting._clear_click_action() + + assert action_setting.part.drop_rel.call_args_list == calls + assert action_setting._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("p:cNvPr", None, PP_ACTION.NONE), + ("p:cNvPr/a:hlinkClick", None, PP_ACTION.HYPERLINK), + ( + "p:cNvPr/a:hlinkClick", + "ppaction://hlinkshowjump?jump=firstslide", + PP_ACTION.FIRST_SLIDE, + ), + ( + "p:cNvPr/a:hlinkClick", + "ppaction://hlinkshowjump?jump=lastslide", + PP_ACTION.LAST_SLIDE, + ), + ( + "p:cNvPr/a:hlinkClick", + "ppaction://hlinkshowjump?jump=nextslide", + PP_ACTION.NEXT_SLIDE, + ), + ( + "p:cNvPr/a:hlinkClick", + "ppaction://hlinkshowjump?jump=previousslide", + PP_ACTION.PREVIOUS_SLIDE, + ), + ( + "p:cNvPr/a:hlinkClick", + "ppaction://hlinkshowjump?jump=endshow", + PP_ACTION.END_SHOW, + ), + ("p:cNvPr/a:hlinkClick", "ppaction://hlinksldjump", PP_ACTION.NAMED_SLIDE), + ("p:cNvPr/a:hlinkClick", "ppaction://hlinkfile", PP_ACTION.OPEN_FILE), + ("p:cNvPr/a:hlinkClick", "ppaction://hlinkpres", PP_ACTION.PLAY), + ( + "p:cNvPr/a:hlinkClick", + "ppaction://customshow", + PP_ACTION.NAMED_SLIDE_SHOW, + ), + ("p:cNvPr/a:hlinkClick", "ppaction://ole", PP_ACTION.OLE_VERB), + ("p:cNvPr/a:hlinkClick", "ppaction://macro", PP_ACTION.RUN_MACRO), + ("p:cNvPr/a:hlinkClick", "ppaction://program", PP_ACTION.RUN_PROGRAM), + ( + "p:cNvPr/a:hlinkClick", + "ppaction://hlinkshowjump?jump=lastslideviewed", + PP_ACTION.LAST_SLIDE_VIEWED, + ), + ("p:cNvPr/a:hlinkClick", "ppaction://media", PP_ACTION.NONE), + ] + ) + def action_fixture(self, request): + cNvPr_cxml, action_text, expected_action = request.param + cNvPr = element(cNvPr_cxml) + if action_text is not None: + cNvPr.hlinkClick.action = action_text + action_setting = ActionSetting(cNvPr, None) + return action_setting, expected_action + + @pytest.fixture( + params=[ + ("p:cNvPr", None, "p:cNvPr"), + ( + "p:cNvPr{a:b=c,r:s=t}/a:hlinkClick{r:id=rId42}", + "rId42", + "p:cNvPr{a:b=c,r:s=t}", + ), + ] + ) + def clear_fixture(self, request, part_prop_, part_): + xPr_cxml, rId, expected_cxml = request.param + action_setting = ActionSetting(element(xPr_cxml), None) + + part_prop_.return_value = part_ + + calls = [call(rId)] if rId else [] + expected_xml = xml(expected_cxml) + return action_setting, calls, expected_xml + + @pytest.fixture + def hyperlink_fixture(self, Hyperlink_, hyperlink_): + xPr, parent = "xPr", "parent" + action_setting = ActionSetting(xPr, parent) + return action_setting, hyperlink_, Hyperlink_, xPr, parent + + @pytest.fixture + def _slide_index_fixture(self, request, part_prop_): + action_setting = ActionSetting(None, None) + slide_part = part_prop_.return_value + slides = slide_part.package.presentation_part.presentation.slides + slide = slide_part.slide + expected_value = 123 + slides.index.return_value = expected_value + return action_setting, slides, slide, expected_value + + @pytest.fixture( + params=[ + (PP_ACTION.NONE, None), + (PP_ACTION.HYPERLINK, None), + (PP_ACTION.FIRST_SLIDE, 0), + (PP_ACTION.LAST_SLIDE, 5), + (PP_ACTION.NEXT_SLIDE, 3), + (PP_ACTION.PREVIOUS_SLIDE, 1), + (PP_ACTION.END_SHOW, None), + (PP_ACTION.NAMED_SLIDE, 4), + (PP_ACTION.OPEN_FILE, None), + (PP_ACTION.PLAY, None), + (PP_ACTION.NAMED_SLIDE_SHOW, None), + (PP_ACTION.OLE_VERB, None), + (PP_ACTION.RUN_MACRO, None), + (PP_ACTION.RUN_PROGRAM, None), + (PP_ACTION.LAST_SLIDE_VIEWED, None), + ] + ) + def target_get_fixture(self, request, action_prop_, _slide_index_prop_, part_prop_): + action_type, expected_value = request.param + cNvPr = element("p:cNvPr/a:hlinkClick{r:id=rId6}") + action_setting = ActionSetting(cNvPr, None) + action_prop_.return_value = action_type + _slide_index_prop_.return_value = 2 + # this becomes the return value of ActionSetting._slides + prs_part_ = part_prop_.return_value.package.presentation_part + prs_part_.presentation.slides = [0, 1, 2, 3, 4, 5] + related_part_ = part_prop_.return_value.related_part + related_part_.return_value.slide = 4 + return action_setting, expected_value + + @pytest.fixture(params=[(PP_ACTION.NEXT_SLIDE, 2), (PP_ACTION.PREVIOUS_SLIDE, 0)]) + def target_raise_fixture(self, request, action_prop_, part_prop_, _slide_index_prop_): + action_type, slide_idx = request.param + action_setting = ActionSetting(None, None) + action_prop_.return_value = action_type + # this becomes the return value of ActionSetting._slides + part_prop_.return_value.package.presentation.slides = [0, 1, 2] + _slide_index_prop_.return_value = slide_idx + return action_setting + + # fixture components --------------------------------------------- + + @pytest.fixture + def action_prop_(self, request): + return property_mock(request, ActionSetting, "action") + + @pytest.fixture + def _clear_click_action_(self, request): + return method_mock(request, ActionSetting, "_clear_click_action") + + @pytest.fixture + def Hyperlink_(self, request, hyperlink_): + return class_mock(request, "pptx.action.Hyperlink", return_value=hyperlink_) + + @pytest.fixture + def hyperlink_(self, request): + return instance_mock(request, Hyperlink) + + @pytest.fixture + def part_(self, request): + return instance_mock(request, XmlPart) + + @pytest.fixture + def part_prop_(self, request): + return property_mock(request, ActionSetting, "part") + + @pytest.fixture + def slide_(self, request): + return instance_mock(request, Slide) + + @pytest.fixture + def _slide_index_prop_(self, request): + return property_mock(request, ActionSetting, "_slide_index") + + +class DescribeHyperlink(object): + """Unit-test suite for `pptx.action.Hyperlink` objects.""" + + def it_knows_the_target_url_of_the_hyperlink(self, address_fixture): + hyperlink, rId, expected_address = address_fixture + address = hyperlink.address + hyperlink.part.target_ref.assert_called_once_with(rId) + assert address == expected_address + + def it_knows_when_theres_no_url(self, no_address_fixture): + hyperlink = no_address_fixture + assert hyperlink.address is None + + def it_can_remove_its_url(self, remove_fixture): + hyperlink, calls, expected_xml = remove_fixture + + hyperlink.address = None + + assert hyperlink.part.drop_rel.call_args_list == calls + assert hyperlink._element.xml == expected_xml + + def it_can_set_its_target_url(self, update_fixture): + hyperlink, url, calls, expected_xml = update_fixture + + hyperlink.address = url + + assert hyperlink.part.relate_to.call_args_list == calls + assert hyperlink._element.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def address_fixture(self, part_prop_): + cNvPr_cxml, rId = "p:cNvPr/a:hlinkClick{r:id=rId1}", "rId1" + expected_address = "http://foobar.com" + cNvPr = element(cNvPr_cxml) + hyperlink = Hyperlink(cNvPr, None) + part_prop_.return_value.target_ref.return_value = expected_address + return hyperlink, rId, expected_address + + @pytest.fixture(params=["p:cNvPr", "p:cNvPr/a:hlinkClick"]) + def no_address_fixture(self, request): + cNvPr_cxml = request.param + cNvPr = element(cNvPr_cxml) + hyperlink = Hyperlink(cNvPr, None) + return hyperlink + + @pytest.fixture( + params=[ + ("p:cNvPr{a:a=a,r:r=r}", []), + ("p:cNvPr{a:a=a,r:r=r}/a:hlinkClick", []), + ("p:cNvPr{a:a=a,r:r=r}/a:hlinkClick{r:id=rId3}", [call("rId3")]), + ] + ) + def remove_fixture(self, request, part_prop_): + cNvPr_cxml, calls = request.param + cNvPr = element(cNvPr_cxml) + expected_xml = xml("p:cNvPr{a:a=a,r:r=r}") + hyperlink = Hyperlink(cNvPr, None) + return hyperlink, calls, expected_xml + + @pytest.fixture( + params=[ + ( + "p:cNvPr{a:a=a,r:r=r}", + "http://foo.com", + False, + True, + "p:cNvPr{a:a=a,r:r=r}/a:hlinkClick{r:id=rId3}", + ), + ( + "p:cNvPr{a:a=a,r:r=r}", + "http://bar.com", + True, + True, + "p:cNvPr{a:a=a,r:r=r}/a:hlinkHover{r:id=rId3}", + ), + ( + "p:cNvPr/a:hlinkClick{r:id=rId6}", + "http://baz.com", + False, + True, + "p:cNvPr/a:hlinkClick{r:id=rId3}", + ), + ( + "p:cNvPr/a:hlinkHover{r:id=rId6}", + "http://zab.com", + True, + True, + "p:cNvPr/a:hlinkHover{r:id=rId3}", + ), + ( + "p:cNvPr/a:hlinkHover{r:id=rId6}", + "http://boo.com", + False, + True, + "p:cNvPr/(a:hlinkClick{r:id=rId3},a:hlinkHover{r:id=rId6})", + ), + ( + "p:cNvPr{a:a=a,r:r=r}/a:hlinkClick{r:id=rId6}", + None, + False, + False, + "p:cNvPr{a:a=a,r:r=r}", + ), + ] + ) + def update_fixture(self, request, part_prop_): + cNvPr_cxml, url, hover, called, expected_cNvPr_cxml = request.param + cNvPr = element(cNvPr_cxml) + hyperlink = Hyperlink(cNvPr, None, hover) + calls = [call(url, RT.HYPERLINK, is_external=True)] if called else [] + part_prop_.return_value.relate_to.return_value = "rId3" + expected_xml = xml(expected_cNvPr_cxml) + return hyperlink, url, calls, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def part_prop_(self, request): + return property_mock(request, Hyperlink, "part") diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_api.py b/tasks/tasksmith-74f059424102/environment/source/tests/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..a48f48912468a01ad22c2930e283b3a684d79423 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_api.py @@ -0,0 +1,48 @@ +"""Unit-test suite for `pptx.api` module.""" + +from __future__ import annotations + +import os + +import pytest + +import pptx +from pptx.api import Presentation +from pptx.opc.constants import CONTENT_TYPE as CT +from pptx.parts.presentation import PresentationPart + +from .unitutil.mock import class_mock, instance_mock + + +class DescribePresentation(object): + def it_opens_default_template_on_no_path_provided(self, call_fixture): + Package_, path, prs_ = call_fixture + prs = Presentation() + Package_.open.assert_called_once_with(path) + assert prs is prs_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def call_fixture(self, Package_, prs_, prs_part_): + path = os.path.abspath( + os.path.join(os.path.split(pptx.__file__)[0], "templates", "default.pptx") + ) + Package_.open.return_value.main_document_part = prs_part_ + prs_part_.content_type = CT.PML_PRESENTATION_MAIN + prs_part_.presentation = prs_ + return Package_, path, prs_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def Package_(self, request): + return class_mock(request, "pptx.api.Package") + + @pytest.fixture + def prs_(self, request): + return instance_mock(request, Presentation) + + @pytest.fixture + def prs_part_(self, request): + return instance_mock(request, PresentationPart) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/calibriz.ttf b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/calibriz.ttf new file mode 100644 index 0000000000000000000000000000000000000000..c62e93071d4ce56163bfe6bd08a4c80a3a3a5713 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/calibriz.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f41ccc168a602923e52188ab9940f7a324100bea1e87bb11e096155719b21d65 +size 867288 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/cdw-logo.eps b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/cdw-logo.eps new file mode 100644 index 0000000000000000000000000000000000000000..6e82d7f4e96a63c513b6b0e4898b5379aa4f2d7a --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/cdw-logo.eps @@ -0,0 +1,420 @@ +%!PS-Adobe-3.0 EPSF-3.0 +%%BoundingBox: 201 324 395 518 +%%LanguageLevel: 2 +%%Creator: CorelDRAW 9 +%%Title: 83.eps +%%CreationDate: Fri Mar 09 20:48:32 2001 +%%For: LDN +%%DocumentProcessColors: Magenta Yellow Black +%%DocumentSuppliedResources: (atend) +%%EndComments +%%BeginProlog +/AutoFlatness false def +/AutoSteps 2 def +/CMYKMarks true def +/UseLevel 2 def +%Build: CorelDRAW 9 Version 9.397 +%Color profile: Disabled +%%BeginResource: procset wCorel9Dict 9.0 0 +/wCorel9Dict 300 dict def wCorel9Dict begin +% Copyright (c)1992-1999 Corel Corporation +% All rights reserved. v9.0 r0.5 +/bd{bind def}bind def/ld{load def}bd/xd{exch def}bd/_ null def/rp{{pop}repeat} +bd/@cp/closepath ld/@gs/gsave ld/@gr/grestore ld/@np/newpath ld/Tl/translate ld +/$sv 0 def/@sv{/$sv save def}bd/@rs{$sv restore}bd/spg/showpage ld/showpage{} +bd currentscreen/@dsp xd/$dsp/@dsp def/$dsa xd/$dsf xd/$sdf false def/$SDF +false def/$Scra 0 def/SetScr/setscreen ld/@ss{2 index 0 eq{$dsf 3 1 roll 4 -1 +roll pop}if exch $Scra add exch load SetScr}bd/SepMode_5 where{pop}{/SepMode_5 +0 def}ifelse/CurrentInkName_5 where{pop}{/CurrentInkName_5(Composite)def} +ifelse/$ink_5 where{pop}{/$ink_5 -1 def}ifelse/$c 0 def/$m 0 def/$y 0 def/$k 0 +def/$t 1 def/$n _ def/$o 0 def/$fil 0 def/$C 0 def/$M 0 def/$Y 0 def/$K 0 def +/$T 1 def/$N _ def/$O 0 def/$PF false def/s1c 0 def/s1m 0 def/s1y 0 def/s1k 0 +def/s1t 0 def/s1n _ def/$bkg false def/SK 0 def/SM 0 def/SY 0 def/SC 0 def/$op +false def matrix currentmatrix/$ctm xd/$ptm matrix def/$ttm matrix def/$stm +matrix def/$ffpnt true def/CorelDrawReencodeVect[16#0/grave 16#5/breve +16#6/dotaccent 16#8/ring 16#A/hungarumlaut 16#B/ogonek 16#C/caron 16#D/dotlessi +16#27/quotesingle 16#60/grave 16#7C/bar +16#82/quotesinglbase/florin/quotedblbase/ellipsis/dagger/daggerdbl +16#88/circumflex/perthousand/Scaron/guilsinglleft/OE +16#91/quoteleft/quoteright/quotedblleft/quotedblright/bullet/endash/emdash +16#98/tilde/trademark/scaron/guilsinglright/oe 16#9F/Ydieresis +16#A1/exclamdown/cent/sterling/currency/yen/brokenbar/section +16#a8/dieresis/copyright/ordfeminine/guillemotleft/logicalnot/minus/registered/macron +16#b0/degree/plusminus/twosuperior/threesuperior/acute/mu/paragraph/periodcentered +16#b8/cedilla/onesuperior/ordmasculine/guillemotright/onequarter/onehalf/threequarters/questiondown +16#c0/Agrave/Aacute/Acircumflex/Atilde/Adieresis/Aring/AE/Ccedilla +16#c8/Egrave/Eacute/Ecircumflex/Edieresis/Igrave/Iacute/Icircumflex/Idieresis +16#d0/Eth/Ntilde/Ograve/Oacute/Ocircumflex/Otilde/Odieresis/multiply +16#d8/Oslash/Ugrave/Uacute/Ucircumflex/Udieresis/Yacute/Thorn/germandbls +16#e0/agrave/aacute/acircumflex/atilde/adieresis/aring/ae/ccedilla +16#e8/egrave/eacute/ecircumflex/edieresis/igrave/iacute/icircumflex/idieresis +16#f0/eth/ntilde/ograve/oacute/ocircumflex/otilde/odieresis/divide +16#f8/oslash/ugrave/uacute/ucircumflex/udieresis/yacute/thorn/ydieresis]def +/L2?/languagelevel where{pop languagelevel 2 ge}{false}ifelse def/Comp?{ +/LumSepsDict where{pop false}{/AldusSepsDict where{pop false}{1 0 0 0 @gs +setcmykcolor currentcmykcolor @gr add add add 0 ne 0 1 0 0 @gs setcmykcolor +currentcmykcolor @gr add add add 0 ne 0 0 1 0 @gs setcmykcolor currentcmykcolor +@gr add add add 0 ne 0 0 0 1 @gs setcmykcolor currentcmykcolor @gr add add add +0 ne and and and}ifelse}ifelse}bd/@PL{/LV where{pop LV 2 ge L2? not and{@np +/Courier findfont 12 scalefont setfont 72 144 m +(The PostScript level set in the Corel application is higher than)show 72 132 m +(the PostScript level of this device. Change the PS Level in the Corel)show 72 +120 m(application to Level 1 by selecting the PostScript tab in the print)show +72 108 m(dialog, and selecting Level 1 from the Compatibility drop down list.) +show flush spg quit}if}if}bd/@BeginSysCorelDict{systemdict/Corel30Dict known +{systemdict/Corel30Dict get exec}if systemdict/CorelLexDict known{1 systemdict +/CorelLexDict get exec}if}bd/@EndSysCorelDict{systemdict/Corel30Dict known +{end}if/EndCorelLexDict where{pop EndCorelLexDict}if}bd AutoFlatness{/@ifl{dup +currentflat exch sub 10 gt{ +([Error: PathTooComplex; OffendingCommand: AnyPaintingOperator]\n)print flush +@np exit}{currentflat 2 add setflat}ifelse}bd/@fill/fill ld/fill{currentflat{ +{@fill}stopped{@ifl}{exit}ifelse}bind loop setflat}bd/@eofill/eofill ld/eofill +{currentflat{{@eofill}stopped{@ifl}{exit}ifelse}bind loop setflat}bd/@clip +/clip ld/clip{currentflat{{@clip}stopped{@ifl}{exit}ifelse}bind loop setflat} +bd/@eoclip/eoclip ld/eoclip{currentflat{{@eoclip}stopped{@ifl}{exit}ifelse} +bind loop setflat}bd/@stroke/stroke ld/stroke{currentflat{{@stroke}stopped +{@ifl}{exit}ifelse}bind loop setflat}bd}if L2?{/@ssa{true setstrokeadjust}bd}{ +/@ssa{}bd}ifelse/d/setdash ld/j/setlinejoin ld/J/setlinecap ld/M/setmiterlimit +ld/w/setlinewidth ld/O{/$o xd}bd/R{/$O xd}bd/W/eoclip ld/c/curveto ld/C/c ld/l +/lineto ld/L/l ld/rl/rlineto ld/m/moveto ld/n/newpath ld/N/newpath ld/P{11 rp} +bd/u{}bd/U{}bd/A{pop}bd/q/@gs ld/Q/@gr ld/&{}bd/@j{@sv @np}bd/@J{@rs}bd/g{1 +exch sub/$k xd/$c 0 def/$m 0 def/$y 0 def/$t 1 def/$n _ def/$fil 0 def}bd/G{1 +sub neg/$K xd _ 1 0 0 0/$C xd/$M xd/$Y xd/$T xd/$N xd}bd/k{1 index type +/stringtype eq{/$t xd/$n xd}{/$t 0 def/$n _ def}ifelse/$k xd/$y xd/$m xd/$c xd +/$fil 0 def}bd/K{1 index type/stringtype eq{/$T xd/$N xd}{/$T 0 def/$N _ def} +ifelse/$K xd/$Y xd/$M xd/$C xd}bd/x/k ld/X/K ld/sf{1 index type/stringtype eq{ +/s1t xd/s1n xd}{/s1t 0 def/s1n _ def}ifelse/s1k xd/s1y xd/s1m xd/s1c xd}bd/i{ +dup 0 ne{setflat}{pop}ifelse}bd/v{4 -2 roll 2 copy 6 -2 roll c}bd/V/v ld/y{2 +copy c}bd/Y/y ld/@w{matrix rotate/$ptm xd matrix scale $ptm dup concatmatrix +/$ptm xd 1 eq{$ptm exch dup concatmatrix/$ptm xd}if 1 w}bd/@g{1 eq dup/$sdf xd +{/$scp xd/$sca xd/$scf xd}if}bd/@G{1 eq dup/$SDF xd{/$SCP xd/$SCA xd/$SCF xd} +if}bd/@D{2 index 0 eq{$dsf 3 1 roll 4 -1 roll pop}if 3 copy exch $Scra add exch +load SetScr/$dsp xd/$dsa xd/$dsf xd}bd/$ngx{$SDF{$SCF SepMode_5 0 eq{$SCA} +{$dsa}ifelse $SCP @ss}if}bd/p{/$pm xd 7 rp/$pyf xd/$pxf xd/$pn xd/$fil 1 def} +bd/@MN{2 copy le{pop}{exch pop}ifelse}bd/@MX{2 copy ge{pop}{exch pop}ifelse}bd +/InRange{3 -1 roll @MN @MX}bd/@sqr{dup 0 rl dup 0 exch rl neg 0 rl @cp}bd +/currentscale{1 0 dtransform matrix defaultmatrix idtransform dup mul exch dup +mul add sqrt 0 1 dtransform matrix defaultmatrix idtransform dup mul exch dup +mul add sqrt}bd/@unscale{}bd/wDstChck{2 1 roll dup 3 -1 roll eq{1 add}if}bd +/@dot{dup mul exch dup mul add 1 exch sub}bd/@lin{exch pop abs 1 exch sub}bd +/cmyk2rgb{3{dup 5 -1 roll add 1 exch sub dup 0 lt{pop 0}if exch}repeat pop}bd +/rgb2cmyk{3{1 exch sub 3 1 roll}repeat 3 copy @MN @MN 3{dup 5 -1 roll sub neg +exch}repeat}bd/rgb2g{2 index .299 mul 2 index .587 mul add 1 index .114 mul add +4 1 roll pop pop pop}bd/WaldoColor_5 where{pop}{/SetRgb/setrgbcolor ld/GetRgb +/currentrgbcolor ld/SetGry/setgray ld/GetGry/currentgray ld/SetRgb2 systemdict +/setrgbcolor get def/GetRgb2 systemdict/currentrgbcolor get def/SetHsb +systemdict/sethsbcolor get def/GetHsb systemdict/currenthsbcolor get def +/rgb2hsb{SetRgb2 GetHsb}bd/hsb2rgb{3 -1 roll dup floor sub 3 1 roll SetHsb +GetRgb2}bd/setcmykcolor where{pop/LumSepsDict where{pop/SetCmyk_5{LumSepsDict +/setcmykcolor get exec}def}{/AldusSepsDict where{pop/SetCmyk_5{AldusSepsDict +/setcmykcolor get exec}def}{/SetCmyk_5/setcmykcolor ld}ifelse}ifelse}{ +/SetCmyk_5{cmyk2rgb SetRgb}bd}ifelse/currentcmykcolor where{pop/GetCmyk +/currentcmykcolor ld}{/GetCmyk{GetRgb rgb2cmyk}bd}ifelse/setoverprint where +{pop}{/setoverprint{/$op xd}bd}ifelse/currentoverprint where{pop}{ +/currentoverprint{$op}bd}ifelse/@tc_5{5 -1 roll dup 1 ge{pop}{4{dup 6 -1 roll +mul exch}repeat pop}ifelse}bd/@trp{exch pop 5 1 roll @tc_5}bd +/setprocesscolor_5{SepMode_5 0 eq{SetCmyk_5}{0 4 $ink_5 sub index exch pop 5 1 +roll pop pop pop pop SepsColor true eq{$ink_5 3 gt{1 sub neg SetGry}{0 0 0 4 +$ink_5 roll SetCmyk_5}ifelse}{1 sub neg SetGry}ifelse}ifelse}bd +/findcmykcustomcolor where{pop}{/findcmykcustomcolor{5 array astore}bd}ifelse +/setcustomcolor where{pop}{/setcustomcolor{exch aload pop SepMode_5 0 eq{pop +@tc_5 setprocesscolor_5}{CurrentInkName_5 eq{4 index}{0}ifelse 6 1 roll 5 rp 1 +sub neg SetGry}ifelse}bd}ifelse/@scc_5{dup type/booleantype eq{setoverprint}{1 +eq setoverprint}ifelse dup _ eq{pop setprocesscolor_5 pop}{findcmykcustomcolor +exch setcustomcolor}ifelse SepMode_5 0 eq{true}{GetGry 1 eq currentoverprint +and not}ifelse}bd/colorimage where{pop/ColorImage{colorimage}def}{/ColorImage{ +/ncolors xd/$multi xd $multi true eq{ncolors 3 eq{/daqB xd/daqG xd/daqR xd pop +pop exch pop abs{daqR pop daqG pop daqB pop}repeat}{/daqK xd/daqY xd/daqM xd +/daqC xd pop pop exch pop abs{daqC pop daqM pop daqY pop daqK pop}repeat} +ifelse}{/dataaq xd{dataaq ncolors dup 3 eq{/$dat xd 0 1 $dat length 3 div 1 sub +{dup 3 mul $dat 1 index get 255 div $dat 2 index 1 add get 255 div $dat 3 index +2 add get 255 div rgb2g 255 mul cvi exch pop $dat 3 1 roll put}for $dat 0 $dat +length 3 idiv getinterval pop}{4 eq{/$dat xd 0 1 $dat length 4 div 1 sub{dup 4 +mul $dat 1 index get 255 div $dat 2 index 1 add get 255 div $dat 3 index 2 add +get 255 div $dat 4 index 3 add get 255 div cmyk2rgb rgb2g 255 mul cvi exch pop +$dat 3 1 roll put}for $dat 0 $dat length ncolors idiv getinterval}if}ifelse} +image}ifelse}bd}ifelse/setcmykcolor{1 5 1 roll _ currentoverprint @scc_5 +/$ffpnt xd}bd/currentcmykcolor{GetCmyk}bd/setrgbcolor{rgb2cmyk setcmykcolor}bd +/currentrgbcolor{currentcmykcolor cmyk2rgb}bd/sethsbcolor{hsb2rgb setrgbcolor} +bd/currenthsbcolor{currentrgbcolor rgb2hsb}bd/setgray{dup dup setrgbcolor}bd +/currentgray{currentrgbcolor rgb2g}bd/InsideDCS false def/IMAGE/image ld/image +{InsideDCS{IMAGE}{/EPSDict where{pop SepMode_5 0 eq{IMAGE}{dup type/dicttype eq +{dup/ImageType get 1 ne{IMAGE}{dup dup/BitsPerComponent get 8 eq exch +/BitsPerComponent get 1 eq or currentcolorspace 0 get/DeviceGray eq and{ +CurrentInkName_5(Black)eq{IMAGE}{dup/DataSource get/TCC xd/Height get abs{TCC +pop}repeat}ifelse}{IMAGE}ifelse}ifelse}{2 index 1 ne{CurrentInkName_5(Black)eq +{IMAGE}{/TCC xd pop pop exch pop abs{TCC pop}repeat}ifelse}{IMAGE}ifelse} +ifelse}ifelse}{IMAGE}ifelse}ifelse}bd}ifelse/WaldoColor_5 true def/@sft{$tllx +$pxf add dup $tllx gt{$pwid sub}if/$tx xd $tury $pyf sub dup $tury lt{$phei +add}if/$ty xd}bd/@stb{pathbbox/$ury xd/$urx xd/$lly xd/$llx xd}bd/@ep{{cvx exec +}forall}bd/@tp{@sv/$in true def 2 copy dup $lly le{/$in false def}if $phei sub +$ury ge{/$in false def}if dup $urx ge{/$in false def}if $pwid add $llx le{/$in +false def}if $in{@np 2 copy m $pwid 0 rl 0 $phei neg rl $pwid neg 0 rl 0 $phei +rl clip @np $pn cvlit load aload pop 7 -1 roll 5 index sub 7 -1 roll 3 index +sub Tl matrix currentmatrix/$ctm xd @ep pop pop pop pop}{pop pop}ifelse @rs}bd +/@th{@sft 0 1 $tly 1 sub{dup $psx mul $tx add{dup $llx gt{$pwid sub}{exit} +ifelse}loop exch $phei mul $ty exch sub 0 1 $tlx 1 sub{$pwid mul 3 copy 3 -1 +roll add exch @tp pop}for pop pop}for}bd/@tv{@sft 0 1 $tlx 1 sub{dup $pwid mul +$tx add exch $psy mul $ty exch sub{dup $ury lt{$phei add}{exit}ifelse}loop 0 1 +$tly 1 sub{$phei mul 3 copy sub @tp pop}for pop pop}for}bd/$fm 0 def/wfill{1 +$fm eq{fill}{eofill}ifelse}bd/wclip{1 $fm eq{clip}{eoclip}ifelse}bd/@pf{@gs +$ctm setmatrix $pm concat @stb wclip @sv Bburx Bbury $pm itransform/$tury xd +/$turx xd Bbllx Bblly $pm itransform/$tlly xd/$tllx xd newpath $tllx $tlly m +$tllx $tury l $turx $tury l $turx $tlly l $tllx $tlly m @cp pathbbox @rs/$tury +xd/$turx xd/$tlly xd/$tllx xd/$wid $turx $tllx sub def/$hei $tury $tlly sub def +@gs $vectpat{1 0 0 0 0 _ $o @scc_5{wfill}if}{$t $c $m $y $k $n $o @scc_5{ +SepMode_5 0 eq $pfrg or{$tllx $tlly Tl $wid $hei scale <00> 8 1 false[8 0 0 1 0 +0]{}imagemask}{/$bkg true def}ifelse}if}ifelse @gr $wid 0 gt $hei 0 gt and{$pn +cvlit load aload pop/$pd xd 3 -1 roll sub/$phei xd exch sub/$pwid xd $wid $pwid +div ceiling 1 add/$tlx xd $hei $phei div ceiling 1 add/$tly xd $psx 0 eq{@tv}{ +@th}ifelse}if @gr @np/$bkg false def}bd/@Pf{@sv SepMode_5 0 eq $Psc 0 ne or +$ink_5 3 eq or{0 J 0 j[]0 d $t $c $m $y $k $n $o @scc_5 pop $ctm setmatrix 72 +1000 div dup matrix scale dup concat dup Bburx exch Bbury exch itransform +ceiling cvi/Bbury xd ceiling cvi/Bburx xd Bbllx exch Bblly exch itransform +floor cvi/Bblly xd floor cvi/Bbllx xd $Prm aload pop $Psn load exec}{1 SetGry +wfill}ifelse @rs @np}bd/F{matrix currentmatrix $sdf{$scf $sca $scp @ss}if $fil +1 eq{@pf}{$fil 2 eq{@ff}{$fil 3 eq{@Pf}{$t $c $m $y $k $n $o @scc_5{wfill} +{@np}ifelse}ifelse}ifelse}ifelse $sdf{$dsf $dsa $dsp @ss}if setmatrix}bd/f{@cp +F}bd/S{matrix currentmatrix $ctm setmatrix $SDF{$SCF $SCA $SCP @ss}if $T $C $M +$Y $K $N $O @scc_5{matrix currentmatrix $ptm concat stroke setmatrix} +{@np}ifelse $SDF{$dsf $dsa $dsp @ss}if setmatrix}bd/s{@cp S}bd/B{@gs F @gr S} +bd/b{@cp B}bd/_E{5 array astore exch cvlit xd}bd/@cc{currentfile $dat +readhexstring pop}bd/@sm{/$ctm $ctm currentmatrix def}bd/@E{/Bbury xd/Bburx xd +/Bblly xd/Bbllx xd}bd/@c{@cp}bd/@p{/$fil 1 def 1 eq dup/$vectpat xd{/$pfrg true +def}{@gs $t $c $m $y $k $n $o @scc_5/$pfrg xd @gr}ifelse/$pm xd/$psy xd/$psx xd +/$pyf xd/$pxf xd/$pn xd}bd/@P{/$fil 3 def/$Psn xd/$Psc xd array astore/$Prm xd +}bd/@ii{concat 3 index 3 index m 3 index 1 index l 2 copy l 1 index 3 index l 3 +index 3 index l clip pop pop pop pop}bd/tcc{@cc}def/@i{@sm @gs @ii 6 index 1 ne +{/$frg true def pop pop}{1 eq{s1t s1c s1m s1y s1k s1n $O @scc_5/$frg xd}{/$frg +false def}ifelse 1 eq{@gs $ctm setmatrix F @gr}if}ifelse @np/$ury xd/$urx xd +/$lly xd/$llx xd/$bts xd/$hei xd/$wid xd/$dat $wid $bts mul 8 div ceiling cvi +string def $bkg $frg or{$SDF{$SCF $SCA $SCP @ss}if $llx $lly Tl $urx $llx sub +$ury $lly sub scale $bkg{$t $c $m $y $k $n $o @scc_5 pop}if $wid $hei abs $bts +1 eq{$bkg}{$bts}ifelse[$wid 0 0 $hei neg 0 $hei 0 gt{$hei}{0}ifelse]/tcc load +$bts 1 eq{imagemask}{image}ifelse $SDF{$dsf $dsa $dsp @ss}if}{$hei abs{tcc pop} +repeat}ifelse @gr $ctm setmatrix}bd/@I{@sm @gs @ii @np/$ury xd/$urx xd/$lly xd +/$llx xd/$ncl xd/$bts xd/$hei xd/$wid xd $ngx $llx $lly Tl $urx $llx sub $ury +$lly sub scale $wid $hei abs $bts[$wid 0 0 $hei neg 0 $hei 0 gt{$hei}{0}ifelse +]$msimage false eq $ncl 1 eq or{/$dat $wid $bts mul $ncl mul 8 div ceiling cvi +string def/@cc load false $ncl ColorImage}{$wid $bts mul 8 div ceiling cvi $ncl +3 eq{dup dup/$dat1 exch string def/$dat2 exch string def/$dat3 exch string def +/@cc1 load/@cc2 load/@cc3 load}{dup dup dup/$dat1 exch string def/$dat2 exch +string def/$dat3 exch string def/$dat4 exch string def/@cc1 load/@cc2 load +/@cc3 load/@cc4 load}ifelse true $ncl ColorImage}ifelse $SDF{$dsf $dsa $dsp +@ss}if @gr $ctm setmatrix}bd/@cc1{currentfile $dat1 readhexstring pop}bd/@cc2{ +currentfile $dat2 readhexstring pop}bd/@cc3{currentfile $dat3 readhexstring pop +}bd/@cc4{currentfile $dat4 readhexstring pop}bd/$msimage false def/COMP 0 def +/MaskedImage false def L2?{/@I_2{@sm @gs @ii @np/$ury xd/$urx xd/$lly xd/$llx +xd/$ncl xd/$bts xd/$hei xd/$wid xd/$dat $wid $bts mul $ncl mul 8 div ceiling +cvi string def $ngx $ncl 1 eq{/DeviceGray}{$ncl 3 eq{/DeviceRGB}{/DeviceCMYK} +ifelse}ifelse setcolorspace $llx $lly Tl $urx $llx sub $ury $lly sub scale 8 +dict begin/ImageType 1 def/Width $wid def/Height $hei abs def/BitsPerComponent +$bts def/Decode $ncl 1 eq{[0 1]}{$ncl 3 eq{[0 1 0 1 0 1]}{[0 1 0 1 0 1 0 1]} +ifelse}ifelse def/ImageMatrix[$wid 0 0 $hei neg 0 $hei 0 gt{$hei}{0}ifelse]def +/DataSource currentfile/ASCII85Decode filter COMP 1 eq{/DCTDecode filter}{COMP +2 eq{/RunLengthDecode filter}if}ifelse def currentdict end image $SDF{$dsf $dsa +$dsp @ss}if @gr $ctm setmatrix}bd}{/@I_2{}bd}ifelse/@I_3{@sm @gs @ii @np/$ury +xd/$urx xd/$lly xd/$llx xd/$ncl xd/$bts xd/$hei xd/$wid xd/$dat $wid $bts mul +$ncl mul 8 div ceiling cvi string def $ngx $ncl 1 eq{/DeviceGray}{$ncl 3 eq +{/DeviceRGB}{/DeviceCMYK}ifelse}ifelse setcolorspace $llx $lly Tl $urx $llx sub +$ury $lly sub scale/ImageDataDict 8 dict def ImageDataDict begin/ImageType 1 +def/Width $wid def/Height $hei abs def/BitsPerComponent $bts def/Decode $ncl 1 +eq{[0 1]}{$ncl 3 eq{[0 1 0 1 0 1]}{[0 1 0 1 0 1 0 1]}ifelse}ifelse def +/ImageMatrix[$wid 0 0 $hei neg 0 $hei 0 gt{$hei}{0}ifelse]def/DataSource +currentfile/ASCII85Decode filter COMP 1 eq{/DCTDecode filter}{COMP 2 eq{ +/RunLengthDecode filter}if}ifelse def end/MaskedImageDict 7 dict def +MaskedImageDict begin/ImageType 3 def/InterleaveType 3 def/MaskDict +ImageMaskDict def/DataDict ImageDataDict def end MaskedImageDict image $SDF +{$dsf $dsa $dsp @ss}if @gr $ctm setmatrix}bd/@SetMask{/$mbts xd/$mhei xd/$mwid +xd/ImageMaskDict 8 dict def ImageMaskDict begin/ImageType 1 def/Width $mwid def +/Height $mhei abs def/BitsPerComponent $mbts def/DataSource maskstream def +/ImageMatrix[$mwid 0 0 $mhei neg 0 $mhei 0 gt{$mhei}{0}ifelse]def/Decode[1 0] +def end}bd/@B{@gs S @gr F}bd/@b{@cp @B}bd/@sep{CurrentInkName_5(Composite)eq +{/$ink_5 -1 def}{CurrentInkName_5(Cyan)eq{/$ink_5 0 def}{CurrentInkName_5 +(Magenta)eq{/$ink_5 1 def}{CurrentInkName_5(Yellow)eq{/$ink_5 2 def}{ +CurrentInkName_5(Black)eq{/$ink_5 3 def}{/$ink_5 4 def}ifelse}ifelse}ifelse} +ifelse}ifelse}bd/@whi{@gs -72000 dup m -72000 72000 l 72000 dup l 72000 -72000 +l @cp 1 SetGry fill @gr}bd/@neg{[{1 exch sub}/exec cvx currenttransfer/exec +cvx]cvx settransfer @whi}bd/deflevel 0 def/@sax{/deflevel deflevel 1 add def} +bd/@eax{/deflevel deflevel dup 0 gt{1 sub}if def deflevel 0 gt{/eax load}{eax} +ifelse}bd/eax{{exec}forall}bd/@rax{deflevel 0 eq{@rs @sv}if}bd/@daq{dup type +/arraytype eq{{}forall}if}bd/@BMP{/@cc xd UseLevel 3 eq MaskedImage true eq and +{7 -2 roll pop pop @I_3}{12 index 1 gt UseLevel 2 eq UseLevel 3 eq or and{7 -2 +roll pop pop @I_2}{11 index 1 eq{12 -1 roll pop @i}{7 -2 roll pop pop @I} +ifelse}ifelse}ifelse}bd systemdict/pdfmark known not{/pdfmark/cleartomark ld} +if +end +%%EndResource +%%EndProlog +%%BeginSetup +wCorel9Dict begin +@BeginSysCorelDict +@ssa +2.6131 setmiterlimit +1.00 setflat +/$fst 128 def +%%EndSetup + +%%Page: 1 1 +%LogicalPage: 1 +%%BeginPageSetup +@sv +@sm +@sv +%%EndPageSetup +@rax %Note: Object +201.25984 324.56693 394.01575 517.32283 @E + 0 O 0 @g +0.00 0.00 0.00 0.00 k +/$fm 0 def +201.25984 517.32283 m +394.01575 517.32283 L +394.01575 324.56693 L +201.25984 324.56693 L +201.25984 517.32283 L +@c +F + +@rax %Note: Object +224.78258 371.57159 391.18110 470.31789 @E + 0 O 0 @g +0.00 1.00 1.00 0.00 k +/$fm 0 def +240.68665 423.64233 m +243.27099 426.53055 245.95654 428.81074 249.25011 431.54702 C +249.35131 433.67528 L +245.19628 430.38170 241.44690 426.98665 238.20378 423.54113 C +240.68665 423.64233 L +@c +231.41395 411.02561 m +227.41087 403.67820 225.84019 396.43228 228.67767 390.85852 C +237.59575 373.42772 278.79109 373.68113 318.41546 390.30123 C +328.39767 394.45625 337.41723 399.32050 345.22044 404.53965 C +368.42769 420.09562 377.44696 437.67808 370.80907 450.70044 C +361.94173 468.13124 325.91480 469.95534 286.29043 453.38598 C +282.03392 451.61263 277.98038 449.68706 274.07877 447.71102 C +270.73446 447.71102 L +276.40970 450.80192 282.74343 453.99430 289.07717 456.67984 C +334.12337 475.52910 378.86570 474.76913 388.89865 454.95694 C +396.49918 440.11049 384.94630 419.33537 358.39474 401.60069 C +349.57814 395.72306 338.53181 389.74394 327.33354 385.03134 C +282.28734 366.18208 237.13965 367.34740 227.05625 387.10885 C +223.50926 394.15209 224.11729 402.36066 228.82989 411.02561 C +231.41395 411.02561 L +@c +F + +@rax %Note: Object +204.09449 407.68129 245.71531 449.94047 @E + 0 O 0 @g +0.00 0.00 0.00 1.00 k +/$fm 0 def +244.08170 424.80794 m +240.83887 412.49480 230.90740 407.68129 220.92520 407.68129 C +206.83871 407.68129 202.12639 416.24447 204.81194 428.96296 C +207.09213 441.47849 216.36482 449.94047 229.94447 449.94047 C +240.12935 449.94047 247.83137 445.83619 245.19628 432.00312 C +230.55250 432.00312 L +231.51543 438.59027 230.04595 439.45172 228.06964 439.45172 C +223.96535 439.45172 222.64781 435.24595 221.27981 428.81074 C +220.01301 422.73043 219.35424 418.17005 223.35732 418.17005 C +225.43483 418.17005 227.10699 419.38611 229.08302 424.80794 C +244.08170 424.80794 L +@c +F + +@rax %Note: Object +242.81490 408.69468 287.86564 448.87635 @E + 0 O 0 @g +0.00 0.00 0.00 1.00 k +/$fm 0 def +242.81490 408.69468 m +262.62709 408.69468 L +274.99068 408.69468 284.51679 416.19373 287.10113 428.35493 C +289.63474 440.26243 286.34088 448.92709 270.22762 448.87635 C +251.32762 448.87635 L +242.81490 408.69468 L +@c +265.00876 439.75559 m +266.52869 439.75559 L +269.11304 439.75559 270.43030 438.84369 271.08907 437.22227 C +271.79858 435.55011 271.49443 432.71263 270.68372 428.81074 C +269.87301 424.90913 268.91036 422.07165 267.49162 420.39950 C +266.17408 418.77808 264.45118 417.81543 261.86712 417.81543 C +260.34690 417.81543 L +265.00876 439.75559 L +@c +F + +@rax %Note: Object +290.59739 408.69468 350.08469 448.87635 @E + 0 O 0 @g +0.00 0.00 0.00 1.00 k +/$fm 0 def +290.59739 448.87635 m +304.88655 448.87635 L +302.91024 423.64233 L +303.01172 423.64233 L +312.13247 448.87635 L +328.60035 448.87635 L +326.97893 423.64233 L +327.08041 423.64233 L +335.84627 448.87635 L +350.08469 448.87635 L +332.85685 408.69468 L +315.57798 408.69468 L +317.40208 434.78986 L +317.30088 434.78986 L +308.02819 408.69468 L +290.74932 408.69468 L +290.59739 448.87635 L +@c +F + +@rax %Note: Object +352.56756 444.36671 356.36797 449.07902 @E + 0 O 0 @g +0.00 0.00 0.00 1.00 k +/$fm 0 def +352.56756 449.07902 m +356.36797 449.07902 L +356.36797 448.31906 L +354.89849 448.31906 L +354.89849 444.36671 L +354.03704 444.36671 L +354.03704 448.31906 L +352.56756 448.31906 L +352.56756 449.07902 L +@c +F + +@rax %Note: Object +356.77332 444.36671 361.68831 449.07902 @E + 0 O 0 @g +0.00 0.00 0.00 1.00 k +/$fm 0 def +356.77332 449.07902 m +357.93865 449.07902 L +359.25619 445.38009 L +360.52299 449.07902 L +361.68831 449.07902 L +361.68831 444.36671 L +360.87761 444.36671 L +360.87761 447.96444 L +359.56006 444.36671 L +358.90157 444.36671 L +357.58403 447.96444 L +357.58403 444.36671 L +356.77332 444.36671 L +356.77332 449.07902 L +@c +F + +%%PageTrailer +@rs +@rs +%%Trailer +@EndSysCorelDict +end +%%DocumentSuppliedResources: procset wCorel9Dict 9.0 0 +%%EOF diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/dummy.mp4 b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/dummy.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..f1874ec0e63c0c4f12d98f2332a1886ff79d5ba5 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/dummy.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbe9541b7050d14c0be1cddb903b6bafc5f11bc952138ebae09ced25359903f5 +size 42 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/[Content_Types].xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/[Content_Types].xml new file mode 100644 index 0000000000000000000000000000000000000000..62e4cf0d9e3170d4140f348d2eb8fccdcea72c83 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/[Content_Types].xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/_rels/.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/_rels/.rels new file mode 100644 index 0000000000000000000000000000000000000000..fe10f03c69dcb77817f8747c902eed160c39abad --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/_rels/.rels @@ -0,0 +1,7 @@ + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/docProps/app.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/docProps/app.xml new file mode 100644 index 0000000000000000000000000000000000000000..35c2e5b3864540fd67672d791e4a3f46f54c27dc --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/docProps/app.xml @@ -0,0 +1,41 @@ + + + 0 + 0 + Microsoft Office PowerPoint + On-screen Show (4:3) + 0 + 1 + 0 + 0 + 0 + false + + + + Theme + + + 1 + + + Slide Titles + + + 1 + + + + + + Office Theme + Slide 1 + + + Microsoft + false + false + false + 14.0000 + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/docProps/core.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/docProps/core.xml new file mode 100644 index 0000000000000000000000000000000000000000..bba7a13eb7b865e9763449d26a8c52774a4d33c0 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/docProps/core.xml @@ -0,0 +1,13 @@ + + + Presentation + python-pptx + python-pptx + 1 + 2012-11-17T11:07:40Z + 2012-11-17T14:05:29Z + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/docProps/thumbnail.jpeg b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/docProps/thumbnail.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..d9eedcb4a4626e082ed0d7d5d79b98e4d8e8b0aa --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/docProps/thumbnail.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c392214dd286efbeea116dd729dbadda3602ecf1242ff48788cc839792a3d05d +size 8147 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/_rels/presentation.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/_rels/presentation.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..56fc345e6323a3f82d74b4ba313de29c28ca6baa --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/_rels/presentation.xml.rels @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/presProps.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/presProps.xml new file mode 100644 index 0000000000000000000000000000000000000000..439ef3f22972249916f0605f9482b8025bde5808 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/presProps.xml @@ -0,0 +1,4 @@ + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/presentation.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/presentation.xml new file mode 100644 index 0000000000000000000000000000000000000000..4a611359f976a56a669905c4d62a994a0fd07ae3 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/presentation.xml @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/printerSettings/printerSettings1.bin b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/printerSettings/printerSettings1.bin new file mode 100644 index 0000000000000000000000000000000000000000..84ae72f2e05b71170a2c5093d0086f0560bef498 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/printerSettings/printerSettings1.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7768f87e07d29634782e448ece1cddd05a52b9499254222b1190bc8f6dc579e +size 9395 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout10.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout10.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout10.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout11.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout11.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout11.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout2.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout2.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout2.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout3.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout3.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout3.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout4.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout4.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout4.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout5.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout5.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout5.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout6.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout6.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout6.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout7.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout7.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout7.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout8.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout8.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout8.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout9.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout9.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..e14ed2392fdcb5897877c4523a3b472d7aec88c8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout9.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout1.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout1.xml new file mode 100644 index 0000000000000000000000000000000000000000..184527518ee4a1331e955cf830681b173fb23af1 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout1.xml @@ -0,0 +1,242 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master subtitle style + + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout10.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout10.xml new file mode 100644 index 0000000000000000000000000000000000000000..6c28fd1b5a2dc375f49dd8250316e590f2abdd0a --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout10.xml @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout11.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout11.xml new file mode 100644 index 0000000000000000000000000000000000000000..04c5416af0c34ee94ddab6a984980d6e66c350a7 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout11.xml @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout2.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout2.xml new file mode 100644 index 0000000000000000000000000000000000000000..507e67e84acb4ebe1ce0d458d9a57601e6283644 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout2.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout3.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout3.xml new file mode 100644 index 0000000000000000000000000000000000000000..2f96686b65000b7cfad85cb426c6c30886ec6446 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout3.xml @@ -0,0 +1,246 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout4.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout4.xml new file mode 100644 index 0000000000000000000000000000000000000000..348d98be4f0e341f8c32b21930c84a7fdfe8d2fa --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout4.xml @@ -0,0 +1,288 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout5.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout5.xml new file mode 100644 index 0000000000000000000000000000000000000000..a937a13c223f1cb740dfc8532cf1da246f1551c9 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout5.xml @@ -0,0 +1,422 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout6.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout6.xml new file mode 100644 index 0000000000000000000000000000000000000000..f1205cd24ad9699be7ce0ef6dc77f882f961d05d --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout6.xml @@ -0,0 +1,118 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout7.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout7.xml new file mode 100644 index 0000000000000000000000000000000000000000..d00d577e570fdad9a47889a512bfdac8188ba3d2 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout7.xml @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout8.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout8.xml new file mode 100644 index 0000000000000000000000000000000000000000..4fe7f079e4b759eb31fcf4876097ba24cb2a3591 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout8.xml @@ -0,0 +1,277 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout9.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout9.xml new file mode 100644 index 0000000000000000000000000000000000000000..f9c7a540ce71903660e79122b6111d232240c709 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout9.xml @@ -0,0 +1,253 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..0124162c6436351ae03700fa4a390500bf8730bb --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideMasters/slideMaster1.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideMasters/slideMaster1.xml new file mode 100644 index 0000000000000000000000000000000000000000..88fbe6f33c01c0ac001c5228c0f953c994e4b6b2 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slideMasters/slideMaster1.xml @@ -0,0 +1,507 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slides/_rels/slide1.xml.rels b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slides/_rels/slide1.xml.rels new file mode 100644 index 0000000000000000000000000000000000000000..a1233b58c488a1ac54bf6d1a8aaaca4bc0dd5484 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slides/_rels/slide1.xml.rels @@ -0,0 +1,4 @@ + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slides/slide1.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slides/slide1.xml new file mode 100644 index 0000000000000000000000000000000000000000..845199ee98c830f4f01c6aa380acbd392e71c0e4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/slides/slide1.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Presentation Title Text + + + + + + + + + + + + + + + + + + + + + + + Subtitle Text + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/tableStyles.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/tableStyles.xml new file mode 100644 index 0000000000000000000000000000000000000000..ecd5f7a0196010d6d2b5b05e9c16060f45835444 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/tableStyles.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/theme/theme1.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/theme/theme1.xml new file mode 100644 index 0000000000000000000000000000000000000000..1482af830b133b6b266715dd4d05ed343473cd5e --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/theme/theme1.xml @@ -0,0 +1,281 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/viewProps.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/viewProps.xml new file mode 100644 index 0000000000000000000000000000000000000000..4fd95f7da381ccd4032fc13276fd3ffa5529e541 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/expanded_pptx/ppt/viewProps.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/minimal.pptx b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/minimal.pptx new file mode 100644 index 0000000000000000000000000000000000000000..4decaca6efefc8923936e6cc84b8292bc5c8200e Binary files /dev/null and b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/minimal.pptx differ diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/minimal_slide.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/minimal_slide.xml new file mode 100644 index 0000000000000000000000000000000000000000..af0252bc7d9629fc840b8c1133947f91285e7d49 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/minimal_slide.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/missing_rels_item.pptx b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/missing_rels_item.pptx new file mode 100644 index 0000000000000000000000000000000000000000..1e0359e010ae1c329f4ea381a4c0afeee0c6885a Binary files /dev/null and b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/missing_rels_item.pptx differ diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/monty-truth.png b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/monty-truth.png new file mode 100644 index 0000000000000000000000000000000000000000..4892f6e537841196119da9a80aa6dc33e929758f --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/monty-truth.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10b7f419d1870f268b69320e43dd8e9630d002b26376de5d9c337beeab09ab22 +size 64276 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/no-core-props.pptx b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/no-core-props.pptx new file mode 100644 index 0000000000000000000000000000000000000000..21cbe84a01ac4eed7b7e88465e8f68ddbafaeaa5 Binary files /dev/null and b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/no-core-props.pptx differ diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/no-slides.pptx b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/no-slides.pptx new file mode 100644 index 0000000000000000000000000000000000000000..9dc99f7b75ab8f5c848679662bd6d56651e0b080 Binary files /dev/null and b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/no-slides.pptx differ diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/presentation.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/presentation.xml new file mode 100644 index 0000000000000000000000000000000000000000..4a611359f976a56a669905c4d62a994a0fd07ae3 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/presentation.xml @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/python-icon.jpeg b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/python-icon.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9ef67b1492e140de2e416cf47fe92af3dbf7c3ae --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/python-icon.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad5afb51d11ed1b0bcd80103519ad198129eb9489637b00b9547f208408548f0 +size 3277 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/python-powered.png b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/python-powered.png new file mode 100644 index 0000000000000000000000000000000000000000..c27c039fa05ae788c0448c0a9971ae5f7708ac17 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/python-powered.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b60f709965eb54e1400cba53617ae2c02f8028f5399cafa32d8ef18bfc803915 +size 6111 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/python.bmp b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/python.bmp new file mode 100644 index 0000000000000000000000000000000000000000..4253daeadcb3a4e55b8a40dc219d0dcf054d20b1 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/python.bmp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:702b53479b595ae6aa2b87527fadb09c3b01f83d7ff20cfaf9eaf8fa7b418755 +size 45210 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/slideLayout1.xml b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/slideLayout1.xml new file mode 100644 index 0000000000000000000000000000000000000000..7fe97cf8c3f8f9a24da403ecc55e9aefa212df26 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/slideLayout1.xml @@ -0,0 +1,265 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master title style + + + + + + + + + + + + + + + + + + + + + + + + 16/07/2012 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master subtitle style + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-date.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-date.txt new file mode 100644 index 0000000000000000000000000000000000000000..43ccca6ed80256a8e725305f519f07b472346e24 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-date.txt @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + yyyy\-mm\-dd + + + 42731.0 + + + 42732.0 + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + yyyy\-mm\-dd + + + 42731.0 + + + 42732.0 + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-float.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-float.txt new file mode 100644 index 0000000000000000000000000000000000000000..48209ee022b1b43a318f782c0ce8f6a4c11a85ee --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-float.txt @@ -0,0 +1,167 @@ + + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + General + + + 1.1 + + + 2.2 + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + General + + + 1.1 + + + 2.2 + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-stacked-100.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-stacked-100.txt new file mode 100644 index 0000000000000000000000000000000000000000..1d35ed369765f96f808288d600ccb29e249868a2 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-stacked-100.txt @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-stacked.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-stacked.txt new file mode 100644 index 0000000000000000000000000000000000000000..cf97ddf180b8d71aa641635c5c72ee78295db0c6 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area-stacked.txt @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area.txt new file mode 100644 index 0000000000000000000000000000000000000000..381aa0d32a427164ea5e42d8f97228f8c7d2ae9a --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-area.txt @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-clustered-date.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-clustered-date.txt new file mode 100644 index 0000000000000000000000000000000000000000..913d01d5e72497351ead03486116ef4bf1539c0b --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-clustered-date.txt @@ -0,0 +1,145 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + yyyy\-mm\-dd + + + 42731.0 + + + 42732.0 + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + yyyy\-mm\-dd + + + 42731.0 + + + 42732.0 + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-clustered-float.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-clustered-float.txt new file mode 100644 index 0000000000000000000000000000000000000000..2dfa3fe6049b13c20f9f168d19dce60dfd322458 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-clustered-float.txt @@ -0,0 +1,145 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + General + + + 1.1 + + + 2.2 + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + General + + + 1.1 + + + 2.2 + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-clustered.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-clustered.txt new file mode 100644 index 0000000000000000000000000000000000000000..02fd74c034dcb85f41fc31e1adca4f3613106185 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-clustered.txt @@ -0,0 +1,143 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-stacked-100.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-stacked-100.txt new file mode 100644 index 0000000000000000000000000000000000000000..5f8d1a876d9dbfc7f1092738024295a1abd23689 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-stacked-100.txt @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-stacked.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-stacked.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d0943825a2f817225c2a09a5e80190de954c24d --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-bar-stacked.txt @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-column-clustered.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-column-clustered.txt new file mode 100644 index 0000000000000000000000000000000000000000..f145618ef080fb86e3a4f802ea6c67d2f53b9b18 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-column-clustered.txt @@ -0,0 +1,143 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-column-stacked-100.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-column-stacked-100.txt new file mode 100644 index 0000000000000000000000000000000000000000..71e8d54842a403fc79f89abf651089d6259ed8ec --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-column-stacked-100.txt @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-column-stacked.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-column-stacked.txt new file mode 100644 index 0000000000000000000000000000000000000000..704a618d31fad956db237d82d65bbe4991b93fc2 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-column-stacked.txt @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-date.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-date.txt new file mode 100644 index 0000000000000000000000000000000000000000..fd907d0b4fa7ae772882fb549614090043ca45df --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-date.txt @@ -0,0 +1,162 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + + + Sheet1!$A$2:$A$3 + + yyyy\-mm\-dd + + + 42731.0 + + + 42732.0 + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + + + + Sheet1!$A$2:$A$3 + + yyyy\-mm\-dd + + + 42731.0 + + + 42732.0 + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-float.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-float.txt new file mode 100644 index 0000000000000000000000000000000000000000..43c3d6ef0a4852b812972198a13df20aede4ca26 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-float.txt @@ -0,0 +1,162 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + + + Sheet1!$A$2:$A$3 + + General + + + 1.1 + + + 2.2 + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + + + + Sheet1!$A$2:$A$3 + + General + + + 1.1 + + + 2.2 + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-markers-stacked-100.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-markers-stacked-100.txt new file mode 100644 index 0000000000000000000000000000000000000000..0b0ac4bd0a9d905462898ee3e0c2fc664902cbea --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-markers-stacked-100.txt @@ -0,0 +1,154 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-markers-stacked.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-markers-stacked.txt new file mode 100644 index 0000000000000000000000000000000000000000..d82893f391530b5f02f4f21b40d77fc65a4b10ea --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-markers-stacked.txt @@ -0,0 +1,154 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-markers.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-markers.txt new file mode 100644 index 0000000000000000000000000000000000000000..090364f7ab5ab9837f291f49b52805f87ed33367 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-markers.txt @@ -0,0 +1,154 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-stacked-100.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-stacked-100.txt new file mode 100644 index 0000000000000000000000000000000000000000..a65fff8d71dd31253070d4ab4e77788d09456bbd --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-stacked-100.txt @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-stacked.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-stacked.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f1d33a2445e69a3b1b7580805a721eceabc53bc --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line-stacked.txt @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line.txt new file mode 100644 index 0000000000000000000000000000000000000000..2cda08eb465f19ad6e7c76ab804036af964c5f6f --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x2-line.txt @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1.1 + + + 2.2 + + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + + + + Sheet1!$A$2:$A$3 + + + + Foo + + + Bar + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 3.3 + + + 4.4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-bubble-3d.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-bubble-3d.txt new file mode 100644 index 0000000000000000000000000000000000000000..ba00b568bd5562d6a3f9df49b7004ec73fd90910 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-bubble-3d.txt @@ -0,0 +1,215 @@ + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + Sheet1!$A$2:$A$4 + + General + + + 1.1 + + + 2.1 + + + 3.1 + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 11.1 + + + 12.1 + + + 13.1 + + + + + + + Sheet1!$C$2:$C$4 + + General + + + 10.0 + + + 20.0 + + + 30.0 + + + + + + + + + + + + Sheet1!$B$6 + + + + Series 2 + + + + + + + + Sheet1!$A$7:$A$9 + + General + + + 1.2 + + + 2.2 + + + 3.2 + + + + + + + Sheet1!$B$7:$B$9 + + General + + + 11.2 + + + 12.2 + + + 13.2 + + + + + + + Sheet1!$C$7:$C$9 + + General + + + 40.0 + + + 50.0 + + + 60.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-bubble.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-bubble.txt new file mode 100644 index 0000000000000000000000000000000000000000..e5f1a56d3fd257165e09b8dc6804510420502a3b --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-bubble.txt @@ -0,0 +1,215 @@ + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + Sheet1!$A$2:$A$4 + + General + + + 1.1 + + + 2.1 + + + 3.1 + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 11.1 + + + 12.1 + + + 13.1 + + + + + + + Sheet1!$C$2:$C$4 + + General + + + 10.0 + + + 20.0 + + + 30.0 + + + + + + + + + + + + Sheet1!$B$6 + + + + Series 2 + + + + + + + + Sheet1!$A$7:$A$9 + + General + + + 1.2 + + + 2.2 + + + 3.2 + + + + + + + Sheet1!$B$7:$B$9 + + General + + + 11.2 + + + 12.2 + + + 13.2 + + + + + + + Sheet1!$C$7:$C$9 + + General + + + 40.0 + + + 50.0 + + + 60.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-lines-no-markers.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-lines-no-markers.txt new file mode 100644 index 0000000000000000000000000000000000000000..22b65e745dd73f2ab5a80d7de27b28f20cd255fa --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-lines-no-markers.txt @@ -0,0 +1,172 @@ + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + + + Sheet1!$A$2:$A$4 + + General + + + 1.1 + + + 2.1 + + + 3.1 + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 11.1 + + + 12.1 + + + 13.1 + + + + + + + + + + + + Sheet1!$B$6 + + + + Series 2 + + + + + + + + + + Sheet1!$A$7:$A$9 + + General + + + 1.2 + + + 2.2 + + + 3.2 + + + + + + + Sheet1!$B$7:$B$9 + + General + + + 11.2 + + + 12.2 + + + 13.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-lines.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-lines.txt new file mode 100644 index 0000000000000000000000000000000000000000..6ba512fea5c667d40bd2c2e54416c4b04c96fda6 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-lines.txt @@ -0,0 +1,166 @@ + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$4 + + General + + + 1.1 + + + 2.1 + + + 3.1 + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 11.1 + + + 12.1 + + + 13.1 + + + + + + + + + + + + Sheet1!$B$6 + + + + Series 2 + + + + + + + Sheet1!$A$7:$A$9 + + General + + + 1.2 + + + 2.2 + + + 3.2 + + + + + + + Sheet1!$B$7:$B$9 + + General + + + 11.2 + + + 12.2 + + + 13.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-smooth-no-markers.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-smooth-no-markers.txt new file mode 100644 index 0000000000000000000000000000000000000000..476b2ee0f0b22cd5c3428166b4523d654f7cabc0 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-smooth-no-markers.txt @@ -0,0 +1,172 @@ + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + + + Sheet1!$A$2:$A$4 + + General + + + 1.1 + + + 2.1 + + + 3.1 + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 11.1 + + + 12.1 + + + 13.1 + + + + + + + + + + + + Sheet1!$B$6 + + + + Series 2 + + + + + + + + + + Sheet1!$A$7:$A$9 + + General + + + 1.2 + + + 2.2 + + + 3.2 + + + + + + + Sheet1!$B$7:$B$9 + + General + + + 11.2 + + + 12.2 + + + 13.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-smooth.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-smooth.txt new file mode 100644 index 0000000000000000000000000000000000000000..e40dbe9eba11ad26bb0d76fc6aa016aa68c13b81 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy-smooth.txt @@ -0,0 +1,166 @@ + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$4 + + General + + + 1.1 + + + 2.1 + + + 3.1 + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 11.1 + + + 12.1 + + + 13.1 + + + + + + + + + + + + Sheet1!$B$6 + + + + Series 2 + + + + + + + Sheet1!$A$7:$A$9 + + General + + + 1.2 + + + 2.2 + + + 3.2 + + + + + + + Sheet1!$B$7:$B$9 + + General + + + 11.2 + + + 12.2 + + + 13.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c8936c11ff71806ab05efeb64510b138b00fa24 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x3-xy.txt @@ -0,0 +1,176 @@ + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + + + + + Sheet1!$A$2:$A$4 + + General + + + 1.1 + + + 2.1 + + + 3.1 + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 11.1 + + + 12.1 + + + 13.1 + + + + + + + + + + + + Sheet1!$B$6 + + + + Series 2 + + + + + + + + + + + + Sheet1!$A$7:$A$9 + + General + + + 1.2 + + + 2.2 + + + 3.2 + + + + + + + Sheet1!$B$7:$B$9 + + General + + + 11.2 + + + 12.2 + + + 13.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x5-radar.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x5-radar.txt new file mode 100644 index 0000000000000000000000000000000000000000..a731c6429d6a45beeaa368312503f76d27432af6 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/2x5-radar.txt @@ -0,0 +1,205 @@ + + + + + + + + + + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + + + Sheet1!$A$2:$A$6 + + + + Foo + + + Bar + + + Baz + + + Boo + + + Far + + + + + + + Sheet1!$B$2:$B$6 + + General + + + 1.1 + + + 2.2 + + + 3.3 + + + 4.4 + + + 5.5 + + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + + + + Sheet1!$A$2:$A$6 + + + + Foo + + + Bar + + + Baz + + + Boo + + + Far + + + + + + + Sheet1!$C$2:$C$6 + + General + + + 6.6 + + + 7.7 + + + 8.8 + + + 9.9 + + + 11.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x1-pie-exploded.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x1-pie-exploded.txt new file mode 100644 index 0000000000000000000000000000000000000000..433d04dd9d044e9bd39916118d967169297a343f --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x1-pie-exploded.txt @@ -0,0 +1,73 @@ + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + Sheet1!$A$2:$A$4 + + + + Foo + + + Bar + + + Baz + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 1.1 + + + 2.2 + + + 3.3 + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x1-pie.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x1-pie.txt new file mode 100644 index 0000000000000000000000000000000000000000..a6e7a6c2d3d932a8b11a2b8867f9fd0b35c3cb15 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x1-pie.txt @@ -0,0 +1,72 @@ + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$4 + + + + Foo + + + Bar + + + Baz + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 1.1 + + + 2.2 + + + 3.3 + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x2-doughnut-exploded.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x2-doughnut-exploded.txt new file mode 100644 index 0000000000000000000000000000000000000000..694fc42c052229c4de9e3b895ba4071277460eeb --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x2-doughnut-exploded.txt @@ -0,0 +1,145 @@ + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + Sheet1!$A$2:$A$4 + + + + Foo + + + Bar + + + Baz + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 1.1 + + + 2.2 + + + 3.3 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + + Sheet1!$A$2:$A$4 + + + + Foo + + + Bar + + + Baz + + + + + + + Sheet1!$C$2:$C$4 + + General + + + 4.4 + + + 5.5 + + + 6.6 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x2-doughnut.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x2-doughnut.txt new file mode 100644 index 0000000000000000000000000000000000000000..eb9f3b1198ba8266d126996f890cc3d5c1e2cf8f --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/3x2-doughnut.txt @@ -0,0 +1,143 @@ + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$4 + + + + Foo + + + Bar + + + Baz + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 1.1 + + + 2.2 + + + 3.3 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$4 + + + + Foo + + + Bar + + + Baz + + + + + + + Sheet1!$C$2:$C$4 + + General + + + 4.4 + + + 5.5 + + + 6.6 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/4x2-multi-cat-bar.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/4x2-multi-cat-bar.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb11c1e8074af3505b886be11aa2ad5eee46c5eb --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/4x2-multi-cat-bar.txt @@ -0,0 +1,181 @@ + + + + + + + + + + + + + + + Sheet1!$C$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$B$5 + + + + + SF + + + LA + + + NY + + + NJ + + + + + WEST + + + EAST + + + + + + + + Sheet1!$C$2:$C$5 + + General + + + 1 + + + 2 + + + 4 + + + + + + + + + + + Sheet1!$D$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$B$5 + + + + + SF + + + LA + + + NY + + + NJ + + + + + WEST + + + EAST + + + + + + + + Sheet1!$D$2:$D$5 + + General + + + 5 + + + 7 + + + 8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/adjust-ser-count.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/adjust-ser-count.txt new file mode 100644 index 0000000000000000000000000000000000000000..24b30a32d9f891a5d177baea6d774b4de94a2870 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/adjust-ser-count.txt @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/cat-labels.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/cat-labels.txt new file mode 100644 index 0000000000000000000000000000000000000000..686a4d21a994915f701e50ef01e9bef41e5378d4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/cat-labels.txt @@ -0,0 +1,146 @@ + + + + + Sheet1!$A$2:$A$4 + + + + Foo + + + Baz + + + + + + + + + + + + Sheet1!$A$2:$B$5 + + + + + SF + + + LA + + + NY + + + Albany + + + + + CA + + + NY + + + + + + + + + + + + + Sheet1!$A$2:$C$9 + + + + + SF + + + LA + + + NY + + + Albany + + + Calgary + + + Edmonton + + + Toronto + + + Ottawa + + + + + CA + + + NY + + + AL + + + ON + + + + + USA + + + CAN + + + + + + + + + + + + + Sheet1!$A$2:$C$9 + + + + + SF + + + LA + + + NY + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/content-types-xml.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/content-types-xml.txt new file mode 100644 index 0000000000000000000000000000000000000000..9e8ee1feb91261766f16a4a9ffa8c639667cc666 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/content-types-xml.txt @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/default-notes.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/default-notes.txt new file mode 100644 index 0000000000000000000000000000000000000000..d831d44802088e126cc1895c2f03b0102d7bcdd8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/default-notes.txt @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/default-notesMaster.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/default-notesMaster.txt new file mode 100644 index 0000000000000000000000000000000000000000..31bbee9973fc3180c866f8ffbdf2a586f2e72cd8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/default-notesMaster.txt @@ -0,0 +1,347 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 10/17/16 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + + + + Second level + + + + + + + Third level + + + + + + + Fourth level + + + + + + + Fifth level + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ‹#› + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/default-theme.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/default-theme.txt new file mode 100644 index 0000000000000000000000000000000000000000..ec5f5c62b405bd0bb21709d2ae7ec89d54395392 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/default-theme.txt @@ -0,0 +1,317 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/freeform.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/freeform.txt new file mode 100644 index 0000000000000000000000000000000000000000..009c702ce474c67849a52b22a44df4b50125659e --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/freeform.txt @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/package-rels-xml.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/package-rels-xml.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc6731bc5de5c28a3640887470a994313a6f62cc --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/package-rels-xml.txt @@ -0,0 +1,7 @@ + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/placeholders.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/placeholders.txt new file mode 100644 index 0000000000000000000000000000000000000000..bc22ae9718c3c3d46e79ee3ef487ff70f071fd38 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/placeholders.txt @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + {5C22544A-7EE6-4342-B048-85BDC9FD1C3A} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/presentation-rels-xml.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/presentation-rels-xml.txt new file mode 100644 index 0000000000000000000000000000000000000000..bb27c2bfd05acfd21020a96cafc668327ef9808c --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/presentation-rels-xml.txt @@ -0,0 +1,6 @@ + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/relationships.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/relationships.txt new file mode 100644 index 0000000000000000000000000000000000000000..db1df33f8ca208a4223bfd58a76eebfd535213cc --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/relationships.txt @@ -0,0 +1,2 @@ + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/rels-load-from-xml.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/rels-load-from-xml.txt new file mode 100644 index 0000000000000000000000000000000000000000..acbdfcc96c1f936a9ffdfb1b2de9d33ed0791446 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/rels-load-from-xml.txt @@ -0,0 +1,6 @@ + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/rewrite-ser.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/rewrite-ser.txt new file mode 100644 index 0000000000000000000000000000000000000000..5f695f5e683550244c403c9d7eb06991e5654dde --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/rewrite-ser.txt @@ -0,0 +1,488 @@ + + + + + + Sheet1!$X$42 + + + + Foo Series Name + + + + + + + Sheet1!$A$2:$A$2 + + + + Boofar + + + + + + + Sheet1!$X$6:$X$6 + + 0.0 + + + 666 + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + + + foo + + + bar + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1 + + + 2 + + + + + + + + + + + + Sheet7!$X$9 + + + + Series 2 + + + + + + + Sheet1!$B$2:$C$4 + + General + + + 0.7 + + + 1.8 + + + 2.6 + + + + + + + Sheet1!$F$6:$F$9 + + General + + + 2.7 + + + 3.2 + + + 0.8 + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + General + + + 1 + + + 3 + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 2 + + + 4 + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + Sheet1!$A$2:$A$4 + + General + + + 0.7 + + + 1.8 + + + 2.6 + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 2.7 + + + 3.2 + + + 0.8 + + + + + + + Sheet1!$C$2:$C$4 + + General + + + 10.0 + + + 4.0 + + + 8.0 + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + Sheet1!$A$2:$A$3 + + General + + + 1 + + + 3 + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 2 + + + 4 + + + + + + + Sheet1!$C$2:$C$3 + + General + + + 10 + + + 20 + + + + + + + + + + + + + Sheet1!$X$42 + + + + Foo Series Name + + + + + + + Sheet1!$A$2:$A$2 + + + + Boofar + + + + + + + Sheet1!$X$6:$X$6 + + 0.0 + + + 666 + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + General + + + 42 + + + 24 + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1 + + + 2 + + + + + + + + + + + + Sheet1!$X$42 + + + + Foo Series Name + + + + + + + Sheet1!$A$2:$A$2 + + + + Boofar + + + + + + + Sheet1!$X$6:$X$6 + + 0.0 + + + 666 + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$3 + + yyyy\-mm\-dd + + + 42726.0 + + + 42727.0 + + + + + + + Sheet1!$B$2:$B$3 + + General + + + 1 + + + 2 + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/timing.txt b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/timing.txt new file mode 100644 index 0000000000000000000000000000000000000000..ad078ae3dc0a755a4ad12637111300c318757c01 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/snippets/timing.txt @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/test.pptx b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/test.pptx new file mode 100644 index 0000000000000000000000000000000000000000..3ba75175d0e8b9b61515e553dd9ce0a4873b434a Binary files /dev/null and b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/test.pptx differ diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_files/test_slides.pptx b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/test_slides.pptx new file mode 100644 index 0000000000000000000000000000000000000000..e9ead6960cda21e77a846c157c599cf88d2dd6e6 Binary files /dev/null and b/tasks/tasksmith-74f059424102/environment/source/tests/test_files/test_slides.pptx differ diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_media.py b/tasks/tasksmith-74f059424102/environment/source/tests/test_media.py new file mode 100644 index 0000000000000000000000000000000000000000..be72f6e0ea1c06489b10b02359a7ad02e626f3ec --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_media.py @@ -0,0 +1,134 @@ +"""Unit test suite for `pptx.media` module.""" + +from __future__ import annotations + +import io + +import pytest + +from pptx.media import Video + +from .unitutil.file import absjoin, test_file_dir +from .unitutil.mock import initializer_mock, instance_mock, method_mock, property_mock + +TEST_VIDEO_PATH = absjoin(test_file_dir, "dummy.mp4") + + +class DescribeVideo(object): + """Unit-test suite for `pptx.media.Video` objects.""" + + def it_can_construct_from_a_path(self, video_, from_blob_): + with open(TEST_VIDEO_PATH, "rb") as f: + blob = f.read() + from_blob_.return_value = video_ + + video = Video.from_path_or_file_like(TEST_VIDEO_PATH, "video/mp4") + + Video.from_blob.assert_called_once_with(blob, "video/mp4", "dummy.mp4") + assert video is video_ + + def it_can_construct_from_a_stream(self, from_stream_fixture): + movie_stream, mime_type, blob, video_ = from_stream_fixture + video = Video.from_path_or_file_like(movie_stream, mime_type) + Video.from_blob.assert_called_once_with(blob, mime_type, None) + assert video is video_ + + def it_can_construct_from_a_blob(self, from_blob_fixture): + blob, mime_type, filename, Video_init_ = from_blob_fixture + video = Video.from_blob(blob, mime_type, filename) + Video_init_.assert_called_once_with(video, blob, mime_type, filename) + assert isinstance(video, Video) + + def it_provides_access_to_the_video_bytestream(self, blob_fixture): + video, expected_value = blob_fixture + assert video.blob == expected_value + + def it_knows_its_content_type(self, content_type_fixture): + video, expected_value = content_type_fixture + assert video.content_type == expected_value + + def it_knows_a_filename_for_the_video(self, filename_fixture): + video, expected_value = filename_fixture + assert video.filename == expected_value + + def it_knows_an_extension_for_the_video(self, ext_fixture): + video, expected_value = ext_fixture + assert video.ext == expected_value + + def it_knows_its_sha1_hash(self, sha1_fixture): + video, expected_value = sha1_fixture + assert video.sha1 == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def blob_fixture(self): + blob = b"blob-bytes" + video = Video(blob, None, None) + expected_value = blob + return video, expected_value + + @pytest.fixture + def content_type_fixture(self): + mime_type = "video/mp4" + video = Video(None, mime_type, None) + expected_value = mime_type + return video, expected_value + + @pytest.fixture( + params=[ + (None, "foo.bar", "bar"), + ("video/mp4", None, "mp4"), + ("video/xyz", None, "vid"), + ] + ) + def ext_fixture(self, request): + mime_type, filename, expected_value = request.param + video = Video(None, mime_type, filename) + return video, expected_value + + @pytest.fixture(params=[("foobar.mp4", None, "foobar.mp4"), (None, "vid", "movie.vid")]) + def filename_fixture(self, request, ext_prop_): + filename, ext, expected_value = request.param + video = Video(None, None, filename) + ext_prop_.return_value = ext + return video, expected_value + + @pytest.fixture + def from_blob_fixture(self, Video_init_): + blob, mime_type, filename = "01234", "video/mp4", "movie.mp4" + return blob, mime_type, filename, Video_init_ + + @pytest.fixture + def from_stream_fixture(self, video_, from_blob_): + with open(TEST_VIDEO_PATH, "rb") as f: + blob = f.read() + movie_stream = io.BytesIO(blob) + mime_type = "video/mp4" + from_blob_.return_value = video_ + return movie_stream, mime_type, blob, video_ + + @pytest.fixture + def sha1_fixture(self): + blob = b"blobish" + video = Video(blob, None, None) + expected_value = "de731a6eed12f427642325193b8e57af3c624d62" + return video, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def ext_prop_(self, request): + return property_mock(request, Video, "ext") + + @pytest.fixture + def from_blob_(self, request): + return method_mock(request, Video, "from_blob", autospec=False) + + @pytest.fixture + def video_(self, request): + return instance_mock(request, Video) + + @pytest.fixture + def Video_init_(self, request): + return initializer_mock(request, Video, autospec=True) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_package.py b/tasks/tasksmith-74f059424102/environment/source/tests/test_package.py new file mode 100644 index 0000000000000000000000000000000000000000..ee02af2d631a3a529beac7f83c66fcafb86d0214 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_package.py @@ -0,0 +1,377 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.package` module.""" + +from __future__ import annotations + +import os + +import pytest + +import pptx +from pptx.media import Video +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.package import Part, _Relationship +from pptx.opc.packuri import PackURI +from pptx.package import Package, _ImageParts, _MediaParts +from pptx.parts.coreprops import CorePropertiesPart +from pptx.parts.image import Image, ImagePart +from pptx.parts.media import MediaPart + +from .unitutil.mock import call, class_mock, instance_mock, method_mock, property_mock + + +class DescribePackage(object): + """Unit-test suite for `pptx.package.Package` objects.""" + + def it_provides_access_to_its_core_properties_part(self): + default_pptx = os.path.abspath( + os.path.join(os.path.split(pptx.__file__)[0], "templates", "default.pptx") + ) + pkg = Package.open(default_pptx) + assert isinstance(pkg.core_properties, CorePropertiesPart) + + def it_can_get_or_add_an_image_part(self, image_part_fixture): + package, image_file, image_parts_, image_part_ = image_part_fixture + image_part = package.get_or_add_image_part(image_file) + image_parts_.get_or_add_image_part.assert_called_once_with(image_file) + assert image_part is image_part_ + + def it_can_get_or_add_a_media_part(self, media_part_fixture): + package, media, media_part_ = media_part_fixture + media_part = package.get_or_add_media_part(media) + package._media_parts.get_or_add_media_part.assert_called_once_with(media) + assert media_part is media_part_ + + def it_knows_the_next_available_image_partname(self, next_fixture): + package, ext, expected_value = next_fixture + partname = package.next_image_partname(ext) + assert partname == expected_value + + def it_knows_the_next_available_media_partname(self, nmp_fixture): + package, ext, expected_value = nmp_fixture + partname = package.next_media_partname(ext) + assert partname == expected_value + + def it_provides_access_to_its_MediaParts_object(self, m_parts_fixture): + package, _MediaParts_, media_parts_ = m_parts_fixture + media_parts = package._media_parts + _MediaParts_.assert_called_once_with(package) + assert media_parts is media_parts_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def image_part_fixture(self, image_parts_, image_part_, _image_parts_prop_): + package = Package(None) + image_file = "foobar.png" + _image_parts_prop_.return_value = image_parts_ + image_parts_.get_or_add_image_part.return_value = image_part_ + return package, image_file, image_parts_, image_part_ + + @pytest.fixture + def media_part_fixture(self, media_, media_part_, _media_parts_prop_, media_parts_): + package = Package(None) + _media_parts_prop_.return_value = media_parts_ + media_parts_.get_or_add_media_part.return_value = media_part_ + return package, media_, media_part_ + + @pytest.fixture + def m_parts_fixture(self, _MediaParts_, media_parts_): + package = Package(None) + _MediaParts_.return_value = media_parts_ + return package, _MediaParts_, media_parts_ + + @pytest.fixture(params=[((3, 4, 2), 1), ((4, 2, 1), 3), ((2, 3, 1), 4)]) + def next_fixture(self, request, iter_parts_): + idxs, idx = request.param + package = Package(None) + package.iter_parts.return_value = self.i_image_parts(request, idxs) + ext = "foo" + expected_value = "/ppt/media/image%d.%s" % (idx, ext) + return package, ext, expected_value + + @pytest.fixture(params=[((3, 4, 2), 1), ((4, 2, 1), 3), ((2, 3, 1), 4)]) + def nmp_fixture(self, request, iter_parts_): + idxs, idx = request.param + package = Package(None) + package.iter_parts.return_value = self.i_media_parts(request, idxs) + ext = "foo" + expected_value = "/ppt/media/media%d.%s" % (idx, ext) + return package, ext, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def image_part_(self, request): + return instance_mock(request, ImagePart) + + @pytest.fixture + def image_parts_(self, request): + return instance_mock(request, _ImageParts) + + @pytest.fixture + def _image_parts_prop_(self, request): + return property_mock(request, Package, "_image_parts") + + def i_image_parts(self, request, idxs): + def part(idx): + partname = PackURI("/ppt/media/image%d.png" % idx) + return instance_mock(request, Part, partname=partname) + + return iter([part(idx) for idx in idxs]) + + def i_media_parts(self, request, idxs): + def part(idx): + partname = PackURI("/ppt/media/media%d.mp4" % idx) + return instance_mock(request, Part, partname=partname) + + return iter([part(idx) for idx in idxs]) + + @pytest.fixture + def iter_parts_(self, request): + return property_mock(request, Package, "iter_parts") + + @pytest.fixture + def media_(self, request): + return instance_mock(request, Video) + + @pytest.fixture + def media_part_(self, request): + return instance_mock(request, MediaPart) + + @pytest.fixture + def _MediaParts_(self, request): + return class_mock(request, "pptx.package._MediaParts") + + @pytest.fixture + def media_parts_(self, request): + return instance_mock(request, _MediaParts) + + @pytest.fixture + def _media_parts_prop_(self, request): + return property_mock(request, Package, "_media_parts") + + +class Describe_ImageParts(object): + """Unit-test suite for `pptx.package._ImageParts` objects.""" + + def it_can_iterate_over_the_package_image_parts(self, iter_fixture): + image_parts, expected_parts = iter_fixture + assert list(image_parts) == expected_parts + + def it_can_get_a_matching_image_part(self, Image_, image_, image_part_, _find_by_sha1_): + Image_.from_file.return_value = image_ + _find_by_sha1_.return_value = image_part_ + image_parts = _ImageParts(None) + + image_part = image_parts.get_or_add_image_part("image.png") + + Image_.from_file.assert_called_once_with("image.png") + _find_by_sha1_.assert_called_once_with(image_parts, image_.sha1) + assert image_part is image_part_ + + def it_can_add_an_image_part( + self, package_, Image_, image_, _find_by_sha1_, ImagePart_, image_part_ + ): + Image_.from_file.return_value = image_ + _find_by_sha1_.return_value = None + ImagePart_.new.return_value = image_part_ + image_parts = _ImageParts(package_) + + image_part = image_parts.get_or_add_image_part("image.png") + + Image_.from_file.assert_called_once_with("image.png") + _find_by_sha1_.assert_called_once_with(image_parts, image_.sha1) + ImagePart_.new.assert_called_once_with(package_, image_) + assert image_part is image_part_ + + def it_can_find_an_image_part_by_sha1_hash(self, find_fixture): + image_parts, sha1, expected_value = find_fixture + image_part = image_parts._find_by_sha1(sha1) + assert image_part is expected_value + + def but_it_skips_unsupported_image_types(self, request, _iter_): + sha1 = "f00beed" + svg_part_ = instance_mock(request, Part, name="svg_part_") + png_part_ = instance_mock(request, ImagePart, name="png_part_", sha1=sha1) + # ---order iteration to encounter svg part before target part--- + _iter_.return_value = iter((svg_part_, png_part_)) + image_parts = _ImageParts(None) + + result = image_parts._find_by_sha1(sha1) + + assert result == png_part_ + + # fixtures --------------------------------------------- + + @pytest.fixture(params=[True, False]) + def find_fixture(self, request, _iter_, image_part_): + image_part_is_present = request.param + image_parts = _ImageParts(None) + _iter_.return_value = iter((image_part_,)) + sha1 = "foobar" + if image_part_is_present: + image_part_.sha1 = "foobar" + expected_value = image_part_ + else: + image_part_.sha1 = "barfoo" + expected_value = None + return image_parts, sha1, expected_value + + @pytest.fixture + def iter_fixture(self, request, package_): + def rel(is_external, reltype): + part = instance_mock(request, Part) + return instance_mock( + request, + _Relationship, + is_external=is_external, + reltype=reltype, + target_part=part, + ) + + rels = (rel(True, RT.IMAGE), rel(False, RT.SLIDE), rel(False, RT.IMAGE)) + + package_.iter_rels.return_value = iter((rels[0], rels[1], rels[2], rels[2])) + image_parts = _ImageParts(package_) + expected_parts = [rels[2].target_part] + return image_parts, expected_parts + + # fixture components --------------------------------------------- + + @pytest.fixture + def _find_by_sha1_(self, request): + return method_mock(request, _ImageParts, "_find_by_sha1") + + @pytest.fixture + def Image_(self, request): + return class_mock(request, "pptx.package.Image") + + @pytest.fixture + def image_(self, request): + return instance_mock(request, Image) + + @pytest.fixture + def ImagePart_(self, request): + return class_mock(request, "pptx.package.ImagePart") + + @pytest.fixture + def image_part_(self, request): + return instance_mock(request, ImagePart) + + @pytest.fixture + def _iter_(self, request): + return method_mock(request, _ImageParts, "__iter__") + + @pytest.fixture + def package_(self, request): + return instance_mock(request, Package) + + +class Describe_MediaParts(object): + """Unit-test suite for `pptx.package._MediaParts` objects.""" + + def it_can_iterate_the_media_parts_in_the_package(self, iter_fixture): + media_parts, expected_parts = iter_fixture + assert list(media_parts) == expected_parts + + def it_can_get_or_add_a_media_part(self, get_or_add_fixture): + media_parts, media_, sha1, MediaPart_, calls = get_or_add_fixture[:5] + media_part_ = get_or_add_fixture[5] + + media_part = media_parts.get_or_add_media_part(media_) + + media_parts._find_by_sha1.assert_called_once_with(media_parts, sha1) + assert MediaPart_.new.call_args_list == calls + assert media_part is media_part_ + + def it_can_find_a_media_part_by_sha1(self, find_fixture): + media_parts, sha1, expected_value = find_fixture + media_part = media_parts._find_by_sha1(sha1) + assert media_part is expected_value + + # fixtures --------------------------------------------- + + @pytest.fixture(params=[True, False]) + def find_fixture(self, request, _iter_, media_part_): + media_part_is_present = request.param + media_parts = _MediaParts(None) + _iter_.return_value = iter((media_part_,)) + sha1 = "foobar" + if media_part_is_present: + media_part_.sha1 = "foobar" + expected_value = media_part_ + else: + media_part_.sha1 = "barfoo" + expected_value = None + return media_parts, sha1, expected_value + + @pytest.fixture(params=[True, False]) + def get_or_add_fixture( + self, request, package_, media_, MediaPart_, media_part_, _find_by_sha1_ + ): + media_present = request.param + media_parts = _MediaParts(package_) + media_.sha1 = sha1 = "2468" + calls = [] if media_present else [call(package_, media_)] + _find_by_sha1_.return_value = media_part_ if media_present else None + MediaPart_.new.return_value = None if media_present else media_part_ + return media_parts, media_, sha1, MediaPart_, calls, media_part_ + + @pytest.fixture + def iter_fixture(self, request, package_): + def rel(is_external, reltype, part): + return instance_mock( + request, + _Relationship, + is_external=is_external, + reltype=reltype, + target_part=part, + ) + + part_mocks = ( + instance_mock(request, Part, name="linked-media"), + instance_mock(request, Part, name="slide"), + instance_mock(request, Part, name="embeded-media"), + ) + + rels = ( + rel(True, RT.MEDIA, part_mocks[0]), + rel(True, RT.VIDEO, part_mocks[0]), + rel(False, RT.SLIDE, part_mocks[1]), + rel(False, RT.MEDIA, part_mocks[2]), + rel(False, RT.VIDEO, part_mocks[2]), + ) + + package_.iter_rels.return_value = iter(rels) + + media_parts = _MediaParts(package_) + expected_parts = [part_mocks[2]] + return media_parts, expected_parts + + # fixture components --------------------------------------------- + + @pytest.fixture + def _find_by_sha1_(self, request): + return method_mock(request, _MediaParts, "_find_by_sha1", autospec=True) + + @pytest.fixture + def _iter_(self, request): + return method_mock(request, _MediaParts, "__iter__") + + @pytest.fixture + def media_(self, request): + return instance_mock(request, Video) + + @pytest.fixture + def MediaPart_(self, request): + return class_mock(request, "pptx.package.MediaPart") + + @pytest.fixture + def media_part_(self, request): + return instance_mock(request, MediaPart) + + @pytest.fixture + def package_(self, request): + return instance_mock(request, Package) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_presentation.py b/tasks/tasksmith-74f059424102/environment/source/tests/test_presentation.py new file mode 100644 index 0000000000000000000000000000000000000000..7c53151433c3a06ee1d50799eb5ca306ef743d89 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_presentation.py @@ -0,0 +1,231 @@ +"""Unit-test suite for `pptx.presentation` module.""" + +from __future__ import annotations + +import pytest + +from pptx.parts.coreprops import CorePropertiesPart +from pptx.parts.presentation import PresentationPart +from pptx.parts.slide import NotesMasterPart +from pptx.presentation import Presentation +from pptx.slide import SlideLayouts, SlideMaster, SlideMasters, Slides + +from .unitutil.cxml import element, xml +from .unitutil.mock import class_mock, instance_mock, property_mock + + +class DescribePresentation(object): + def it_knows_the_height_of_its_slides(self, sld_height_get_fixture): + prs, expected_value = sld_height_get_fixture + assert prs.slide_height == expected_value + + def it_can_change_the_height_of_its_slides(self, sld_height_set_fixture): + prs, slide_height, expected_xml = sld_height_set_fixture + prs.slide_height = slide_height + assert prs._element.xml == expected_xml + + def it_knows_the_width_of_its_slides(self, sld_width_get_fixture): + prs, expected_value = sld_width_get_fixture + assert prs.slide_width == expected_value + + def it_can_change_the_width_of_its_slides(self, sld_width_set_fixture): + prs, slide_width, expected_xml = sld_width_set_fixture + prs.slide_width = slide_width + assert prs._element.xml == expected_xml + + def it_knows_its_part(self, part_fixture): + prs, prs_part_ = part_fixture + assert prs.part is prs_part_ + + def it_provides_access_to_its_core_properties(self, core_props_fixture): + prs, core_properties_ = core_props_fixture + assert prs.core_properties is core_properties_ + + def it_provides_access_to_its_notes_master(self, notes_master_fixture): + prs, notes_master_ = notes_master_fixture + assert prs.notes_master is notes_master_ + + def it_provides_access_to_its_slides(self, slides_fixture): + prs, rename_slide_parts_, rIds = slides_fixture[:3] + Slides_, slides_, expected_xml = slides_fixture[3:] + slides = prs.slides + rename_slide_parts_.assert_called_once_with(rIds) + Slides_.assert_called_once_with(prs._element.xpath("p:sldIdLst")[0], prs) + assert prs._element.xml == expected_xml + assert slides is slides_ + + def it_provides_access_to_its_slide_layouts(self, layouts_fixture): + prs, slide_layouts_ = layouts_fixture + assert prs.slide_layouts is slide_layouts_ + + def it_provides_access_to_its_slide_master(self, master_fixture): + prs, getitem_, slide_master_ = master_fixture + slide_master = prs.slide_master + getitem_.assert_called_once_with(0) + assert slide_master is slide_master_ + + def it_provides_access_to_its_slide_masters(self, masters_fixture): + prs, SlideMasters_, slide_masters_, expected_xml = masters_fixture + slide_masters = prs.slide_masters + SlideMasters_.assert_called_once_with(prs._element.xpath("p:sldMasterIdLst")[0], prs) + assert slide_masters is slide_masters_ + assert prs._element.xml == expected_xml + + def it_can_save_the_presentation_to_a_file(self, save_fixture): + prs, file_, prs_part_ = save_fixture + prs.save(file_) + prs_part_.save.assert_called_once_with(file_) + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def core_props_fixture(self, prs_part_, core_properties_): + prs = Presentation(None, prs_part_) + prs_part_.core_properties = core_properties_ + return prs, core_properties_ + + @pytest.fixture + def layouts_fixture(self, masters_prop_, slide_layouts_): + prs = Presentation(None, None) + masters_prop_.return_value.__getitem__.return_value.slide_layouts = slide_layouts_ + return prs, slide_layouts_ + + @pytest.fixture + def master_fixture(self, masters_prop_, slide_master_): + prs = Presentation(None, None) + getitem_ = masters_prop_.return_value.__getitem__ + getitem_.return_value = slide_master_ + return prs, getitem_, slide_master_ + + @pytest.fixture( + params=[ + ("p:presentation", "p:presentation/p:sldMasterIdLst"), + ("p:presentation/p:sldMasterIdLst", "p:presentation/p:sldMasterIdLst"), + ] + ) + def masters_fixture(self, request, SlideMasters_, slide_masters_): + prs_cxml, expected_cxml = request.param + prs = Presentation(element(prs_cxml), None) + expected_xml = xml(expected_cxml) + return prs, SlideMasters_, slide_masters_, expected_xml + + @pytest.fixture + def notes_master_fixture(self, prs_part_, notes_master_): + prs = Presentation(None, prs_part_) + prs_part_.notes_master = notes_master_ + return prs, notes_master_ + + @pytest.fixture + def part_fixture(self, prs_part_): + prs = Presentation(None, prs_part_) + return prs, prs_part_ + + @pytest.fixture + def save_fixture(self, prs_part_): + prs = Presentation(None, prs_part_) + file_ = "foobar.docx" + return prs, file_, prs_part_ + + @pytest.fixture(params=[("p:presentation", None), ("p:presentation/p:sldSz{cy=42}", 42)]) + def sld_height_get_fixture(self, request): + prs_cxml, expected_value = request.param + prs = Presentation(element(prs_cxml), None) + return prs, expected_value + + @pytest.fixture( + params=[ + ("p:presentation", "p:presentation/p:sldSz{cy=914400}"), + ("p:presentation/p:sldSz{cy=424242}", "p:presentation/p:sldSz{cy=914400}"), + ] + ) + def sld_height_set_fixture(self, request): + prs_cxml, expected_cxml = request.param + prs = Presentation(element(prs_cxml), None) + expected_xml = xml(expected_cxml) + return prs, 914400, expected_xml + + @pytest.fixture(params=[("p:presentation", None), ("p:presentation/p:sldSz{cx=42}", 42)]) + def sld_width_get_fixture(self, request): + prs_cxml, expected_value = request.param + prs = Presentation(element(prs_cxml), None) + return prs, expected_value + + @pytest.fixture( + params=[ + ("p:presentation", "p:presentation/p:sldSz{cx=914400}"), + ("p:presentation/p:sldSz{cx=424242}", "p:presentation/p:sldSz{cx=914400}"), + ] + ) + def sld_width_set_fixture(self, request): + prs_cxml, expected_cxml = request.param + prs = Presentation(element(prs_cxml), None) + expected_xml = xml(expected_cxml) + return prs, 914400, expected_xml + + @pytest.fixture( + params=[ + ("p:presentation", [], "p:presentation/p:sldIdLst"), + ( + "p:presentation/p:sldIdLst/p:sldId{r:id=a}", + ["a"], + "p:presentation/p:sldIdLst/p:sldId{r:id=a}", + ), + ( + "p:presentation/p:sldIdLst/(p:sldId{r:id=a},p:sldId{r:id=b})", + ["a", "b"], + "p:presentation/p:sldIdLst/(p:sldId{r:id=a},p:sldId{r:id=b})", + ), + ] + ) + def slides_fixture(self, request, part_prop_, Slides_, slides_): + prs_cxml, rIds, expected_cxml = request.param + prs = Presentation(element(prs_cxml), None) + rename_slide_parts_ = part_prop_.return_value.rename_slide_parts + expected_xml = xml(expected_cxml) + return prs, rename_slide_parts_, rIds, Slides_, slides_, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def core_properties_(self, request): + return instance_mock(request, CorePropertiesPart) + + @pytest.fixture + def masters_prop_(self, request): + return property_mock(request, Presentation, "slide_masters") + + @pytest.fixture + def notes_master_(self, request): + return instance_mock(request, NotesMasterPart) + + @pytest.fixture + def part_prop_(self, request): + return property_mock(request, Presentation, "part") + + @pytest.fixture + def prs_part_(self, request): + return instance_mock(request, PresentationPart) + + @pytest.fixture + def slide_layouts_(self, request): + return instance_mock(request, SlideLayouts) + + @pytest.fixture + def SlideMasters_(self, request, slide_masters_): + return class_mock(request, "pptx.presentation.SlideMasters", return_value=slide_masters_) + + @pytest.fixture + def slide_master_(self, request): + return instance_mock(request, SlideMaster) + + @pytest.fixture + def slide_masters_(self, request): + return instance_mock(request, SlideMasters) + + @pytest.fixture + def Slides_(self, request, slides_): + return class_mock(request, "pptx.presentation.Slides", return_value=slides_) + + @pytest.fixture + def slides_(self, request): + return instance_mock(request, Slides) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_shared.py b/tasks/tasksmith-74f059424102/environment/source/tests/test_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..72a0ebc0e4f44b389b96823eeaa0ab99151bfada --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_shared.py @@ -0,0 +1,83 @@ +"""Unit-test suite for `pptx.shared` module.""" + +from __future__ import annotations + +import pytest + +from pptx.opc.package import XmlPart +from pptx.shared import ElementProxy, ParentedElementProxy + +from .unitutil.cxml import element +from .unitutil.mock import instance_mock + + +class DescribeElementProxy(object): + """Unit-test suite for `pptx.shared.ElementProxy` objects.""" + + def it_knows_when_its_equal_to_another_proxy_object(self, eq_fixture): + proxy, proxy_2, proxy_3, not_a_proxy = eq_fixture + + assert (proxy == proxy_2) is True + assert (proxy == proxy_3) is False + assert (proxy == not_a_proxy) is False + + assert (proxy != proxy_2) is False + assert (proxy != proxy_3) is True + assert (proxy != not_a_proxy) is True + + def it_knows_its_element(self, element_fixture): + proxy, element = element_fixture + assert proxy.element is element + + # fixture -------------------------------------------------------- + + @pytest.fixture + def element_fixture(self): + p = element("w:p") + proxy = ElementProxy(p) + return proxy, p + + @pytest.fixture + def eq_fixture(self): + p, q = element("w:p"), element("w:p") + proxy = ElementProxy(p) + proxy_2 = ElementProxy(p) + proxy_3 = ElementProxy(q) + not_a_proxy = "Foobar" + return proxy, proxy_2, proxy_3, not_a_proxy + + +class DescribeParentedElementProxy(object): + """Unit-test suite for `pptx.shared.ParentedElementProxy` objects.""" + + def it_knows_its_parent(self, parent_fixture): + proxy, parent = parent_fixture + assert proxy.parent is parent + + def it_knows_its_part(self, part_fixture): + proxy, part_ = part_fixture + assert proxy.part is part_ + + # fixture -------------------------------------------------------- + + @pytest.fixture + def parent_fixture(self): + parent = 42 + proxy = ParentedElementProxy(element("w:p"), parent) + return proxy, parent + + @pytest.fixture + def part_fixture(self, other_proxy_, part_): + other_proxy_.part = part_ + proxy = ParentedElementProxy(None, other_proxy_) + return proxy, part_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def other_proxy_(self, request): + return instance_mock(request, ParentedElementProxy) + + @pytest.fixture + def part_(self, request): + return instance_mock(request, XmlPart) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_slide.py b/tasks/tasksmith-74f059424102/environment/source/tests/test_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..74b528c3b93c825b9d58a6bc76612d8b68378740 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_slide.py @@ -0,0 +1,1040 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.slide` module.""" + +from __future__ import annotations + +import pytest + +from pptx.dml.fill import FillFormat +from pptx.enum.shapes import PP_PLACEHOLDER +from pptx.package import Package +from pptx.parts.presentation import PresentationPart +from pptx.parts.slide import SlideLayoutPart, SlideMasterPart, SlidePart +from pptx.presentation import Presentation +from pptx.shapes.base import BaseShape +from pptx.shapes.placeholder import LayoutPlaceholder, NotesSlidePlaceholder +from pptx.shapes.shapetree import ( + LayoutPlaceholders, + LayoutShapes, + MasterPlaceholders, + MasterShapes, + NotesSlidePlaceholders, + NotesSlideShapes, + SlidePlaceholders, + SlideShapes, +) +from pptx.slide import ( + NotesMaster, + NotesSlide, + Slide, + SlideLayout, + SlideLayouts, + SlideMaster, + SlideMasters, + Slides, + _Background, + _BaseMaster, + _BaseSlide, +) +from pptx.text.text import TextFrame + +from .unitutil.cxml import element, xml +from .unitutil.mock import call, class_mock, instance_mock, method_mock, property_mock + + +class Describe_BaseSlide(object): + """Unit-test suite for `pptx.slide._BaseSlide` objects.""" + + def it_knows_its_name(self, name_get_fixture): + base_slide, expected_value = name_get_fixture + assert base_slide.name == expected_value + + def it_can_change_its_name(self, name_set_fixture): + base_slide, new_value, expected_xml = name_set_fixture + base_slide.name = new_value + assert base_slide._element.xml == expected_xml + + def it_provides_access_to_its_background(self, background_fixture): + slide, _Background_, cSld, background_ = background_fixture + + background = slide.background + + _Background_.assert_called_once_with(cSld) + assert background is background_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def background_fixture(self, _Background_, background_): + sld = element("p:sld/p:cSld") + slide = _BaseSlide(sld, None) + cSld = sld.xpath("//p:cSld")[0] + _Background_.return_value = background_ + return slide, _Background_, cSld, background_ + + @pytest.fixture(params=[("p:sld/p:cSld", ""), ("p:sld/p:cSld{name=Foobar}", "Foobar")]) + def name_get_fixture(self, request): + sld_cxml, expected_name = request.param + base_slide = _BaseSlide(element(sld_cxml), None) + return base_slide, expected_name + + @pytest.fixture( + params=[ + ("p:sld/p:cSld", "foo", "p:sld/p:cSld{name=foo}"), + ("p:sld/p:cSld{name=foo}", "bar", "p:sld/p:cSld{name=bar}"), + ("p:sld/p:cSld{name=bar}", "", "p:sld/p:cSld"), + ("p:sld/p:cSld{name=bar}", None, "p:sld/p:cSld"), + ("p:sld/p:cSld", "", "p:sld/p:cSld"), + ("p:sld/p:cSld", None, "p:sld/p:cSld"), + ] + ) + def name_set_fixture(self, request): + xSld_cxml, new_value, expected_cxml = request.param + base_slide = _BaseSlide(element(xSld_cxml), None) + expected_xml = xml(expected_cxml) + return base_slide, new_value, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def _Background_(self, request): + return class_mock(request, "pptx.slide._Background") + + @pytest.fixture + def background_(self, request): + return instance_mock(request, _Background) + + +class Describe_BaseMaster(object): + """Unit-test suite for `pptx.slide._BaseMaster` objects.""" + + def it_is_a_BaseSlide_subclass(self, subclass_fixture): + base_master = subclass_fixture + assert isinstance(base_master, _BaseSlide) + + def it_provides_access_to_its_placeholders(self, placeholders_fixture): + base_master, MasterPlaceholders_, spTree, placeholders_ = placeholders_fixture + placeholders = base_master.placeholders + MasterPlaceholders_.assert_called_once_with(spTree, base_master) + assert placeholders is placeholders_ + + def it_provides_access_to_its_shapes(self, shapes_fixture): + base_master, MasterShapes_, spTree, shapes_ = shapes_fixture + shapes = base_master.shapes + MasterShapes_.assert_called_once_with(spTree, base_master) + assert shapes is shapes_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def placeholders_fixture(self, MasterPlaceholders_, placeholders_): + master_element = element("p:sldMaster/p:cSld/p:spTree") + base_master = _BaseMaster(master_element, None) + spTree = master_element.xpath("//p:spTree")[0] + return base_master, MasterPlaceholders_, spTree, placeholders_ + + @pytest.fixture + def shapes_fixture(self, MasterShapes_, shapes_): + master_element = element("p:sldMaster/p:cSld/p:spTree") + base_master = _BaseMaster(master_element, None) + spTree = master_element.xpath("//p:spTree")[0] + return base_master, MasterShapes_, spTree, shapes_ + + @pytest.fixture + def subclass_fixture(self): + return _BaseMaster(None, None) + + # fixture components ----------------------------------- + + @pytest.fixture + def MasterPlaceholders_(self, request, placeholders_): + return class_mock(request, "pptx.slide.MasterPlaceholders", return_value=placeholders_) + + @pytest.fixture + def MasterShapes_(self, request, shapes_): + return class_mock(request, "pptx.slide.MasterShapes", return_value=shapes_) + + @pytest.fixture + def placeholders_(self, request): + return instance_mock(request, MasterPlaceholders) + + @pytest.fixture + def shapes_(self, request): + return instance_mock(request, MasterShapes) + + +class DescribeNotesSlide(object): + """Unit-test suite for `pptx.slide.NotesSlide` objects.""" + + def it_can_clone_the_notes_master_placeholders(self, request, notes_master_, shapes_): + placeholders = notes_master_.placeholders = ( + BaseShape(element("p:sp/p:nvSpPr/p:nvPr/p:ph{type=body}"), None), + BaseShape(element("p:sp/p:nvSpPr/p:nvPr/p:ph{type=dt}"), None), + ) + property_mock(request, NotesSlide, "shapes", return_value=shapes_) + notes_slide = NotesSlide(None, None) + + notes_slide.clone_master_placeholders(notes_master_) + + assert shapes_.clone_placeholder.call_args_list == [call(placeholders[0])] + + def it_provides_access_to_its_shapes(self, shapes_fixture): + notes_slide, NotesSlideShapes_, spTree, shapes_ = shapes_fixture + shapes = notes_slide.shapes + NotesSlideShapes_.assert_called_once_with(spTree, notes_slide) + assert shapes is shapes_ + + def it_provides_access_to_its_placeholders(self, placeholders_fixture): + ( + notes_slide, + NotesSlidePlaceholders_, + spTree, + placeholders_, + ) = placeholders_fixture + placeholders = notes_slide.placeholders + NotesSlidePlaceholders_.assert_called_once_with(spTree, notes_slide) + assert placeholders is placeholders_ + + def it_provides_access_to_its_notes_placeholder(self, notes_ph_fixture): + notes_slide, expected_value = notes_ph_fixture + placeholder = notes_slide.notes_placeholder + assert placeholder is expected_value + + def it_provides_access_to_its_notes_text_frame(self, notes_tf_fixture): + notes_slide, expected_value = notes_tf_fixture + text_frame = notes_slide.notes_text_frame + assert text_frame is expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + (("SLIDE_IMAGE", "BODY", "SLIDE_NUMBER"), 1), + (("DATE", "SLIDE_IMAGE", "FOOTER"), None), + ] + ) + def notes_ph_fixture(self, request, placeholders_prop_): + type_names, match = request.param + notes_slide = NotesSlide(None, None) + placeholders_ = [] + for type_name in type_names: + placeholder_ = instance_mock( + request, NotesSlidePlaceholder, name="%s-placeholder" % type_name + ) + placeholder_.placeholder_format.type = getattr(PP_PLACEHOLDER, type_name) + placeholders_.append(placeholder_) + placeholders_prop_.return_value = placeholders_ + expected_value = None if match is None else placeholders_[match] + return notes_slide, expected_value + + @pytest.fixture(params=[True, False]) + def notes_tf_fixture(self, request, notes_placeholder_prop_, placeholder_, text_frame_): + has_text_frame = request.param + notes_slide = NotesSlide(None, None) + if has_text_frame: + notes_placeholder_prop_.return_value = placeholder_ + placeholder_.text_frame = text_frame_ + expected_value = text_frame_ + else: + notes_placeholder_prop_.return_value = None + expected_value = None + return notes_slide, expected_value + + @pytest.fixture + def placeholders_fixture(self, NotesSlidePlaceholders_, placeholders_): + notes = element("p:notes/p:cSld/p:spTree") + notes_slide = NotesSlide(notes, None) + spTree = notes.xpath("//p:spTree")[0] + return notes_slide, NotesSlidePlaceholders_, spTree, placeholders_ + + @pytest.fixture + def shapes_fixture(self, NotesSlideShapes_, shapes_): + notes = element("p:notes/p:cSld/p:spTree") + notes_slide = NotesSlide(notes, None) + spTree = notes.xpath("//p:spTree")[0] + return notes_slide, NotesSlideShapes_, spTree, shapes_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def notes_master_(self, request): + return instance_mock(request, NotesMaster) + + @pytest.fixture + def notes_placeholder_prop_(self, request, placeholder_): + return property_mock(request, NotesSlide, "notes_placeholder", return_value=placeholder_) + + @pytest.fixture + def NotesSlidePlaceholders_(self, request, placeholders_): + return class_mock(request, "pptx.slide.NotesSlidePlaceholders", return_value=placeholders_) + + @pytest.fixture + def NotesSlideShapes_(self, request, shapes_): + return class_mock(request, "pptx.slide.NotesSlideShapes", return_value=shapes_) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, NotesSlidePlaceholder) + + @pytest.fixture + def placeholders_(self, request): + return instance_mock(request, NotesSlidePlaceholders) + + @pytest.fixture + def placeholders_prop_(self, request, placeholders_): + return property_mock(request, NotesSlide, "placeholders", return_value=placeholders_) + + @pytest.fixture + def shapes_(self, request): + return instance_mock(request, NotesSlideShapes) + + @pytest.fixture + def text_frame_(self, request): + return instance_mock(request, TextFrame) + + +class DescribeSlide(object): + """Unit-test suite for `pptx.slide.Slide` objects.""" + + def it_is_a_BaseSlide_subclass(self, subclass_fixture): + slide = subclass_fixture + assert isinstance(slide, _BaseSlide) + + def it_provides_access_to_its_background(self, background_fixture): + slide, _BaseSlide_background_, background_ = background_fixture + + background = slide.background + + _BaseSlide_background_.assert_called_once_with() + assert background is background_ + + def it_knows_whether_it_follows_the_mstr_bkgd(self, follow_get_fixture): + slide, expected_value = follow_get_fixture + follows = slide.follow_master_background + assert follows is expected_value + + def it_knows_whether_it_has_a_notes_slide(self, has_notes_slide_fixture): + slide, expected_value = has_notes_slide_fixture + assert slide.has_notes_slide is expected_value + + def it_knows_its_slide_id(self, slide_id_fixture): + slide, expected_value = slide_id_fixture + assert slide.slide_id == expected_value + + def it_provides_access_to_its_shapes(self, shapes_fixture): + slide, SlideShapes_, spTree, shapes_ = shapes_fixture + shapes = slide.shapes + SlideShapes_.assert_called_once_with(spTree, slide) + assert shapes is shapes_ + + def it_provides_access_to_its_placeholders(self, placeholders_fixture): + slide, SlidePlaceholders_, spTree, placeholders_ = placeholders_fixture + placeholders = slide.placeholders + SlidePlaceholders_.assert_called_once_with(spTree, slide) + assert placeholders is placeholders_ + + def it_provides_access_to_its_slide_layout(self, layout_fixture): + slide, slide_layout_ = layout_fixture + assert slide.slide_layout is slide_layout_ + + def it_provides_access_to_its_notes_slide(self, notes_slide_fixture): + slide, notes_slide_ = notes_slide_fixture + assert slide.notes_slide is notes_slide_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def background_fixture(self, _BaseSlide_background_, background_): + slide = Slide(None, None) + _BaseSlide_background_.return_value = background_ + return slide, _BaseSlide_background_, background_ + + @pytest.fixture(params=[("p:sld/p:cSld", True), ("p:sld/p:cSld/p:bg", False)]) + def follow_get_fixture(self, request): + pSld_cxml, expected_value = request.param + slide = Slide(element(pSld_cxml), None) + return slide, expected_value + + @pytest.fixture + def has_notes_slide_fixture(self, part_prop_, slide_part_): + slide = Slide(None, None) + expected_value = slide_part_.has_notes_slide = 42 + return slide, expected_value + + @pytest.fixture + def layout_fixture(self, slide_layout_, part_prop_, slide_part_): + slide = Slide(None, None) + part_prop_.return_value = slide_part_ + slide_part_.slide_layout = slide_layout_ + return slide, slide_layout_ + + @pytest.fixture + def notes_slide_fixture(self, notes_slide_, part_prop_, slide_part_): + slide = Slide(None, None) + slide_part_.notes_slide = notes_slide_ + return slide, notes_slide_ + + @pytest.fixture + def placeholders_fixture(self, SlidePlaceholders_, placeholders_): + sld = element("p:sld/p:cSld/p:spTree") + slide = Slide(sld, None) + spTree = sld.xpath("//p:spTree")[0] + return slide, SlidePlaceholders_, spTree, placeholders_ + + @pytest.fixture + def shapes_fixture(self, SlideShapes_, shapes_): + sld = element("p:sld/p:cSld/p:spTree") + spTree = sld.xpath("//p:spTree")[0] + slide = Slide(sld, None) + return slide, SlideShapes_, spTree, shapes_ + + @pytest.fixture + def slide_id_fixture(self, part_prop_, slide_part_): + slide = Slide(None, None) + slide_id = 256 + slide_part_.slide_id = slide_id + return slide, slide_id + + @pytest.fixture + def subclass_fixture(self): + return Slide(None, None) + + # fixture components --------------------------------------------- + + @pytest.fixture + def _BaseSlide_background_(self, request): + return property_mock(request, _BaseSlide, "background") + + @pytest.fixture + def background_(self, request): + return instance_mock(request, _Background) + + @pytest.fixture + def notes_slide_(self, request): + return instance_mock(request, NotesSlide) + + @pytest.fixture + def part_prop_(self, request, slide_part_): + return property_mock(request, Slide, "part", return_value=slide_part_) + + @pytest.fixture + def placeholders_(self, request): + return instance_mock(request, SlidePlaceholders) + + @pytest.fixture + def SlidePlaceholders_(self, request, placeholders_): + return class_mock(request, "pptx.slide.SlidePlaceholders", return_value=placeholders_) + + @pytest.fixture + def SlideShapes_(self, request, shapes_): + return class_mock(request, "pptx.slide.SlideShapes", return_value=shapes_) + + @pytest.fixture + def shapes_(self, request): + return instance_mock(request, SlideShapes) + + @pytest.fixture + def slide_layout_(self, request): + return instance_mock(request, SlideLayout) + + @pytest.fixture + def slide_part_(self, request): + return instance_mock(request, SlidePart) + + +class DescribeSlides(object): + """Unit-test suite for `pptx.slide.Slides` objects.""" + + def it_supports_indexed_access(self, getitem_fixture): + slides, prs_part_, rId, slide_ = getitem_fixture + slide = slides[0] + prs_part_.related_slide.assert_called_once_with(rId) + assert slide is slide_ + + def it_raises_on_slide_index_out_of_range(self, getitem_raises_fixture): + slides = getitem_raises_fixture + with pytest.raises(IndexError): + slides[2] + + def it_knows_the_index_of_a_slide_it_contains(self, index_fixture): + slides, slide, expected_value = index_fixture + index = slides.index(slide) + assert index == expected_value + + def it_raises_on_slide_not_in_collection(self, raises_fixture): + slides, slide = raises_fixture + with pytest.raises(ValueError): + slides.index(slide) + + def it_can_iterate_its_slides(self, iter_fixture): + slides, related_slide_, calls, expected_value = iter_fixture + slide_lst = [s for s in slides] + assert related_slide_.call_args_list == calls + assert slide_lst == expected_value + + def it_supports_len(self, len_fixture): + slides, expected_value = len_fixture + assert len(slides) == expected_value + + def it_can_add_a_new_slide(self, add_fixture): + slides, slide_layout_, part_ = add_fixture[:3] + clone_layout_placeholders_, expected_xml, slide_ = add_fixture[3:] + + slide = slides.add_slide(slide_layout_) + + part_.add_slide.assert_called_once_with(slide_layout_) + clone_layout_placeholders_.assert_called_once_with(slide_layout_) + assert slides._sldIdLst.xml == expected_xml + assert slide is slide_ + + def it_finds_a_slide_by_slide_id(self, get_fixture): + slides, slide_id, default, prs_part_, expected_value = get_fixture + slide = slides.get(slide_id, default) + prs_part_.get_slide.assert_called_once_with(slide_id) + assert slide is expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def add_fixture(self, slide_layout_, part_prop_, slide_): + slides = Slides(element("p:sldIdLst/p:sldId{r:id=rId1}"), None) + part_ = part_prop_.return_value + clone_layout_placeholders_ = slide_.shapes.clone_layout_placeholders + expected_xml = xml("p:sldIdLst/(p:sldId{r:id=rId1},p:sldId{r:id=rId2,id=256})") + part_.add_slide.return_value = "rId2", slide_ + return ( + slides, + slide_layout_, + part_, + clone_layout_placeholders_, + expected_xml, + slide_, + ) + + @pytest.fixture(params=[True, False]) + def get_fixture(self, request, part_prop_, prs_part_, slide_): + found = request.param + slides = Slides(None, None) + slide_id, default = 256, "foobar" + expected_value = slide_ if found else default + prs_part_.get_slide.return_value = slide_ if found else None + return slides, slide_id, default, prs_part_, expected_value + + @pytest.fixture + def getitem_fixture(self, prs_part_, slide_, part_prop_): + sldIdLst = element("p:sldIdLst/p:sldId{r:id=rId1}") + slides = Slides(sldIdLst, None) + prs_part_.related_slide.return_value = slide_ + return slides, prs_part_, "rId1", slide_ + + @pytest.fixture + def getitem_raises_fixture(self): + sldIdLst = element("p:sldIdLst/p:sldId{r:id=rId1}") + slides = Slides(sldIdLst, None) + return slides + + @pytest.fixture(params=[0, 1]) + def index_fixture(self, request, part_prop_): + idx = request.param + sldIdLst = element("p:sldIdLst/(p:sldId{r:id=a},p:sldId{r:id=b})") + slides = Slides(sldIdLst, None) + _slides = [Slide(element("p:sld"), None), Slide(element("p:sld"), None)] + part_prop_.return_value.related_slide.side_effect = _slides + return slides, _slides[idx], idx + + @pytest.fixture + def iter_fixture(self, part_prop_, slide_): + sldIdLst = element("p:sldIdLst/(p:sldId{r:id=a},p:sldId{r:id=b})") + slides = Slides(sldIdLst, None) + related_slide_ = part_prop_.return_value.related_slide + related_slide_.return_value = slide_ + calls = [call("a"), call("b")] + _slides = [slide_, slide_] + return slides, related_slide_, calls, _slides + + @pytest.fixture( + params=[ + ("p:sldIdLst", 0), + ("p:sldIdLst/p:sldId{r:id=a}", 1), + ("p:sldIdLst/(p:sldId{r:id=a},p:sldId{r:id=b})", 2), + ] + ) + def len_fixture(self, request): + sldIdLst_cxml, expected_value = request.param + slides = Slides(element(sldIdLst_cxml), None) + return slides, expected_value + + @pytest.fixture + def raises_fixture(self): + slides = Slides(element("p:sldIdLst"), None) + slide = Slide(element("p:sld"), None) + return slides, slide + + # fixture components --------------------------------------------- + + @pytest.fixture + def part_prop_(self, request, prs_part_): + return property_mock(request, Slides, "part", return_value=prs_part_) + + @pytest.fixture + def prs_part_(self, request): + return instance_mock(request, PresentationPart) + + @pytest.fixture + def slide_(self, request): + return instance_mock(request, Slide) + + @pytest.fixture + def slide_layout_(self, request): + return instance_mock(request, SlideLayout) + + +class DescribeSlideLayout(object): + """Unit-test suite for `pptx.slide.SlideLayout` objects.""" + + def it_is_a_BaseSlide_subclass(self): + slide_layout = SlideLayout(None, None) + assert isinstance(slide_layout, _BaseSlide) + + def it_can_iterate_its_clonable_placeholders(self, cloneable_fixture): + slide_layout, expected_placeholders = cloneable_fixture + cloneable = list(slide_layout.iter_cloneable_placeholders()) + assert cloneable == expected_placeholders + + def it_provides_access_to_its_placeholders(self, LayoutPlaceholders_, placeholders_): + sldLayout = element("p:sldLayout/p:cSld/p:spTree") + spTree = sldLayout.xpath("//p:spTree")[0] + slide_layout = SlideLayout(sldLayout, None) + + placeholders = slide_layout.placeholders + + LayoutPlaceholders_.assert_called_once_with(spTree, slide_layout) + assert placeholders is placeholders_ + + def it_provides_access_to_its_shapes(self, LayoutShapes_, shapes_): + sldLayout = element("p:sldLayout/p:cSld/p:spTree") + spTree = sldLayout.xpath("//p:spTree")[0] + slide_layout = SlideLayout(sldLayout, None) + + shapes = slide_layout.shapes + + LayoutShapes_.assert_called_once_with(spTree, slide_layout) + assert shapes is shapes_ + + def it_provides_access_to_its_slide_master(self, slide_master_, part_prop_): + part_prop_.return_value.slide_master = slide_master_ + slide_layout = SlideLayout(None, None) + + slide_master = slide_layout.slide_master + + assert slide_master is slide_master_ + + def it_knows_which_slides_are_based_on_it( + self, + used_by_fixture, + part_prop_, + slide_layout_part_, + package_, + presentation_part_, + presentation_, + ): + presentation_, slide_layout, expected_value = used_by_fixture + part_prop_.return_value = slide_layout_part_ + slide_layout_part_.package = package_ + package_.presentation_part = presentation_part_ + presentation_part_.presentation = presentation_ + + used_by_slides = slide_layout.used_by_slides + + assert used_by_slides == expected_value + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ((PP_PLACEHOLDER.TITLE, PP_PLACEHOLDER.BODY), (0, 1)), + ((PP_PLACEHOLDER.TITLE, PP_PLACEHOLDER.DATE), (0,)), + ((PP_PLACEHOLDER.FOOTER, PP_PLACEHOLDER.OBJECT), (1,)), + ((PP_PLACEHOLDER.SLIDE_NUMBER, PP_PLACEHOLDER.FOOTER), ()), + ] + ) + def cloneable_fixture(self, request, placeholders_prop_, placeholder_, placeholder_2_): + ph_types, expected_indices = request.param + slide_layout = SlideLayout(None, None) + placeholder_.element.ph_type = ph_types[0] + placeholder_2_.element.ph_type = ph_types[1] + _placeholders = (placeholder_, placeholder_2_) + expected_placeholders = [_placeholders[idx] for idx in expected_indices] + placeholders_prop_.return_value = _placeholders + return slide_layout, expected_placeholders + + @pytest.fixture(params=[(), (0,), (1,), (0, 1)]) + def used_by_fixture(self, request, presentation_, slide_, slide_2_): + used_by_idxs = request.param + slides = (slide_, slide_2_) + slide_layout = SlideLayout(None, None) + for idx, s in enumerate(slides): + s.slide_layout = slide_layout if idx in used_by_idxs else None + presentation_.slides = slides + expected_value = tuple(s for i, s in enumerate(slides) if i in used_by_idxs) + return presentation_, slide_layout, expected_value + + # fixture components ----------------------------------- + + @pytest.fixture + def LayoutPlaceholders_(self, request, placeholders_): + return class_mock(request, "pptx.slide.LayoutPlaceholders", return_value=placeholders_) + + @pytest.fixture + def LayoutShapes_(self, request, shapes_): + return class_mock(request, "pptx.slide.LayoutShapes", return_value=shapes_) + + @pytest.fixture + def package_(self, request): + return instance_mock(request, Package) + + @pytest.fixture + def part_prop_(self, request, slide_layout_part_): + return property_mock(request, SlideLayout, "part", return_value=slide_layout_part_) + + @pytest.fixture + def placeholder_(self, request): + return instance_mock(request, LayoutPlaceholder) + + @pytest.fixture + def placeholder_2_(self, request): + return instance_mock(request, LayoutPlaceholder) + + @pytest.fixture + def placeholders_(self, request): + return instance_mock(request, LayoutPlaceholders) + + @pytest.fixture + def placeholders_prop_(self, request, placeholders_): + return property_mock(request, SlideLayout, "placeholders", return_value=placeholders_) + + @pytest.fixture + def presentation_(self, request): + return instance_mock(request, Presentation) + + @pytest.fixture + def presentation_part_(self, request): + return instance_mock(request, PresentationPart) + + @pytest.fixture + def shapes_(self, request): + return instance_mock(request, LayoutShapes) + + @pytest.fixture + def slide_(self, request): + return instance_mock(request, Slide) + + @pytest.fixture + def slide_2_(self, request): + return instance_mock(request, Slide) + + @pytest.fixture + def slide_layout_part_(self, request): + return instance_mock(request, SlideLayoutPart) + + @pytest.fixture + def slide_master_(self, request): + return instance_mock(request, SlideMaster) + + +class DescribeSlideLayouts(object): + """Unit-test suite for `pptx.slide.SlideLayouts` objects.""" + + def it_supports_len(self, len_fixture): + slide_layouts, expected_value = len_fixture + assert len(slide_layouts) == expected_value + + def it_can_iterate_its_slide_layouts(self, part_prop_, slide_master_part_): + sldLayoutIdLst = element("p:sldLayoutIdLst/(p:sldLayoutId{r:id=a},p:sldLayoutId{r:id=b})") + _slide_layouts = [ + SlideLayout(element("p:sldLayout"), None), + SlideLayout(element("p:sldLayout"), None), + ] + part_prop_.return_value = slide_master_part_ + related_slide_layout_ = slide_master_part_.related_slide_layout + related_slide_layout_.side_effect = _slide_layouts + slide_layouts = SlideLayouts(sldLayoutIdLst, None) + + slide_layout_lst = [sl for sl in slide_layouts] + + assert related_slide_layout_.call_args_list == [call("a"), call("b")] + assert slide_layout_lst == _slide_layouts + + def it_supports_indexed_access(self, slide_layout_, part_prop_, slide_master_part_): + part_prop_.return_value = slide_master_part_ + slide_master_part_.related_slide_layout.return_value = slide_layout_ + slide_layouts = SlideLayouts(element("p:sldLayoutIdLst/p:sldLayoutId{r:id=rId1}"), None) + + slide_layout = slide_layouts[0] + + slide_master_part_.related_slide_layout.assert_called_once_with("rId1") + assert slide_layout is slide_layout_ + + def but_it_raises_on_index_out_of_range(self, part_prop_): + slide_layouts = SlideLayouts(element("p:sldLayoutIdLst/p:sldLayoutId{r:id=rId1}"), None) + with pytest.raises(IndexError): + slide_layouts[1] + + def it_can_find_a_slide_layout_by_name(self, _iter_, slide_layout_, slide_layout_2_): + _iter_.return_value = iter((slide_layout_, slide_layout_2_)) + slide_layout_2_.name = "pick me!" + slide_layouts = SlideLayouts(None, None) + + slide_layout = slide_layouts.get_by_name("pick me!") + + assert slide_layout is slide_layout_2_ + + def but_it_returns_the_default_value_when_no_layout_has_that_name( + self, _iter_, slide_layout_, slide_layout_2_ + ): + _iter_.return_value = iter((slide_layout_, slide_layout_2_)) + slide_layout_2_.name = "not the droid you're looking for" + slide_layouts = SlideLayouts(None, None) + + # ---default-default is None--- + slide_layout = slide_layouts.get_by_name("pick me!") + assert slide_layout is None + + # ---but default can be specified--- + slide_layout = slide_layouts.get_by_name("pick me!", "default-value") + assert slide_layout == "default-value" + + def it_knows_the_index_of_each_of_its_slide_layouts( + self, _iter_, slide_layout_, slide_layout_2_ + ): + _iter_.return_value = iter((slide_layout_, slide_layout_2_)) + slide_layouts = SlideLayouts(None, None) + + index = slide_layouts.index(slide_layout_2_) + + assert index == 1 + + def but_it_raises_on_slide_layout_not_in_collection( + self, _iter_, slide_layout_, slide_layout_2_ + ): + _iter_.return_value = iter((slide_layout_,)) + slide_layouts = SlideLayouts(None, None) + + with pytest.raises(ValueError) as e: + slide_layouts.index(slide_layout_2_) + assert str(e.value) == "layout not in this SlideLayouts collection" + + def it_can_remove_an_unused_slide_layout( + self, slide_layout_, index_, slide_master_, slide_master_part_ + ): + slide_layout_.used_by_slides = () + index_.return_value = 0 + sldLayoutIdLst = element( + "p:sldLayoutIdLst/(p:sldLayoutId{r:id=rId1},p:sldLayoutId{r:id=rId2})" + ) + slide_layout_.slide_master = slide_master_ + slide_master_.part = slide_master_part_ + slide_layouts = SlideLayouts(sldLayoutIdLst, None) + + slide_layouts.remove(slide_layout_) + + assert slide_layouts._sldLayoutIdLst.xml == xml("p:sldLayoutIdLst/p:sldLayoutId{r:id=rId2}") + slide_master_part_.drop_rel.assert_called_once_with("rId1") + + def but_it_raises_on_attempt_to_remove_slide_layout_in_use(self, slide_layout_, slide_): + slide_layout_.used_by_slides = (slide_,) + slide_layouts = SlideLayouts(None, None) + + with pytest.raises(ValueError): + slide_layouts.remove(slide_layout_) + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("p:sldLayoutIdLst", 0), + ("p:sldLayoutIdLst/p:sldLayoutId", 1), + ("p:sldLayoutIdLst/(p:sldLayoutId,p:sldLayoutId)", 2), + ] + ) + def len_fixture(self, request): + sldLayoutIdLst_cxml, expected_value = request.param + slide_layouts = SlideLayouts(element(sldLayoutIdLst_cxml), None) + return slide_layouts, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def index_(self, request): + return method_mock(request, SlideLayouts, "index") + + @pytest.fixture + def _iter_(self, request): + return method_mock(request, SlideLayouts, "__iter__") + + @pytest.fixture + def part_prop_(self, request): + return property_mock(request, SlideLayouts, "part") + + @pytest.fixture + def slide_(self, request): + return instance_mock(request, Slide) + + @pytest.fixture + def slide_layout_(self, request): + return instance_mock(request, SlideLayout) + + @pytest.fixture + def slide_layout_2_(self, request): + return instance_mock(request, SlideLayout) + + @pytest.fixture + def slide_master_(self, request): + return instance_mock(request, SlideMaster) + + @pytest.fixture + def slide_master_part_(self, request): + return instance_mock(request, SlideMasterPart) + + +class DescribeSlideMaster(object): + """Unit-test suite for `pptx.slide.SlideMaster` objects.""" + + def it_is_a_BaseMaster_subclass(self, subclass_fixture): + slide_master = subclass_fixture + assert isinstance(slide_master, _BaseMaster) + + def it_provides_access_to_its_slide_layouts(self, layouts_fixture): + slide_master, SlideLayouts_, sldLayoutIdLst, slide_layouts_ = layouts_fixture + slide_layouts = slide_master.slide_layouts + SlideLayouts_.assert_called_once_with(sldLayoutIdLst, slide_master) + assert slide_layouts is slide_layouts_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def layouts_fixture(self, SlideLayouts_, slide_layouts_): + sldMaster = element("p:sldMaster/p:sldLayoutIdLst") + slide_master = SlideMaster(sldMaster, None) + sldMasterIdLst = sldMaster.sldLayoutIdLst + return slide_master, SlideLayouts_, sldMasterIdLst, slide_layouts_ + + @pytest.fixture + def subclass_fixture(self): + return SlideMaster(None, None) + + # fixture components ----------------------------------- + + @pytest.fixture + def SlideLayouts_(self, request, slide_layouts_): + return class_mock(request, "pptx.slide.SlideLayouts", return_value=slide_layouts_) + + @pytest.fixture + def slide_layouts_(self, request): + return instance_mock(request, SlideLayouts) + + +class DescribeSlideMasters(object): + """Unit-test suite for `pptx.slide.SlideMasters` objects.""" + + def it_knows_how_many_masters_it_contains(self, len_fixture): + slide_masters, expected_value = len_fixture + assert len(slide_masters) == expected_value + + def it_can_iterate_the_slide_masters(self, iter_fixture): + slide_masters, related_slide_master_, calls, expected_values = iter_fixture + _slide_masters = [sm for sm in slide_masters] + assert related_slide_master_.call_args_list == calls + assert _slide_masters == expected_values + + def it_supports_indexed_access(self, getitem_fixture): + slide_masters, part_, slide_master_, rId = getitem_fixture + slide_master = slide_masters[0] + part_.related_slide_master.assert_called_once_with(rId) + assert slide_master is slide_master_ + + def it_raises_on_index_out_of_range(self, getitem_raises_fixture): + slides = getitem_raises_fixture + with pytest.raises(IndexError): + slides[1] + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def getitem_fixture(self, part_, slide_master_, part_prop_): + slide_masters = SlideMasters(element("p:sldMasterIdLst/p:sldMasterId{r:id=rId1}"), None) + part_.related_slide_master.return_value = slide_master_ + return slide_masters, part_, slide_master_, "rId1" + + @pytest.fixture + def getitem_raises_fixture(self, part_prop_): + return SlideMasters(element("p:sldMasterIdLst/p:sldMasterId{r:id=rId1}"), None) + + @pytest.fixture + def iter_fixture(self, part_prop_): + sldMasterIdLst = element("p:sldMasterIdLst/(p:sldMasterId{r:id=a},p:sldMasterId{r:id=b})") + slide_masters = SlideMasters(sldMasterIdLst, None) + related_slide_master_ = part_prop_.return_value.related_slide_master + calls = [call("a"), call("b")] + _slide_masters = [ + SlideMaster(element("p:sldMaster"), None), + SlideMaster(element("p:sldMaster"), None), + ] + related_slide_master_.side_effect = _slide_masters + return slide_masters, related_slide_master_, calls, _slide_masters + + @pytest.fixture( + params=[ + ("p:sldMasterIdLst", 0), + ("p:sldMasterIdLst/p:sldMasterId", 1), + ("p:sldMasterIdLst/(p:sldMasterId,p:sldMasterId)", 2), + ] + ) + def len_fixture(self, request): + sldMasterIdLst_cxml, expected_value = request.param + slide_masters = SlideMasters(element(sldMasterIdLst_cxml), None) + return slide_masters, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def part_(self, request): + return instance_mock(request, PresentationPart) + + @pytest.fixture + def part_prop_(self, request, part_): + return property_mock(request, SlideMasters, "part", return_value=part_) + + @pytest.fixture + def slide_master_(self, request): + return instance_mock(request, SlideMaster) + + +class Describe_Background(object): + """Unit-test suite for `pptx.slide._Background` objects.""" + + @pytest.mark.parametrize( + "cSld_xml, expected_cxml", + ( + ("p:cSld{a:b=c}", "p:cSld{a:b=c}/p:bg/p:bgPr/(a:noFill,a:effectLst)"), + ( + "p:cSld{a:b=c}/p:bg/p:bgRef", + "p:cSld{a:b=c}/p:bg/p:bgPr/(a:noFill,a:effectLst)", + ), + ("p:cSld/p:bg/p:bgPr/a:solidFill", "p:cSld/p:bg/p:bgPr/a:solidFill"), + ), + ) + def it_provides_access_to_its_fill(self, request, cSld_xml, expected_cxml): + fill_ = instance_mock(request, FillFormat) + from_fill_parent_ = method_mock( + request, FillFormat, "from_fill_parent", autospec=False, return_value=fill_ + ) + cSld = element(cSld_xml) + background = _Background(cSld) + + fill = background.fill + + assert cSld.xml == xml(expected_cxml) + from_fill_parent_.assert_called_once_with(cSld.xpath("p:bg/p:bgPr")[0]) + assert fill is fill_ diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_table.py b/tasks/tasksmith-74f059424102/environment/source/tests/test_table.py new file mode 100644 index 0000000000000000000000000000000000000000..c53f1261ffbe714078c91c20ef179ed9157b76ed --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_table.py @@ -0,0 +1,800 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.table` module.""" + +from __future__ import annotations + +import pytest + +from pptx.dml.fill import FillFormat +from pptx.enum.text import MSO_ANCHOR +from pptx.oxml.ns import qn +from pptx.oxml.table import CT_Table, CT_TableCell, TcRange +from pptx.shapes.graphfrm import GraphicFrame +from pptx.table import ( + Table, + _Cell, + _CellCollection, + _Column, + _ColumnCollection, + _Row, + _RowCollection, +) +from pptx.text.text import TextFrame +from pptx.util import Inches, Length, Pt + +from .unitutil.cxml import element, xml +from .unitutil.mock import call, class_mock, instance_mock, property_mock + + +class DescribeTable(object): + """Unit-test suite for `pptx.table.Table` objects.""" + + def it_provides_access_to_its_cells(self, tbl_, tc_, _Cell_, cell_): + row_idx, col_idx = 4, 2 + tbl_.tc.return_value = tc_ + _Cell_.return_value = cell_ + table = Table(tbl_, None) + + cell = table.cell(row_idx, col_idx) + + tbl_.tc.assert_called_once_with(row_idx, col_idx) + _Cell_.assert_called_once_with(tc_, table) + assert cell is cell_ + + def it_provides_access_to_its_columns(self, request): + columns_ = instance_mock(request, _ColumnCollection) + _ColumnCollection_ = class_mock( + request, "pptx.table._ColumnCollection", return_value=columns_ + ) + tbl = element("a:tbl") + table = Table(tbl, None) + + columns = table.columns + + _ColumnCollection_.assert_called_once_with(tbl, table) + assert columns is columns_ + + def it_can_iterate_its_grid_cells(self, request, _Cell_): + tbl = element("a:tbl/(a:tr/(a:tc,a:tc),a:tr/(a:tc,a:tc))") + expected_tcs = tbl.xpath(".//a:tc") + expected_cells = _Cell_.side_effect = [ + instance_mock(request, _Cell, name="cell%d" % idx) for idx in range(4) + ] + table = Table(tbl, None) + + cells = list(table.iter_cells()) + + assert cells == expected_cells + assert _Cell_.call_args_list == [call(tc, table) for tc in expected_tcs] + + def it_provides_access_to_its_rows(self, request): + rows_ = instance_mock(request, _RowCollection) + _RowCollection_ = class_mock(request, "pptx.table._RowCollection", return_value=rows_) + tbl = element("a:tbl") + table = Table(tbl, None) + + rows = table.rows + + _RowCollection_.assert_called_once_with(tbl, table) + assert rows is rows_ + + def it_updates_graphic_frame_width_on_width_change(self, dx_fixture): + table, expected_width = dx_fixture + table.notify_width_changed() + assert table._graphic_frame.width == expected_width + + def it_updates_graphic_frame_height_on_height_change(self, dy_fixture): + table, expected_height = dy_fixture + table.notify_height_changed() + assert table._graphic_frame.height == expected_height + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def dx_fixture(self, graphic_frame_): + tbl_cxml = "a:tbl/a:tblGrid/(a:gridCol{w=111},a:gridCol{w=222})" + table = Table(element(tbl_cxml), graphic_frame_) + expected_width = 333 + return table, expected_width + + @pytest.fixture + def dy_fixture(self, graphic_frame_): + tbl_cxml = "a:tbl/(a:tr{h=100},a:tr{h=200})" + table = Table(element(tbl_cxml), graphic_frame_) + expected_height = 300 + return table, expected_height + + # fixture components --------------------------------------------- + + @pytest.fixture + def _Cell_(self, request): + return class_mock(request, "pptx.table._Cell") + + @pytest.fixture + def cell_(self, request): + return instance_mock(request, _Cell) + + @pytest.fixture + def graphic_frame_(self, request): + return instance_mock(request, GraphicFrame) + + @pytest.fixture + def tbl_(self, request): + return instance_mock(request, CT_Table) + + @pytest.fixture + def tc_(self, request): + return instance_mock(request, CT_TableCell) + + +class DescribeTableBooleanProperties(object): + def it_knows_its_boolean_property_settings(self, boolprop_get_fixture): + table, boolprop_name, expected_value = boolprop_get_fixture + boolprop_value = getattr(table, boolprop_name) + assert boolprop_value is expected_value + + def it_can_change_its_boolean_property_settings(self, boolprop_set_fixture): + table, boolprop_name, new_value, expected_xml = boolprop_set_fixture + setattr(table, boolprop_name, new_value) + assert table._tbl.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("a:tbl", "first_row", False), + ("a:tbl/a:tblPr", "first_row", False), + ("a:tbl/a:tblPr{firstRow=1}", "first_row", True), + ("a:tbl/a:tblPr{firstRow=0}", "first_row", False), + ("a:tbl/a:tblPr{firstRow=true}", "first_row", True), + ("a:tbl/a:tblPr{firstRow=false}", "first_row", False), + ("a:tbl/a:tblPr{firstCol=1}", "first_col", True), + ("a:tbl/a:tblPr{lastRow=0}", "last_row", False), + ("a:tbl/a:tblPr{lastCol=true}", "last_col", True), + ("a:tbl/a:tblPr{bandRow=false}", "horz_banding", False), + ("a:tbl/a:tblPr", "vert_banding", False), + ] + ) + def boolprop_get_fixture(self, request): + tbl_cxml, boolprop_name, expected_value = request.param + table = Table(element(tbl_cxml), None) + return table, boolprop_name, expected_value + + @pytest.fixture( + params=[ + ("a:tbl", "first_row", True, "a:tbl/a:tblPr{firstRow=1}"), + ("a:tbl", "first_row", False, "a:tbl/a:tblPr"), + ("a:tbl/a:tblPr", "first_row", True, "a:tbl/a:tblPr{firstRow=1}"), + ("a:tbl/a:tblPr", "first_row", False, "a:tbl/a:tblPr"), + ( + "a:tbl/a:tblPr{firstRow=true}", + "first_row", + True, + "a:tbl/a:tblPr{firstRow=1}", + ), + ("a:tbl/a:tblPr{firstRow=false}", "first_row", False, "a:tbl/a:tblPr"), + ( + "a:tbl/a:tblPr{bandRow=1}", + "first_row", + True, + "a:tbl/a:tblPr{bandRow=1,firstRow=1}", + ), + ("a:tbl", "first_col", True, "a:tbl/a:tblPr{firstCol=1}"), + ("a:tbl", "last_row", True, "a:tbl/a:tblPr{lastRow=1}"), + ("a:tbl", "last_col", True, "a:tbl/a:tblPr{lastCol=1}"), + ("a:tbl", "horz_banding", True, "a:tbl/a:tblPr{bandRow=1}"), + ("a:tbl", "vert_banding", True, "a:tbl/a:tblPr{bandCol=1}"), + ] + ) + def boolprop_set_fixture(self, request): + tbl_cxml, boolprop_name, new_value, expected_tbl_cxml = request.param + table = Table(element(tbl_cxml), None) + expected_xml = xml(expected_tbl_cxml) + return table, boolprop_name, new_value, expected_xml + + +class Describe_Cell(object): + """Unit-test suite for `pptx.table._Cell` object.""" + + def it_is_equal_to_other_instance_having_same_tc(self): + tc = element("a:tc") + other_tc = element("a:tc") + cell = _Cell(tc, None) + cell_with_same_tc = _Cell(tc, None) + cell_with_other_tc = _Cell(other_tc, None) + + assert cell == cell_with_same_tc + assert cell != cell_with_other_tc + + def it_has_a_fill(self, fill_fixture): + cell = fill_fixture + assert isinstance(cell.fill, FillFormat) + + def it_knows_whether_it_is_merge_origin_cell(self, origin_fixture): + tc, expected_value = origin_fixture + cell = _Cell(tc, None) + + is_merge_origin = cell.is_merge_origin + + assert is_merge_origin is expected_value + + def it_knows_whether_it_is_spanned(self, spanned_fixture): + tc, expected_value = spanned_fixture + cell = _Cell(tc, None) + + is_spanned = cell.is_spanned + + assert is_spanned is expected_value + + def it_knows_its_margin_settings(self, margin_get_fixture): + cell, margin_prop_name, expected_value = margin_get_fixture + margin_value = getattr(cell, margin_prop_name) + assert margin_value == expected_value + + def it_can_change_its_margin_settings(self, margin_set_fixture): + cell, margin_prop_name, new_value, expected_xml = margin_set_fixture + setattr(cell, margin_prop_name, new_value) + assert cell._tc.xml == expected_xml + + def it_raises_on_margin_assigned_other_than_int_or_None(self, margin_raises_fixture): + cell, margin_attr_name, val_of_invalid_type = margin_raises_fixture + with pytest.raises(TypeError): + setattr(cell, margin_attr_name, val_of_invalid_type) + + def it_can_merge_a_range_of_cells(self, TcRange_, tc_range_): + tbl = element("a:tbl/(a:tr/(a:tc,a:tc),a:tr/(a:tc,a:tc))") + tc, other_tc = tbl.tc(0, 0), tbl.tc(1, 1) + TcRange_.return_value = tc_range_ + tc_range_.contains_merged_cell = False + tc_range_.dimensions = 2, 2 + + def tcs(*rowcols): + return (tbl.tc(*rowcol) for rowcol in rowcols) + + tc_range_.iter_top_row_tcs.return_value = tcs((0, 0), (0, 1)) + tc_range_.iter_left_col_tcs.return_value = tcs((0, 0), (1, 0)) + tc_range_.iter_except_left_col_tcs.return_value = tcs((0, 1), (1, 1)) + tc_range_.iter_except_top_row_tcs.return_value = tcs((1, 0), (1, 1)) + expected_xml = xml( + "a:tbl/(a:tr/(a:tc{gridSpan=2,rowSpan=2},a:tc{rowSpan=2,hMerge=1" + "}),a:tr/(a:tc{gridSpan=2,vMerge=1},a:tc{hMerge=1,vMerge=1}))" + ) + cell, other_cell = _Cell(tc, None), _Cell(other_tc, None) + + cell.merge(other_cell) + + TcRange_.assert_called_once_with(tc, other_tc) + tc_range_.move_content_to_origin.assert_called_once_with() + assert tbl.xml == expected_xml + + def but_it_raises_when_cells_are_from_different_tables(self, TcRange_, tc_range_): + TcRange_.return_value = tc_range_ + tc_range_.in_same_table = False + cell, other_cell = _Cell(None, None), _Cell(None, None) + + with pytest.raises(ValueError) as e: + cell.merge(other_cell) + assert "different table" in str(e.value) + + def and_it_raises_when_range_contains_merged_cell(self, TcRange_, tc_range_): + TcRange_.return_value = tc_range_ + tc_range_.contains_merged_cell = True + cell, other_cell = _Cell(None, None), _Cell(None, None) + + with pytest.raises(ValueError) as e: + cell.merge(other_cell) + assert "contains one or more merged cells" in str(e.value) + + def it_knows_how_many_rows_the_merge_spans(self, height_fixture): + tc, expected_value = height_fixture + cell = _Cell(tc, None) + span_height = cell.span_height + assert span_height == expected_value + + def it_knows_how_many_columns_the_merge_spans(self, width_fixture): + tc, expected_value = width_fixture + cell = _Cell(tc, None) + span_width = cell.span_width + assert span_width == expected_value + + def it_can_split_a_merged_cell(self, split_fixture): + origin_tc, range_tcs = split_fixture + cell = _Cell(origin_tc, None) + + cell.split() + + assert all(tc.gridSpan == 1 for tc in range_tcs) + assert all(tc.rowSpan == 1 for tc in range_tcs) + assert all(not tc.hMerge for tc in range_tcs) + assert all(not tc.vMerge for tc in range_tcs) + + def but_it_raises_when_cell_to_be_split_is_not_merge_origin(self): + tc = element("a:tbl/a:tr/a:tc").xpath("//a:tc")[0] + cell = _Cell(tc, None) + + with pytest.raises(ValueError) as e: + cell.split() + assert "not a merge-origin cell" in str(e.value) + + def it_knows_what_text_it_contains(self, text_frame_prop_, text_frame_): + text_frame_prop_.return_value = text_frame_ + text_frame_.text = "foobar" + cell = _Cell(None, None) + + text = cell.text + + assert text == "foobar" + + def it_can_change_its_text(self, text_frame_prop_, text_frame_): + text_frame_prop_.return_value = text_frame_ + cell = _Cell(None, None) + + cell.text = "føøbår" + + assert text_frame_.text == "føøbår" + + def it_knows_its_vertical_anchor_setting(self, anchor_get_fixture): + cell, expected_value = anchor_get_fixture + assert cell.vertical_anchor == expected_value + + def it_can_change_its_vertical_anchor(self, anchor_set_fixture): + cell, new_value, expected_xml = anchor_set_fixture + cell.vertical_anchor = new_value + assert cell._tc.xml == expected_xml + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + ("a:tc", None), + ("a:tc/a:tcPr", None), + ("a:tc/a:tcPr{anchor=t}", MSO_ANCHOR.TOP), + ("a:tc/a:tcPr{anchor=ctr}", MSO_ANCHOR.MIDDLE), + ("a:tc/a:tcPr{anchor=b}", MSO_ANCHOR.BOTTOM), + ] + ) + def anchor_get_fixture(self, request): + tc_cxml, expected_value = request.param + cell = _Cell(element(tc_cxml), None) + return cell, expected_value + + @pytest.fixture( + params=[ + ("a:tc", None, "a:tc"), + ("a:tc", MSO_ANCHOR.TOP, "a:tc/a:tcPr{anchor=t}"), + ("a:tc", MSO_ANCHOR.MIDDLE, "a:tc/a:tcPr{anchor=ctr}"), + ("a:tc", MSO_ANCHOR.BOTTOM, "a:tc/a:tcPr{anchor=b}"), + ("a:tc/a:tcPr{anchor=t}", MSO_ANCHOR.MIDDLE, "a:tc/a:tcPr{anchor=ctr}"), + ("a:tc/a:tcPr{anchor=ctr}", None, "a:tc/a:tcPr"), + ] + ) + def anchor_set_fixture(self, request): + tc_cxml, new_value, expected_tc_cxml = request.param + cell = _Cell(element(tc_cxml), None) + expected_xml = xml(expected_tc_cxml) + return cell, new_value, expected_xml + + @pytest.fixture + def fill_fixture(self, cell): + return cell + + @pytest.fixture(params=[("a:tc", 1), ("a:tc{gridSpan=2}", 1), ("a:tc{rowSpan=42}", 42)]) + def height_fixture(self, request): + tc_cxml, expected_value = request.param + tc = element(tc_cxml) + return tc, expected_value + + @pytest.fixture( + params=[ + ("a:tc/a:tcPr{marL=82296}", "margin_left", Inches(0.09)), + ("a:tc/a:tcPr{marR=73152}", "margin_right", Inches(0.08)), + ("a:tc/a:tcPr{marT=64008}", "margin_top", Inches(0.07)), + ("a:tc/a:tcPr{marB=54864}", "margin_bottom", Inches(0.06)), + ("a:tc", "margin_left", Inches(0.1)), + ("a:tc/a:tcPr", "margin_right", Inches(0.1)), + ("a:tc", "margin_top", Inches(0.05)), + ("a:tc/a:tcPr", "margin_bottom", Inches(0.05)), + ] + ) + def margin_get_fixture(self, request): + tc_cxml, margin_prop_name, expected_value = request.param + cell = _Cell(element(tc_cxml), None) + return cell, margin_prop_name, expected_value + + @pytest.fixture( + params=[ + ("a:tc", "margin_left", Inches(0.08), "a:tc/a:tcPr{marL=73152}"), + ("a:tc", "margin_right", Inches(0.08), "a:tc/a:tcPr{marR=73152}"), + ("a:tc", "margin_top", Inches(0.08), "a:tc/a:tcPr{marT=73152}"), + ("a:tc", "margin_bottom", Inches(0.08), "a:tc/a:tcPr{marB=73152}"), + ("a:tc", "margin_left", None, "a:tc"), + ("a:tc/a:tcPr{marL=42}", "margin_left", None, "a:tc/a:tcPr"), + ] + ) + def margin_set_fixture(self, request): + tc_cxml, margin_prop_name, new_value, expected_tc_cxml = request.param + cell = _Cell(element(tc_cxml), None) + expected_xml = xml(expected_tc_cxml) + return cell, margin_prop_name, new_value, expected_xml + + @pytest.fixture(params=["margin_left", "margin_right", "margin_top", "margin_bottom"]) + def margin_raises_fixture(self, request): + margin_prop_name = request.param + cell = _Cell(element("a:tc"), None) + val_of_invalid_type = "foobar" + return cell, margin_prop_name, val_of_invalid_type + + @pytest.fixture( + params=[ + ("a:tc", False), + ("a:tc{gridSpan=1}", False), + ("a:tc{hMerge=1}", False), + ("a:tc{gridSpan=2,vMerge=1}", False), + ("a:tc{gridSpan=2}", True), + ("a:tc{rowSpan=2}", True), + ("a:tc{gridSpan=2,rowSpan=3}", True), + ] + ) + def origin_fixture(self, request): + tc_cxml, expected_value = request.param + tc = element(tc_cxml) + return tc, expected_value + + @pytest.fixture( + params=[ + ("a:tc", False), + ("a:tc{gridSpan=2}", False), + ("a:tc{hMerge=1}", True), + ("a:tc{gridSpan=2,vMerge=1}", True), + ("a:tc{rowSpan=2,hMerge=true}", True), + ("a:tc{gridSpan=2,rowSpan=3}", False), + ] + ) + def spanned_fixture(self, request): + tc_cxml, expected_value = request.param + tc = element(tc_cxml) + return tc, expected_value + + @pytest.fixture( + params=[ + ( + "a:tbl/(a:tr/(a:tc{gridSpan=2},a:tc{hMerge=1}),a:tr/(a:tc,a:tc))", + 0, + [0, 1], + ), + ( + "a:tbl/(a:tr/(a:tc{rowSpan=2},a:tc),a:tr/(a:tc{vMerge=1},a:tc))", + 0, + [0, 2], + ), + ( + "a:tbl/(a:tr/(a:tc{gridSpan=2,rowSpan=2},a:tc{hMerge=1,rowSpan=2})," + "a:tr/(a:tc{gridSpan=2,vMerge=1},a:tc{hMerge=1,vMerge=1}))", + 0, + [0, 1, 2, 3], + ), + ] + ) + def split_fixture(self, request): + tbl_cxml, origin_tc_idx, range_tc_idxs = request.param + tcs = element(tbl_cxml).xpath("//a:tc") + origin_tc = tcs[origin_tc_idx] + range_tcs = tuple(tcs[idx] for idx in range_tc_idxs) + return origin_tc, range_tcs + + @pytest.fixture(params=[("a:tc", 1), ("a:tc{rowSpan=2}", 1), ("a:tc{gridSpan=24}", 24)]) + def width_fixture(self, request): + tc_cxml, expected_value = request.param + tc = element(tc_cxml) + return tc, expected_value + + # fixture components --------------------------------------------- + + @pytest.fixture + def cell(self): + return _Cell(element("a:tc"), None) + + @pytest.fixture + def TcRange_(self, request): + return class_mock(request, "pptx.table.TcRange") + + @pytest.fixture + def tc_range_(self, request): + return instance_mock(request, TcRange) + + @pytest.fixture + def text_frame_(self, request): + return instance_mock(request, TextFrame) + + @pytest.fixture + def text_frame_prop_(self, request): + return property_mock(request, _Cell, "text_frame") + + +class Describe_CellCollection(object): + def it_knows_how_many_cells_it_contains(self, len_fixture): + cells, expected_count = len_fixture + assert len(cells) == expected_count + + def it_can_iterate_over_the_cells_it_contains(self, iter_fixture): + cell_collection, _Cell_, calls, expected_cells = iter_fixture + + cells = list(cell_collection) + + assert _Cell_.call_args_list == calls + assert cells == expected_cells + + def it_supports_indexed_access(self, _Cell_, cell_): + tr = element("a:tr/(a:tc, a:tc, a:tc)") + tcs = tr.xpath("//a:tc") + _Cell_.return_value = cell_ + cell_collection = _CellCollection(tr, None) + + cell = cell_collection[1] + + _Cell_.assert_called_once_with(tcs[1], cell_collection) + assert cell is cell_ + + def it_raises_on_indexed_access_out_of_range(self): + cells = _CellCollection(element("a:tr/a:tc"), None) + with pytest.raises(IndexError): + cells[-1] + with pytest.raises(IndexError): + cells[9] + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=["a:tr", "a:tr/a:tc", "a:tr/(a:tc, a:tc, a:tc)"]) + def iter_fixture(self, request, _Cell_): + tr_cxml = request.param + tr = element(tr_cxml) + tcs = tr.xpath("//a:tc") + cell_collection = _CellCollection(tr, None) + + expected_cells = [ + instance_mock(request, _Cell, name="cell%d" % idx) for idx in range(len(tcs)) + ] + _Cell_.side_effect = expected_cells + calls = [call(tc, cell_collection) for tc in tcs] + + return cell_collection, _Cell_, calls, expected_cells + + @pytest.fixture(params=[("a:tr", 0), ("a:tr/a:tc", 1), ("a:tr/(a:tc, a:tc)", 2)]) + def len_fixture(self, request): + tr_cxml, expected_len = request.param + cells = _CellCollection(element(tr_cxml), None) + return cells, expected_len + + # fixture components --------------------------------------------- + + @pytest.fixture + def _Cell_(self, request): + return class_mock(request, "pptx.table._Cell") + + @pytest.fixture + def cell_(self, request): + return instance_mock(request, _Cell) + + +class Describe_Column(object): + def it_knows_its_width(self, width_get_fixture): + column, expected_value = width_get_fixture + width = column.width + assert width == expected_value + assert isinstance(width, Length) + + def it_can_change_its_width(self, width_set_fixture): + column, new_width, expected_xml, parent_ = width_set_fixture + column.width = new_width + assert column._gridCol.xml == expected_xml + parent_.notify_width_changed.assert_called_once_with() + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=[("a:gridCol{w=914400}", Inches(1)), ("a:gridCol{w=10pt}", Pt(10))]) + def width_get_fixture(self, request): + gridCol_cxml, expected_value = request.param + column = _Column(element(gridCol_cxml), None) + return column, expected_value + + @pytest.fixture( + params=[ + ("a:gridCol{w=12pt}", Inches(1), "a:gridCol{w=914400}"), + ("a:gridCol{w=1234}", Inches(1), "a:gridCol{w=914400}"), + ] + ) + def width_set_fixture(self, request, parent_): + gridCol_cxml, new_width, expected_gridCol_cxml = request.param + column = _Column(element(gridCol_cxml), parent_) + expected_xml = xml(expected_gridCol_cxml) + return column, new_width, expected_xml, parent_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def parent_(self, request): + return instance_mock(request, _ColumnCollection) + + +class Describe_ColumnCollection(object): + def it_knows_how_many_columns_it_contains(self, len_fixture): + columns, expected_count = len_fixture + assert len(columns) == expected_count + + def it_can_iterate_over_the_columns_it_contains(self, iter_fixture): + columns, expected_gridCol_lst = iter_fixture + count = 0 + for idx, column in enumerate(columns): + assert isinstance(column, _Column) + assert column._gridCol is expected_gridCol_lst[idx] + count += 1 + assert count == len(expected_gridCol_lst) + + def it_supports_indexed_access(self, getitem_fixture): + columns, expected_gridCol_lst = getitem_fixture + for idx, gridCol in enumerate(expected_gridCol_lst): + column = columns[idx] + assert isinstance(column, _Column) + assert column._gridCol is gridCol + + def it_raises_on_indexed_access_out_of_range(self): + columns = _ColumnCollection(element("a:tbl/a:tblGrid/a:gridCol"), None) + with pytest.raises(IndexError): + columns[-1] + with pytest.raises(IndexError): + columns[9] + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + "a:tbl/a:tblGrid", + "a:tbl/a:tblGrid/a:gridCol", + "a:tbl/a:tblGrid/(a:gridCol, a:gridCol, a:gridCol)", + ] + ) + def getitem_fixture(self, request): + tbl_cxml = request.param + tbl = element(tbl_cxml) + columns = _ColumnCollection(tbl, None) + expected_column_lst = tbl.xpath("//a:gridCol") + return columns, expected_column_lst + + @pytest.fixture( + params=[ + "a:tbl/a:tblGrid", + "a:tbl/a:tblGrid/a:gridCol", + "a:tbl/a:tblGrid/(a:gridCol, a:gridCol, a:gridCol)", + ] + ) + def iter_fixture(self, request): + tbl_cxml = request.param + tbl = element(tbl_cxml) + columns = _ColumnCollection(tbl, None) + expected_column_lst = tbl.xpath("//a:gridCol") + return columns, expected_column_lst + + @pytest.fixture( + params=[ + ("a:tbl/a:tblGrid", 0), + ("a:tbl/a:tblGrid/a:gridCol", 1), + ("a:tbl/a:tblGrid/(a:gridCol,a:gridCol)", 2), + ] + ) + def len_fixture(self, request): + tbl_cxml, expected_len = request.param + columns = _ColumnCollection(element(tbl_cxml), None) + return columns, expected_len + + +class Describe_Row(object): + def it_knows_its_height(self, height_get_fixture): + row, expected_value = height_get_fixture + height = row.height + assert height == expected_value + assert isinstance(height, Length) + + def it_can_change_its_height(self, height_set_fixture): + row, new_height, expected_xml, parent_ = height_set_fixture + row.height = new_height + assert row._tr.xml == expected_xml + parent_.notify_height_changed.assert_called_once_with() + + def it_provides_access_to_its_cells(self, cells_fixture): + row, _CellCollection_, cells_ = cells_fixture + cells = row.cells + _CellCollection_.assert_called_once_with(row._tr, row) + assert cells is cells_ + + # fixtures ------------------------------------------------------- + + @pytest.fixture + def cells_fixture(self, _CellCollection_, cells_): + row = _Row(element("a:tr"), None) + return row, _CellCollection_, cells_ + + @pytest.fixture(params=[("a:tr{h=914400}", Inches(1)), ("a:tr{h=10pt}", Pt(10))]) + def height_get_fixture(self, request): + tr_cxml, expected_value = request.param + row = _Row(element(tr_cxml), None) + return row, expected_value + + @pytest.fixture( + params=[ + ("a:tr{h=12pt}", Inches(1), "a:tr{h=914400}"), + ("a:tr{h=1234}", Inches(1), "a:tr{h=914400}"), + ] + ) + def height_set_fixture(self, request, parent_): + tr_cxml, new_height, expected_tr_cxml = request.param + row = _Row(element(tr_cxml), parent_) + expected_xml = xml(expected_tr_cxml) + return row, new_height, expected_xml, parent_ + + # fixture components --------------------------------------------- + + @pytest.fixture + def _CellCollection_(self, request, cells_): + return class_mock(request, "pptx.table._CellCollection", return_value=cells_) + + @pytest.fixture + def cells_(self, request): + return instance_mock(request, _CellCollection) + + @pytest.fixture + def parent_(self, request): + return instance_mock(request, _RowCollection) + + +class Describe_RowCollection(object): + def it_knows_how_many_rows_it_contains(self, len_fixture): + rows, expected_count = len_fixture + assert len(rows) == expected_count + + def it_can_iterate_over_the_rows_it_contains(self, iter_fixture): + rows, expected_tr_lst = iter_fixture + count = 0 + for idx, row in enumerate(rows): + assert isinstance(row, _Row) + assert row._tr is expected_tr_lst[idx] + count += 1 + assert count == len(expected_tr_lst) + + def it_supports_indexed_access(self, getitem_fixture): + rows, expected_tr_lst = getitem_fixture + for idx, tr in enumerate(expected_tr_lst): + row = rows[idx] + assert isinstance(row, _Row) + assert row._tr is tr + + def it_raises_on_indexed_access_out_of_range(self): + rows = _RowCollection(element("a:tbl/a:tr"), None) + with pytest.raises(IndexError): + rows[-1] + with pytest.raises(IndexError): + rows[9] + + # fixtures ------------------------------------------------------- + + @pytest.fixture(params=["a:tbl", "a:tbl/a:tr", "a:tbl/(a:tr, a:tr, a:tr)"]) + def getitem_fixture(self, request): + tbl_cxml = request.param + tbl = element(tbl_cxml) + rows = _RowCollection(tbl, None) + expected_row_lst = tbl.findall(qn("a:tr")) + return rows, expected_row_lst + + @pytest.fixture(params=["a:tbl", "a:tbl/a:tr", "a:tbl/(a:tr, a:tr, a:tr)"]) + def iter_fixture(self, request): + tbl_cxml = request.param + tbl = element(tbl_cxml) + rows = _RowCollection(tbl, None) + expected_row_lst = tbl.findall(qn("a:tr")) + return rows, expected_row_lst + + @pytest.fixture(params=[("a:tbl", 0), ("a:tbl/a:tr", 1), ("a:tbl/(a:tr, a:tr)", 2)]) + def len_fixture(self, request): + tbl_cxml, expected_len = request.param + rows = _RowCollection(element(tbl_cxml), None) + return rows, expected_len diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/test_util.py b/tasks/tasksmith-74f059424102/environment/source/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..97e46fa4c48b526c785a2432648b4f42565a5a37 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/test_util.py @@ -0,0 +1,52 @@ +"""Unit-test suite for `pptx.util` module.""" + +from __future__ import annotations + +import pytest + +from pptx.util import Centipoints, Cm, Emu, Inches, Length, Mm, Pt + + +class DescribeLength(object): + def it_can_construct_from_convenient_units(self, construct_fixture): + UnitCls, units_val, emu = construct_fixture + length = UnitCls(units_val) + assert isinstance(length, Length) + assert length == emu + + def it_can_self_convert_to_convenient_units(self, units_fixture): + emu, units_prop_name, expected_length_in_units = units_fixture + length = Length(emu) + length_in_units = getattr(length, units_prop_name) + assert length_in_units == expected_length_in_units + + # fixtures ------------------------------------------------------- + + @pytest.fixture( + params=[ + (Length, 914400, 914400), + (Inches, 1.1, 1005840), + (Centipoints, 12.5, 1587), + (Cm, 2.53, 910799), + (Emu, 9144.9, 9144), + (Mm, 13.8, 496800), + (Pt, 24.5, 311150), + ] + ) + def construct_fixture(self, request): + UnitCls, units_val, emu = request.param + return UnitCls, units_val, emu + + @pytest.fixture( + params=[ + (914400, "inches", 1.0), + (914400, "centipoints", 7200.0), + (914400, "cm", 2.54), + (914400, "emu", 914400), + (914400, "mm", 25.4), + (914400, "pt", 72.0), + ] + ) + def units_fixture(self, request): + emu, units_prop_name, expected_length_in_units = request.param + return emu, units_prop_name, expected_length_in_units diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/text/__init__.py b/tasks/tasksmith-74f059424102/environment/source/tests/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/text/test_fonts.py b/tasks/tasksmith-74f059424102/environment/source/tests/text/test_fonts.py new file mode 100644 index 0000000000000000000000000000000000000000..995c78dd202322d5feed5ae29f9dc7242cdaa766 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/text/test_fonts.py @@ -0,0 +1,702 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.text.fonts` module.""" + +from __future__ import annotations + +import io +from struct import calcsize + +import pytest + +from pptx.text.fonts import ( + FontFiles, + _BaseTable, + _Font, + _HeadTable, + _NameTable, + _Stream, + _TableFactory, +) + +from ..unitutil.file import test_file_dir, testfile +from ..unitutil.mock import ( + call, + class_mock, + function_mock, + initializer_mock, + instance_mock, + method_mock, + open_mock, + property_mock, + var_mock, +) + + +class DescribeFontFiles(object): + """Unit-test suite for `pptx.text.fonts.FontFiles` object.""" + + def it_can_find_a_system_font_file(self, find_fixture): + family_name, is_bold, is_italic, expected_path = find_fixture + path = FontFiles.find(family_name, is_bold, is_italic) + assert path == expected_path + + def it_catalogs_the_system_fonts_to_help_find(self, installed_fixture): + expected_call_args, expected_values = installed_fixture + installed_fonts = FontFiles._installed_fonts() + assert FontFiles._iter_font_files_in.call_args_list == (expected_call_args) + assert installed_fonts == expected_values + + def it_generates_font_dirs_to_help_find(self, font_dirs_fixture): + expected_values = font_dirs_fixture + font_dirs = FontFiles._font_directories() + assert font_dirs == expected_values + + def it_knows_os_x_font_dirs_to_help_find(self, osx_dirs_fixture): + expected_dirs = osx_dirs_fixture + font_dirs = FontFiles._os_x_font_directories() + assert font_dirs == expected_dirs + + def it_knows_windows_font_dirs_to_help_find(self, win_dirs_fixture): + expected_dirs = win_dirs_fixture + font_dirs = FontFiles._windows_font_directories() + assert font_dirs == expected_dirs + + def it_iterates_over_fonts_in_dir_to_help_find(self, iter_fixture): + directory, _Font_, expected_calls, expected_paths = iter_fixture + + paths = list(FontFiles._iter_font_files_in(directory)) + + assert _Font_.open.call_args_list == expected_calls + assert paths == expected_paths + + # fixtures --------------------------------------------- + + @pytest.fixture( + params=[ + ("Foobar", False, False, "foobar.ttf"), + ("Foobar", True, False, "foobarb.ttf"), + ("Barfoo", False, True, "barfooi.ttf"), + ] + ) + def find_fixture(self, request, _installed_fonts_): + family_name, is_bold, is_italic, expected_path = request.param + return family_name, is_bold, is_italic, expected_path + + @pytest.fixture(params=[("darwin", ["a", "b"]), ("win32", ["c", "d"])]) + def font_dirs_fixture(self, request, _os_x_font_directories_, _windows_font_directories_): + platform, expected_dirs = request.param + dirs_meth_mock = { + "darwin": _os_x_font_directories_, + "win32": _windows_font_directories_, + }[platform] + sys_ = var_mock(request, "pptx.text.fonts.sys") + sys_.platform = platform + dirs_meth_mock.return_value = expected_dirs + return expected_dirs + + @pytest.fixture + def installed_fixture(self, _iter_font_files_in_, _font_directories_): + _font_directories_.return_value = ["d", "d_2"] + _iter_font_files_in_.side_effect = [ + [(("A", True, False), "a.ttf")], + [(("B", False, True), "b.ttf")], + ] + expected_call_args = [call("d"), call("d_2")] + expected_values = {("A", True, False): "a.ttf", ("B", False, True): "b.ttf"} + return expected_call_args, expected_values + + @pytest.fixture + def iter_fixture(self, _Font_): + directory = test_file_dir + font_file_path = testfile("calibriz.ttf") + font = _Font_.open.return_value.__enter__.return_value + font.family_name, font.is_bold, font.is_italic = "Arial", True, True + expected_calls = [call(font_file_path)] + expected_paths = [(("Arial", True, True), font_file_path)] + return directory, _Font_, expected_calls, expected_paths + + @pytest.fixture + def osx_dirs_fixture(self, request): + import os + + os_ = var_mock(request, "pptx.text.fonts.os") + os_.path = os.path + os_.environ = {"HOME": "/Users/fbar"} + return [ + "/Library/Fonts", + "/Network/Library/Fonts", + "/System/Library/Fonts", + "/Users/fbar/Library/Fonts", + "/Users/fbar/.fonts", + ] + + @pytest.fixture + def win_dirs_fixture(self, request): + return [r"C:\Windows\Fonts"] + + # fixture components ----------------------------------- + + @pytest.fixture + def _Font_(self, request): + return class_mock(request, "pptx.text.fonts._Font") + + @pytest.fixture + def _font_directories_(self, request): + return method_mock(request, FontFiles, "_font_directories", autospec=False) + + @pytest.fixture + def _installed_fonts_(self, request): + return method_mock( + request, + FontFiles, + "_installed_fonts", + autospec=False, + return_value={ + ("Foobar", False, False): "foobar.ttf", + ("Foobar", True, False): "foobarb.ttf", + ("Barfoo", False, True): "barfooi.ttf", + }, + ) + + @pytest.fixture + def _iter_font_files_in_(self, request): + return method_mock(request, FontFiles, "_iter_font_files_in", autospec=False) + + @pytest.fixture + def _os_x_font_directories_(self, request): + return method_mock(request, FontFiles, "_os_x_font_directories", autospec=False) + + @pytest.fixture + def _windows_font_directories_(self, request): + return method_mock(request, FontFiles, "_windows_font_directories", autospec=False) + + +class Describe_Font(object): + """Unit-test suite for `pptx.text.fonts._Font` object.""" + + def it_can_construct_from_a_font_file_path(self, open_fixture): + path, _Stream_, stream_ = open_fixture + with _Font.open(path) as f: + _Stream_.open.assert_called_once_with(path) + assert isinstance(f, _Font) + stream_.close.assert_called_once_with() + + def it_knows_its_family_name(self, family_fixture): + font, expected_name = family_fixture + family_name = font.family_name + assert family_name == expected_name + + def it_knows_whether_it_is_bold(self, bold_fixture): + font, expected_value = bold_fixture + assert font.is_bold is expected_value + + def it_knows_whether_it_is_italic(self, italic_fixture): + font, expected_value = italic_fixture + assert font.is_italic is expected_value + + def it_provides_access_to_its_tables(self, tables_fixture): + font, _TableFactory_, expected_calls, expected_tables = tables_fixture + tables = font._tables + assert _TableFactory_.call_args_list == expected_calls + assert tables == expected_tables + + def it_generates_table_records_to_help_read_tables(self, iter_fixture): + font, expected_values = iter_fixture + values = list(font._iter_table_records()) + assert values == expected_values + + def it_knows_the_table_count_to_help_read(self, table_count_fixture): + font, expected_value = table_count_fixture + assert font._table_count == expected_value + + def it_reads_the_header_to_help_read_font(self, request): + stream_ = instance_mock(request, _Stream) + stream_.read_fields.return_value = ("foob", 42, 64, 7, 16) + font = _Font(stream_) + + fields = font._fields + + stream_.read_fields.assert_called_once_with(">4sHHHH", 0) + assert fields == ("foob", 42, 64, 7, 16) + + # fixtures --------------------------------------------- + + @pytest.fixture(params=[("head", True, True), ("head", False, False), ("foob", True, False)]) + def bold_fixture(self, request, _tables_, head_table_): + key, is_bold, expected_value = request.param + head_table_.is_bold = is_bold + _tables_.return_value = {key: head_table_} + font = _Font(None) + return font, expected_value + + @pytest.fixture + def family_fixture(self, _tables_, name_table_): + font = _Font(None) + expected_name = "Foobar" + _tables_.return_value = {"name": name_table_} + name_table_.family_name = expected_name + return font, expected_name + + @pytest.fixture(params=[("head", True, True), ("head", False, False), ("foob", True, False)]) + def italic_fixture(self, request, _tables_, head_table_): + key, is_italic, expected_value = request.param + head_table_.is_italic = is_italic + _tables_.return_value = {key: head_table_} + font = _Font(None) + return font, expected_value + + @pytest.fixture + def iter_fixture(self, _table_count_, stream_read_): + stream = _Stream(None) + font = _Font(stream) + _table_count_.return_value = 2 + stream_read_.return_value = ( + b"name" + b"xxxx" + b"\x00\x00\x00\x2A" + b"\x00\x00\x00\x15" + b"head" + b"xxxx" + b"\x00\x00\x00\x15" + b"\x00\x00\x00\x2A" + ) + expected_values = [("name", 42, 21), ("head", 21, 42)] + return font, expected_values + + @pytest.fixture + def open_fixture(self, _Stream_): + path = "foobar.ttf" + stream_ = _Stream_.open.return_value + return path, _Stream_, stream_ + + @pytest.fixture + def tables_fixture( + self, stream_, name_table_, head_table_, _iter_table_records_, _TableFactory_ + ): + font = _Font(stream_) + _iter_table_records_.return_value = iter([("name", 11, 22), ("head", 33, 44)]) + _TableFactory_.side_effect = [name_table_, head_table_] + + expected_calls = [call("name", stream_, 11, 22), call("head", stream_, 33, 44)] + expected_tables = {"name": name_table_, "head": head_table_} + return font, _TableFactory_, expected_calls, expected_tables + + @pytest.fixture + def table_count_fixture(self, _fields_): + font = _Font(None) + _fields_.return_value = (-666, 42) + expected_value = 42 + return font, expected_value + + # fixture components ----------------------------------- + + @pytest.fixture + def _fields_(self, request): + return property_mock(request, _Font, "_fields") + + @pytest.fixture + def head_table_(self, request): + return instance_mock(request, _HeadTable) + + @pytest.fixture + def _iter_table_records_(self, request): + return method_mock(request, _Font, "_iter_table_records") + + @pytest.fixture + def name_table_(self, request): + return instance_mock(request, _NameTable) + + @pytest.fixture + def _Stream_(self, request): + return class_mock(request, "pptx.text.fonts._Stream") + + @pytest.fixture + def stream_(self, request): + return instance_mock(request, _Stream) + + @pytest.fixture + def stream_read_(self, request): + return method_mock(request, _Stream, "read") + + @pytest.fixture + def _TableFactory_(self, request): + return function_mock(request, "pptx.text.fonts._TableFactory") + + @pytest.fixture + def _table_count_(self, request): + return property_mock(request, _Font, "_table_count") + + @pytest.fixture + def _tables_(self, request): + return property_mock(request, _Font, "_tables") + + +class Describe_Stream(object): + """Unit-test suite for `pptx.text.fonts._Stream` object.""" + + def it_can_construct_from_a_path(self, request): + open_ = open_mock(request, "pptx.text.fonts") + _init_ = initializer_mock(request, _Stream) + file_ = open_.return_value + + stream = _Stream.open("foobar.ttf") + + open_.assert_called_once_with("foobar.ttf", "rb") + _init_.assert_called_once_with(stream, file_) + assert isinstance(stream, _Stream) + + def it_can_be_closed(self, close_fixture): + stream, file_ = close_fixture + stream.close() + file_.close.assert_called_once_with() + + def it_can_read_fields_from_a_template(self, read_flds_fixture): + stream, tmpl, offset, file_, expected_values = read_flds_fixture + fields = stream.read_fields(tmpl, offset) + file_.seek.assert_called_once_with(offset) + file_.read.assert_called_once_with(calcsize(tmpl)) + assert fields == expected_values + + def it_can_read_bytes(self, read_fixture): + stream, offset, length, file_, expected_value = read_fixture + bytes_ = stream.read(offset, length) + file_.seek.assert_called_once_with(offset) + file_.read.assert_called_once_with(length) + assert bytes_ == expected_value + + # fixtures --------------------------------------------- + + @pytest.fixture + def close_fixture(self, file_): + stream = _Stream(file_) + return stream, file_ + + @pytest.fixture + def read_fixture(self, file_): + stream = _Stream(file_) + offset, length = 42, 21 + file_.read.return_value = "foobar" + expected_value = "foobar" + return stream, offset, length, file_, expected_value + + @pytest.fixture + def read_flds_fixture(self, file_): + stream = _Stream(file_) + tmpl, offset = b">4sHH", 0 + file_.read.return_value = b"foob" b"\x00\x2A" b"\x00\x15" + expected_values = (b"foob", 42, 21) + return stream, tmpl, offset, file_, expected_values + + # fixture components ----------------------------------- + + @pytest.fixture + def file_(self, request): + return instance_mock(request, io.RawIOBase) + + +class Describe_TableFactory(object): + """Unit-test suite for `pptx.text.fonts._TableFactory` object.""" + + def it_constructs_the_appropriate_table_object(self, fixture): + tag, stream_, offset, length, TableClass_, TableClass = fixture + table = _TableFactory(tag, stream_, offset, length) + TableClass_.assert_called_once_with(tag, stream_, offset, length) + assert isinstance(table, TableClass) + + # fixtures --------------------------------------------- + + @pytest.fixture(params=["name", "head", "foob"]) + def fixture(self, request, stream_): + tag = request.param + offset, length = 42, 21 + TableClass, target = { + "name": (_NameTable, "pptx.text.fonts._NameTable"), + "head": (_HeadTable, "pptx.text.fonts._HeadTable"), + "foob": (_BaseTable, "pptx.text.fonts._BaseTable"), + }[tag] + TableClass_ = class_mock(request, target) + return tag, stream_, offset, length, TableClass_, TableClass + + # fixture components ----------------------------------- + + @pytest.fixture + def stream_(self, request): + return instance_mock(request, _Stream) + + +class Describe_HeadTable(object): + """Unit-test suite for `pptx.text.fonts._HeadTable` object.""" + + def it_knows_whether_the_font_is_bold(self, bold_fixture): + head_table, expected_value = bold_fixture + assert head_table.is_bold is expected_value + + def it_knows_whether_the_font_is_italic(self, italic_fixture): + head_table, expected_value = italic_fixture + assert head_table.is_italic is expected_value + + def it_reads_its_macStyle_field_to_help(self, macStyle_fixture): + head_table, expected_value = macStyle_fixture + assert head_table._macStyle == expected_value + + # fixtures --------------------------------------------- + + @pytest.fixture(params=[(0, False), (1, True)]) + def bold_fixture(self, request, _macStyle_): + macStyle, expected_value = request.param + _macStyle_.return_value = macStyle + head_table = _HeadTable(None, None, None, None) + return head_table, expected_value + + @pytest.fixture(params=[(5, False), (7, True)]) + def italic_fixture(self, request, _macStyle_): + macStyle, expected_value = request.param + _macStyle_.return_value = macStyle + head_table = _HeadTable(None, None, None, None) + return head_table, expected_value + + @pytest.fixture + def macStyle_fixture(self): + bytes_ = b"xxxxyyyy....................................\xF0\xBA........" + stream = _Stream(io.BytesIO(bytes_)) + offset, length = 0, len(bytes_) + head_table = _HeadTable(None, stream, offset, length) + expected_value = 61626 + return head_table, expected_value + + # fixture components ----------------------------------- + + @pytest.fixture + def _macStyle_(self, request): + return property_mock(request, _HeadTable, "_macStyle") + + +class Describe_NameTable(object): + """Unit-test suite for `pptx.text.fonts._NameTable` object.""" + + def it_knows_the_font_family_name(self, family_fixture): + name_table, expected_value = family_fixture + family_name = name_table.family_name + assert family_name == expected_value + + def it_provides_access_to_its_names_to_help_props(self, request): + _iter_names_ = method_mock( + request, + _NameTable, + "_iter_names", + return_value=iter([((0, 1), "Foobar"), ((3, 1), "Barfoo")]), + ) + name_table = _NameTable(None, None, None, None) + + names = name_table._names + + _iter_names_.assert_called_once_with(name_table) + assert names == {(0, 1): "Foobar", (3, 1): "Barfoo"} + + def it_iterates_over_its_names_to_help_read_names(self, request, _table_bytes_prop_): + property_mock(request, _NameTable, "_table_header", return_value=(0, 3, 42)) + _table_bytes_prop_.return_value = "xXx" + _read_name_ = method_mock( + request, + _NameTable, + "_read_name", + side_effect=iter([(0, 1, "Foobar"), (3, 1, "Barfoo"), (9, 9, None)]), + ) + name_table = _NameTable(None, None, None, None) + + names = list(name_table._iter_names()) + + assert _read_name_.call_args_list == [ + call(name_table, "xXx", 0, 42), + call(name_table, "xXx", 1, 42), + call(name_table, "xXx", 2, 42), + ] + assert names == [((0, 1), "Foobar"), ((3, 1), "Barfoo")] + + def it_reads_the_table_header_to_help_read_names(self, header_fixture): + names_table, expected_value = header_fixture + header = names_table._table_header + assert header == expected_value + + def it_buffers_the_table_bytes_to_help_read_names(self, bytes_fixture): + name_table, expected_value = bytes_fixture + table_bytes = name_table._table_bytes + name_table._stream.read.assert_called_once_with(name_table._offset, name_table._length) + assert table_bytes == expected_value + + def it_reads_a_name_to_help_read_names(self, request): + bufr, idx, strs_offset, platform_id, name_id = "buffer", 3, 47, 0, 1 + encoding_id, name_str_offset, length, name = 7, 36, 12, "Arial" + _name_header_ = method_mock( + request, + _NameTable, + "_name_header", + autospec=False, + return_value=( + platform_id, + encoding_id, + 666, + name_id, + length, + name_str_offset, + ), + ) + _read_name_text_ = method_mock(request, _NameTable, "_read_name_text", return_value=name) + name_table = _NameTable(None, None, None, None) + + actual = name_table._read_name(bufr, idx, strs_offset) + + _name_header_.assert_called_once_with(bufr, idx) + _read_name_text_.assert_called_once_with( + name_table, + bufr, + platform_id, + encoding_id, + strs_offset, + name_str_offset, + length, + ) + assert actual == (platform_id, name_id, name) + + def it_reads_a_name_header_to_help_read_names(self, name_hdr_fixture): + name_table, bufr, idx, expected_value = name_hdr_fixture + header = name_table._name_header(bufr, idx) + assert header == expected_value + + def it_reads_name_text_to_help_read_names(self, name_text_fixture): + name_table, bufr, platform_id, encoding_id = name_text_fixture[:4] + strings_offset, name_str_offset, length = name_text_fixture[4:7] + raw_name, name_ = name_text_fixture[7:] + + name = name_table._read_name_text( + bufr, platform_id, encoding_id, strings_offset, name_str_offset, length + ) + + name_table._raw_name_string.assert_called_once_with( + bufr, strings_offset, name_str_offset, length + ) + name_table._decode_name.assert_called_once_with(raw_name, platform_id, encoding_id) + assert name is name_ + + def it_reads_name_bytes_to_help_read_names(self, raw_fixture): + name_table, bufr, strings_offset, str_offset = raw_fixture[:4] + length, expected_bytes = raw_fixture[4:] + bytes_ = name_table._raw_name_string(bufr, strings_offset, str_offset, length) + assert bytes_ == expected_bytes + + def it_decodes_a_raw_name_to_help_read_names(self, decode_fixture): + name_table, raw_name, platform_id, encoding_id, expected_value = decode_fixture + name = name_table._decode_name(raw_name, platform_id, encoding_id) + assert name == expected_value + + # fixtures --------------------------------------------- + + @pytest.fixture + def bytes_fixture(self, stream_): + name_table = _NameTable(None, stream_, 42, 360) + bytes_ = "\x00\x01\x02\x03\x04\x05" + stream_.read.return_value = bytes_ + expected_value = bytes_ + return name_table, expected_value + + @pytest.fixture( + params=[ + (1, 0, b"Foob\x8Ar", "Foobär"), + (1, 1, b"Foobar", None), + (0, 9, "Foobär".encode("utf-16-be"), "Foobär"), + (3, 6, "Foobär".encode("utf-16-be"), "Foobär"), + (2, 0, "Foobar", None), + ] + ) + def decode_fixture(self, request): + platform_id, encoding_id, raw_name, expected_value = request.param + name_table = _NameTable(None, None, None, None) + return name_table, raw_name, platform_id, encoding_id, expected_value + + @pytest.fixture( + params=[ + ({(0, 1): "Foobar", (1, 1): "Barfoo"}, "Foobar"), + ({(1, 1): "Barfoo", (3, 1): "Farbaz"}, "Barfoo"), + ({(3, 1): "Farbaz", (6, 2): "BazFoo"}, "Farbaz"), + ({(9, 1): "Foobar", (6, 1): "Barfoo"}, None), + ] + ) + def family_fixture(self, request, _names_prop_): + names, expected_value = request.param + name_table = _NameTable(None, None, None, None) + _names_prop_.return_value = names + return name_table, expected_value + + @pytest.fixture + def header_fixture(self, _table_bytes_prop_): + name_table = _NameTable(None, None, None, None) + _table_bytes_prop_.return_value = b"\x00\x00\x00\x02\x00\x2A" + expected_value = (0, 2, 42) + return name_table, expected_value + + @pytest.fixture + def name_hdr_fixture(self): + name_table = _NameTable(None, None, None, None) + bufr = ( + b"123456" + b"123456789012" + b"\x00\x00" + b"\x00\x01" + b"\x00\x02" + b"\x00\x03" + b"\x00\x04" + b"\x00\x05" + ) + idx = 1 + expected_value = (0, 1, 2, 3, 4, 5) + return name_table, bufr, idx, expected_value + + @pytest.fixture + def name_text_fixture(self, _raw_name_string_, _decode_name_): + name_table = _NameTable(None, None, None, None) + bufr, platform_id, encoding_id, strings_offset = "xXx", 6, 7, 8 + name_str_offset, length, raw_name = 9, 10, "Foobar" + _raw_name_string_.return_value = raw_name + name_ = _decode_name_.return_value + return ( + name_table, + bufr, + platform_id, + encoding_id, + strings_offset, + name_str_offset, + length, + raw_name, + name_, + ) + + @pytest.fixture + def raw_fixture(self): + name_table = _NameTable(None, None, None, None) + bufr = b"xXxFoobarxXx" + strings_offset, str_offset, length = 1, 2, 6 + expected_bytes = b"Foobar" + return (name_table, bufr, strings_offset, str_offset, length, expected_bytes) + + # fixture components ----------------------------------- + + @pytest.fixture + def _decode_name_(self, request): + return method_mock(request, _NameTable, "_decode_name", autospec=False) + + @pytest.fixture + def _names_prop_(self, request): + return property_mock(request, _NameTable, "_names") + + @pytest.fixture + def _raw_name_string_(self, request): + return method_mock(request, _NameTable, "_raw_name_string", autospec=False) + + @pytest.fixture + def stream_(self, request): + return instance_mock(request, _Stream) + + @pytest.fixture + def _table_bytes_prop_(self, request): + return property_mock(request, _NameTable, "_table_bytes") diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/text/test_layout.py b/tasks/tasksmith-74f059424102/environment/source/tests/text/test_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..6e2c83d6aec5e9411d05d105c9e282e4838b0851 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/text/test_layout.py @@ -0,0 +1,245 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.text.layout` module.""" + +from __future__ import annotations + +import pytest + +from pptx.text.layout import TextFitter, _BinarySearchTree, _Line, _LineSource + +from ..unitutil.mock import ( + ANY, + call, + class_mock, + function_mock, + initializer_mock, + instance_mock, + method_mock, + property_mock, +) + + +class DescribeTextFitter(object): + """Unit-test suite for `pptx.text.layout.TextFitter` object.""" + + def it_can_determine_the_best_fit_font_size(self, request, line_source_): + _LineSource_ = class_mock( + request, "pptx.text.layout._LineSource", return_value=line_source_ + ) + _init_ = initializer_mock(request, TextFitter) + _best_fit_font_size_ = method_mock( + request, TextFitter, "_best_fit_font_size", return_value=36 + ) + extents, max_size = (19, 20), 42 + + font_size = TextFitter.best_fit_font_size("Foobar", extents, max_size, "foobar.ttf") + + _LineSource_.assert_called_once_with("Foobar") + _init_.assert_called_once_with(line_source_, extents, "foobar.ttf") + _best_fit_font_size_.assert_called_once_with(ANY, max_size) + assert font_size == 36 + + def it_finds_best_fit_font_size_to_help_best_fit(self, _best_fit_fixture): + text_fitter, max_size, _BinarySearchTree_ = _best_fit_fixture[:3] + sizes_, predicate_, font_size_ = _best_fit_fixture[3:] + + font_size = text_fitter._best_fit_font_size(max_size) + + _BinarySearchTree_.from_ordered_sequence.assert_called_once_with(range(1, max_size + 1)) + sizes_.find_max.assert_called_once_with(predicate_) + assert font_size is font_size_ + + @pytest.mark.parametrize( + "extents, point_size, text_lines, expected_value", + ( + ((66, 99), 6, ("foo", "bar"), False), + ((66, 100), 6, ("foo", "bar"), True), + ((66, 101), 6, ("foo", "bar"), True), + ), + ) + def it_provides_a_fits_inside_predicate_fn( + self, + request, + line_source_, + _rendered_size_, + extents, + point_size, + text_lines, + expected_value, + ): + _wrap_lines_ = method_mock(request, TextFitter, "_wrap_lines", return_value=text_lines) + _rendered_size_.return_value = (None, 50) + text_fitter = TextFitter(line_source_, extents, "foobar.ttf") + + predicate = text_fitter._fits_inside_predicate + result = predicate(point_size) + + _wrap_lines_.assert_called_once_with(text_fitter, line_source_, point_size) + _rendered_size_.assert_called_once_with("Ty", point_size, text_fitter._font_file) + assert result is expected_value + + def it_provides_a_fits_in_width_predicate_fn(self, fits_cx_pred_fixture): + text_fitter, point_size, line = fits_cx_pred_fixture[:3] + _rendered_size_, expected_value = fits_cx_pred_fixture[3:] + + predicate = text_fitter._fits_in_width_predicate(point_size) + result = predicate(line) + + _rendered_size_.assert_called_once_with(line.text, point_size, text_fitter._font_file) + assert result is expected_value + + def it_wraps_lines_to_help_best_fit(self, request): + line_source, remainder = _LineSource("foo bar"), _LineSource("bar") + _break_line_ = method_mock( + request, + TextFitter, + "_break_line", + side_effect=[("foo", remainder), ("bar", _LineSource(""))], + ) + text_fitter = TextFitter(None, (None, None), None) + + text_fitter._wrap_lines(line_source, 21) + + assert _break_line_.call_args_list == [ + call(text_fitter, line_source, 21), + call(text_fitter, remainder, 21), + ] + + def it_breaks_off_a_line_to_help_wrap(self, request, line_source_, _BinarySearchTree_): + bst_ = instance_mock(request, _BinarySearchTree) + _fits_in_width_predicate_ = method_mock(request, TextFitter, "_fits_in_width_predicate") + _BinarySearchTree_.from_ordered_sequence.return_value = bst_ + predicate_ = _fits_in_width_predicate_.return_value + max_value_ = bst_.find_max.return_value + text_fitter = TextFitter(None, (None, None), None) + + value = text_fitter._break_line(line_source_, 21) + + _BinarySearchTree_.from_ordered_sequence.assert_called_once_with(line_source_) + text_fitter._fits_in_width_predicate.assert_called_once_with(text_fitter, 21) + bst_.find_max.assert_called_once_with(predicate_) + assert value is max_value_ + + # fixtures --------------------------------------------- + + @pytest.fixture + def _best_fit_fixture(self, _BinarySearchTree_, _fits_inside_predicate_): + text_fitter = TextFitter(None, (None, None), None) + max_size = 42 + sizes_ = _BinarySearchTree_.from_ordered_sequence.return_value + predicate_ = _fits_inside_predicate_.return_value + font_size_ = sizes_.find_max.return_value + return ( + text_fitter, + max_size, + _BinarySearchTree_, + sizes_, + predicate_, + font_size_, + ) + + @pytest.fixture(params=[(49, True), (50, True), (51, False)]) + def fits_cx_pred_fixture(self, request, _rendered_size_): + rendered_width, expected_value = request.param + text_fitter = TextFitter(None, (50, None), "foobar.ttf") + point_size, line = 12, _Line("foobar", None) + _rendered_size_.return_value = (rendered_width, None) + return (text_fitter, point_size, line, _rendered_size_, expected_value) + + # fixture components ----------------------------------- + + @pytest.fixture + def _BinarySearchTree_(self, request): + return class_mock(request, "pptx.text.layout._BinarySearchTree") + + @pytest.fixture + def _fits_inside_predicate_(self, request): + return property_mock(request, TextFitter, "_fits_inside_predicate") + + @pytest.fixture + def line_source_(self, request): + return instance_mock(request, _LineSource) + + @pytest.fixture + def _rendered_size_(self, request): + return function_mock(request, "pptx.text.layout._rendered_size") + + +class Describe_BinarySearchTree(object): + """Unit-test suite for `pptx.text.layout._BinarySearchTree` object.""" + + def it_can_construct_from_an_ordered_sequence(self): + bst = _BinarySearchTree.from_ordered_sequence(range(10)) + + def in_order(node): + """ + Traverse the tree depth first to produce a list of its values, + in order. + """ + result = [] + if node is None: + return result + result.extend(in_order(node._lesser)) + result.append(node.value) + result.extend(in_order(node._greater)) + return result + + assert bst.value == 9 + assert bst._lesser.value == 4 + assert bst._greater is None + assert in_order(bst) == list(range(10)) + + def it_can_find_the_max_value_satisfying_a_predicate(self, max_fixture): + bst, predicate, expected_value = max_fixture + assert bst.find_max(predicate) == expected_value + + # fixtures --------------------------------------------- + + @pytest.fixture( + params=[ + (range(10), lambda n: n < 6.5, 6), + (range(10), lambda n: n > 9.9, None), + (range(10), lambda n: n < 0.0, None), + ] + ) + def max_fixture(self, request): + seq, predicate, expected_value = request.param + bst = _BinarySearchTree.from_ordered_sequence(seq) + return bst, predicate, expected_value + + +class Describe_LineSource(object): + """Unit-test suite for `pptx.text.layout._LineSource` object.""" + + def it_generates_text_remainder_pairs(self): + line_source = _LineSource("foo bar baz") + expected = ( + ("foo", _LineSource("bar baz")), + ("foo bar", _LineSource("baz")), + ("foo bar baz", _LineSource("")), + ) + assert all((a == b) for a, b in zip(expected, line_source)) + + +# produces different results on Linux, fails Travis-CI + +# from pptx.text.layout import _rendered_size +# from ..unitutil.file import testfile +# class Describe_rendered_size(object): + +# def it_calculates_the_rendered_size_of_text_at_point_size(self, fixture): +# text, point_size, font_file, expected_value = fixture +# extents = _rendered_size(text, point_size, font_file) +# assert extents == expected_value + +# # fixtures --------------------------------------------- + +# @pytest.fixture(params=[ +# ('Typical', 18, (673100, 254000)), +# ('foo bar baz', 12, (698500, 165100)), +# ]) +# def fixture(self, request): +# text, point_size, expected_value = request.param +# font_file = testfile('calibriz.ttf') +# return text, point_size, font_file, expected_value diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/text/test_text.py b/tasks/tasksmith-74f059424102/environment/source/tests/text/test_text.py new file mode 100644 index 0000000000000000000000000000000000000000..3a1a7a0bbf54eaeecb2c799d51ea9a68bc2ced52 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/text/test_text.py @@ -0,0 +1,1214 @@ +# pyright: reportPrivateUsage=false + +"""Unit-test suite for `pptx.text.text` module.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +import pytest + +from pptx.dml.color import ColorFormat +from pptx.dml.fill import FillFormat +from pptx.enum.lang import MSO_LANGUAGE_ID +from pptx.enum.text import MSO_ANCHOR, MSO_AUTO_SIZE, MSO_UNDERLINE, PP_ALIGN +from pptx.opc.constants import RELATIONSHIP_TYPE as RT +from pptx.opc.package import XmlPart +from pptx.shapes.autoshape import Shape +from pptx.text.text import Font, TextFrame, _Hyperlink, _Paragraph, _Run +from pptx.util import Inches, Pt + +from ..oxml.unitdata.text import a_p, a_t, an_hlinkClick, an_r, an_rPr +from ..unitutil.cxml import element, xml +from ..unitutil.mock import ( + class_mock, + instance_mock, + loose_mock, + method_mock, + property_mock, +) + +if TYPE_CHECKING: + from pptx.oxml.text import CT_TextBody, CT_TextParagraph + + +class DescribeTextFrame(object): + """Unit-test suite for `pptx.text.text.TextFrame` object.""" + + def it_can_add_a_paragraph_to_itself(self, add_paragraph_fixture): + text_frame, expected_xml = add_paragraph_fixture + text_frame.add_paragraph() + assert text_frame._txBody.xml == expected_xml + + def it_knows_its_autosize_setting(self, autosize_get_fixture): + text_frame, expected_value = autosize_get_fixture + assert text_frame.auto_size == expected_value + + @pytest.mark.parametrize( + ("txBody_cxml", "value", "expected_cxml"), + [ + ("p:txBody/a:bodyPr", MSO_AUTO_SIZE.NONE, "p:txBody/a:bodyPr/a:noAutofit"), + ( + "p:txBody/a:bodyPr/a:noAutofit", + MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT, + "p:txBody/a:bodyPr/a:spAutoFit", + ), + ( + "p:txBody/a:bodyPr/a:spAutoFit", + MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE, + "p:txBody/a:bodyPr/a:normAutofit", + ), + ("p:txBody/a:bodyPr/a:normAutofit", None, "p:txBody/a:bodyPr"), + ], + ) + def it_can_change_its_autosize_setting( + self, txBody_cxml: str, value: MSO_AUTO_SIZE | None, expected_cxml: str + ): + text_frame = TextFrame(element(txBody_cxml), None) + text_frame.auto_size = value + assert text_frame._txBody.xml == xml(expected_cxml) + + @pytest.mark.parametrize( + "txBody_cxml", + ( + "p:txBody/(a:p,a:p,a:p)", + 'p:txBody/a:p/a:r/a:t"foo"', + 'p:txBody/a:p/(a:br,a:r/a:t"foo")', + 'p:txBody/a:p/(a:fld,a:br,a:r/a:t"foo")', + ), + ) + def it_can_clear_itself_of_content(self, txBody_cxml): + text_frame = TextFrame(element(txBody_cxml), None) + text_frame.clear() + assert text_frame._element.xml == xml("p:txBody/a:p") + + def it_knows_its_margin_settings(self, margin_get_fixture): + text_frame, prop_name, unit, expected_value = margin_get_fixture + margin_value = getattr(text_frame, prop_name) + assert getattr(margin_value, unit) == expected_value + + def it_can_change_its_margin_settings(self, margin_set_fixture): + text_frame, prop_name, new_value, expected_xml = margin_set_fixture + setattr(text_frame, prop_name, new_value) + assert text_frame._txBody.xml == expected_xml + + @pytest.mark.parametrize( + ("txBody_cxml", "expected_value"), + [ + ("p:txBody/a:bodyPr", None), + ("p:txBody/a:bodyPr{anchor=t}", MSO_ANCHOR.TOP), + ("p:txBody/a:bodyPr{anchor=b}", MSO_ANCHOR.BOTTOM), + ], + ) + def it_knows_its_vertical_alignment(self, txBody_cxml: str, expected_value: MSO_ANCHOR | None): + text_frame = TextFrame(cast("CT_TextBody", element(txBody_cxml)), None) + assert text_frame.vertical_anchor == expected_value + + @pytest.mark.parametrize( + ("txBody_cxml", "new_value", "expected_cxml"), + [ + ("p:txBody/a:bodyPr", MSO_ANCHOR.TOP, "p:txBody/a:bodyPr{anchor=t}"), + ( + "p:txBody/a:bodyPr{anchor=t}", + MSO_ANCHOR.MIDDLE, + "p:txBody/a:bodyPr{anchor=ctr}", + ), + ( + "p:txBody/a:bodyPr{anchor=ctr}", + MSO_ANCHOR.BOTTOM, + "p:txBody/a:bodyPr{anchor=b}", + ), + ("p:txBody/a:bodyPr{anchor=b}", None, "p:txBody/a:bodyPr"), + ], + ) + def it_can_change_its_vertical_alignment( + self, txBody_cxml: str, new_value: MSO_ANCHOR | None, expected_cxml: str + ): + text_frame = TextFrame(cast("CT_TextBody", element(txBody_cxml)), None) + text_frame.vertical_anchor = new_value + assert text_frame._element.xml == xml(expected_cxml) + + def it_knows_its_word_wrap_setting(self, wrap_get_fixture): + text_frame, expected_value = wrap_get_fixture + assert text_frame.word_wrap == expected_value + + def it_can_change_its_word_wrap_setting(self, wrap_set_fixture): + text_frame, new_value, expected_xml = wrap_set_fixture + text_frame.word_wrap = new_value + assert text_frame._element.xml == expected_xml + + def it_provides_access_to_its_paragraphs(self, paragraphs_fixture): + text_frame, ps = paragraphs_fixture + paragraphs = text_frame.paragraphs + assert len(paragraphs) == len(ps) + for idx, paragraph in enumerate(paragraphs): + assert isinstance(paragraph, _Paragraph) + assert paragraph._element is ps[idx] + + def it_raises_on_attempt_to_set_margin_to_non_int(self): + text_frame = TextFrame(element("p:txBody/a:bodyPr"), None) + with pytest.raises(TypeError): + text_frame.margin_bottom = "0.1" + + def it_knows_the_part_it_belongs_to(self, text_frame_with_parent_): + text_frame, parent_ = text_frame_with_parent_ + part = text_frame.part + assert part is parent_.part + + def it_knows_what_text_it_contains(self, request, text_get_fixture, paragraphs_prop_): + paragraph_texts, expected_value = text_get_fixture + paragraphs_prop_.return_value = tuple( + instance_mock(request, _Paragraph, text=text) for text in paragraph_texts + ) + text_frame = TextFrame(None, None) + + text = text_frame.text + + assert text == expected_value + + def it_can_replace_the_text_it_contains(self, text_set_fixture): + txBody, text, expected_xml = text_set_fixture + text_frame = TextFrame(txBody, None) + + text_frame.text = text + + assert text_frame._element.xml == expected_xml + + def it_can_resize_its_text_to_best_fit(self, request, text_prop_): + family, max_size, bold, italic, font_file, font_size = ( + "Family", + 42, + "bold", + "italic", + "font_file", + 21, + ) + text_prop_.return_value = "some text" + _best_fit_font_size_ = method_mock( + request, TextFrame, "_best_fit_font_size", return_value=font_size + ) + _apply_fit_ = method_mock(request, TextFrame, "_apply_fit") + text_frame = TextFrame(None, None) + + text_frame.fit_text(family, max_size, bold, italic, font_file) + + _best_fit_font_size_.assert_called_once_with( + text_frame, family, max_size, bold, italic, font_file + ) + _apply_fit_.assert_called_once_with(text_frame, family, font_size, bold, italic) + + def it_calculates_its_best_fit_font_size_to_help_fit_text(self, size_font_fixture): + text_frame, family, max_size, bold, italic = size_font_fixture[:5] + FontFiles_, TextFitter_, text, extents = size_font_fixture[5:9] + font_file_, font_size_ = size_font_fixture[9:] + + font_size = text_frame._best_fit_font_size(family, max_size, bold, italic, None) + + FontFiles_.find.assert_called_once_with(family, bold, italic) + TextFitter_.best_fit_font_size.assert_called_once_with(text, extents, max_size, font_file_) + assert font_size is font_size_ + + def it_calculates_its_effective_size_to_help_fit_text(self): + sp_cxml = ( + "p:sp/(p:spPr/a:xfrm/(a:off{x=914400,y=914400},a:ext{cx=914400,c" + "y=914400}),p:txBody/(a:bodyPr,a:p))" + ) + text_frame = Shape(element(sp_cxml), None).text_frame + assert text_frame._extents == (731520, 822960) + + def it_applies_fit_to_help_fit_text(self, request): + family, font_size, bold, italic = "Family", 42, True, False + _set_font_ = method_mock(request, TextFrame, "_set_font") + text_frame = TextFrame(element("p:txBody/a:bodyPr"), None) + + text_frame._apply_fit(family, font_size, bold, italic) + + assert text_frame.auto_size is MSO_AUTO_SIZE.NONE + assert text_frame.word_wrap is True + _set_font_.assert_called_once_with(text_frame, family, font_size, bold, italic) + + def it_sets_its_font_to_help_fit_text(self, set_font_fixture): + text_frame, family, size, bold, italic, expected_xml = set_font_fixture + text_frame._set_font(family, size, bold, italic) + assert text_frame._element.xml == expected_xml + + # fixtures --------------------------------------------- + + @pytest.fixture( + params=[ + ("p:txBody/a:bodyPr", "p:txBody/(a:bodyPr,a:p)"), + ("p:txBody/(a:bodyPr,a:p)", "p:txBody/(a:bodyPr,a:p,a:p)"), + ] + ) + def add_paragraph_fixture(self, request): + txBody_cxml, expected_cxml = request.param + text_frame = TextFrame(element(txBody_cxml), None) + expected_xml = xml(expected_cxml) + return text_frame, expected_xml + + @pytest.fixture( + params=[ + ("p:txBody/a:bodyPr", None), + ("p:txBody/a:bodyPr/a:noAutofit", MSO_AUTO_SIZE.NONE), + ("p:txBody/a:bodyPr/a:spAutoFit", MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT), + ("p:txBody/a:bodyPr/a:normAutofit", MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE), + ] + ) + def autosize_get_fixture(self, request): + txBody_cxml, expected_value = request.param + text_frame = TextFrame(element(txBody_cxml), None) + return text_frame, expected_value + + @pytest.fixture( + params=[ + ("p:txBody/a:bodyPr", "left", "emu", Inches(0.1)), + ("p:txBody/a:bodyPr", "top", "emu", Inches(0.05)), + ("p:txBody/a:bodyPr", "right", "emu", Inches(0.1)), + ("p:txBody/a:bodyPr", "bottom", "emu", Inches(0.05)), + ("p:txBody/a:bodyPr{lIns=9144}", "left", "cm", 0.0254), + ("p:txBody/a:bodyPr{tIns=18288}", "top", "mm", 0.508), + ("p:txBody/a:bodyPr{rIns=76200}", "right", "pt", 6.0), + ("p:txBody/a:bodyPr{bIns=36576}", "bottom", "inches", 0.04), + ] + ) + def margin_get_fixture(self, request): + txBody_cxml, side, unit, expected_value = request.param + text_frame = TextFrame(element(txBody_cxml), None) + prop_name = "margin_%s" % side + return text_frame, prop_name, unit, expected_value + + @pytest.fixture( + params=[ + ( + "p:txBody/a:bodyPr", + "left", + Inches(0.11), + "p:txBody/a:bodyPr{lIns=100584}", + ), + ( + "p:txBody/a:bodyPr{tIns=1234}", + "top", + Inches(0.12), + "p:txBody/a:bodyPr{tIns=109728}", + ), + ( + "p:txBody/a:bodyPr{rIns=2345}", + "right", + Inches(0.13), + "p:txBody/a:bodyPr{rIns=118872}", + ), + ( + "p:txBody/a:bodyPr{bIns=3456}", + "bottom", + Inches(0.14), + "p:txBody/a:bodyPr{bIns=128016}", + ), + ("p:txBody/a:bodyPr", "left", Inches(0.1), "p:txBody/a:bodyPr"), + ("p:txBody/a:bodyPr", "top", Inches(0.05), "p:txBody/a:bodyPr"), + ("p:txBody/a:bodyPr", "right", Inches(0.1), "p:txBody/a:bodyPr"), + ("p:txBody/a:bodyPr", "bottom", Inches(0.05), "p:txBody/a:bodyPr"), + ] + ) + def margin_set_fixture(self, request): + txBody_cxml, side, new_value, expected_txBody_cxml = request.param + text_frame = TextFrame(element(txBody_cxml), None) + prop_name = "margin_%s" % side + expected_xml = xml(expected_txBody_cxml) + return text_frame, prop_name, new_value, expected_xml + + @pytest.fixture(params=["p:txBody", "p:txBody/a:p", "p:txBody/(a:p,a:p)"]) + def paragraphs_fixture(self, request): + txBody_cxml = request.param + txBody = element(txBody_cxml) + text_frame = TextFrame(txBody, None) + ps = txBody.xpath(".//a:p") + return text_frame, ps + + @pytest.fixture( + params=[ + ( + "p:txBody/(a:bodyPr,a:p/a:r)", + True, + False, + "p:txBody/(a:bodyPr,a:p/(a:r/a:rPr{sz=600,b=1,i=0}/a:latin{typeface" + "=F},a:endParaRPr{sz=600,b=1,i=0}/a:latin{typeface=F}))", + ), + ( + "p:txBody/a:p/a:br", + True, + False, + "p:txBody/a:p/(a:br/a:rPr{sz=600,b=1,i=0}/a:latin{typeface=F},a:end" + "ParaRPr{sz=600,b=1,i=0}/a:latin{typeface=F})", + ), + ( + "p:txBody/a:p/a:fld", + True, + False, + "p:txBody/a:p/(a:fld/a:rPr{sz=600,b=1,i=0}/a:latin{typeface=F},a:en" + "dParaRPr{sz=600,b=1,i=0}/a:latin{typeface=F})", + ), + ] + ) + def set_font_fixture(self, request): + txBody_cxml, bold, italic, expected_cxml = request.param + family, size = "F", 6 + text_frame = TextFrame(element(txBody_cxml), None) + expected_xml = xml(expected_cxml) + return text_frame, family, size, bold, italic, expected_xml + + @pytest.fixture + def size_font_fixture(self, FontFiles_, TextFitter_, text_prop_, _extents_prop_): + text_frame = TextFrame(None, None) + family, max_size, bold, italic = "Family", 42, True, False + text, extents, font_size, font_file = "text", (111, 222), 21, "f.ttf" + text_prop_.return_value = text + _extents_prop_.return_value = extents + FontFiles_.find.return_value = font_file + TextFitter_.best_fit_font_size.return_value = font_size + return ( + text_frame, + family, + max_size, + bold, + italic, + FontFiles_, + TextFitter_, + text, + extents, + font_file, + font_size, + ) + + @pytest.fixture(params=[(["foobar"], "foobar"), (["foo", "bar", "baz"], "foo\nbar\nbaz")]) + def text_get_fixture(self, request): + paragraph_texts, expected_value = request.param + return paragraph_texts, expected_value + + @pytest.fixture( + params=[ + # ---empty to something--- + ("p:txBody/a:p", "foobar", 'p:txBody/a:p/a:r/a:t"foobar"'), + # ---something to something else--- + ('p:txBody/a:p/a:r/a:t"foobar"', "barfoo", 'p:txBody/a:p/a:r/a:t"barfoo"'), + # ---single paragraph to multiple--- + ( + 'p:txBody/a:p/a:r/a:t"barfoo"', + "foo\nbar", + 'p:txBody/(a:p/a:r/a:t"foo",a:p/a:r/a:t"bar")', + ), + # ---multiple paragraphs to single--- + ( + 'p:txBody/(a:p/a:r/a:t"foo",a:p/a:r/a:t"bar")', + "barfoo", + 'p:txBody/a:p/a:r/a:t"barfoo"', + ), + # ---something to empty--- + ('p:txBody/a:p/a:r/a:t"foobar"', "", "p:txBody/a:p"), + # ---vertical-tab becomes line-break--- + ("p:txBody/a:p", "a\vb", 'p:txBody/a:p/(a:r/a:t"a",a:br,a:r/a:t"b")'), + ] + ) + def text_set_fixture(self, request): + txBody_cxml, text, expected_cxml = request.param + txBody = element(txBody_cxml) + expected_xml = xml(expected_cxml) + return txBody, text, expected_xml + + @pytest.fixture( + params=[ + ("p:txBody/a:bodyPr", None), + ("p:txBody/a:bodyPr{wrap=square}", True), + ("p:txBody/a:bodyPr{wrap=none}", False), + ] + ) + def wrap_get_fixture(self, request): + txBody_cxml, expected_value = request.param + text_frame = TextFrame(element(txBody_cxml), None) + return text_frame, expected_value + + @pytest.fixture( + params=[ + ("p:txBody/a:bodyPr", True, "p:txBody/a:bodyPr{wrap=square}"), + ("p:txBody/a:bodyPr{wrap=square}", False, "p:txBody/a:bodyPr{wrap=none}"), + ("p:txBody/a:bodyPr{wrap=none}", None, "p:txBody/a:bodyPr"), + ] + ) + def wrap_set_fixture(self, request): + txBody_cxml, new_value, expected_txBody_cxml = request.param + text_frame = TextFrame(element(txBody_cxml), None) + expected_xml = xml(expected_txBody_cxml) + return text_frame, new_value, expected_xml + + # fixture components ----------------------------------- + + @pytest.fixture + def _extents_prop_(self, request): + return property_mock(request, TextFrame, "_extents") + + @pytest.fixture + def FontFiles_(self, request): + return class_mock(request, "pptx.text.text.FontFiles") + + @pytest.fixture + def paragraphs_prop_(self, request): + return property_mock(request, TextFrame, "paragraphs") + + @pytest.fixture + def TextFitter_(self, request): + return class_mock(request, "pptx.text.text.TextFitter") + + @pytest.fixture + def text_frame_with_parent_(self, request): + parent_ = loose_mock(request, name="parent_") + text_frame = TextFrame(None, parent_) + return text_frame, parent_ + + @pytest.fixture + def text_prop_(self, request): + return property_mock(request, TextFrame, "text") + + +class DescribeFont(object): + """Unit-test suite for `pptx.text.text.Font` object.""" + + def it_knows_its_bold_setting(self, bold_get_fixture): + font, expected_value = bold_get_fixture + assert font.bold == expected_value + + def it_can_change_its_bold_setting(self, bold_set_fixture): + font, new_value, expected_xml = bold_set_fixture + font.bold = new_value + assert font._element.xml == expected_xml + + def it_knows_its_italic_setting(self, italic_get_fixture): + font, expected_value = italic_get_fixture + assert font.italic == expected_value + + def it_can_change_its_italic_setting(self, italic_set_fixture): + font, new_value, expected_xml = italic_set_fixture + font.italic = new_value + assert font._element.xml == expected_xml + + def it_knows_its_language_id(self, language_id_get_fixture): + font, expected_value = language_id_get_fixture + assert font.language_id == expected_value + + def it_can_change_its_language_id_setting(self, language_id_set_fixture): + font, new_value, expected_xml = language_id_set_fixture + font.language_id = new_value + assert font._element.xml == expected_xml + + def it_knows_its_underline_setting(self, underline_get_fixture): + font, expected_value = underline_get_fixture + assert font.underline is expected_value, "got %s" % font.underline + + def it_can_change_its_underline_setting(self, underline_set_fixture): + font, new_value, expected_xml = underline_set_fixture + font.underline = new_value + assert font._element.xml == expected_xml + + def it_knows_its_size(self, size_get_fixture): + font, expected_value = size_get_fixture + assert font.size == expected_value + + def it_can_change_its_size(self, size_set_fixture): + font, new_value, expected_xml = size_set_fixture + font.size = new_value + assert font._element.xml == expected_xml + + def it_knows_its_latin_typeface(self, name_get_fixture): + font, expected_value = name_get_fixture + assert font.name == expected_value + + def it_can_change_its_latin_typeface(self, name_set_fixture): + font, new_value, expected_xml = name_set_fixture + font.name = new_value + assert font._element.xml == expected_xml + + def it_provides_access_to_its_color(self, font): + assert isinstance(font.color, ColorFormat) + + def it_provides_access_to_its_fill(self, font): + assert isinstance(font.fill, FillFormat) + + # fixtures --------------------------------------------- + + @pytest.fixture(params=[("a:rPr", None), ("a:rPr{b=0}", False), ("a:rPr{b=1}", True)]) + def bold_get_fixture(self, request): + rPr_cxml, expected_value = request.param + font = Font(element(rPr_cxml)) + return font, expected_value + + @pytest.fixture( + params=[ + ("a:rPr", True, "a:rPr{b=1}"), + ("a:rPr{b=1}", False, "a:rPr{b=0}"), + ("a:rPr{b=0}", None, "a:rPr"), + ] + ) + def bold_set_fixture(self, request): + rPr_cxml, new_value, expected_rPr_cxml = request.param + font = Font(element(rPr_cxml)) + expected_xml = xml(expected_rPr_cxml) + return font, new_value, expected_xml + + @pytest.fixture(params=[("a:rPr", None), ("a:rPr{i=0}", False), ("a:rPr{i=1}", True)]) + def italic_get_fixture(self, request): + rPr_cxml, expected_value = request.param + font = Font(element(rPr_cxml)) + return font, expected_value + + @pytest.fixture( + params=[ + ("a:rPr", True, "a:rPr{i=1}"), + ("a:rPr{i=1}", False, "a:rPr{i=0}"), + ("a:rPr{i=0}", None, "a:rPr"), + ] + ) + def italic_set_fixture(self, request): + rPr_cxml, new_value, expected_rPr_cxml = request.param + font = Font(element(rPr_cxml)) + expected_xml = xml(expected_rPr_cxml) + return font, new_value, expected_xml + + @pytest.fixture( + params=[ + ("a:rPr", MSO_LANGUAGE_ID.NONE), + ("a:rPr{lang=pl-PL}", MSO_LANGUAGE_ID.POLISH), + ("a:rPr{lang=de-AT}", MSO_LANGUAGE_ID.GERMAN_AUSTRIA), + ("a:rPr{lang=fr-FR}", MSO_LANGUAGE_ID.FRENCH), + ] + ) + def language_id_get_fixture(self, request): + rPr_cxml, expected_value = request.param + font = Font(element(rPr_cxml)) + return font, expected_value + + @pytest.fixture( + params=[ + ("a:rPr", MSO_LANGUAGE_ID.ZULU, "a:rPr{lang=zu-ZA}"), + ("a:rPr{lang=zu-ZA}", MSO_LANGUAGE_ID.URDU, "a:rPr{lang=ur-PK}"), + ("a:rPr{lang=ur-PK}", MSO_LANGUAGE_ID.NONE, "a:rPr"), + ("a:rPr{lang=ur-PK}", None, "a:rPr"), + ("a:rPr", MSO_LANGUAGE_ID.NONE, "a:rPr"), + ("a:rPr", None, "a:rPr"), + ] + ) + def language_id_set_fixture(self, request): + rPr_cxml, new_value, expected_rPr_cxml = request.param + font = Font(element(rPr_cxml)) + expected_xml = xml(expected_rPr_cxml) + return font, new_value, expected_xml + + @pytest.fixture(params=[("a:rPr", None), ("a:rPr/a:latin{typeface=Foobar}", "Foobar")]) + def name_get_fixture(self, request): + rPr_cxml, expected_value = request.param + font = Font(element(rPr_cxml)) + return font, expected_value + + @pytest.fixture( + params=[ + ("a:rPr", "Foobar", "a:rPr/a:latin{typeface=Foobar}"), + ( + "a:rPr/a:latin{typeface=Foobar}", + "Barfoo", + "a:rPr/a:latin{typeface=Barfoo}", + ), + ("a:rPr/a:latin{typeface=Barfoo}", None, "a:rPr"), + ] + ) + def name_set_fixture(self, request): + rPr_cxml, new_value, expected_rPr_cxml = request.param + font = Font(element(rPr_cxml)) + expected_xml = xml(expected_rPr_cxml) + return font, new_value, expected_xml + + @pytest.fixture(params=[("a:rPr", None), ("a:rPr{sz=2400}", 304800)]) + def size_get_fixture(self, request): + rPr_cxml, expected_value = request.param + font = Font(element(rPr_cxml)) + return font, expected_value + + @pytest.fixture(params=[("a:rPr", Pt(24), "a:rPr{sz=2400}"), ("a:rPr{sz=2400}", None, "a:rPr")]) + def size_set_fixture(self, request): + rPr_cxml, new_value, expected_rPr_cxml = request.param + font = Font(element(rPr_cxml)) + expected_xml = xml(expected_rPr_cxml) + return font, new_value, expected_xml + + @pytest.fixture( + params=[ + ("a:rPr", None), + ("a:rPr{u=none}", False), + ("a:rPr{u=sng}", True), + ("a:rPr{u=dbl}", MSO_UNDERLINE.DOUBLE_LINE), + ] + ) + def underline_get_fixture(self, request): + rPr_cxml, expected_value = request.param + font = Font(element(rPr_cxml)) + return font, expected_value + + @pytest.fixture( + params=[ + ("a:rPr", True, "a:rPr{u=sng}"), + ("a:rPr{u=sng}", False, "a:rPr{u=none}"), + ("a:rPr{u=none}", MSO_UNDERLINE.WAVY_LINE, "a:rPr{u=wavy}"), + ("a:rPr{u=wavy}", MSO_UNDERLINE.NONE, "a:rPr{u=none}"), + ("a:rPr{u=wavy}", None, "a:rPr"), + ] + ) + def underline_set_fixture(self, request): + rPr_cxml, new_value, expected_rPr_cxml = request.param + font = Font(element(rPr_cxml)) + expected_xml = xml(expected_rPr_cxml) + return font, new_value, expected_xml + + # fixture components --------------------------------------------- + + @pytest.fixture + def font(self): + return Font(element("a:rPr")) + + +class Describe_Hyperlink(object): + """Unit-test suite for `pptx.text.text._Hyperlink` object.""" + + def it_knows_the_target_url_of_the_hyperlink(self, hlink_with_url_): + hlink, rId, url = hlink_with_url_ + assert hlink.address == url + hlink.part.target_ref.assert_called_once_with(rId) + + def it_has_None_for_address_when_no_hyperlink_is_present(self, hlink): + assert hlink.address is None + + def it_can_set_the_target_url(self, hlink, rPr_with_hlinkClick_xml, url): + hlink.address = url + # verify ----------------------- + hlink.part.relate_to.assert_called_once_with(url, RT.HYPERLINK, is_external=True) + assert hlink._rPr.xml == rPr_with_hlinkClick_xml + assert hlink.address == url + + def it_can_remove_the_hyperlink(self, remove_hlink_fixture_): + hlink, rPr_xml, rId = remove_hlink_fixture_ + hlink.address = None + assert hlink._rPr.xml == rPr_xml + hlink.part.drop_rel.assert_called_once_with(rId) + + def it_should_remove_the_hyperlink_when_url_set_to_empty_string(self, remove_hlink_fixture_): + hlink, rPr_xml, rId = remove_hlink_fixture_ + hlink.address = "" + assert hlink._rPr.xml == rPr_xml + hlink.part.drop_rel.assert_called_once_with(rId) + + def it_can_change_the_target_url(self, change_hlink_fixture_): + # fixture ---------------------- + hlink, rId_existing, new_url, new_rPr_xml = change_hlink_fixture_ + # exercise --------------------- + hlink.address = new_url + # verify ----------------------- + assert hlink._rPr.xml == new_rPr_xml + hlink.part.drop_rel.assert_called_once_with(rId_existing) + hlink.part.relate_to.assert_called_once_with(new_url, RT.HYPERLINK, is_external=True) + + # fixtures --------------------------------------------- + + @pytest.fixture + def change_hlink_fixture_(self, request, hlink_with_hlinkClick, rId, rId_2, part_, url_2): + hlinkClick_bldr = an_hlinkClick().with_rId(rId_2) + new_rPr_xml = an_rPr().with_nsdecls("a", "r").with_child(hlinkClick_bldr).xml() + part_.relate_to.return_value = rId_2 + property_mock(request, _Hyperlink, "part", return_value=part_) + return hlink_with_hlinkClick, rId, url_2, new_rPr_xml + + @pytest.fixture + def hlink(self, request, part_): + rPr = an_rPr().with_nsdecls("a", "r").element + hlink = _Hyperlink(rPr, None) + property_mock(request, _Hyperlink, "part", return_value=part_) + return hlink + + @pytest.fixture + def hlink_with_hlinkClick(self, request, rPr_with_hlinkClick_bldr): + rPr = rPr_with_hlinkClick_bldr.element + return _Hyperlink(rPr, None) + + @pytest.fixture + def hlink_with_url_(self, request, part_, hlink_with_hlinkClick, rId, url): + property_mock(request, _Hyperlink, "part", return_value=part_) + return hlink_with_hlinkClick, rId, url + + @pytest.fixture + def part_(self, request, url, rId): + """ + Mock Part instance suitable for patching into _Hyperlink.part + property. It returns url for target_ref() and rId for relate_to(). + """ + part_ = instance_mock(request, XmlPart) + part_.target_ref.return_value = url + part_.relate_to.return_value = rId + return part_ + + @pytest.fixture + def rId(self): + return "rId2" + + @pytest.fixture + def rId_2(self): + return "rId6" + + @pytest.fixture + def remove_hlink_fixture_(self, request, hlink_with_hlinkClick, rPr_xml, rId): + property_mock(request, _Hyperlink, "part") + return hlink_with_hlinkClick, rPr_xml, rId + + @pytest.fixture + def rPr_with_hlinkClick_bldr(self, rId): + hlinkClick_bldr = an_hlinkClick().with_rId(rId) + rPr_bldr = an_rPr().with_nsdecls("a", "r").with_child(hlinkClick_bldr) + return rPr_bldr + + @pytest.fixture + def rPr_with_hlinkClick_xml(self, rPr_with_hlinkClick_bldr): + return rPr_with_hlinkClick_bldr.xml() + + @pytest.fixture + def rPr_xml(self): + return an_rPr().with_nsdecls("a", "r").xml() + + @pytest.fixture + def url(self): + return "https://github.com/scanny/python-pptx" + + @pytest.fixture + def url_2(self): + return "https://pypi.python.org/pypi/python-pptx" + + +class Describe_Paragraph(object): + """Unit test suite for pptx.text.text._Paragraph object.""" + + def it_can_add_a_line_break(self, line_break_fixture): + paragraph, expected_xml = line_break_fixture + paragraph.add_line_break() + assert paragraph._p.xml == expected_xml + + def it_can_add_a_run(self, paragraph, p_with_r_xml): + run = paragraph.add_run() + assert paragraph._p.xml == p_with_r_xml + assert isinstance(run, _Run) + + def it_knows_its_horizontal_alignment(self, alignment_get_fixture): + paragraph, expected_value = alignment_get_fixture + assert paragraph.alignment == expected_value + + def it_can_change_its_horizontal_alignment(self, alignment_set_fixture): + paragraph, new_value, expected_xml = alignment_set_fixture + paragraph.alignment = new_value + assert paragraph._element.xml == expected_xml + + def it_can_clear_itself_of_content(self, clear_fixture): + paragraph, expected_xml = clear_fixture + paragraph.clear() + assert paragraph._element.xml == expected_xml + + def it_provides_access_to_the_default_paragraph_font(self, paragraph, Font_): + font = paragraph.font + Font_.assert_called_once_with(paragraph._defRPr) + assert font == Font_.return_value + + def it_knows_its_indentation_level(self, level_get_fixture): + paragraph, expected_value = level_get_fixture + assert paragraph.level == expected_value + + def it_can_change_its_indentation_level(self, level_set_fixture): + paragraph, new_value, expected_xml = level_set_fixture + paragraph.level = new_value + assert paragraph._element.xml == expected_xml + + def it_knows_its_line_spacing(self, spacing_get_fixture): + paragraph, expected_value = spacing_get_fixture + assert paragraph.line_spacing == expected_value + + def it_can_change_its_line_spacing(self, spacing_set_fixture): + paragraph, new_value, expected_xml = spacing_set_fixture + paragraph.line_spacing = new_value + assert paragraph._element.xml == expected_xml + + def it_provides_access_to_its_runs(self, runs_fixture): + paragraph, expected_text = runs_fixture + runs = paragraph.runs + assert tuple(r.text for r in runs) == expected_text + for r in runs: + assert isinstance(r, _Run) + assert r._parent == paragraph + + def it_knows_its_space_after(self, after_get_fixture): + paragraph, expected_value = after_get_fixture + assert paragraph.space_after == expected_value + + def it_can_change_its_space_after(self, after_set_fixture): + paragraph, new_value, expected_xml = after_set_fixture + paragraph.space_after = new_value + assert paragraph._element.xml == expected_xml + + def it_knows_its_space_before(self, before_get_fixture): + paragraph, expected_value = before_get_fixture + assert paragraph.space_before == expected_value + + def it_can_change_its_space_before(self, before_set_fixture): + paragraph, new_value, expected_xml = before_set_fixture + paragraph.space_before = new_value + assert paragraph._element.xml == expected_xml + + def it_knows_what_text_it_contains(self, text_get_fixture): + p, expected_value = text_get_fixture + paragraph = _Paragraph(p, None) + + text = paragraph.text + + assert text == expected_value + assert isinstance(text, str) + + @pytest.mark.parametrize( + ("p_cxml", "value", "expected_cxml"), + [ + ('a:p/(a:r/a:t"foo",a:r/a:t"bar")', "foobar", 'a:p/a:r/a:t"foobar"'), + ("a:p", "", "a:p"), + ("a:p", "foobar", 'a:p/a:r/a:t"foobar"'), + ("a:p", "foo\nbar", 'a:p/(a:r/a:t"foo",a:br,a:r/a:t"bar")'), + ("a:p", "\vfoo\n", 'a:p/(a:br,a:r/a:t"foo",a:br)'), + ("a:p", "\n\nfoo", 'a:p/(a:br,a:br,a:r/a:t"foo")'), + ("a:p", "foo\n", 'a:p/(a:r/a:t"foo",a:br)'), + ("a:p", "foo\x07\n", 'a:p/(a:r/a:t"foo_x0007_",a:br)'), + ("a:p", "ŮŦƑ-8\x1bliteral", 'a:p/a:r/a:t"ŮŦƑ-8_x001B_literal"'), + ( + "a:p", + "utf-8 unicode: Hér er texti", + 'a:p/a:r/a:t"utf-8 unicode: Hér er texti"', + ), + ], + ) + def it_can_change_its_text(self, p_cxml: str, value: str, expected_cxml: str): + p = cast("CT_TextParagraph", element(p_cxml)) + paragraph = _Paragraph(p, None) + + paragraph.text = value + + assert paragraph._element.xml == xml(expected_cxml) + + # fixtures --------------------------------------------- + + @pytest.fixture( + params=[ + ("a:p", None), + ("a:p/a:pPr", None), + ("a:p/a:pPr/a:spcAft/a:spcPct{val=150000}", None), + ("a:p/a:pPr/a:spcAft/a:spcPts{val=600}", 76200), + ] + ) + def after_get_fixture(self, request): + p_cxml, expected_value = request.param + paragraph = _Paragraph(element(p_cxml), None) + return paragraph, expected_value + + @pytest.fixture( + params=[ + ("a:p", Pt(8.333), "a:p/a:pPr/a:spcAft/a:spcPts{val=833}"), + ( + "a:p/a:pPr/a:spcAft/a:spcPts{val=600}", + Pt(42), + "a:p/a:pPr/a:spcAft/a:spcPts{val=4200}", + ), + ( + "a:p/a:pPr/a:spcAft/a:spcPct{val=150000}", + Pt(24), + "a:p/a:pPr/a:spcAft/a:spcPts{val=2400}", + ), + ("a:p/a:pPr/a:spcAft/a:spcPts{val=600}", None, "a:p/a:pPr"), + ] + ) + def after_set_fixture(self, request): + p_cxml, new_value, expected_p_cxml = request.param + paragraph = _Paragraph(element(p_cxml), None) + expected_xml = xml(expected_p_cxml) + return paragraph, new_value, expected_xml + + @pytest.fixture( + params=[ + ("a:p", None), + ("a:p/a:pPr{algn=ctr}", PP_ALIGN.CENTER), + ("a:p/a:pPr{algn=r}", PP_ALIGN.RIGHT), + ] + ) + def alignment_get_fixture(self, request): + p_cxml, expected_value = request.param + paragraph = _Paragraph(element(p_cxml), None) + return paragraph, expected_value + + @pytest.fixture( + params=[ + ("a:p", PP_ALIGN.LEFT, "a:p/a:pPr{algn=l}"), + ("a:p/a:pPr{algn=l}", PP_ALIGN.JUSTIFY, "a:p/a:pPr{algn=just}"), + ("a:p/a:pPr{algn=just}", None, "a:p/a:pPr"), + ] + ) + def alignment_set_fixture(self, request): + p_cxml, new_value, expected_p_cxml = request.param + paragraph = _Paragraph(element(p_cxml), None) + expected_xml = xml(expected_p_cxml) + return paragraph, new_value, expected_xml + + @pytest.fixture( + params=[ + ("a:p", None), + ("a:p/a:pPr", None), + ("a:p/a:pPr/a:spcBef/a:spcPct{val=150000}", None), + ("a:p/a:pPr/a:spcBef/a:spcPts{val=600}", 76200), + ] + ) + def before_get_fixture(self, request): + p_cxml, expected_value = request.param + paragraph = _Paragraph(element(p_cxml), None) + return paragraph, expected_value + + @pytest.fixture( + params=[ + ("a:p", Pt(8.333), "a:p/a:pPr/a:spcBef/a:spcPts{val=833}"), + ( + "a:p/a:pPr/a:spcBef/a:spcPts{val=600}", + Pt(42), + "a:p/a:pPr/a:spcBef/a:spcPts{val=4200}", + ), + ( + "a:p/a:pPr/a:spcBef/a:spcPct{val=150000}", + Pt(24), + "a:p/a:pPr/a:spcBef/a:spcPts{val=2400}", + ), + ("a:p/a:pPr/a:spcBef/a:spcPts{val=600}", None, "a:p/a:pPr"), + ] + ) + def before_set_fixture(self, request): + p_cxml, new_value, expected_p_cxml = request.param + paragraph = _Paragraph(element(p_cxml), None) + expected_xml = xml(expected_p_cxml) + return paragraph, new_value, expected_xml + + @pytest.fixture( + params=[ + ('a:p/a:r/a:t"foo"', "a:p"), + ('a:p/(a:br,a:r/a:t"foo")', "a:p"), + ('a:p/(a:fld,a:br,a:r/a:t"foo")', "a:p"), + ] + ) + def clear_fixture(self, request): + p_cxml, expected_p_cxml = request.param + paragraph = _Paragraph(element(p_cxml), None) + expected_xml = xml(expected_p_cxml) + return paragraph, expected_xml + + @pytest.fixture(params=[("a:p", 0), ("a:p/a:pPr{lvl=2}", 2)]) + def level_get_fixture(self, request): + p_cxml, expected_value = request.param + paragraph = _Paragraph(element(p_cxml), None) + return paragraph, expected_value + + @pytest.fixture( + params=[ + ("a:p", 1, "a:p/a:pPr{lvl=1}"), + ("a:p/a:pPr{lvl=1}", 2, "a:p/a:pPr{lvl=2}"), + ("a:p/a:pPr{lvl=2}", 0, "a:p/a:pPr"), + ] + ) + def level_set_fixture(self, request): + p_cxml, new_value, expected_p_cxml = request.param + paragraph = _Paragraph(element(p_cxml), None) + expected_xml = xml(expected_p_cxml) + return paragraph, new_value, expected_xml + + @pytest.fixture( + params=[ + ("a:p", "a:p/a:br"), + ("a:p/a:r", "a:p/(a:r,a:br)"), + ("a:p/a:br", "a:p/(a:br,a:br)"), + ] + ) + def line_break_fixture(self, request): + cxml, expected_cxml = request.param + paragraph = _Paragraph(element(cxml), None) + expected_xml = xml(expected_cxml) + return paragraph, expected_xml + + @pytest.fixture + def runs_fixture(self): + p_cxml = 'a:p/(a:r/a:t"Foo",a:r/a:t"Bar",a:r/a:t"Baz")' + paragraph = _Paragraph(element(p_cxml), None) + expected_text = ("Foo", "Bar", "Baz") + return paragraph, expected_text + + @pytest.fixture( + params=[ + ("a:p", None), + ("a:p/a:pPr", None), + ("a:p/a:pPr/a:lnSpc/a:spcPts{val=1800}", 228600), + ("a:p/a:pPr/a:lnSpc/a:spcPct{val=142000}", 1.42), + ("a:p/a:pPr/a:lnSpc/a:spcPct{val=124.64%}", 1.2464), + ] + ) + def spacing_get_fixture(self, request): + p_cxml, expected_value = request.param + paragraph = _Paragraph(element(p_cxml), None) + return paragraph, expected_value + + @pytest.fixture( + params=[ + ("a:p", 1.42, "a:p/a:pPr/a:lnSpc/a:spcPct{val=142000}"), + ("a:p", Pt(42), "a:p/a:pPr/a:lnSpc/a:spcPts{val=4200}"), + ( + "a:p/a:pPr/a:lnSpc/a:spcPct{val=110000}", + 0.875, + "a:p/a:pPr/a:lnSpc/a:spcPct{val=87500}", + ), + ( + "a:p/a:pPr/a:lnSpc/a:spcPts{val=600}", + Pt(42), + "a:p/a:pPr/a:lnSpc/a:spcPts{val=4200}", + ), + ( + "a:p/a:pPr/a:lnSpc/a:spcPts{val=1900}", + 0.925, + "a:p/a:pPr/a:lnSpc/a:spcPct{val=92500}", + ), + ( + "a:p/a:pPr/a:lnSpc/a:spcPct{val=150000}", + Pt(24), + "a:p/a:pPr/a:lnSpc/a:spcPts{val=2400}", + ), + ("a:p/a:pPr/a:lnSpc/a:spcPts{val=600}", None, "a:p/a:pPr"), + ("a:p/a:pPr/a:lnSpc/a:spcPct{val=150000}", None, "a:p/a:pPr"), + ] + ) + def spacing_set_fixture(self, request): + p_cxml, new_value, expected_p_cxml = request.param + paragraph = _Paragraph(element(p_cxml), None) + expected_xml = xml(expected_p_cxml) + return paragraph, new_value, expected_xml + + @pytest.fixture( + params=[ + # ---single-run--- + ('a:p/a:r/a:t"foobar"', "foobar"), + # ---multiple-runs--- + ('a:p/(a:r/a:t"foo",a:r/a:t"bar")', "foobar"), + # ---line-break between runs--- + ('a:p/(a:r/a:t"foo",a:br,a:r/a:t"bar")', "foo\vbar"), + # ---field between runs--- + ('a:p/(a:r/a:t"foo ",a:fld/a:t"42",a:r/a:t" bar")', "foo 42 bar"), + # ---line-break and field--- + ('a:p/(a:r/a:t" foo",a:br,a:fld/a:t"42")', " foo\v42"), + # ---other common p child elements included--- + ('a:p/(a:pPr,a:r/a:t"foobar",a:endParaRPr)', "foobar"), + # ---field by itself--- + ('a:p/a:fld/a:t"42"', "42"), + # ---line-break by itself--- + ("a:p/a:br", "\v"), + ] + ) + def text_get_fixture(self, request): + p_cxml, expected_value = request.param + p = element(p_cxml) + return p, expected_value + + # fixture components ----------------------------------- + + @pytest.fixture + def Font_(self, request): + return class_mock(request, "pptx.text.text.Font") + + @pytest.fixture + def p_bldr(self): + return a_p().with_nsdecls() + + @pytest.fixture + def p_with_r_xml(self): + run_bldr = an_r().with_child(a_t()) + return a_p().with_nsdecls().with_child(run_bldr).xml() + + @pytest.fixture + def paragraph(self, p_bldr): + return _Paragraph(p_bldr.element, None) + + +class Describe_Run(object): + """Unit-test suite for `pptx.text.text._Run` object.""" + + def it_provides_access_to_its_font(self, font_fixture): + run, rPr, Font_, font_ = font_fixture + font = run.font + Font_.assert_called_once_with(rPr) + assert font == font_ + + def it_provides_access_to_a_hyperlink_proxy(self, hyperlink_fixture): + run, rPr, _Hyperlink_, hlink_ = hyperlink_fixture + hlink = run.hyperlink + _Hyperlink_.assert_called_once_with(rPr, run) + assert hlink is hlink_ + + def it_can_get_the_text_of_the_run(self, text_get_fixture): + run, expected_value = text_get_fixture + text = run.text + assert text == expected_value + assert isinstance(text, str) + + @pytest.mark.parametrize( + "r_cxml, new_value, expected_r_cxml", + ( + ("a:r/a:t", "barfoo", 'a:r/a:t"barfoo"'), + ("a:r/a:t", "bar\x1bfoo", 'a:r/a:t"bar_x001B_foo"'), + ("a:r/a:t", "bar\tfoo", 'a:r/a:t"bar\tfoo"'), + ), + ) + def it_can_change_its_text(self, r_cxml, new_value, expected_r_cxml): + run = _Run(element(r_cxml), None) + run.text = new_value + assert run._r.xml == xml(expected_r_cxml) + + # fixtures --------------------------------------------- + + @pytest.fixture + def font_fixture(self, Font_, font_): + r = element("a:r/a:rPr") + rPr = r.rPr + run = _Run(r, None) + return run, rPr, Font_, font_ + + @pytest.fixture + def hyperlink_fixture(self, _Hyperlink_, hlink_): + r = element("a:r/a:rPr") + rPr = r.rPr + run = _Run(r, None) + return run, rPr, _Hyperlink_, hlink_ + + @pytest.fixture + def text_get_fixture(self): + r = element('a:r/a:t"foobar"') + run = _Run(r, None) + return run, "foobar" + + # fixture components ----------------------------------- + + @pytest.fixture + def Font_(self, request, font_): + return class_mock(request, "pptx.text.text.Font", return_value=font_) + + @pytest.fixture + def font_(self, request): + return instance_mock(request, Font) + + @pytest.fixture + def _Hyperlink_(self, request, hlink_): + return class_mock(request, "pptx.text.text._Hyperlink", return_value=hlink_) + + @pytest.fixture + def hlink_(self, request): + return instance_mock(request, _Hyperlink) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/unitdata.py b/tasks/tasksmith-74f059424102/environment/source/tests/unitdata.py new file mode 100644 index 0000000000000000000000000000000000000000..97864786595d2b80d179f59c532168cdba9cb36e --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/unitdata.py @@ -0,0 +1,120 @@ +"""Shared objects for unit data builder modules.""" + +from __future__ import annotations + +from pptx.oxml import parse_xml +from pptx.oxml.ns import nsdecls + + +class BaseBuilder(object): + """ + Provides common behavior for all data builders. + """ + + def __init__(self): + self._empty = False + self._nsdecls = "" + self._text = "" + self._xmlattrs = [] + self._xmlattr_method_map = {} + for attr_name in self.__attrs__: + base_name = attr_name.split(":")[1] if ":" in attr_name else attr_name + method_name = "with_%s" % base_name + self._xmlattr_method_map[method_name] = attr_name + self._child_bldrs = [] + + def __getattr__(self, name): + """ + Intercept attribute access to generalize "with_{xmlattr_name}()" + methods. + """ + if name in self._xmlattr_method_map: + + def with_xmlattr(value): + xmlattr_name = self._xmlattr_method_map[name] + self._set_xmlattr(xmlattr_name, value) + return self + + return with_xmlattr + + @property + def element(self): + """ + Element parsed from XML generated by builder in current state + """ + elm = parse_xml(self.xml()) + return elm + + def with_child(self, child_bldr): + """ + Cause new child element specified by *child_bldr* to be appended to + the children of this element. + """ + self._child_bldrs.append(child_bldr) + return self + + def with_nsdecls(self, *nspfxs): + """ + Cause the element to contain namespace declarations. By default, the + namespace prefixes defined in the Builder class are used. These can + be overridden by providing exlicit prefixes, e.g. + ``with_nsdecls('a', 'r')``. + """ + if not nspfxs: + nspfxs = self.__nspfxs__ + self._nsdecls = " %s" % nsdecls(*nspfxs) + return self + + def xml(self, indent=0): + """ + Return element XML based on attribute settings + """ + indent_str = " " * indent + if self._is_empty: + xml = "%s%s\n" % (indent_str, self._empty_element_tag) + else: + xml = "%s\n" % self._non_empty_element_xml(indent) + return xml + + @property + def _empty_element_tag(self): + return "<%s%s%s/>" % (self.__tag__, self._nsdecls, self._xmlattrs_str) + + @property + def _end_tag(self): + return "" % self.__tag__ + + @property + def _is_empty(self): + return len(self._child_bldrs) == 0 and len(self._text) == 0 + + def _non_empty_element_xml(self, indent): + indent_str = " " * indent + if self._text: + xml = "%s%s%s%s" % ( # pragma: no cover + indent_str, + self._start_tag, + self._text, + self._end_tag, + ) + else: + xml = "%s%s\n" % (indent_str, self._start_tag) + for child_bldr in self._child_bldrs: + xml += child_bldr.xml(indent + 2) + xml += "%s%s" % (indent_str, self._end_tag) + return xml + + def _set_xmlattr(self, xmlattr_name, value): + xmlattr_str = ' %s="%s"' % (xmlattr_name, str(value)) + self._xmlattrs.append(xmlattr_str) + + @property + def _start_tag(self): + return "<%s%s%s>" % (self.__tag__, self._nsdecls, self._xmlattrs_str) + + @property + def _xmlattrs_str(self): + """ + Return all element attributes as a string, like ' foo="bar" x="1"'. + """ + return "".join(self._xmlattrs) diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/__init__.py b/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5a5b584054c09ce6d6e00c66b5195379be9486 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/__init__.py @@ -0,0 +1,13 @@ +"""Helper objects for unit testing.""" + +from __future__ import annotations + + +def count(start=0, step=1): + """ + Local implementation of `itertools.count()` to allow v2.6 compatibility. + """ + n = start + while True: + yield n + n += step diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/cxml.py b/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/cxml.py new file mode 100644 index 0000000000000000000000000000000000000000..79e217c209ba81d23a45cb1f0bff72931c8cd12f --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/cxml.py @@ -0,0 +1,283 @@ +"""Parser for Compact XML Expression Language (CXEL) ('see-ex-ell'). + +CXEL is a compact XML specification language I made up that's useful for producing XML element +trees suitable for unit testing. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pyparsing import ( + Combine, + Forward, + Group, + Literal, + Optional, + Suppress, + Word, + alphanums, + alphas, + dblQuotedString, + delimitedList, + removeQuotes, + stringEnd, +) + +from pptx.oxml import parse_xml +from pptx.oxml.ns import _nsmap as nsmap + +if TYPE_CHECKING: + from pptx.oxml.xmlchemy import BaseOxmlElement + +# ==================================================================== +# api functions +# ==================================================================== + + +def element(cxel_str: str) -> BaseOxmlElement: + """Return an oxml element parsed from the XML generated from `cxel_str`.""" + _xml = xml(cxel_str) + return parse_xml(_xml) + + +def xml(cxel_str: str) -> str: + """Return the XML generated from `cxel_str`.""" + root_node.parseWithTabs() + root_token = root_node.parseString(cxel_str) + xml = root_token.element.xml + return xml + + +# ==================================================================== +# internals +# ==================================================================== + + +def nsdecls(*nspfxs): + """ + Return a string containing a namespace declaration for each of *nspfxs*, + in the order they are specified. + """ + nsdecls = "" + for nspfx in nspfxs: + nsdecls += ' xmlns:%s="%s"' % (nspfx, nsmap[nspfx]) + return nsdecls + + +class Element(object): + """ + Represents an XML element, having a namespace, tagname, attributes, and + may contain either text or children (but not both) or may be empty. + """ + + def __init__(self, tagname, attrs, text): + self._tagname = tagname + self._attrs = attrs + self._text = text + self._children = [] + self._is_root = False + + def __repr__(self): + """ + Provide a more meaningful repr value for an Element object, one that + displays the tagname as a simple empty element, e.g. ````. + """ + return "<%s/>" % self._tagname # pragma: no cover + + def connect_children(self, child_node_list): + """ + Make each of the elements appearing in *child_node_list* a child of + this element. + """ + for node in child_node_list: + child = node.element + self._children.append(child) + + @classmethod + def from_token(cls, token): + """ + Return an ``Element`` object constructed from a parser element token. + """ + tagname = token.tagname + attrs = [(name, value) for name, value in token.attr_list] + text = token.text + return cls(tagname, attrs, text) + + @property + def is_root(self): + """ + |True| if this element is the root of the tree and should include the + namespace prefixes. |False| otherwise. + """ + return self._is_root + + @is_root.setter + def is_root(self, value): + self._is_root = bool(value) + + @property + def local_nspfxs(self): + """ + The namespace prefixes local to this element, both on the tagname and + all of its attributes. An empty string (``''``) is used to represent + the default namespace for an element tag having no prefix. + """ + + def nspfx(name, is_element=False): + idx = name.find(":") + if idx == -1: + return "" if is_element else None + return name[:idx] + + nspfxs = [nspfx(self._tagname, True)] + for name, val in self._attrs: + pfx = nspfx(name) + if pfx is None or pfx in nspfxs: + continue # pragma: no cover + nspfxs.append(pfx) + return nspfxs + + @property + def nspfxs(self): + """ + A sequence containing each of the namespace prefixes appearing in + this tree. Each prefix appears once and only once, and in document + order. + """ + + def merge(seq, seq_2): + for item in seq_2: + if item in seq: + continue + seq.append(item) + + nspfxs = self.local_nspfxs + for child in self._children: + merge(nspfxs, child.nspfxs) + return nspfxs + + @property + def xml(self): + """ + The XML corresponding to the tree rooted at this element, + pretty-printed using 2-spaces indentation at each level and with + a trailing '\n'. + """ + return self._xml(indent=0) + + def _xml(self, indent): + """ + Return a string containing the XML of this element and all its + children with a starting indent of *indent* spaces. + """ + self._indent_str = " " * indent + xml = self._start_tag + for child in self._children: + xml += child._xml(indent + 2) + xml += self._end_tag + return xml + + @property + def _start_tag(self): + """ + The text of the opening tag of this element, including attributes. If + this is the root element, a namespace declaration for each of the + namespace prefixes that occur in this tree is added in front of any + attributes. If this element contains text, that text follows the + start tag. If not, and this element has no children, an empty tag is + returned. Otherwise, an opening tag is returned, followed by + a newline. The tag is indented by this element's indent value in all + cases. + """ + _nsdecls = nsdecls(*self.nspfxs) if self.is_root else "" + tag = "%s<%s%s" % (self._indent_str, self._tagname, _nsdecls) + for attr in self._attrs: + name, value = attr + tag += ' %s="%s"' % (name, value) + if self._text: + tag += ">%s" % self._text + elif self._children: + tag += ">\n" + else: + tag += "/>\n" + return tag + + @property + def _end_tag(self): + """ + The text of the closing tag of this element, if there is one. If the + element contains text, no leading indentation is included. + """ + if self._text: + tag = "\n" % self._tagname + elif self._children: + tag = "%s\n" % (self._indent_str, self._tagname) + else: + tag = "" + return tag + + +# ==================================================================== +# parser +# ==================================================================== + +# parse actions ---------------------------------- + + +def connect_node_children(s, loc, tokens): + node = tokens[0] + node.element.connect_children(node.child_node_list) + + +def connect_root_node_children(root_node): + root_node.element.connect_children(root_node.child_node_list) + root_node.element.is_root = True + + +def grammar(): + # terminals ---------------------------------- + colon = Literal(":") + equal = Suppress("=") + slash = Suppress("/") + open_paren = Suppress("(") + close_paren = Suppress(")") + open_brace = Suppress("{") + close_brace = Suppress("}") + + # np:tagName --------------------------------- + nspfx = Word(alphas) + local_name = Word(alphanums) + tagname = Combine(nspfx + colon + local_name) + + # np:attr_name=attr_val ---------------------- + attr_name = Word(alphas + ":") + attr_val = Word(alphanums + " %-./:_") + attr_def = Group(attr_name + equal + attr_val) + attr_list = open_brace + delimitedList(attr_def) + close_brace + + text = dblQuotedString.setParseAction(removeQuotes) + + # w:jc{val=right} ---------------------------- + element = ( + tagname("tagname") + + Group(Optional(attr_list))("attr_list") + + Optional(text, default="")("text") + ).setParseAction(Element.from_token) + + child_node_list = Forward() + + node = Group( + element("element") + Group(Optional(slash + child_node_list))("child_node_list") + ).setParseAction(connect_node_children) + + child_node_list << (open_paren + delimitedList(node) + close_paren | node) + + root_node = ( + element("element") + Group(Optional(slash + child_node_list))("child_node_list") + stringEnd + ).setParseAction(connect_root_node_children) + + return root_node + + +root_node = grammar() diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/file.py b/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/file.py new file mode 100644 index 0000000000000000000000000000000000000000..938d42ef0221bdfbf94ed24733b34ad0767ae4e5 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/file.py @@ -0,0 +1,57 @@ +"""Utility functions for loading files for unit testing.""" + +import os +import sys + +_thisdir = os.path.split(__file__)[0] +test_file_dir = os.path.abspath(os.path.join(_thisdir, "..", "test_files")) + + +def absjoin(*paths: str): + return os.path.abspath(os.path.join(*paths)) + + +def snippet_bytes(snippet_file_name: str): + """Return bytes read from snippet file having `snippet_file_name`.""" + snippet_file_path = os.path.join(test_file_dir, "snippets", "%s.txt" % snippet_file_name) + with open(snippet_file_path, "rb") as f: + return f.read().strip() + + +def snippet_seq(name: str, offset: int = 0, count: int = sys.maxsize): + """ + Return a tuple containing the unicode text snippets read from the snippet + file having *name*. Snippets are delimited by a blank line. If specified, + *count* snippets starting at *offset* are returned. + """ + path = os.path.join(test_file_dir, "snippets", "%s.txt" % name) + with open(path, "rb") as f: + text = f.read().decode("utf-8") + snippets = text.split("\n\n") + start, end = offset, offset + count + return tuple(snippets[start:end]) + + +def snippet_text(snippet_file_name: str): + """ + Return the unicode text read from the test snippet file having + *snippet_file_name*. + """ + snippet_file_path = os.path.join(test_file_dir, "snippets", "%s.txt" % snippet_file_name) + with open(snippet_file_path, "rb") as f: + snippet_bytes = f.read() + return snippet_bytes.decode("utf-8") + + +def testfile(name: str): + """ + Return the absolute path to test file having *name*. + """ + return absjoin(test_file_dir, name) + + +def testfile_bytes(*segments: str): + """Return bytes of file at path formed by adding `segments` to test file dir.""" + path = os.path.join(test_file_dir, *segments) + with open(path, "rb") as f: + return f.read() diff --git a/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/mock.py b/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/mock.py new file mode 100644 index 0000000000000000000000000000000000000000..3b681d98339ed33d1ff1fdfd4e59cc3e4f68456a --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/tests/unitutil/mock.py @@ -0,0 +1,130 @@ +"""Utility functions wrapping the excellent `mock` library.""" + +from __future__ import annotations + +from typing import Any +from unittest import mock +from unittest.mock import ( + ANY, + MagicMock, + Mock, + PropertyMock, + call, + create_autospec, + mock_open, + patch, +) + +from pytest import FixtureRequest, LogCaptureFixture # noqa: PT013 + +__all__ = ["ANY", "FixtureRequest", "LogCaptureFixture", "MagicMock", "call", "mock"] + + +def class_mock( + request: FixtureRequest, q_class_name: str, autospec: bool = True, **kwargs: Any +) -> Mock: + """Return a mock patching the class with qualified name *q_class_name*. + + The mock is autospec'ed based on the patched class unless the optional argument + *autospec* is set to False. Any other keyword arguments are passed through to + Mock(). Patch is reversed after calling test returns. + """ + _patch = patch(q_class_name, autospec=autospec, **kwargs) + request.addfinalizer(_patch.stop) + return _patch.start() + + +def cls_attr_mock( + request: FixtureRequest, cls: type, attr_name: str, name: str | None = None, **kwargs: Any +) -> Mock: + """Return a mock for an attribute (class variable) `attr_name` on `cls`. + + Patch is reversed after pytest uses it. + """ + name = request.fixturename if name is None else name + _patch = patch.object(cls, attr_name, name=name, **kwargs) + request.addfinalizer(_patch.stop) + return _patch.start() + + +def function_mock( + request: FixtureRequest, q_function_name: str, autospec: bool = True, **kwargs: Any +): + """Return mock patching function with qualified name `q_function_name`. + + Patch is reversed after calling test returns. + """ + _patch = patch(q_function_name, autospec=autospec, **kwargs) + request.addfinalizer(_patch.stop) + return _patch.start() + + +def initializer_mock(request: FixtureRequest, cls: type, autospec: bool = True, **kwargs: Any): + """Return mock for __init__() method on `cls`. + + The patch is reversed after pytest uses it. + """ + _patch = patch.object(cls, "__init__", autospec=autospec, return_value=None, **kwargs) + request.addfinalizer(_patch.stop) + return _patch.start() + + +def instance_mock( + request: FixtureRequest, + cls: type, + name: str | None = None, + spec_set: bool = True, + **kwargs: Any, +) -> Mock: + """Return mock for instance of `cls` that draws its spec from that class. + + The mock does not allow new attributes to be set on the instance. If `name` is + missing or |None|, the name of the returned |Mock| instance is set to + `request.fixturename`. Additional keyword arguments are passed through to the Mock() + call that creates the mock. + """ + name = name if name is not None else request.fixturename + return create_autospec(cls, _name=name, spec_set=spec_set, instance=True, **kwargs) + + +def loose_mock(request: FixtureRequest, name: str | None = None, **kwargs: Any): + """Return a "loose" mock, meaning it has no spec to constrain calls on it. + + Additional keyword arguments are passed through to Mock(). If called without a name, + it is assigned the name of the fixture. + """ + return Mock(name=request.fixturename if name is None else name, **kwargs) + + +def method_mock( + request: FixtureRequest, cls: type, method_name: str, autospec: bool = True, **kwargs: Any +): + """Return mock for method `method_name` on `cls`. + + The patch is reversed after pytest uses it. + """ + _patch = patch.object(cls, method_name, autospec=autospec, **kwargs) + request.addfinalizer(_patch.stop) + return _patch.start() + + +def open_mock(request: FixtureRequest, module_name: str, **kwargs: Any): + """Return a mock for the builtin `open()` method in `module_name`.""" + target = "%s.open" % module_name + _patch = patch(target, mock_open(), create=True, **kwargs) + request.addfinalizer(_patch.stop) + return _patch.start() + + +def property_mock(request: FixtureRequest, cls: type, prop_name: str, **kwargs: Any): + """Return a mock for property `prop_name` on class `cls`.""" + _patch = patch.object(cls, prop_name, new_callable=PropertyMock, **kwargs) + request.addfinalizer(_patch.stop) + return _patch.start() + + +def var_mock(request: FixtureRequest, q_var_name: str, **kwargs: Any): + """Return mock patching the variable with qualified name *q_var_name*.""" + _patch = patch(q_var_name, **kwargs) + request.addfinalizer(_patch.stop) + return _patch.start() diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/behave/__init__.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/behave/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f8ffc205873d0d7ea5cf7dad12ac53324b9f25e4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/behave/__init__.pyi @@ -0,0 +1,17 @@ +from __future__ import annotations + +from typing import Callable + +from typing_extensions import TypeAlias + +from .runner import Context + +_ThreeArgStep: TypeAlias = Callable[[Context, str, str, str], None] +_TwoArgStep: TypeAlias = Callable[[Context, str, str], None] +_OneArgStep: TypeAlias = Callable[[Context, str], None] +_NoArgStep: TypeAlias = Callable[[Context], None] +_Step: TypeAlias = _NoArgStep | _OneArgStep | _TwoArgStep | _ThreeArgStep + +def given(phrase: str) -> Callable[[_Step], _Step]: ... +def when(phrase: str) -> Callable[[_Step], _Step]: ... +def then(phrase: str) -> Callable[[_Step], _Step]: ... diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/behave/runner.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/behave/runner.pyi new file mode 100644 index 0000000000000000000000000000000000000000..aaea74dade4a957d65a34741df0c2e6ded2f82fe --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/behave/runner.pyi @@ -0,0 +1,3 @@ +from types import SimpleNamespace + +class Context(SimpleNamespace): ... diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/lxml/_types.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/_types.pyi new file mode 100644 index 0000000000000000000000000000000000000000..34d2095db5576b34f514818dc1116482913b7071 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/_types.pyi @@ -0,0 +1,40 @@ +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +from typing import Any, Callable, Collection, Literal, Mapping, Protocol, TypeVar + +from typing_extensions import TypeAlias + +from .etree import QName, _Element, _ElementTree + +_ET = TypeVar("_ET", bound=_Element, default=_Element) +_ET_co = TypeVar("_ET_co", bound=_Element, default=_Element, covariant=True) +_KT_co = TypeVar("_KT_co", covariant=True) +_VT_co = TypeVar("_VT_co", covariant=True) + +_AttrName: TypeAlias = str + +_AttrVal: TypeAlias = _TextArg + +_ElemPathArg: TypeAlias = str | QName + +_ElementOrTree: TypeAlias = _ET | _ElementTree[_ET] + +_NSMapArg = Mapping[None, str] | Mapping[str, str] | Mapping[str | None, str] + +_NonDefaultNSMapArg = Mapping[str, str] + +_OutputMethodArg = Literal["html", "text", "xml"] + +_TagName: TypeAlias = str + +_TagSelector: TypeAlias = _TagName | Callable[..., _Element] + +# String argument also support QName in various places +_TextArg: TypeAlias = str | bytes | QName + +_XPathObject = Any + +class SupportsLaxedItems(Protocol[_KT_co, _VT_co]): + def items(self) -> Collection[tuple[_KT_co, _VT_co]]: ... diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/__init__.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e649ce0b294723a195e029ac11215aa5da3ee827 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/__init__.pyi @@ -0,0 +1,18 @@ +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +from ._classlookup import ElementBase as ElementBase +from ._classlookup import ElementDefaultClassLookup as ElementDefaultClassLookup +from ._cleanup import strip_elements as strip_elements +from ._element import _Element as _Element +from ._element import _ElementTree as _ElementTree +from ._module_func import fromstring as fromstring +from ._module_func import tostring as tostring +from ._module_misc import QName as QName +from ._nsclasses import ElementNamespaceClassLookup as ElementNamespaceClassLookup +from ._parser import HTMLParser as HTMLParser +from ._parser import XMLParser as XMLParser + +class CDATA: + def __init__(self, data: str) -> None: ... diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_classlookup.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_classlookup.pyi new file mode 100644 index 0000000000000000000000000000000000000000..03313c3c415ccae6751fc407b6f958d5c17c93f8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_classlookup.pyi @@ -0,0 +1,75 @@ +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +from ._element import _Element + +class ElementBase(_Element): + """The public Element class + + Original Docstring + ------------------ + All custom Element classes must inherit from this one. + To create an Element, use the `Element()` factory. + + BIG FAT WARNING: Subclasses *must not* override `__init__` or + `__new__` as it is absolutely undefined when these objects will be + created or destroyed. All persistent state of Elements must be + stored in the underlying XML. If you really need to initialize + the object after creation, you can implement an ``_init(self)`` + method that will be called directly after object creation. + + Subclasses of this class can be instantiated to create a new + Element. By default, the tag name will be the class name and the + namespace will be empty. You can modify this with the following + class attributes: + + * TAG - the tag name, possibly containing a namespace in Clark + notation + + * NAMESPACE - the default namespace URI, unless provided as part + of the TAG attribute. + + * HTML - flag if the class is an HTML tag, as opposed to an XML + tag. This only applies to un-namespaced tags and defaults to + false (i.e. XML). + + * PARSER - the parser that provides the configuration for the + newly created document. Providing an HTML parser here will + default to creating an HTML element. + + In user code, the latter three are commonly inherited in class + hierarchies that implement a common namespace. + """ + + def __init__( + self, + *children: object, + attrib: dict[str, str] | None = None, + **_extra: str, + ) -> None: ... + def _init(self) -> None: ... + +class ElementClassLookup: + """Superclass of Element class lookups""" + +class ElementDefaultClassLookup(ElementClassLookup): + """Element class lookup scheme that always returns the default Element + class. + + The keyword arguments ``element``, ``comment``, ``pi`` and ``entity`` + accept the respective Element classes.""" + + def __init__( + self, + element: type[ElementBase] | None = None, + ) -> None: ... + +class FallbackElementClassLookup(ElementClassLookup): + """Superclass of Element class lookups with additional fallback""" + + @property + def fallback(self) -> ElementClassLookup | None: ... + def __init__(self, fallback: ElementClassLookup | None = None) -> None: ... + def set_fallback(self, lookup: ElementClassLookup) -> None: + """Sets the fallback scheme for this lookup method""" diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_cleanup.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_cleanup.pyi new file mode 100644 index 0000000000000000000000000000000000000000..29e6bd8616a136899ed056941ab1271f70fab328 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_cleanup.pyi @@ -0,0 +1,21 @@ +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +from typing import Collection, overload + +from .._types import _ElementOrTree, _TagSelector + +@overload +def strip_elements( + __tree_or_elem: _ElementOrTree, + *tag_names: _TagSelector, + with_tail: bool = True, +) -> None: ... +@overload +def strip_elements( + __tree_or_elem: _ElementOrTree, + __tag: Collection[_TagSelector], + /, + with_tail: bool = True, +) -> None: ... diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_element.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_element.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f25a147a93861b39b5c6ef0e98d6e8ef831079c4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_element.pyi @@ -0,0 +1,96 @@ +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +from typing import Collection, Generic, Iterable, Iterator, TypeVar, overload + +from typing_extensions import Self + +from .. import _types as _t +from . import CDATA + +_T = TypeVar("_T") + +# Behaves like MutableMapping but deviates a lot in details +class _Attrib: + def __bool__(self) -> bool: ... + def __contains__(self, __o: object) -> bool: ... + def __delitem__(self, __k: _t._AttrName) -> None: ... + def __getitem__(self, __k: _t._AttrName) -> str: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __setitem__(self, __k: _t._AttrName, __v: _t._AttrVal) -> None: ... + @property + def _element(self) -> _Element: ... + def get(self, key: _t._AttrName, default: _T) -> str | _T: ... + def has_key(self, key: _t._AttrName) -> bool: ... + def items(self) -> list[tuple[str, str]]: ... + def iteritems(self) -> Iterator[tuple[str, str]]: ... + def iterkeys(self) -> Iterator[str]: ... + def itervalues(self) -> Iterator[str]: ... + def keys(self) -> list[str]: ... + def values(self) -> list[str]: ... + +class _Element: + @overload + def __getitem__(self, __x: int) -> _Element: ... + @overload + def __getitem__(self, __x: slice) -> list[_Element]: ... + def __contains__(self, __o: object) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_Element]: ... + def addprevious(self, element: _Element) -> None: ... + def append(self, element: _Element) -> None: ... + @property + def attrib(self) -> _Attrib: ... + def find(self, path: _t._ElemPathArg) -> Self | None: ... + def findall( + self, path: _t._ElemPathArg, namespaces: _t._NSMapArg | None = None + ) -> list[_Element]: ... + @overload + def get(self, key: _t._AttrName) -> str | None: ... + @overload + def get(self, key: _t._AttrName, default: _T) -> str | _T: ... + def getparent(self) -> _Element | None: ... + def index(self, child: _Element, start: int | None = None, end: int | None = None) -> int: ... + def iterancestors( + self, *, tag: _t._TagSelector | Collection[_t._TagSelector] | None = None + ) -> Iterator[Self]: ... + @overload + def iterchildren( + self, *tags: _t._TagSelector, reversed: bool = False + ) -> Iterator[_Element]: ... + @overload + def iterchildren( + self, + *, + tag: _t._TagSelector | Iterable[_t._TagSelector] | None = None, + reversed: bool = False, + ) -> Iterator[_Element]: ... + @overload + def itertext(self, *tags: _t._TagSelector, with_tail: bool = True) -> Iterator[str]: ... + @overload + def itertext( + self, + *, + tag: _t._TagSelector | Collection[_t._TagSelector] | None = None, + with_tail: bool = True, + ) -> Iterator[str]: ... + def remove(self, element: _Element) -> None: ... + def set(self, key: _t._AttrName, value: _t._AttrVal) -> None: ... + @property + def tag(self) -> str: ... + @property + def tail(self) -> str | None: ... + @property + def text(self) -> str | None: ... + @text.setter + def text(self, value: str | CDATA | None) -> None: ... + def xpath( + self, + _path: str, + /, + namespaces: _t._NonDefaultNSMapArg | None = None, + ) -> _t._XPathObject: ... + +class _ElementTree(Generic[_t._ET_co]): ... diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_module_func.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_module_func.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e2910f503d169c29a1d2aba3333c629b9a9ff61c --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_module_func.pyi @@ -0,0 +1,38 @@ +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +from typing import Literal, overload + +from .._types import _ElementOrTree, _OutputMethodArg +from ..etree import HTMLParser, XMLParser +from ._element import _Element + +def fromstring(text: str | bytes, parser: XMLParser | HTMLParser) -> _Element: ... + +# -- Native str, no XML declaration -- +@overload +def tostring( # type: ignore[overload-overlap] + element_or_tree: _ElementOrTree, + *, + encoding: type[str] | Literal["unicode"], + method: _OutputMethodArg = "xml", + pretty_print: bool = False, + with_tail: bool = True, + standalone: bool | None = None, + doctype: str | None = None, +) -> str: ... + +# -- bytes, str encoded with `encoding`, no XML declaration -- +@overload +def tostring( + element_or_tree: _ElementOrTree, + *, + encoding: str | None = None, + method: _OutputMethodArg = "xml", + xml_declaration: bool | None = None, + pretty_print: bool = False, + with_tail: bool = True, + standalone: bool | None = None, + doctype: str | None = None, +) -> bytes: ... diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_module_misc.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_module_misc.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9da021f0c5d64811c958cfe289870d00ff97b508 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_module_misc.pyi @@ -0,0 +1,5 @@ +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +class QName: ... diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_nsclasses.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_nsclasses.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5118f7a80bf6617401ff76ed3e782e984360ed23 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_nsclasses.pyi @@ -0,0 +1,31 @@ +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +from typing import Iterable, Iterator, MutableMapping, TypeVar + +from .._types import SupportsLaxedItems +from ._classlookup import ElementBase, ElementClassLookup, FallbackElementClassLookup + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +class _NamespaceRegistry(MutableMapping[_KT, _VT]): + def __delitem__(self, __key: _KT) -> None: ... + def __getitem__(self, __key: _KT) -> _VT: ... + def __setitem__(self, __key: _KT, __value: _VT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __len__(self) -> int: ... + def update( # type: ignore[override] + self, + class_dict_iterable: SupportsLaxedItems[_KT, _VT] | Iterable[tuple[_KT, _VT]], + ) -> None: ... + def items(self) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] + def iteritems(self) -> Iterator[tuple[_KT, _VT]]: ... + def clear(self) -> None: ... + +class _ClassNamespaceRegistry(_NamespaceRegistry[str | None, type[ElementBase]]): ... + +class ElementNamespaceClassLookup(FallbackElementClassLookup): + def __init__(self, fallback: ElementClassLookup | None = None) -> None: ... + def get_namespace(self, ns_uri: str | None) -> _ClassNamespaceRegistry: ... diff --git a/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_parser.pyi b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_parser.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2fdd144fa83c36df7dba2b0b7a5f7a7ef79d9606 --- /dev/null +++ b/tasks/tasksmith-74f059424102/environment/source/typings/lxml/etree/_parser.pyi @@ -0,0 +1,81 @@ +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +from typing import Literal + +from ._classlookup import ElementClassLookup +from .._types import _ET_co, _NSMapArg, _TagName, SupportsLaxedItems + +class HTMLParser: + def __init__( + self, + *, + encoding: str | None = None, + remove_blank_text: bool = False, + remove_comments: bool = False, + remove_pis: bool = False, + strip_cdata: bool = True, + no_network: bool = True, + recover: bool = True, + compact: bool = True, + default_doctype: bool = True, + collect_ids: bool = True, + huge_tree: bool = False, + ) -> None: ... + def set_element_class_lookup(self, lookup: ElementClassLookup | None = None) -> None: ... + +class XMLParser: + def __init__( + self, + *, + attribute_defaults: bool = False, + collect_ids: bool = True, + compact: bool = True, + dtd_validation: bool = False, + encoding: str | None = None, + huge_tree: bool = False, + load_dtd: bool = False, + no_network: bool = True, + ns_clean: bool = False, + recover: bool = False, + remove_blank_text: bool = False, + remove_comments: bool = False, + remove_pis: bool = False, + resolve_entities: bool | Literal["internal"] = "internal", + strip_cdata: bool = True, + ) -> None: ... + def makeelement( + self, + _tag: _TagName, + /, + attrib: SupportsLaxedItems[str, str] | None = None, + nsmap: _NSMapArg | None = None, + **_extra: str, + ) -> _ET_co: ... + def set_element_class_lookup(self, lookup: ElementClassLookup | None = None) -> None: + """ + Notes + ----- + When calling this method, it is advised to also change typing + specialization of concerned parser too, because current python + typing system can't change it automatically. + + Example + ------- + Following code demonstrates how to create ``lxml.html.HTMLParser`` + manually from ``lxml.etree.HTMLParser``:: + + ```python + parser = etree.HTMLParser() + reveal_type(parser) # HTMLParser[_Element] + if TYPE_CHECKING: + parser = cast('etree.HTMLParser[HtmlElement]', parser) + else: + parser.set_element_class_lookup( + html.HtmlElementClassLookup()) + result = etree.fromstring(data, parser=parser) + reveal_type(result) # HtmlElement + ``` + """ + ... diff --git a/tasks/tasksmith-74f059424102/instruction.md b/tasks/tasksmith-74f059424102/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84001b5d0d4f3ac6ed4420f39e1aab4c20f24ff1 --- /dev/null +++ b/tasks/tasksmith-74f059424102/instruction.md @@ -0,0 +1,15 @@ +In `CT_SlideIdList._next_id`, the "max + 1" algorithm for picking the next slide ID must stay within the valid range 256–2,147,483,647 (inclusive). + +**Normal behaviour (unchanged):** When no slides exist, return 256. When existing IDs are all in range, return `max(used_ids) + 1`. + +**New requirement – fallback when max ID is saturated:** If `max(used_ids) + 1` would exceed 2,147,483,647, search upward from 256 for the first integer in [256, 2,147,483,647] that is not already in use, and return that value. Out-of-range IDs already present (e.g. values below 256 or above 2,147,483,647) must be ignored during the fallback search. + +Observable examples for the fallback path: +- Only `[2147483647]` used → return `256` +- Only `[2147483648]` used (out-of-range) → return `256` +- `[256, 2147483647]` used → return `257` +- `[256, 257, 2147483647]` used → return `258` +- `[245, 256, 2147483647]` used (245 is out-of-range) → return `257` +- `[2147483646]` used → return `2147483647` (normal path still works here) + +Work in `/workspace`. Submit your fix in Python source files under `src/pptx`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files. diff --git a/tasks/tasksmith-74f059424102/solution/reference/src/pptx/oxml/presentation.py b/tasks/tasksmith-74f059424102/solution/reference/src/pptx/oxml/presentation.py new file mode 100644 index 0000000000000000000000000000000000000000..2544724930aa7e51908a42ae30ffbd51c58de632 --- /dev/null +++ b/tasks/tasksmith-74f059424102/solution/reference/src/pptx/oxml/presentation.py @@ -0,0 +1,130 @@ +"""Custom element classes for presentation-related XML elements.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Callable, cast + +from pptx.oxml.simpletypes import ST_SlideId, ST_SlideSizeCoordinate, XsdString +from pptx.oxml.xmlchemy import BaseOxmlElement, RequiredAttribute, ZeroOrMore, ZeroOrOne + +if TYPE_CHECKING: + from pptx.util import Length + + +class CT_Presentation(BaseOxmlElement): + """`p:presentation` element, root of the Presentation part stored as `/ppt/presentation.xml`.""" + + get_or_add_sldSz: Callable[[], CT_SlideSize] + get_or_add_sldIdLst: Callable[[], CT_SlideIdList] + get_or_add_sldMasterIdLst: Callable[[], CT_SlideMasterIdList] + + sldMasterIdLst: CT_SlideMasterIdList | None = ( + ZeroOrOne( # pyright: ignore[reportAssignmentType] + "p:sldMasterIdLst", + successors=( + "p:notesMasterIdLst", + "p:handoutMasterIdLst", + "p:sldIdLst", + "p:sldSz", + "p:notesSz", + ), + ) + ) + sldIdLst: CT_SlideIdList | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "p:sldIdLst", successors=("p:sldSz", "p:notesSz") + ) + sldSz: CT_SlideSize | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] + "p:sldSz", successors=("p:notesSz",) + ) + + +class CT_SlideId(BaseOxmlElement): + """`p:sldId` element. + + Direct child of `p:sldIdLst` that contains an `rId` reference to a slide in the presentation. + """ + + id: int = RequiredAttribute("id", ST_SlideId) # pyright: ignore[reportAssignmentType] + rId: str = RequiredAttribute("r:id", XsdString) # pyright: ignore[reportAssignmentType] + + +class CT_SlideIdList(BaseOxmlElement): + """`p:sldIdLst` element. + + Direct child of that contains a list of the slide parts in the presentation. + """ + + sldId_lst: list[CT_SlideId] + + _add_sldId: Callable[..., CT_SlideId] + sldId = ZeroOrMore("p:sldId") + + def add_sldId(self, rId: str) -> CT_SlideId: + """Create and return a reference to a new `p:sldId` child element. + + The new `p:sldId` element has its r:id attribute set to `rId`. + """ + return self._add_sldId(id=self._next_id, rId=rId) + + @property + def _next_id(self) -> int: + """The next available slide ID as an `int`. + + Valid slide IDs start at 256. The next integer value greater than the max value in use is + chosen, which minimizes that chance of reusing the id of a deleted slide. + """ + MIN_SLIDE_ID = 256 + MAX_SLIDE_ID = 2147483647 + + used_ids = [int(s) for s in cast(list[str], self.xpath("./p:sldId/@id"))] + simple_next = max([MIN_SLIDE_ID - 1] + used_ids) + 1 + if simple_next <= MAX_SLIDE_ID: + return simple_next + + # -- fall back to search for next unused from bottom -- + valid_used_ids = sorted(id for id in used_ids if (MIN_SLIDE_ID <= id <= MAX_SLIDE_ID)) + return ( + next( + candidate_id + for candidate_id, used_id in enumerate(valid_used_ids, start=MIN_SLIDE_ID) + if candidate_id != used_id + ) + if valid_used_ids + else 256 + ) + + +class CT_SlideMasterIdList(BaseOxmlElement): + """`p:sldMasterIdLst` element. + + Child of `p:presentation` containing references to the slide masters that belong to the + presentation. + """ + + sldMasterId_lst: list[CT_SlideMasterIdListEntry] + + sldMasterId = ZeroOrMore("p:sldMasterId") + + +class CT_SlideMasterIdListEntry(BaseOxmlElement): + """ + ```` element, child of ```` containing + a reference to a slide master. + """ + + rId: str = RequiredAttribute("r:id", XsdString) # pyright: ignore[reportAssignmentType] + + +class CT_SlideSize(BaseOxmlElement): + """`p:sldSz` element. + + Direct child of that contains the width and height of slides in the + presentation. + """ + + cx: Length = RequiredAttribute( # pyright: ignore[reportAssignmentType] + "cx", ST_SlideSizeCoordinate + ) + cy: Length = RequiredAttribute( # pyright: ignore[reportAssignmentType] + "cy", ST_SlideSizeCoordinate + ) diff --git a/tasks/tasksmith-74f059424102/solution/solve.sh b/tasks/tasksmith-74f059424102/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..fc77a377c8c18df85019c959372db2ceb0f4f30b --- /dev/null +++ b/tasks/tasksmith-74f059424102/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p -- /workspace/src/pptx/oxml +cp /solution/reference/src/pptx/oxml/presentation.py /workspace/src/pptx/oxml/presentation.py diff --git a/tasks/tasksmith-74f059424102/task.toml b/tasks/tasksmith-74f059424102/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1911db621c377934de9c3bac9d129630d3decce9 --- /dev/null +++ b/tasks/tasksmith-74f059424102/task.toml @@ -0,0 +1,1734 @@ +schema_version = "1.3" + +[task] +name = "repo2rlenv/tasksmith-74f059424102" + +[metadata.repo2env] +recipe = "tasksmith" +recipe_version = "1" +source_url = "https://github.com/scanny/python-pptx/pull/994" +source_head = "64fb8b83494b3dee9c4c0049c32ca5d98fc05983" +source_base = "d5c95be6d51dbf1db6d99951bdb28efb86054de7" +workspace_strategy = "head_minus_source_patch" +source_diff_sha256 = "fedbc945adcbaa1a97f943913ba3ab98ef7df30697a9eb4a1fee52ee3701478a" +acceptance_profile = "practical-generation-v1" +upstream_test_policy = "retain" +reward_kinds = [ + "test_execution", +] +quality_status = "exported" +fail_to_pass_count = 5 +pass_to_pass_count = 7 +tracked_files = [ + "environment/Dockerfile", + "environment/source/.github/workflows/ci.yml", + "environment/source/.gitignore", + "environment/source/.travis.yml", + "environment/source/Dockerfile", + "environment/source/HISTORY.rst", + "environment/source/LICENSE", + "environment/source/MANIFEST.in", + "environment/source/README.rst", + "environment/source/docs/.themes/armstrong/LICENSE", + "environment/source/docs/.themes/armstrong/layout.html", + "environment/source/docs/.themes/armstrong/rtd-themes.conf", + "environment/source/docs/.themes/armstrong/static/rtd.css_t", + "environment/source/docs/.themes/armstrong/theme.conf", + "environment/source/docs/.themes/armstrong/theme.conf.orig", + "environment/source/docs/Makefile", + "environment/source/docs/_static/img/add-picture.png", + "environment/source/docs/_static/img/add-shape.png", + "environment/source/docs/_static/img/add-table.png", + "environment/source/docs/_static/img/add-textbox.png", + "environment/source/docs/_static/img/bullet-slide.png", + "environment/source/docs/_static/img/chart-01.png", + "environment/source/docs/_static/img/chart-02.png", + "environment/source/docs/_static/img/chart-03.png", + "environment/source/docs/_static/img/chart-04.png", + "environment/source/docs/_static/img/chart-05.png", + "environment/source/docs/_static/img/chart-06.png", + "environment/source/docs/_static/img/chart-07.png", + "environment/source/docs/_static/img/chart-08.png", + "environment/source/docs/_static/img/chart-09.png", + "environment/source/docs/_static/img/freeform-01.png", + "environment/source/docs/_static/img/freeform-02.png", + "environment/source/docs/_static/img/freeform-03.png", + "environment/source/docs/_static/img/hello-world.png", + "environment/source/docs/_static/img/table-01.png", + "environment/source/docs/_static/img/table-02.png", + "environment/source/docs/_static/img/table-03.png", + "environment/source/docs/_static/img/table-04.png", + "environment/source/docs/_static/img/table-05.png", + "environment/source/docs/_static/img/table-06.png", + "environment/source/docs/_static/img/table-07.png", + "environment/source/docs/_templates/sidebarlinks.html", + "environment/source/docs/api/action.rst", + "environment/source/docs/api/chart-data.rst", + "environment/source/docs/api/chart.rst", + "environment/source/docs/api/dml.rst", + "environment/source/docs/api/enum/ExcelNumFormat.rst", + "environment/source/docs/api/enum/MsoAutoShapeType.rst", + "environment/source/docs/api/enum/MsoAutoSize.rst", + "environment/source/docs/api/enum/MsoColorType.rst", + "environment/source/docs/api/enum/MsoConnectorType.rst", + "environment/source/docs/api/enum/MsoFillType.rst", + "environment/source/docs/api/enum/MsoLanguageId.rst", + "environment/source/docs/api/enum/MsoLineDashStyle.rst", + "environment/source/docs/api/enum/MsoPatternType.rst", + "environment/source/docs/api/enum/MsoShapeType.rst", + "environment/source/docs/api/enum/MsoTextUnderlineType.rst", + "environment/source/docs/api/enum/MsoThemeColorIndex.rst", + "environment/source/docs/api/enum/MsoVerticalAnchor.rst", + "environment/source/docs/api/enum/PpActionType.rst", + "environment/source/docs/api/enum/PpMediaType.rst", + "environment/source/docs/api/enum/PpParagraphAlignment.rst", + "environment/source/docs/api/enum/PpPlaceholderType.rst", + "environment/source/docs/api/enum/XlAxisCrosses.rst", + "environment/source/docs/api/enum/XlCategoryType.rst", + "environment/source/docs/api/enum/XlChartType.rst", + "environment/source/docs/api/enum/XlDataLabelPosition.rst", + "environment/source/docs/api/enum/XlLegendPosition.rst", + "environment/source/docs/api/enum/XlMarkerStyle.rst", + "environment/source/docs/api/enum/XlTickLabelPosition.rst", + "environment/source/docs/api/enum/XlTickMark.rst", + "environment/source/docs/api/enum/index.rst", + "environment/source/docs/api/exc.rst", + "environment/source/docs/api/image.rst", + "environment/source/docs/api/placeholders.rst", + "environment/source/docs/api/presentation.rst", + "environment/source/docs/api/shapes.rst", + "environment/source/docs/api/slides.rst", + "environment/source/docs/api/table.rst", + "environment/source/docs/api/text.rst", + "environment/source/docs/api/util.rst", + "environment/source/docs/community/faq.rst", + "environment/source/docs/community/support.rst", + "environment/source/docs/community/updates.rst", + "environment/source/docs/conf.py", + "environment/source/docs/dev/analysis/cht-access-xlsx.rst", + "environment/source/docs/dev/analysis/cht-add-chart.rst", + "environment/source/docs/dev/analysis/cht-area-chart.rst", + "environment/source/docs/dev/analysis/cht-axes.rst", + "environment/source/docs/dev/analysis/cht-axis-has-gridlines.rst", + "environment/source/docs/dev/analysis/cht-axis-title.rst", + "environment/source/docs/dev/analysis/cht-axis-unit.rst", + "environment/source/docs/dev/analysis/cht-bar-chart.rst", + "environment/source/docs/dev/analysis/cht-bubble-chart.rst", + "environment/source/docs/dev/analysis/cht-categories.rst", + "environment/source/docs/dev/analysis/cht-chart-data.rst", + "environment/source/docs/dev/analysis/cht-chart-overview.rst", + "environment/source/docs/dev/analysis/cht-chart-shape.rst", + "environment/source/docs/dev/analysis/cht-chart-title.rst", + "environment/source/docs/dev/analysis/cht-chart-type.rst", + "environment/source/docs/dev/analysis/cht-chart.rst", + "environment/source/docs/dev/analysis/cht-data-labels.rst", + "environment/source/docs/dev/analysis/cht-date-axis.rst", + "environment/source/docs/dev/analysis/cht-doughnut-chart.rst", + "environment/source/docs/dev/analysis/cht-invert-if-negative.rst", + "environment/source/docs/dev/analysis/cht-legend.rst", + "environment/source/docs/dev/analysis/cht-line-chart.rst", + "environment/source/docs/dev/analysis/cht-marker.rst", + "environment/source/docs/dev/analysis/cht-pie-chart.rst", + "environment/source/docs/dev/analysis/cht-plot-data.rst", + "environment/source/docs/dev/analysis/cht-plots.rst", + "environment/source/docs/dev/analysis/cht-points.rst", + "environment/source/docs/dev/analysis/cht-radar-chart.rst", + "environment/source/docs/dev/analysis/cht-series.rst", + "environment/source/docs/dev/analysis/cht-tick-labels.rst", + "environment/source/docs/dev/analysis/cht-xy-chart.rst", + "environment/source/docs/dev/analysis/dml-color.rst", + "environment/source/docs/dev/analysis/dml-fill.rst", + "environment/source/docs/dev/analysis/dml-gradient.rst", + "environment/source/docs/dev/analysis/dml-line.rst", + "environment/source/docs/dev/analysis/enumerations.rst", + "environment/source/docs/dev/analysis/index.rst", + "environment/source/docs/dev/analysis/pkg-coreprops.rst", + "environment/source/docs/dev/analysis/placeholders/index.rst", + "environment/source/docs/dev/analysis/placeholders/layout-placeholders.rst", + "environment/source/docs/dev/analysis/placeholders/master-placeholders.rst", + "environment/source/docs/dev/analysis/placeholders/slide-placeholders/index.rst", + "environment/source/docs/dev/analysis/placeholders/slide-placeholders/picture-placeholder.rst", + "environment/source/docs/dev/analysis/placeholders/slide-placeholders/placeholders-in-new-slide.rst", + "environment/source/docs/dev/analysis/placeholders/slide-placeholders/table-placeholder.rst", + "environment/source/docs/dev/analysis/prs-properties.rst", + "environment/source/docs/dev/analysis/shp-autofit.rst", + "environment/source/docs/dev/analysis/shp-autoshape.rst", + "environment/source/docs/dev/analysis/shp-connector.rst", + "environment/source/docs/dev/analysis/shp-freeform.rst", + "environment/source/docs/dev/analysis/shp-graphfrm.rst", + "environment/source/docs/dev/analysis/shp-group-shape.rst", + "environment/source/docs/dev/analysis/shp-hyperlink.rst", + "environment/source/docs/dev/analysis/shp-movie.rst", + "environment/source/docs/dev/analysis/shp-ole-object.rst", + "environment/source/docs/dev/analysis/shp-picture.rst", + "environment/source/docs/dev/analysis/shp-pos-and-size.rst", + "environment/source/docs/dev/analysis/shp-preset-geom.rst", + "environment/source/docs/dev/analysis/shp-shadow.rst", + "environment/source/docs/dev/analysis/shp-shapes.rst", + "environment/source/docs/dev/analysis/sld-background.rst", + "environment/source/docs/dev/analysis/sld-base.rst", + "environment/source/docs/dev/analysis/sld-layout.rst", + "environment/source/docs/dev/analysis/sld-master.rst", + "environment/source/docs/dev/analysis/sld-notes-master.rst", + "environment/source/docs/dev/analysis/sld-notes-slide.rst", + "environment/source/docs/dev/analysis/sld-slide-shapes.rst", + "environment/source/docs/dev/analysis/sld-slide.rst", + "environment/source/docs/dev/analysis/tbl-merge.rst", + "environment/source/docs/dev/analysis/tbl-table-style.rst", + "environment/source/docs/dev/analysis/tbl-table.rst", + "environment/source/docs/dev/analysis/txt-autofit-text.rst", + "environment/source/docs/dev/analysis/txt-fit-text.rst", + "environment/source/docs/dev/analysis/txt-font-color.rst", + "environment/source/docs/dev/analysis/txt-font-typeface.rst", + "environment/source/docs/dev/analysis/txt-font-underline.rst", + "environment/source/docs/dev/analysis/txt-hyperlink.rst", + "environment/source/docs/dev/analysis/txt-para-spacing.rst", + "environment/source/docs/dev/analysis/txt-text.rst", + "environment/source/docs/dev/development_practices.rst", + "environment/source/docs/dev/philosophy.rst", + "environment/source/docs/dev/resources/about_packaging.rst", + "environment/source/docs/dev/resources/about_relationships.rst", + "environment/source/docs/dev/resources/applescript.rst", + "environment/source/docs/dev/resources/index.rst", + "environment/source/docs/dev/resources/odds_and_ends.rst", + "environment/source/docs/dev/resources/python_packaging.rst", + "environment/source/docs/dev/resources/technical_topics.rst", + "environment/source/docs/dev/resources/web_resources.rst", + "environment/source/docs/dev/runtests.rst", + "environment/source/docs/dev/xmlchemy.rst", + "environment/source/docs/index.rst", + "environment/source/docs/user/autoshapes.rst", + "environment/source/docs/user/charts.rst", + "environment/source/docs/user/concepts.rst", + "environment/source/docs/user/install.rst", + "environment/source/docs/user/intro.rst", + "environment/source/docs/user/notes.rst", + "environment/source/docs/user/placeholders-understanding.rst", + "environment/source/docs/user/placeholders-using.rst", + "environment/source/docs/user/presentations.rst", + "environment/source/docs/user/quickstart.rst", + "environment/source/docs/user/slides.rst", + "environment/source/docs/user/table.rst", + "environment/source/docs/user/text.rst", + "environment/source/docs/user/understanding-shapes.rst", + "environment/source/docs/user/use-cases.rst", + "environment/source/features/act-action.feature", + "environment/source/features/act-hyperlink.feature", + "environment/source/features/cht-axis-props.feature", + "environment/source/features/cht-axistitle-props.feature", + "environment/source/features/cht-category-access.feature", + "environment/source/features/cht-category-props.feature", + "environment/source/features/cht-chart.feature", + "environment/source/features/cht-charttitle-props.feature", + "environment/source/features/cht-data-props.feature", + "environment/source/features/cht-datalabels.feature", + "environment/source/features/cht-gridlines-props.feature", + "environment/source/features/cht-legend-access.feature", + "environment/source/features/cht-legend-props.feature", + "environment/source/features/cht-marker-props.feature", + "environment/source/features/cht-plot-props.feature", + "environment/source/features/cht-point-access.feature", + "environment/source/features/cht-point-props.feature", + "environment/source/features/cht-replace-data.feature", + "environment/source/features/cht-series.feature", + "environment/source/features/cht-ticklabels-props.feature", + "environment/source/features/dml-color.feature", + "environment/source/features/dml-effect.feature", + "environment/source/features/dml-fill.feature", + "environment/source/features/dml-line.feature", + "environment/source/features/environment.py", + "environment/source/features/ph-inherit-props.feature", + "environment/source/features/ph-insert-shape.feature", + "environment/source/features/ph-phfmt-props.feature", + "environment/source/features/ph-placeholder-props.feature", + "environment/source/features/prs-coreprops.feature", + "environment/source/features/prs-default-template.feature", + "environment/source/features/prs-open-save.feature", + "environment/source/features/prs-presentation-props.feature", + "environment/source/features/shp-autoshape.feature", + "environment/source/features/shp-connector.feature", + "environment/source/features/shp-freeform.feature", + "environment/source/features/shp-graphicframe.feature", + "environment/source/features/shp-groupshape.feature", + "environment/source/features/shp-movie-props.feature", + "environment/source/features/shp-picture.feature", + "environment/source/features/shp-placeholder.feature", + "environment/source/features/shp-shapes.feature", + "environment/source/features/shp-shared.feature", + "environment/source/features/sld-background.feature", + "environment/source/features/sld-slide.feature", + "environment/source/features/sld-slides.feature", + "environment/source/features/steps/action.py", + "environment/source/features/steps/axis.py", + "environment/source/features/steps/background.py", + "environment/source/features/steps/category.py", + "environment/source/features/steps/chart.py", + "environment/source/features/steps/chartdata.py", + "environment/source/features/steps/color.py", + "environment/source/features/steps/coreprops.py", + "environment/source/features/steps/datalabel.py", + "environment/source/features/steps/effect.py", + "environment/source/features/steps/fill.py", + "environment/source/features/steps/font.py", + "environment/source/features/steps/font_color.py", + "environment/source/features/steps/helpers.py", + "environment/source/features/steps/legend.py", + "environment/source/features/steps/line.py", + "environment/source/features/steps/picture.py", + "environment/source/features/steps/placeholder.py", + "environment/source/features/steps/plot.py", + "environment/source/features/steps/presentation.py", + "environment/source/features/steps/series.py", + "environment/source/features/steps/shape.py", + "environment/source/features/steps/shapes.py", + "environment/source/features/steps/slide.py", + "environment/source/features/steps/slides.py", + "environment/source/features/steps/table.py", + "environment/source/features/steps/test_files/72-dpi.tiff", + "environment/source/features/steps/test_files/CVS_LOGO.WMF", + "environment/source/features/steps/test_files/act-props.pptm", + "environment/source/features/steps/test_files/calibriz.ttf", + "environment/source/features/steps/test_files/cht-axis-props.pptx", + "environment/source/features/steps/test_files/cht-category-access.pptx", + "environment/source/features/steps/test_files/cht-chart-props.pptx", + "environment/source/features/steps/test_files/cht-chart-type.pptx", + "environment/source/features/steps/test_files/cht-charts.pptx", + "environment/source/features/steps/test_files/cht-datalabels.pptx", + "environment/source/features/steps/test_files/cht-gridlines-props.pptx", + "environment/source/features/steps/test_files/cht-legend-props.pptx", + "environment/source/features/steps/test_files/cht-legend.pptx", + "environment/source/features/steps/test_files/cht-marker-props.pptx", + "environment/source/features/steps/test_files/cht-plot-props.pptx", + "environment/source/features/steps/test_files/cht-point-access.pptx", + "environment/source/features/steps/test_files/cht-point-props.pptx", + "environment/source/features/steps/test_files/cht-replace-data.pptx", + "environment/source/features/steps/test_files/cht-series.pptx", + "environment/source/features/steps/test_files/cht-ticklabels-props.pptx", + "environment/source/features/steps/test_files/dml-effect.pptx", + "environment/source/features/steps/test_files/dml-fill.pptx", + "environment/source/features/steps/test_files/dml-line.pptx", + "environment/source/features/steps/test_files/ext-rels.pptx", + "environment/source/features/steps/test_files/extracted-pptx/[Content_Types].xml", + "environment/source/features/steps/test_files/extracted-pptx/_rels/.rels", + "environment/source/features/steps/test_files/extracted-pptx/docProps/app.xml", + "environment/source/features/steps/test_files/extracted-pptx/docProps/core.xml", + "environment/source/features/steps/test_files/extracted-pptx/docProps/thumbnail.jpeg", + "environment/source/features/steps/test_files/extracted-pptx/ppt/_rels/presentation.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/presProps.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/presentation.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/printerSettings/printerSettings1.bin", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout10.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout11.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout2.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout3.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout4.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout5.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout6.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout7.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout8.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout9.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout1.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout10.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout11.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout2.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout3.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout4.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout5.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout6.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout7.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout8.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout9.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slideMasters/slideMaster1.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slides/_rels/slide1.xml.rels", + "environment/source/features/steps/test_files/extracted-pptx/ppt/slides/slide1.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/tableStyles.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/theme/theme1.xml", + "environment/source/features/steps/test_files/extracted-pptx/ppt/viewProps.xml", + "environment/source/features/steps/test_files/font-color.pptx", + "environment/source/features/steps/test_files/just-two-mice.mp4", + "environment/source/features/steps/test_files/just-two-mice.png", + "environment/source/features/steps/test_files/lyt-shapes.pptx", + "environment/source/features/steps/test_files/minimal.pptx", + "environment/source/features/steps/test_files/monty-truth.png", + "environment/source/features/steps/test_files/mst-placeholders.pptx", + "environment/source/features/steps/test_files/mst-shapes.pptx", + "environment/source/features/steps/test_files/mst-slide-layouts.pptx", + "environment/source/features/steps/test_files/ph-inherit-props.pptx", + "environment/source/features/steps/test_files/ph-populated-placeholders.pptx", + "environment/source/features/steps/test_files/ph-unpopulated-placeholders.pptx", + "environment/source/features/steps/test_files/pic.emf", + "environment/source/features/steps/test_files/prs-add-slide.pptx", + "environment/source/features/steps/test_files/prs-notes.pptx", + "environment/source/features/steps/test_files/prs-properties.pptx", + "environment/source/features/steps/test_files/prs-slide-masters.pptx", + "environment/source/features/steps/test_files/python-icon.jpeg", + "environment/source/features/steps/test_files/python-powered.png", + "environment/source/features/steps/test_files/python.bmp", + "environment/source/features/steps/test_files/shp-access-chart.pptx", + "environment/source/features/steps/test_files/shp-access-ole-object.pptx", + "environment/source/features/steps/test_files/shp-autoshape-adjustments.pptx", + "environment/source/features/steps/test_files/shp-autoshape-props.pptx", + "environment/source/features/steps/test_files/shp-common-props.pptx", + "environment/source/features/steps/test_files/shp-connector-props.pptx", + "environment/source/features/steps/test_files/shp-embedded-docx.docx", + "environment/source/features/steps/test_files/shp-embedded-pptx.pptx", + "environment/source/features/steps/test_files/shp-embedded-xlsx.xlsx", + "environment/source/features/steps/test_files/shp-freeform.pptx", + "environment/source/features/steps/test_files/shp-groupshape.pptx", + "environment/source/features/steps/test_files/shp-movie-props.pptx", + "environment/source/features/steps/test_files/shp-picture.pptx", + "environment/source/features/steps/test_files/shp-pos-and-size.pptx", + "environment/source/features/steps/test_files/shp-shapes.pptx", + "environment/source/features/steps/test_files/sld-background.pptx", + "environment/source/features/steps/test_files/sld-blank.pptx", + "environment/source/features/steps/test_files/sld-notes.pptx", + "environment/source/features/steps/test_files/sld-slide.pptx", + "environment/source/features/steps/test_files/sld-slides.pptx", + "environment/source/features/steps/test_files/sonic.gif", + "environment/source/features/steps/test_files/tbl-cell.pptx", + "environment/source/features/steps/test_files/test.pptx", + "environment/source/features/steps/test_files/txt-fit-text.pptx", + "environment/source/features/steps/test_files/txt-font-props.pptx", + "environment/source/features/steps/test_files/txt-font-typeface.pptx", + "environment/source/features/steps/test_files/txt-paragraph-spacing.pptx", + "environment/source/features/steps/test_files/txt-text-frame.pptx", + "environment/source/features/steps/test_files/txt-text.pptx", + "environment/source/features/steps/text.py", + "environment/source/features/steps/text_frame.py", + "environment/source/features/tbl-cell.feature", + "environment/source/features/tbl-column.feature", + "environment/source/features/tbl-table.feature", + "environment/source/features/txt-fit-text.feature", + "environment/source/features/txt-font-color.feature", + "environment/source/features/txt-font-props.feature", + "environment/source/features/txt-paragraph.feature", + "environment/source/features/txt-text.feature", + "environment/source/features/txt-textframe.feature", + "environment/source/lab/README.txt", + "environment/source/lab/cust-elm-classes/gen_oxml_classes.py", + "environment/source/lab/cust-elm-classes/main.py", + "environment/source/lab/parse_xsd/objectify_lab.py", + "environment/source/lab/parse_xsd/parse_xsd.py", + "environment/source/lab/parse_xsd/slide1.xml", + "environment/source/lab/parse_xsd/validate.py", + "environment/source/lab/parse_xsd/xsd/dml-chart.xsd", + "environment/source/lab/parse_xsd/xsd/dml-chartDrawing.xsd", + "environment/source/lab/parse_xsd/xsd/dml-diagram.xsd", + "environment/source/lab/parse_xsd/xsd/dml-lockedCanvas.xsd", + "environment/source/lab/parse_xsd/xsd/dml-main.xsd", + "environment/source/lab/parse_xsd/xsd/dml-picture.xsd", + "environment/source/lab/parse_xsd/xsd/dml-spreadsheetDrawing.xsd", + "environment/source/lab/parse_xsd/xsd/dml-wordprocessingDrawing.xsd", + "environment/source/lab/parse_xsd/xsd/pml.xsd", + "environment/source/lab/parse_xsd/xsd/shared-additionalCharacteristics.xsd", + "environment/source/lab/parse_xsd/xsd/shared-bibliography.xsd", + "environment/source/lab/parse_xsd/xsd/shared-commonSimpleTypes.xsd", + "environment/source/lab/parse_xsd/xsd/shared-customXmlDataProperties.xsd", + "environment/source/lab/parse_xsd/xsd/shared-customXmlSchemaProperties.xsd", + "environment/source/lab/parse_xsd/xsd/shared-documentPropertiesCustom.xsd", + "environment/source/lab/parse_xsd/xsd/shared-documentPropertiesExtended.xsd", + "environment/source/lab/parse_xsd/xsd/shared-documentPropertiesVariantTypes.xsd", + "environment/source/lab/parse_xsd/xsd/shared-math.xsd", + "environment/source/lab/parse_xsd/xsd/shared-relationshipReference.xsd", + "environment/source/lab/parse_xsd/xsd/sml.xsd", + "environment/source/lab/parse_xsd/xsd/vml-main.xsd", + "environment/source/lab/parse_xsd/xsd/vml-officeDrawing.xsd", + "environment/source/lab/parse_xsd/xsd/vml-presentationDrawing.xsd", + "environment/source/lab/parse_xsd/xsd/vml-spreadsheetDrawing.xsd", + "environment/source/lab/parse_xsd/xsd/vml-wordprocessingDrawing.xsd", + "environment/source/lab/parse_xsd/xsd/wml.xsd", + "environment/source/pyproject.toml", + "environment/source/requirements-test.txt", + "environment/source/requirements.txt", + "environment/source/setup.cfg", + "environment/source/setup.py", + "environment/source/spec/ISO-IEC-29500-1/ISO-IEC-29500-1.pdf", + "environment/source/spec/ISO-IEC-29500-1/schemas/dml-geometries/OfficeOpenXML-DrawingMLGeometries/presetShapeDefinitions.xml", + "environment/source/spec/ISO-IEC-29500-1/schemas/dml-geometries/OfficeOpenXML-DrawingMLGeometries/presetTextWarpDefinitions.xml", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-chart.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-chartDrawing.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-diagram.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-lockedCanvas.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-main.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-picture.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-spreadsheetDrawing.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-wordprocessingDrawing.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/pml.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-additionalCharacteristics.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-bibliography.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-commonSimpleTypes.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-customXmlDataProperties.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-customXmlSchemaProperties.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-documentPropertiesCustom.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-documentPropertiesExtended.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-documentPropertiesVariantTypes.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-math.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-relationshipReference.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/sml.xsd", + "environment/source/spec/ISO-IEC-29500-1/schemas/xsd/wml.xsd", + "environment/source/spec/ISO-IEC-29500-2/ISO-IEC-29500-2.pdf", + "environment/source/spec/ISO-IEC-29500-2/opc-xsd/opc-contentTypes.xsd", + "environment/source/spec/ISO-IEC-29500-2/opc-xsd/opc-coreProperties.xsd", + "environment/source/spec/ISO-IEC-29500-2/opc-xsd/opc-digSig.xsd", + "environment/source/spec/ISO-IEC-29500-2/opc-xsd/opc-relationships.xsd", + "environment/source/spec/ISO-IEC-29500-3/ISO-IEC-29500-3.pdf", + "environment/source/spec/ISO-IEC-29500-4/ISO-IEC-29500-4.pdf", + "environment/source/spec/ISO-IEC-29500-4/xsd/dml-chart.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/dml-chartDrawing.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/dml-diagram.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/dml-lockedCanvas.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/dml-main.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/dml-picture.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/dml-spreadsheetDrawing.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/dml-wordprocessingDrawing.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/pml.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/shared-additionalCharacteristics.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/shared-bibliography.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/shared-commonSimpleTypes.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/shared-customXmlDataProperties.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/shared-customXmlSchemaProperties.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/shared-documentPropertiesCustom.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/shared-documentPropertiesExtended.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/shared-documentPropertiesVariantTypes.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/shared-math.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/shared-relationshipReference.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/sml.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/vml-main.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/vml-officeDrawing.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/vml-presentationDrawing.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/vml-spreadsheetDrawing.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/vml-wordprocessingDrawing.xsd", + "environment/source/spec/ISO-IEC-29500-4/xsd/wml.xsd", + "environment/source/spec/gen_spec/Makefile", + "environment/source/spec/gen_spec/enum/MsoAutoShapeType.xml", + "environment/source/spec/gen_spec/gen_spec.py", + "environment/source/spec/gen_spec/sql/dump.sql", + "environment/source/spec/gen_spec/src_data/enums/MsoAutoShapeType/MsoAutoShapeType.txt", + "environment/source/spec/gen_spec/src_data/enums/MsoAutoShapeType/ST_ShapeType.xml", + "environment/source/spec/gen_spec/src_data/enums/MsoAutoShapeType/mapping.txt", + "environment/source/spec/gen_spec/src_data/msoAutoShapeType.py", + "environment/source/spec/gen_spec/src_data/scratch.py", + "environment/source/src/pptx/__init__.py", + "environment/source/src/pptx/action.py", + "environment/source/src/pptx/api.py", + "environment/source/src/pptx/chart/__init__.py", + "environment/source/src/pptx/chart/axis.py", + "environment/source/src/pptx/chart/category.py", + "environment/source/src/pptx/chart/chart.py", + "environment/source/src/pptx/chart/data.py", + "environment/source/src/pptx/chart/datalabel.py", + "environment/source/src/pptx/chart/legend.py", + "environment/source/src/pptx/chart/marker.py", + "environment/source/src/pptx/chart/plot.py", + "environment/source/src/pptx/chart/point.py", + "environment/source/src/pptx/chart/series.py", + "environment/source/src/pptx/chart/xlsx.py", + "environment/source/src/pptx/chart/xmlwriter.py", + "environment/source/src/pptx/dml/__init__.py", + "environment/source/src/pptx/dml/chtfmt.py", + "environment/source/src/pptx/dml/color.py", + "environment/source/src/pptx/dml/effect.py", + "environment/source/src/pptx/dml/fill.py", + "environment/source/src/pptx/dml/line.py", + "environment/source/src/pptx/enum/__init__.py", + "environment/source/src/pptx/enum/action.py", + "environment/source/src/pptx/enum/base.py", + "environment/source/src/pptx/enum/chart.py", + "environment/source/src/pptx/enum/dml.py", + "environment/source/src/pptx/enum/lang.py", + "environment/source/src/pptx/enum/shapes.py", + "environment/source/src/pptx/enum/text.py", + "environment/source/src/pptx/exc.py", + "environment/source/src/pptx/media.py", + "environment/source/src/pptx/opc/__init__.py", + "environment/source/src/pptx/opc/constants.py", + "environment/source/src/pptx/opc/oxml.py", + "environment/source/src/pptx/opc/package.py", + "environment/source/src/pptx/opc/packuri.py", + "environment/source/src/pptx/opc/serialized.py", + "environment/source/src/pptx/opc/shared.py", + "environment/source/src/pptx/opc/spec.py", + "environment/source/src/pptx/oxml/__init__.py", + "environment/source/src/pptx/oxml/action.py", + "environment/source/src/pptx/oxml/chart/__init__.py", + "environment/source/src/pptx/oxml/chart/axis.py", + "environment/source/src/pptx/oxml/chart/chart.py", + "environment/source/src/pptx/oxml/chart/datalabel.py", + "environment/source/src/pptx/oxml/chart/legend.py", + "environment/source/src/pptx/oxml/chart/marker.py", + "environment/source/src/pptx/oxml/chart/plot.py", + "environment/source/src/pptx/oxml/chart/series.py", + "environment/source/src/pptx/oxml/chart/shared.py", + "environment/source/src/pptx/oxml/coreprops.py", + "environment/source/src/pptx/oxml/dml/__init__.py", + "environment/source/src/pptx/oxml/dml/color.py", + "environment/source/src/pptx/oxml/dml/fill.py", + "environment/source/src/pptx/oxml/dml/line.py", + "environment/source/src/pptx/oxml/ns.py", + "environment/source/src/pptx/oxml/presentation.py", + "environment/source/src/pptx/oxml/shapes/__init__.py", + "environment/source/src/pptx/oxml/shapes/autoshape.py", + "environment/source/src/pptx/oxml/shapes/connector.py", + "environment/source/src/pptx/oxml/shapes/graphfrm.py", + "environment/source/src/pptx/oxml/shapes/groupshape.py", + "environment/source/src/pptx/oxml/shapes/picture.py", + "environment/source/src/pptx/oxml/shapes/shared.py", + "environment/source/src/pptx/oxml/simpletypes.py", + "environment/source/src/pptx/oxml/slide.py", + "environment/source/src/pptx/oxml/table.py", + "environment/source/src/pptx/oxml/text.py", + "environment/source/src/pptx/oxml/theme.py", + "environment/source/src/pptx/oxml/xmlchemy.py", + "environment/source/src/pptx/package.py", + "environment/source/src/pptx/parts/__init__.py", + "environment/source/src/pptx/parts/chart.py", + "environment/source/src/pptx/parts/coreprops.py", + "environment/source/src/pptx/parts/embeddedpackage.py", + "environment/source/src/pptx/parts/image.py", + "environment/source/src/pptx/parts/media.py", + "environment/source/src/pptx/parts/presentation.py", + "environment/source/src/pptx/parts/slide.py", + "environment/source/src/pptx/presentation.py", + "environment/source/src/pptx/shapes/__init__.py", + "environment/source/src/pptx/shapes/autoshape.py", + "environment/source/src/pptx/shapes/base.py", + "environment/source/src/pptx/shapes/connector.py", + "environment/source/src/pptx/shapes/freeform.py", + "environment/source/src/pptx/shapes/graphfrm.py", + "environment/source/src/pptx/shapes/group.py", + "environment/source/src/pptx/shapes/picture.py", + "environment/source/src/pptx/shapes/placeholder.py", + "environment/source/src/pptx/shapes/shapetree.py", + "environment/source/src/pptx/shared.py", + "environment/source/src/pptx/slide.py", + "environment/source/src/pptx/spec.py", + "environment/source/src/pptx/table.py", + "environment/source/src/pptx/templates/default.pptx", + "environment/source/src/pptx/templates/docx-icon.emf", + "environment/source/src/pptx/templates/generic-icon.emf", + "environment/source/src/pptx/templates/notes.xml", + "environment/source/src/pptx/templates/notesMaster.xml", + "environment/source/src/pptx/templates/pptx-icon.emf", + "environment/source/src/pptx/templates/theme.xml", + "environment/source/src/pptx/templates/xlsx-icon.emf", + "environment/source/src/pptx/text/__init__.py", + "environment/source/src/pptx/text/fonts.py", + "environment/source/src/pptx/text/layout.py", + "environment/source/src/pptx/text/text.py", + "environment/source/src/pptx/types.py", + "environment/source/src/pptx/util.py", + "environment/source/src/python_pptx.egg-info/PKG-INFO", + "environment/source/src/python_pptx.egg-info/SOURCES.txt", + "environment/source/src/python_pptx.egg-info/dependency_links.txt", + "environment/source/src/python_pptx.egg-info/not-zip-safe", + "environment/source/src/python_pptx.egg-info/requires.txt", + "environment/source/src/python_pptx.egg-info/top_level.txt", + "environment/source/tests/__init__.py", + "environment/source/tests/chart/__init__.py", + "environment/source/tests/chart/test_axis.py", + "environment/source/tests/chart/test_category.py", + "environment/source/tests/chart/test_chart.py", + "environment/source/tests/chart/test_data.py", + "environment/source/tests/chart/test_datalabel.py", + "environment/source/tests/chart/test_legend.py", + "environment/source/tests/chart/test_marker.py", + "environment/source/tests/chart/test_plot.py", + "environment/source/tests/chart/test_point.py", + "environment/source/tests/chart/test_series.py", + "environment/source/tests/chart/test_xlsx.py", + "environment/source/tests/chart/test_xmlwriter.py", + "environment/source/tests/dml/__init__.py", + "environment/source/tests/dml/test_chtfmt.py", + "environment/source/tests/dml/test_color.py", + "environment/source/tests/dml/test_effect.py", + "environment/source/tests/dml/test_fill.py", + "environment/source/tests/dml/test_line.py", + "environment/source/tests/enum/__init__.py", + "environment/source/tests/enum/test_base.py", + "environment/source/tests/enum/test_shapes.py", + "environment/source/tests/opc/__init__.py", + "environment/source/tests/opc/test_oxml.py", + "environment/source/tests/opc/test_package.py", + "environment/source/tests/opc/test_packuri.py", + "environment/source/tests/opc/test_serialized.py", + "environment/source/tests/parts/__init__.py", + "environment/source/tests/parts/test_chart.py", + "environment/source/tests/parts/test_coreprops.py", + "environment/source/tests/parts/test_embeddedpackage.py", + "environment/source/tests/parts/test_image.py", + "environment/source/tests/parts/test_media.py", + "environment/source/tests/parts/test_presentation.py", + "environment/source/tests/parts/test_slide.py", + "environment/source/tests/shapes/__init__.py", + "environment/source/tests/shapes/test_autoshape.py", + "environment/source/tests/shapes/test_base.py", + "environment/source/tests/shapes/test_connector.py", + "environment/source/tests/shapes/test_freeform.py", + "environment/source/tests/shapes/test_graphfrm.py", + "environment/source/tests/shapes/test_group.py", + "environment/source/tests/shapes/test_picture.py", + "environment/source/tests/shapes/test_placeholder.py", + "environment/source/tests/shapes/test_shapetree.py", + "environment/source/tests/test_action.py", + "environment/source/tests/test_api.py", + "environment/source/tests/test_files/calibriz.ttf", + "environment/source/tests/test_files/cdw-logo.eps", + "environment/source/tests/test_files/dummy.mp4", + "environment/source/tests/test_files/expanded_pptx/[Content_Types].xml", + "environment/source/tests/test_files/expanded_pptx/_rels/.rels", + "environment/source/tests/test_files/expanded_pptx/docProps/app.xml", + "environment/source/tests/test_files/expanded_pptx/docProps/core.xml", + "environment/source/tests/test_files/expanded_pptx/docProps/thumbnail.jpeg", + "environment/source/tests/test_files/expanded_pptx/ppt/_rels/presentation.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/presProps.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/presentation.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/printerSettings/printerSettings1.bin", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout10.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout11.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout2.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout3.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout4.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout5.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout6.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout7.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout8.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout9.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout1.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout10.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout11.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout2.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout3.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout4.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout5.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout6.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout7.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout8.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout9.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slideMasters/slideMaster1.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/slides/_rels/slide1.xml.rels", + "environment/source/tests/test_files/expanded_pptx/ppt/slides/slide1.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/tableStyles.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/theme/theme1.xml", + "environment/source/tests/test_files/expanded_pptx/ppt/viewProps.xml", + "environment/source/tests/test_files/minimal.pptx", + "environment/source/tests/test_files/minimal_slide.xml", + "environment/source/tests/test_files/missing_rels_item.pptx", + "environment/source/tests/test_files/monty-truth.png", + "environment/source/tests/test_files/no-core-props.pptx", + "environment/source/tests/test_files/no-slides.pptx", + "environment/source/tests/test_files/presentation.xml", + "environment/source/tests/test_files/python-icon.jpeg", + "environment/source/tests/test_files/python-powered.png", + "environment/source/tests/test_files/python.bmp", + "environment/source/tests/test_files/slideLayout1.xml", + "environment/source/tests/test_files/snippets/2x2-area-date.txt", + "environment/source/tests/test_files/snippets/2x2-area-float.txt", + "environment/source/tests/test_files/snippets/2x2-area-stacked-100.txt", + "environment/source/tests/test_files/snippets/2x2-area-stacked.txt", + "environment/source/tests/test_files/snippets/2x2-area.txt", + "environment/source/tests/test_files/snippets/2x2-bar-clustered-date.txt", + "environment/source/tests/test_files/snippets/2x2-bar-clustered-float.txt", + "environment/source/tests/test_files/snippets/2x2-bar-clustered.txt", + "environment/source/tests/test_files/snippets/2x2-bar-stacked-100.txt", + "environment/source/tests/test_files/snippets/2x2-bar-stacked.txt", + "environment/source/tests/test_files/snippets/2x2-column-clustered.txt", + "environment/source/tests/test_files/snippets/2x2-column-stacked-100.txt", + "environment/source/tests/test_files/snippets/2x2-column-stacked.txt", + "environment/source/tests/test_files/snippets/2x2-line-date.txt", + "environment/source/tests/test_files/snippets/2x2-line-float.txt", + "environment/source/tests/test_files/snippets/2x2-line-markers-stacked-100.txt", + "environment/source/tests/test_files/snippets/2x2-line-markers-stacked.txt", + "environment/source/tests/test_files/snippets/2x2-line-markers.txt", + "environment/source/tests/test_files/snippets/2x2-line-stacked-100.txt", + "environment/source/tests/test_files/snippets/2x2-line-stacked.txt", + "environment/source/tests/test_files/snippets/2x2-line.txt", + "environment/source/tests/test_files/snippets/2x3-bubble-3d.txt", + "environment/source/tests/test_files/snippets/2x3-bubble.txt", + "environment/source/tests/test_files/snippets/2x3-xy-lines-no-markers.txt", + "environment/source/tests/test_files/snippets/2x3-xy-lines.txt", + "environment/source/tests/test_files/snippets/2x3-xy-smooth-no-markers.txt", + "environment/source/tests/test_files/snippets/2x3-xy-smooth.txt", + "environment/source/tests/test_files/snippets/2x3-xy.txt", + "environment/source/tests/test_files/snippets/2x5-radar.txt", + "environment/source/tests/test_files/snippets/3x1-pie-exploded.txt", + "environment/source/tests/test_files/snippets/3x1-pie.txt", + "environment/source/tests/test_files/snippets/3x2-doughnut-exploded.txt", + "environment/source/tests/test_files/snippets/3x2-doughnut.txt", + "environment/source/tests/test_files/snippets/4x2-multi-cat-bar.txt", + "environment/source/tests/test_files/snippets/adjust-ser-count.txt", + "environment/source/tests/test_files/snippets/cat-labels.txt", + "environment/source/tests/test_files/snippets/content-types-xml.txt", + "environment/source/tests/test_files/snippets/default-notes.txt", + "environment/source/tests/test_files/snippets/default-notesMaster.txt", + "environment/source/tests/test_files/snippets/default-theme.txt", + "environment/source/tests/test_files/snippets/freeform.txt", + "environment/source/tests/test_files/snippets/package-rels-xml.txt", + "environment/source/tests/test_files/snippets/placeholders.txt", + "environment/source/tests/test_files/snippets/presentation-rels-xml.txt", + "environment/source/tests/test_files/snippets/relationships.txt", + "environment/source/tests/test_files/snippets/rels-load-from-xml.txt", + "environment/source/tests/test_files/snippets/rewrite-ser.txt", + "environment/source/tests/test_files/snippets/timing.txt", + "environment/source/tests/test_files/test.pptx", + "environment/source/tests/test_files/test_slides.pptx", + "environment/source/tests/test_media.py", + "environment/source/tests/test_package.py", + "environment/source/tests/test_presentation.py", + "environment/source/tests/test_shared.py", + "environment/source/tests/test_slide.py", + "environment/source/tests/test_table.py", + "environment/source/tests/test_util.py", + "environment/source/tests/text/__init__.py", + "environment/source/tests/text/test_fonts.py", + "environment/source/tests/text/test_layout.py", + "environment/source/tests/text/test_text.py", + "environment/source/tests/unitdata.py", + "environment/source/tests/unitutil/__init__.py", + "environment/source/tests/unitutil/cxml.py", + "environment/source/tests/unitutil/file.py", + "environment/source/tests/unitutil/mock.py", + "environment/source/typings/behave/__init__.pyi", + "environment/source/typings/behave/runner.pyi", + "environment/source/typings/lxml/_types.pyi", + "environment/source/typings/lxml/etree/__init__.pyi", + "environment/source/typings/lxml/etree/_classlookup.pyi", + "environment/source/typings/lxml/etree/_cleanup.pyi", + "environment/source/typings/lxml/etree/_element.pyi", + "environment/source/typings/lxml/etree/_module_func.pyi", + "environment/source/typings/lxml/etree/_module_misc.pyi", + "environment/source/typings/lxml/etree/_nsclasses.pyi", + "environment/source/typings/lxml/etree/_parser.pyi", + "solution/reference/src/pptx/oxml/presentation.py", + "solution/solve.sh", + "tests/Dockerfile", + "tests/contract.json", + "tests/grade.py", + "tests/source/.github/workflows/ci.yml", + "tests/source/.gitignore", + "tests/source/.travis.yml", + "tests/source/Dockerfile", + "tests/source/HISTORY.rst", + "tests/source/LICENSE", + "tests/source/MANIFEST.in", + "tests/source/Makefile", + "tests/source/README.rst", + "tests/source/docs/.themes/armstrong/LICENSE", + "tests/source/docs/.themes/armstrong/layout.html", + "tests/source/docs/.themes/armstrong/rtd-themes.conf", + "tests/source/docs/.themes/armstrong/static/rtd.css_t", + "tests/source/docs/.themes/armstrong/theme.conf", + "tests/source/docs/.themes/armstrong/theme.conf.orig", + "tests/source/docs/Makefile", + "tests/source/docs/_static/img/add-picture.png", + "tests/source/docs/_static/img/add-shape.png", + "tests/source/docs/_static/img/add-table.png", + "tests/source/docs/_static/img/add-textbox.png", + "tests/source/docs/_static/img/bullet-slide.png", + "tests/source/docs/_static/img/chart-01.png", + "tests/source/docs/_static/img/chart-02.png", + "tests/source/docs/_static/img/chart-03.png", + "tests/source/docs/_static/img/chart-04.png", + "tests/source/docs/_static/img/chart-05.png", + "tests/source/docs/_static/img/chart-06.png", + "tests/source/docs/_static/img/chart-07.png", + "tests/source/docs/_static/img/chart-08.png", + "tests/source/docs/_static/img/chart-09.png", + "tests/source/docs/_static/img/freeform-01.png", + "tests/source/docs/_static/img/freeform-02.png", + "tests/source/docs/_static/img/freeform-03.png", + "tests/source/docs/_static/img/hello-world.png", + "tests/source/docs/_static/img/table-01.png", + "tests/source/docs/_static/img/table-02.png", + "tests/source/docs/_static/img/table-03.png", + "tests/source/docs/_static/img/table-04.png", + "tests/source/docs/_static/img/table-05.png", + "tests/source/docs/_static/img/table-06.png", + "tests/source/docs/_static/img/table-07.png", + "tests/source/docs/_templates/sidebarlinks.html", + "tests/source/docs/api/action.rst", + "tests/source/docs/api/chart-data.rst", + "tests/source/docs/api/chart.rst", + "tests/source/docs/api/dml.rst", + "tests/source/docs/api/enum/ExcelNumFormat.rst", + "tests/source/docs/api/enum/MsoAutoShapeType.rst", + "tests/source/docs/api/enum/MsoAutoSize.rst", + "tests/source/docs/api/enum/MsoColorType.rst", + "tests/source/docs/api/enum/MsoConnectorType.rst", + "tests/source/docs/api/enum/MsoFillType.rst", + "tests/source/docs/api/enum/MsoLanguageId.rst", + "tests/source/docs/api/enum/MsoLineDashStyle.rst", + "tests/source/docs/api/enum/MsoPatternType.rst", + "tests/source/docs/api/enum/MsoShapeType.rst", + "tests/source/docs/api/enum/MsoTextUnderlineType.rst", + "tests/source/docs/api/enum/MsoThemeColorIndex.rst", + "tests/source/docs/api/enum/MsoVerticalAnchor.rst", + "tests/source/docs/api/enum/PpActionType.rst", + "tests/source/docs/api/enum/PpMediaType.rst", + "tests/source/docs/api/enum/PpParagraphAlignment.rst", + "tests/source/docs/api/enum/PpPlaceholderType.rst", + "tests/source/docs/api/enum/XlAxisCrosses.rst", + "tests/source/docs/api/enum/XlCategoryType.rst", + "tests/source/docs/api/enum/XlChartType.rst", + "tests/source/docs/api/enum/XlDataLabelPosition.rst", + "tests/source/docs/api/enum/XlLegendPosition.rst", + "tests/source/docs/api/enum/XlMarkerStyle.rst", + "tests/source/docs/api/enum/XlTickLabelPosition.rst", + "tests/source/docs/api/enum/XlTickMark.rst", + "tests/source/docs/api/enum/index.rst", + "tests/source/docs/api/exc.rst", + "tests/source/docs/api/image.rst", + "tests/source/docs/api/placeholders.rst", + "tests/source/docs/api/presentation.rst", + "tests/source/docs/api/shapes.rst", + "tests/source/docs/api/slides.rst", + "tests/source/docs/api/table.rst", + "tests/source/docs/api/text.rst", + "tests/source/docs/api/util.rst", + "tests/source/docs/community/faq.rst", + "tests/source/docs/community/support.rst", + "tests/source/docs/community/updates.rst", + "tests/source/docs/conf.py", + "tests/source/docs/dev/analysis/cht-access-xlsx.rst", + "tests/source/docs/dev/analysis/cht-add-chart.rst", + "tests/source/docs/dev/analysis/cht-area-chart.rst", + "tests/source/docs/dev/analysis/cht-axes.rst", + "tests/source/docs/dev/analysis/cht-axis-has-gridlines.rst", + "tests/source/docs/dev/analysis/cht-axis-title.rst", + "tests/source/docs/dev/analysis/cht-axis-unit.rst", + "tests/source/docs/dev/analysis/cht-bar-chart.rst", + "tests/source/docs/dev/analysis/cht-bubble-chart.rst", + "tests/source/docs/dev/analysis/cht-categories.rst", + "tests/source/docs/dev/analysis/cht-chart-data.rst", + "tests/source/docs/dev/analysis/cht-chart-overview.rst", + "tests/source/docs/dev/analysis/cht-chart-shape.rst", + "tests/source/docs/dev/analysis/cht-chart-title.rst", + "tests/source/docs/dev/analysis/cht-chart-type.rst", + "tests/source/docs/dev/analysis/cht-chart.rst", + "tests/source/docs/dev/analysis/cht-data-labels.rst", + "tests/source/docs/dev/analysis/cht-date-axis.rst", + "tests/source/docs/dev/analysis/cht-doughnut-chart.rst", + "tests/source/docs/dev/analysis/cht-invert-if-negative.rst", + "tests/source/docs/dev/analysis/cht-legend.rst", + "tests/source/docs/dev/analysis/cht-line-chart.rst", + "tests/source/docs/dev/analysis/cht-marker.rst", + "tests/source/docs/dev/analysis/cht-pie-chart.rst", + "tests/source/docs/dev/analysis/cht-plot-data.rst", + "tests/source/docs/dev/analysis/cht-plots.rst", + "tests/source/docs/dev/analysis/cht-points.rst", + "tests/source/docs/dev/analysis/cht-radar-chart.rst", + "tests/source/docs/dev/analysis/cht-series.rst", + "tests/source/docs/dev/analysis/cht-tick-labels.rst", + "tests/source/docs/dev/analysis/cht-xy-chart.rst", + "tests/source/docs/dev/analysis/dml-color.rst", + "tests/source/docs/dev/analysis/dml-fill.rst", + "tests/source/docs/dev/analysis/dml-gradient.rst", + "tests/source/docs/dev/analysis/dml-line.rst", + "tests/source/docs/dev/analysis/enumerations.rst", + "tests/source/docs/dev/analysis/index.rst", + "tests/source/docs/dev/analysis/pkg-coreprops.rst", + "tests/source/docs/dev/analysis/placeholders/index.rst", + "tests/source/docs/dev/analysis/placeholders/layout-placeholders.rst", + "tests/source/docs/dev/analysis/placeholders/master-placeholders.rst", + "tests/source/docs/dev/analysis/placeholders/slide-placeholders/index.rst", + "tests/source/docs/dev/analysis/placeholders/slide-placeholders/picture-placeholder.rst", + "tests/source/docs/dev/analysis/placeholders/slide-placeholders/placeholders-in-new-slide.rst", + "tests/source/docs/dev/analysis/placeholders/slide-placeholders/table-placeholder.rst", + "tests/source/docs/dev/analysis/prs-properties.rst", + "tests/source/docs/dev/analysis/shp-autofit.rst", + "tests/source/docs/dev/analysis/shp-autoshape.rst", + "tests/source/docs/dev/analysis/shp-connector.rst", + "tests/source/docs/dev/analysis/shp-freeform.rst", + "tests/source/docs/dev/analysis/shp-graphfrm.rst", + "tests/source/docs/dev/analysis/shp-group-shape.rst", + "tests/source/docs/dev/analysis/shp-hyperlink.rst", + "tests/source/docs/dev/analysis/shp-movie.rst", + "tests/source/docs/dev/analysis/shp-ole-object.rst", + "tests/source/docs/dev/analysis/shp-picture.rst", + "tests/source/docs/dev/analysis/shp-pos-and-size.rst", + "tests/source/docs/dev/analysis/shp-preset-geom.rst", + "tests/source/docs/dev/analysis/shp-shadow.rst", + "tests/source/docs/dev/analysis/shp-shapes.rst", + "tests/source/docs/dev/analysis/sld-background.rst", + "tests/source/docs/dev/analysis/sld-base.rst", + "tests/source/docs/dev/analysis/sld-layout.rst", + "tests/source/docs/dev/analysis/sld-master.rst", + "tests/source/docs/dev/analysis/sld-notes-master.rst", + "tests/source/docs/dev/analysis/sld-notes-slide.rst", + "tests/source/docs/dev/analysis/sld-slide-shapes.rst", + "tests/source/docs/dev/analysis/sld-slide.rst", + "tests/source/docs/dev/analysis/tbl-merge.rst", + "tests/source/docs/dev/analysis/tbl-table-style.rst", + "tests/source/docs/dev/analysis/tbl-table.rst", + "tests/source/docs/dev/analysis/txt-autofit-text.rst", + "tests/source/docs/dev/analysis/txt-fit-text.rst", + "tests/source/docs/dev/analysis/txt-font-color.rst", + "tests/source/docs/dev/analysis/txt-font-typeface.rst", + "tests/source/docs/dev/analysis/txt-font-underline.rst", + "tests/source/docs/dev/analysis/txt-hyperlink.rst", + "tests/source/docs/dev/analysis/txt-para-spacing.rst", + "tests/source/docs/dev/analysis/txt-text.rst", + "tests/source/docs/dev/development_practices.rst", + "tests/source/docs/dev/philosophy.rst", + "tests/source/docs/dev/resources/about_packaging.rst", + "tests/source/docs/dev/resources/about_relationships.rst", + "tests/source/docs/dev/resources/applescript.rst", + "tests/source/docs/dev/resources/index.rst", + "tests/source/docs/dev/resources/odds_and_ends.rst", + "tests/source/docs/dev/resources/python_packaging.rst", + "tests/source/docs/dev/resources/technical_topics.rst", + "tests/source/docs/dev/resources/web_resources.rst", + "tests/source/docs/dev/runtests.rst", + "tests/source/docs/dev/xmlchemy.rst", + "tests/source/docs/index.rst", + "tests/source/docs/user/autoshapes.rst", + "tests/source/docs/user/charts.rst", + "tests/source/docs/user/concepts.rst", + "tests/source/docs/user/install.rst", + "tests/source/docs/user/intro.rst", + "tests/source/docs/user/notes.rst", + "tests/source/docs/user/placeholders-understanding.rst", + "tests/source/docs/user/placeholders-using.rst", + "tests/source/docs/user/presentations.rst", + "tests/source/docs/user/quickstart.rst", + "tests/source/docs/user/slides.rst", + "tests/source/docs/user/table.rst", + "tests/source/docs/user/text.rst", + "tests/source/docs/user/understanding-shapes.rst", + "tests/source/docs/user/use-cases.rst", + "tests/source/features/act-action.feature", + "tests/source/features/act-hyperlink.feature", + "tests/source/features/cht-axis-props.feature", + "tests/source/features/cht-axistitle-props.feature", + "tests/source/features/cht-category-access.feature", + "tests/source/features/cht-category-props.feature", + "tests/source/features/cht-chart.feature", + "tests/source/features/cht-charttitle-props.feature", + "tests/source/features/cht-data-props.feature", + "tests/source/features/cht-datalabels.feature", + "tests/source/features/cht-gridlines-props.feature", + "tests/source/features/cht-legend-access.feature", + "tests/source/features/cht-legend-props.feature", + "tests/source/features/cht-marker-props.feature", + "tests/source/features/cht-plot-props.feature", + "tests/source/features/cht-point-access.feature", + "tests/source/features/cht-point-props.feature", + "tests/source/features/cht-replace-data.feature", + "tests/source/features/cht-series.feature", + "tests/source/features/cht-ticklabels-props.feature", + "tests/source/features/dml-color.feature", + "tests/source/features/dml-effect.feature", + "tests/source/features/dml-fill.feature", + "tests/source/features/dml-line.feature", + "tests/source/features/environment.py", + "tests/source/features/ph-inherit-props.feature", + "tests/source/features/ph-insert-shape.feature", + "tests/source/features/ph-phfmt-props.feature", + "tests/source/features/ph-placeholder-props.feature", + "tests/source/features/prs-coreprops.feature", + "tests/source/features/prs-default-template.feature", + "tests/source/features/prs-open-save.feature", + "tests/source/features/prs-presentation-props.feature", + "tests/source/features/shp-autoshape.feature", + "tests/source/features/shp-connector.feature", + "tests/source/features/shp-freeform.feature", + "tests/source/features/shp-graphicframe.feature", + "tests/source/features/shp-groupshape.feature", + "tests/source/features/shp-movie-props.feature", + "tests/source/features/shp-picture.feature", + "tests/source/features/shp-placeholder.feature", + "tests/source/features/shp-shapes.feature", + "tests/source/features/shp-shared.feature", + "tests/source/features/sld-background.feature", + "tests/source/features/sld-slide.feature", + "tests/source/features/sld-slides.feature", + "tests/source/features/steps/action.py", + "tests/source/features/steps/axis.py", + "tests/source/features/steps/background.py", + "tests/source/features/steps/category.py", + "tests/source/features/steps/chart.py", + "tests/source/features/steps/chartdata.py", + "tests/source/features/steps/color.py", + "tests/source/features/steps/coreprops.py", + "tests/source/features/steps/datalabel.py", + "tests/source/features/steps/effect.py", + "tests/source/features/steps/fill.py", + "tests/source/features/steps/font.py", + "tests/source/features/steps/font_color.py", + "tests/source/features/steps/helpers.py", + "tests/source/features/steps/legend.py", + "tests/source/features/steps/line.py", + "tests/source/features/steps/picture.py", + "tests/source/features/steps/placeholder.py", + "tests/source/features/steps/plot.py", + "tests/source/features/steps/presentation.py", + "tests/source/features/steps/series.py", + "tests/source/features/steps/shape.py", + "tests/source/features/steps/shapes.py", + "tests/source/features/steps/slide.py", + "tests/source/features/steps/slides.py", + "tests/source/features/steps/table.py", + "tests/source/features/steps/test_files/72-dpi.tiff", + "tests/source/features/steps/test_files/CVS_LOGO.WMF", + "tests/source/features/steps/test_files/act-props.pptm", + "tests/source/features/steps/test_files/calibriz.ttf", + "tests/source/features/steps/test_files/cht-axis-props.pptx", + "tests/source/features/steps/test_files/cht-category-access.pptx", + "tests/source/features/steps/test_files/cht-chart-props.pptx", + "tests/source/features/steps/test_files/cht-chart-type.pptx", + "tests/source/features/steps/test_files/cht-charts.pptx", + "tests/source/features/steps/test_files/cht-datalabels.pptx", + "tests/source/features/steps/test_files/cht-gridlines-props.pptx", + "tests/source/features/steps/test_files/cht-legend-props.pptx", + "tests/source/features/steps/test_files/cht-legend.pptx", + "tests/source/features/steps/test_files/cht-marker-props.pptx", + "tests/source/features/steps/test_files/cht-plot-props.pptx", + "tests/source/features/steps/test_files/cht-point-access.pptx", + "tests/source/features/steps/test_files/cht-point-props.pptx", + "tests/source/features/steps/test_files/cht-replace-data.pptx", + "tests/source/features/steps/test_files/cht-series.pptx", + "tests/source/features/steps/test_files/cht-ticklabels-props.pptx", + "tests/source/features/steps/test_files/dml-effect.pptx", + "tests/source/features/steps/test_files/dml-fill.pptx", + "tests/source/features/steps/test_files/dml-line.pptx", + "tests/source/features/steps/test_files/ext-rels.pptx", + "tests/source/features/steps/test_files/extracted-pptx/[Content_Types].xml", + "tests/source/features/steps/test_files/extracted-pptx/_rels/.rels", + "tests/source/features/steps/test_files/extracted-pptx/docProps/app.xml", + "tests/source/features/steps/test_files/extracted-pptx/docProps/core.xml", + "tests/source/features/steps/test_files/extracted-pptx/docProps/thumbnail.jpeg", + "tests/source/features/steps/test_files/extracted-pptx/ppt/_rels/presentation.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/presProps.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/presentation.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/printerSettings/printerSettings1.bin", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout10.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout11.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout2.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout3.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout4.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout5.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout6.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout7.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout8.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout9.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout1.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout10.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout11.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout2.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout3.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout4.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout5.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout6.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout7.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout8.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout9.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slideMasters/slideMaster1.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slides/_rels/slide1.xml.rels", + "tests/source/features/steps/test_files/extracted-pptx/ppt/slides/slide1.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/tableStyles.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/theme/theme1.xml", + "tests/source/features/steps/test_files/extracted-pptx/ppt/viewProps.xml", + "tests/source/features/steps/test_files/font-color.pptx", + "tests/source/features/steps/test_files/just-two-mice.mp4", + "tests/source/features/steps/test_files/just-two-mice.png", + "tests/source/features/steps/test_files/lyt-shapes.pptx", + "tests/source/features/steps/test_files/minimal.pptx", + "tests/source/features/steps/test_files/monty-truth.png", + "tests/source/features/steps/test_files/mst-placeholders.pptx", + "tests/source/features/steps/test_files/mst-shapes.pptx", + "tests/source/features/steps/test_files/mst-slide-layouts.pptx", + "tests/source/features/steps/test_files/ph-inherit-props.pptx", + "tests/source/features/steps/test_files/ph-populated-placeholders.pptx", + "tests/source/features/steps/test_files/ph-unpopulated-placeholders.pptx", + "tests/source/features/steps/test_files/pic.emf", + "tests/source/features/steps/test_files/prs-add-slide.pptx", + "tests/source/features/steps/test_files/prs-notes.pptx", + "tests/source/features/steps/test_files/prs-properties.pptx", + "tests/source/features/steps/test_files/prs-slide-masters.pptx", + "tests/source/features/steps/test_files/python-icon.jpeg", + "tests/source/features/steps/test_files/python-powered.png", + "tests/source/features/steps/test_files/python.bmp", + "tests/source/features/steps/test_files/shp-access-chart.pptx", + "tests/source/features/steps/test_files/shp-access-ole-object.pptx", + "tests/source/features/steps/test_files/shp-autoshape-adjustments.pptx", + "tests/source/features/steps/test_files/shp-autoshape-props.pptx", + "tests/source/features/steps/test_files/shp-common-props.pptx", + "tests/source/features/steps/test_files/shp-connector-props.pptx", + "tests/source/features/steps/test_files/shp-embedded-docx.docx", + "tests/source/features/steps/test_files/shp-embedded-pptx.pptx", + "tests/source/features/steps/test_files/shp-embedded-xlsx.xlsx", + "tests/source/features/steps/test_files/shp-freeform.pptx", + "tests/source/features/steps/test_files/shp-groupshape.pptx", + "tests/source/features/steps/test_files/shp-movie-props.pptx", + "tests/source/features/steps/test_files/shp-picture.pptx", + "tests/source/features/steps/test_files/shp-pos-and-size.pptx", + "tests/source/features/steps/test_files/shp-shapes.pptx", + "tests/source/features/steps/test_files/sld-background.pptx", + "tests/source/features/steps/test_files/sld-blank.pptx", + "tests/source/features/steps/test_files/sld-notes.pptx", + "tests/source/features/steps/test_files/sld-slide.pptx", + "tests/source/features/steps/test_files/sld-slides.pptx", + "tests/source/features/steps/test_files/sonic.gif", + "tests/source/features/steps/test_files/tbl-cell.pptx", + "tests/source/features/steps/test_files/test.pptx", + "tests/source/features/steps/test_files/txt-fit-text.pptx", + "tests/source/features/steps/test_files/txt-font-props.pptx", + "tests/source/features/steps/test_files/txt-font-typeface.pptx", + "tests/source/features/steps/test_files/txt-paragraph-spacing.pptx", + "tests/source/features/steps/test_files/txt-text-frame.pptx", + "tests/source/features/steps/test_files/txt-text.pptx", + "tests/source/features/steps/text.py", + "tests/source/features/steps/text_frame.py", + "tests/source/features/tbl-cell.feature", + "tests/source/features/tbl-column.feature", + "tests/source/features/tbl-table.feature", + "tests/source/features/txt-fit-text.feature", + "tests/source/features/txt-font-color.feature", + "tests/source/features/txt-font-props.feature", + "tests/source/features/txt-paragraph.feature", + "tests/source/features/txt-text.feature", + "tests/source/features/txt-textframe.feature", + "tests/source/lab/README.txt", + "tests/source/lab/cust-elm-classes/gen_oxml_classes.py", + "tests/source/lab/cust-elm-classes/main.py", + "tests/source/lab/parse_xsd/objectify_lab.py", + "tests/source/lab/parse_xsd/parse_xsd.py", + "tests/source/lab/parse_xsd/slide1.xml", + "tests/source/lab/parse_xsd/validate.py", + "tests/source/lab/parse_xsd/xsd/dml-chart.xsd", + "tests/source/lab/parse_xsd/xsd/dml-chartDrawing.xsd", + "tests/source/lab/parse_xsd/xsd/dml-diagram.xsd", + "tests/source/lab/parse_xsd/xsd/dml-lockedCanvas.xsd", + "tests/source/lab/parse_xsd/xsd/dml-main.xsd", + "tests/source/lab/parse_xsd/xsd/dml-picture.xsd", + "tests/source/lab/parse_xsd/xsd/dml-spreadsheetDrawing.xsd", + "tests/source/lab/parse_xsd/xsd/dml-wordprocessingDrawing.xsd", + "tests/source/lab/parse_xsd/xsd/pml.xsd", + "tests/source/lab/parse_xsd/xsd/shared-additionalCharacteristics.xsd", + "tests/source/lab/parse_xsd/xsd/shared-bibliography.xsd", + "tests/source/lab/parse_xsd/xsd/shared-commonSimpleTypes.xsd", + "tests/source/lab/parse_xsd/xsd/shared-customXmlDataProperties.xsd", + "tests/source/lab/parse_xsd/xsd/shared-customXmlSchemaProperties.xsd", + "tests/source/lab/parse_xsd/xsd/shared-documentPropertiesCustom.xsd", + "tests/source/lab/parse_xsd/xsd/shared-documentPropertiesExtended.xsd", + "tests/source/lab/parse_xsd/xsd/shared-documentPropertiesVariantTypes.xsd", + "tests/source/lab/parse_xsd/xsd/shared-math.xsd", + "tests/source/lab/parse_xsd/xsd/shared-relationshipReference.xsd", + "tests/source/lab/parse_xsd/xsd/sml.xsd", + "tests/source/lab/parse_xsd/xsd/vml-main.xsd", + "tests/source/lab/parse_xsd/xsd/vml-officeDrawing.xsd", + "tests/source/lab/parse_xsd/xsd/vml-presentationDrawing.xsd", + "tests/source/lab/parse_xsd/xsd/vml-spreadsheetDrawing.xsd", + "tests/source/lab/parse_xsd/xsd/vml-wordprocessingDrawing.xsd", + "tests/source/lab/parse_xsd/xsd/wml.xsd", + "tests/source/pyproject.toml", + "tests/source/requirements-test.txt", + "tests/source/requirements.txt", + "tests/source/setup.cfg", + "tests/source/setup.py", + "tests/source/spec/ISO-IEC-29500-1/ISO-IEC-29500-1.pdf", + "tests/source/spec/ISO-IEC-29500-1/schemas/dml-geometries/OfficeOpenXML-DrawingMLGeometries/presetShapeDefinitions.xml", + "tests/source/spec/ISO-IEC-29500-1/schemas/dml-geometries/OfficeOpenXML-DrawingMLGeometries/presetTextWarpDefinitions.xml", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-chart.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-chartDrawing.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-diagram.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-lockedCanvas.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-main.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-picture.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-spreadsheetDrawing.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/dml-wordprocessingDrawing.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/pml.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-additionalCharacteristics.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-bibliography.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-commonSimpleTypes.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-customXmlDataProperties.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-customXmlSchemaProperties.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-documentPropertiesCustom.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-documentPropertiesExtended.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-documentPropertiesVariantTypes.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-math.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/shared-relationshipReference.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/sml.xsd", + "tests/source/spec/ISO-IEC-29500-1/schemas/xsd/wml.xsd", + "tests/source/spec/ISO-IEC-29500-2/ISO-IEC-29500-2.pdf", + "tests/source/spec/ISO-IEC-29500-2/opc-xsd/opc-contentTypes.xsd", + "tests/source/spec/ISO-IEC-29500-2/opc-xsd/opc-coreProperties.xsd", + "tests/source/spec/ISO-IEC-29500-2/opc-xsd/opc-digSig.xsd", + "tests/source/spec/ISO-IEC-29500-2/opc-xsd/opc-relationships.xsd", + "tests/source/spec/ISO-IEC-29500-3/ISO-IEC-29500-3.pdf", + "tests/source/spec/ISO-IEC-29500-4/ISO-IEC-29500-4.pdf", + "tests/source/spec/ISO-IEC-29500-4/xsd/dml-chart.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/dml-chartDrawing.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/dml-diagram.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/dml-lockedCanvas.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/dml-main.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/dml-picture.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/dml-spreadsheetDrawing.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/dml-wordprocessingDrawing.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/pml.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/shared-additionalCharacteristics.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/shared-bibliography.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/shared-commonSimpleTypes.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/shared-customXmlDataProperties.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/shared-customXmlSchemaProperties.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/shared-documentPropertiesCustom.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/shared-documentPropertiesExtended.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/shared-documentPropertiesVariantTypes.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/shared-math.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/shared-relationshipReference.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/sml.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/vml-main.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/vml-officeDrawing.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/vml-presentationDrawing.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/vml-spreadsheetDrawing.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/vml-wordprocessingDrawing.xsd", + "tests/source/spec/ISO-IEC-29500-4/xsd/wml.xsd", + "tests/source/spec/gen_spec/Makefile", + "tests/source/spec/gen_spec/enum/MsoAutoShapeType.xml", + "tests/source/spec/gen_spec/gen_spec.py", + "tests/source/spec/gen_spec/sql/dump.sql", + "tests/source/spec/gen_spec/src_data/enums/MsoAutoShapeType/MsoAutoShapeType.txt", + "tests/source/spec/gen_spec/src_data/enums/MsoAutoShapeType/ST_ShapeType.xml", + "tests/source/spec/gen_spec/src_data/enums/MsoAutoShapeType/mapping.txt", + "tests/source/spec/gen_spec/src_data/msoAutoShapeType.py", + "tests/source/spec/gen_spec/src_data/scratch.py", + "tests/source/src/pptx/__init__.py", + "tests/source/src/pptx/action.py", + "tests/source/src/pptx/api.py", + "tests/source/src/pptx/chart/__init__.py", + "tests/source/src/pptx/chart/axis.py", + "tests/source/src/pptx/chart/category.py", + "tests/source/src/pptx/chart/chart.py", + "tests/source/src/pptx/chart/data.py", + "tests/source/src/pptx/chart/datalabel.py", + "tests/source/src/pptx/chart/legend.py", + "tests/source/src/pptx/chart/marker.py", + "tests/source/src/pptx/chart/plot.py", + "tests/source/src/pptx/chart/point.py", + "tests/source/src/pptx/chart/series.py", + "tests/source/src/pptx/chart/xlsx.py", + "tests/source/src/pptx/chart/xmlwriter.py", + "tests/source/src/pptx/dml/__init__.py", + "tests/source/src/pptx/dml/chtfmt.py", + "tests/source/src/pptx/dml/color.py", + "tests/source/src/pptx/dml/effect.py", + "tests/source/src/pptx/dml/fill.py", + "tests/source/src/pptx/dml/line.py", + "tests/source/src/pptx/enum/__init__.py", + "tests/source/src/pptx/enum/action.py", + "tests/source/src/pptx/enum/base.py", + "tests/source/src/pptx/enum/chart.py", + "tests/source/src/pptx/enum/dml.py", + "tests/source/src/pptx/enum/lang.py", + "tests/source/src/pptx/enum/shapes.py", + "tests/source/src/pptx/enum/text.py", + "tests/source/src/pptx/exc.py", + "tests/source/src/pptx/media.py", + "tests/source/src/pptx/opc/__init__.py", + "tests/source/src/pptx/opc/constants.py", + "tests/source/src/pptx/opc/oxml.py", + "tests/source/src/pptx/opc/package.py", + "tests/source/src/pptx/opc/packuri.py", + "tests/source/src/pptx/opc/serialized.py", + "tests/source/src/pptx/opc/shared.py", + "tests/source/src/pptx/opc/spec.py", + "tests/source/src/pptx/oxml/__init__.py", + "tests/source/src/pptx/oxml/action.py", + "tests/source/src/pptx/oxml/chart/__init__.py", + "tests/source/src/pptx/oxml/chart/axis.py", + "tests/source/src/pptx/oxml/chart/chart.py", + "tests/source/src/pptx/oxml/chart/datalabel.py", + "tests/source/src/pptx/oxml/chart/legend.py", + "tests/source/src/pptx/oxml/chart/marker.py", + "tests/source/src/pptx/oxml/chart/plot.py", + "tests/source/src/pptx/oxml/chart/series.py", + "tests/source/src/pptx/oxml/chart/shared.py", + "tests/source/src/pptx/oxml/coreprops.py", + "tests/source/src/pptx/oxml/dml/__init__.py", + "tests/source/src/pptx/oxml/dml/color.py", + "tests/source/src/pptx/oxml/dml/fill.py", + "tests/source/src/pptx/oxml/dml/line.py", + "tests/source/src/pptx/oxml/ns.py", + "tests/source/src/pptx/oxml/presentation.py", + "tests/source/src/pptx/oxml/shapes/__init__.py", + "tests/source/src/pptx/oxml/shapes/autoshape.py", + "tests/source/src/pptx/oxml/shapes/connector.py", + "tests/source/src/pptx/oxml/shapes/graphfrm.py", + "tests/source/src/pptx/oxml/shapes/groupshape.py", + "tests/source/src/pptx/oxml/shapes/picture.py", + "tests/source/src/pptx/oxml/shapes/shared.py", + "tests/source/src/pptx/oxml/simpletypes.py", + "tests/source/src/pptx/oxml/slide.py", + "tests/source/src/pptx/oxml/table.py", + "tests/source/src/pptx/oxml/text.py", + "tests/source/src/pptx/oxml/theme.py", + "tests/source/src/pptx/oxml/xmlchemy.py", + "tests/source/src/pptx/package.py", + "tests/source/src/pptx/parts/__init__.py", + "tests/source/src/pptx/parts/chart.py", + "tests/source/src/pptx/parts/coreprops.py", + "tests/source/src/pptx/parts/embeddedpackage.py", + "tests/source/src/pptx/parts/image.py", + "tests/source/src/pptx/parts/media.py", + "tests/source/src/pptx/parts/presentation.py", + "tests/source/src/pptx/parts/slide.py", + "tests/source/src/pptx/presentation.py", + "tests/source/src/pptx/shapes/__init__.py", + "tests/source/src/pptx/shapes/autoshape.py", + "tests/source/src/pptx/shapes/base.py", + "tests/source/src/pptx/shapes/connector.py", + "tests/source/src/pptx/shapes/freeform.py", + "tests/source/src/pptx/shapes/graphfrm.py", + "tests/source/src/pptx/shapes/group.py", + "tests/source/src/pptx/shapes/picture.py", + "tests/source/src/pptx/shapes/placeholder.py", + "tests/source/src/pptx/shapes/shapetree.py", + "tests/source/src/pptx/shared.py", + "tests/source/src/pptx/slide.py", + "tests/source/src/pptx/spec.py", + "tests/source/src/pptx/table.py", + "tests/source/src/pptx/templates/default.pptx", + "tests/source/src/pptx/templates/docx-icon.emf", + "tests/source/src/pptx/templates/generic-icon.emf", + "tests/source/src/pptx/templates/notes.xml", + "tests/source/src/pptx/templates/notesMaster.xml", + "tests/source/src/pptx/templates/pptx-icon.emf", + "tests/source/src/pptx/templates/theme.xml", + "tests/source/src/pptx/templates/xlsx-icon.emf", + "tests/source/src/pptx/text/__init__.py", + "tests/source/src/pptx/text/fonts.py", + "tests/source/src/pptx/text/layout.py", + "tests/source/src/pptx/text/text.py", + "tests/source/src/pptx/types.py", + "tests/source/src/pptx/util.py", + "tests/source/src/python_pptx.egg-info/PKG-INFO", + "tests/source/src/python_pptx.egg-info/SOURCES.txt", + "tests/source/src/python_pptx.egg-info/dependency_links.txt", + "tests/source/src/python_pptx.egg-info/not-zip-safe", + "tests/source/src/python_pptx.egg-info/requires.txt", + "tests/source/src/python_pptx.egg-info/top_level.txt", + "tests/source/tests/__init__.py", + "tests/source/tests/chart/__init__.py", + "tests/source/tests/chart/test_axis.py", + "tests/source/tests/chart/test_category.py", + "tests/source/tests/chart/test_chart.py", + "tests/source/tests/chart/test_data.py", + "tests/source/tests/chart/test_datalabel.py", + "tests/source/tests/chart/test_legend.py", + "tests/source/tests/chart/test_marker.py", + "tests/source/tests/chart/test_plot.py", + "tests/source/tests/chart/test_point.py", + "tests/source/tests/chart/test_series.py", + "tests/source/tests/chart/test_xlsx.py", + "tests/source/tests/chart/test_xmlwriter.py", + "tests/source/tests/dml/__init__.py", + "tests/source/tests/dml/test_chtfmt.py", + "tests/source/tests/dml/test_color.py", + "tests/source/tests/dml/test_effect.py", + "tests/source/tests/dml/test_fill.py", + "tests/source/tests/dml/test_line.py", + "tests/source/tests/enum/__init__.py", + "tests/source/tests/enum/test_base.py", + "tests/source/tests/enum/test_shapes.py", + "tests/source/tests/opc/__init__.py", + "tests/source/tests/opc/test_oxml.py", + "tests/source/tests/opc/test_package.py", + "tests/source/tests/opc/test_packuri.py", + "tests/source/tests/opc/test_serialized.py", + "tests/source/tests/oxml/__init__.py", + "tests/source/tests/oxml/shapes/__init__.py", + "tests/source/tests/oxml/shapes/test_autoshape.py", + "tests/source/tests/oxml/shapes/test_graphfrm.py", + "tests/source/tests/oxml/shapes/test_groupshape.py", + "tests/source/tests/oxml/shapes/test_picture.py", + "tests/source/tests/oxml/test___init__.py", + "tests/source/tests/oxml/test_dml.py", + "tests/source/tests/oxml/test_ns.py", + "tests/source/tests/oxml/test_presentation.py", + "tests/source/tests/oxml/test_simpletypes.py", + "tests/source/tests/oxml/test_slide.py", + "tests/source/tests/oxml/test_table.py", + "tests/source/tests/oxml/test_theme.py", + "tests/source/tests/oxml/test_xmlchemy.py", + "tests/source/tests/oxml/unitdata/__init__.py", + "tests/source/tests/oxml/unitdata/dml.py", + "tests/source/tests/oxml/unitdata/shape.py", + "tests/source/tests/oxml/unitdata/text.py", + "tests/source/tests/parts/__init__.py", + "tests/source/tests/parts/test_chart.py", + "tests/source/tests/parts/test_coreprops.py", + "tests/source/tests/parts/test_embeddedpackage.py", + "tests/source/tests/parts/test_image.py", + "tests/source/tests/parts/test_media.py", + "tests/source/tests/parts/test_presentation.py", + "tests/source/tests/parts/test_slide.py", + "tests/source/tests/shapes/__init__.py", + "tests/source/tests/shapes/test_autoshape.py", + "tests/source/tests/shapes/test_base.py", + "tests/source/tests/shapes/test_connector.py", + "tests/source/tests/shapes/test_freeform.py", + "tests/source/tests/shapes/test_graphfrm.py", + "tests/source/tests/shapes/test_group.py", + "tests/source/tests/shapes/test_picture.py", + "tests/source/tests/shapes/test_placeholder.py", + "tests/source/tests/shapes/test_shapetree.py", + "tests/source/tests/test_action.py", + "tests/source/tests/test_api.py", + "tests/source/tests/test_files/calibriz.ttf", + "tests/source/tests/test_files/cdw-logo.eps", + "tests/source/tests/test_files/dummy.mp4", + "tests/source/tests/test_files/expanded_pptx/[Content_Types].xml", + "tests/source/tests/test_files/expanded_pptx/_rels/.rels", + "tests/source/tests/test_files/expanded_pptx/docProps/app.xml", + "tests/source/tests/test_files/expanded_pptx/docProps/core.xml", + "tests/source/tests/test_files/expanded_pptx/docProps/thumbnail.jpeg", + "tests/source/tests/test_files/expanded_pptx/ppt/_rels/presentation.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/presProps.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/presentation.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/printerSettings/printerSettings1.bin", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout1.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout10.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout11.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout2.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout3.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout4.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout5.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout6.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout7.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout8.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout9.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout1.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout10.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout11.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout2.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout3.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout4.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout5.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout6.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout7.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout8.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout9.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slideMasters/_rels/slideMaster1.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slideMasters/slideMaster1.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/slides/_rels/slide1.xml.rels", + "tests/source/tests/test_files/expanded_pptx/ppt/slides/slide1.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/tableStyles.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/theme/theme1.xml", + "tests/source/tests/test_files/expanded_pptx/ppt/viewProps.xml", + "tests/source/tests/test_files/minimal.pptx", + "tests/source/tests/test_files/minimal_slide.xml", + "tests/source/tests/test_files/missing_rels_item.pptx", + "tests/source/tests/test_files/monty-truth.png", + "tests/source/tests/test_files/no-core-props.pptx", + "tests/source/tests/test_files/no-slides.pptx", + "tests/source/tests/test_files/presentation.xml", + "tests/source/tests/test_files/python-icon.jpeg", + "tests/source/tests/test_files/python-powered.png", + "tests/source/tests/test_files/python.bmp", + "tests/source/tests/test_files/slideLayout1.xml", + "tests/source/tests/test_files/snippets/2x2-area-date.txt", + "tests/source/tests/test_files/snippets/2x2-area-float.txt", + "tests/source/tests/test_files/snippets/2x2-area-stacked-100.txt", + "tests/source/tests/test_files/snippets/2x2-area-stacked.txt", + "tests/source/tests/test_files/snippets/2x2-area.txt", + "tests/source/tests/test_files/snippets/2x2-bar-clustered-date.txt", + "tests/source/tests/test_files/snippets/2x2-bar-clustered-float.txt", + "tests/source/tests/test_files/snippets/2x2-bar-clustered.txt", + "tests/source/tests/test_files/snippets/2x2-bar-stacked-100.txt", + "tests/source/tests/test_files/snippets/2x2-bar-stacked.txt", + "tests/source/tests/test_files/snippets/2x2-column-clustered.txt", + "tests/source/tests/test_files/snippets/2x2-column-stacked-100.txt", + "tests/source/tests/test_files/snippets/2x2-column-stacked.txt", + "tests/source/tests/test_files/snippets/2x2-line-date.txt", + "tests/source/tests/test_files/snippets/2x2-line-float.txt", + "tests/source/tests/test_files/snippets/2x2-line-markers-stacked-100.txt", + "tests/source/tests/test_files/snippets/2x2-line-markers-stacked.txt", + "tests/source/tests/test_files/snippets/2x2-line-markers.txt", + "tests/source/tests/test_files/snippets/2x2-line-stacked-100.txt", + "tests/source/tests/test_files/snippets/2x2-line-stacked.txt", + "tests/source/tests/test_files/snippets/2x2-line.txt", + "tests/source/tests/test_files/snippets/2x3-bubble-3d.txt", + "tests/source/tests/test_files/snippets/2x3-bubble.txt", + "tests/source/tests/test_files/snippets/2x3-xy-lines-no-markers.txt", + "tests/source/tests/test_files/snippets/2x3-xy-lines.txt", + "tests/source/tests/test_files/snippets/2x3-xy-smooth-no-markers.txt", + "tests/source/tests/test_files/snippets/2x3-xy-smooth.txt", + "tests/source/tests/test_files/snippets/2x3-xy.txt", + "tests/source/tests/test_files/snippets/2x5-radar.txt", + "tests/source/tests/test_files/snippets/3x1-pie-exploded.txt", + "tests/source/tests/test_files/snippets/3x1-pie.txt", + "tests/source/tests/test_files/snippets/3x2-doughnut-exploded.txt", + "tests/source/tests/test_files/snippets/3x2-doughnut.txt", + "tests/source/tests/test_files/snippets/4x2-multi-cat-bar.txt", + "tests/source/tests/test_files/snippets/adjust-ser-count.txt", + "tests/source/tests/test_files/snippets/cat-labels.txt", + "tests/source/tests/test_files/snippets/content-types-xml.txt", + "tests/source/tests/test_files/snippets/default-notes.txt", + "tests/source/tests/test_files/snippets/default-notesMaster.txt", + "tests/source/tests/test_files/snippets/default-theme.txt", + "tests/source/tests/test_files/snippets/freeform.txt", + "tests/source/tests/test_files/snippets/package-rels-xml.txt", + "tests/source/tests/test_files/snippets/placeholders.txt", + "tests/source/tests/test_files/snippets/presentation-rels-xml.txt", + "tests/source/tests/test_files/snippets/relationships.txt", + "tests/source/tests/test_files/snippets/rels-load-from-xml.txt", + "tests/source/tests/test_files/snippets/rewrite-ser.txt", + "tests/source/tests/test_files/snippets/timing.txt", + "tests/source/tests/test_files/test.pptx", + "tests/source/tests/test_files/test_slides.pptx", + "tests/source/tests/test_media.py", + "tests/source/tests/test_package.py", + "tests/source/tests/test_presentation.py", + "tests/source/tests/test_shared.py", + "tests/source/tests/test_slide.py", + "tests/source/tests/test_table.py", + "tests/source/tests/test_util.py", + "tests/source/tests/text/__init__.py", + "tests/source/tests/text/test_fonts.py", + "tests/source/tests/text/test_layout.py", + "tests/source/tests/text/test_text.py", + "tests/source/tests/unitdata.py", + "tests/source/tests/unitutil/__init__.py", + "tests/source/tests/unitutil/cxml.py", + "tests/source/tests/unitutil/file.py", + "tests/source/tests/unitutil/mock.py", + "tests/source/tox.ini", + "tests/source/typings/behave/__init__.pyi", + "tests/source/typings/behave/runner.pyi", + "tests/source/typings/lxml/_types.pyi", + "tests/source/typings/lxml/etree/__init__.pyi", + "tests/source/typings/lxml/etree/_classlookup.pyi", + "tests/source/typings/lxml/etree/_cleanup.pyi", + "tests/source/typings/lxml/etree/_element.pyi", + "tests/source/typings/lxml/etree/_module_func.pyi", + "tests/source/typings/lxml/etree/_module_misc.pyi", + "tests/source/typings/lxml/etree/_nsclasses.pyi", + "tests/source/typings/lxml/etree/_parser.pyi", + "tests/test.sh", + "tests/test_driver.py", + "tests/test_results.py", +] +executable_files = [ + "environment/source/features/steps/test_files/just-two-mice.mp4", + "environment/source/features/steps/test_files/pic.emf", + "environment/source/lab/cust-elm-classes/gen_oxml_classes.py", + "environment/source/lab/cust-elm-classes/main.py", + "environment/source/lab/parse_xsd/objectify_lab.py", + "environment/source/lab/parse_xsd/parse_xsd.py", + "environment/source/lab/parse_xsd/validate.py", + "environment/source/setup.py", + "environment/source/spec/gen_spec/gen_spec.py", + "environment/source/spec/gen_spec/src_data/scratch.py", + "environment/source/tests/test_files/cdw-logo.eps", + "solution/solve.sh", + "tests/source/features/steps/test_files/just-two-mice.mp4", + "tests/source/features/steps/test_files/pic.emf", + "tests/source/lab/cust-elm-classes/gen_oxml_classes.py", + "tests/source/lab/cust-elm-classes/main.py", + "tests/source/lab/parse_xsd/objectify_lab.py", + "tests/source/lab/parse_xsd/parse_xsd.py", + "tests/source/lab/parse_xsd/validate.py", + "tests/source/setup.py", + "tests/source/spec/gen_spec/gen_spec.py", + "tests/source/spec/gen_spec/src_data/scratch.py", + "tests/source/tests/test_files/cdw-logo.eps", + "tests/test.sh", +] +bundle_hash = "sha256:745d74181f2aaf6681b26aaf84fa6ac062ab3e52632d9b0e1b57601820922e2c" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "verified" +stage = "complete" +reason_codes = [ + "quality_verified", +] +detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile." +checked_at = "2026-11-20T10:25:47.706055Z" +provenance = "unknown" +subject_bundle_hash = "sha256:745d74181f2aaf6681b26aaf84fa6ac062ab3e52632d9b0e1b57601820922e2c" +profile = "evidence-review-v2" +source_task_path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/f6c0c34e92f7/candidates/74f059424102/quality/revisions/r0/tasksmith-74f059424102" +source_task_toml_sha256 = "3c703744ac862a074d18e48ce0eb60bfb94793551589e35dbb9011c8c425a0bc" + +[[metadata.repo2env.evaluation.evidence]] +kind = "quality_result" +path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/f6c0c34e92f7/candidates/74f059424102/quality/result.json" +sha256 = "4e2f1eb090a7cdf732e311c6175662c4e0ea1fa3563ea324286e066bc98230a0" +subject_bundle_hash = "sha256:745d74181f2aaf6681b26aaf84fa6ac062ab3e52632d9b0e1b57601820922e2c" + +[[metadata.repo2env.evaluation.evidence]] +kind = "baseline" +path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/f6c0c34e92f7/candidates/74f059424102/quality/trials/r0-baseline/tsbatch-195cc094e760-f6c0c34e92f7-q-74f05942-r0-baseline/tasksmith-74f059424102__U2sKFax/result.json" +sha256 = "5a88308f9f4469a6ab47148e1f4e8d3bb2ae912cb27ce888763b3b3e1c77f937" +subject_bundle_hash = "sha256:745d74181f2aaf6681b26aaf84fa6ac062ab3e52632d9b0e1b57601820922e2c" +harbor_task_checksum = "200433650d2f6a8ee56ebb21da19827c1e6f366661786fd950eb5ae11b2bde95" + +[[metadata.repo2env.evaluation.evidence]] +kind = "oracle" +path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/f6c0c34e92f7/candidates/74f059424102/quality/trials/r0-oracle/tsbatch-195cc094e760-f6c0c34e92f7-q-74f05942-r0-oracle/tasksmith-74f059424102__bGPfNou/result.json" +sha256 = "ce57ba2ddd621efa364843e4464db85814af24585b27e144fe923e2214b76411" +subject_bundle_hash = "sha256:745d74181f2aaf6681b26aaf84fa6ac062ab3e52632d9b0e1b57601820922e2c" +harbor_task_checksum = "200433650d2f6a8ee56ebb21da19827c1e6f366661786fd950eb5ae11b2bde95" + +[[metadata.repo2env.evaluation.evidence]] +kind = "probe" +path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/f6c0c34e92f7/candidates/74f059424102/quality/trials/r0-probe0/tsbatch-195cc094e760-f6c0c34e92f7-q-74f05942-r0-probe0/tasksmith-74f059424102__iJc2R2K/result.json" +sha256 = "aae50d544f6de1c013b440357b2cd849670ef9b15b7b0d1b39ee5c446df6cf54" +subject_bundle_hash = "sha256:12e065c356085797fcdb4e75cb2771e01a0db5c5eb78f8bab4930d6151577a13" +harbor_task_checksum = "5cea2e63133a4d23c2111b6d253f421e73430a69b179d98804836554b57e0825" + +[[metadata.repo2env.evaluation.evidence]] +kind = "probe" +path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/f6c0c34e92f7/candidates/74f059424102/quality/trials/r0-probe1/tsbatch-195cc094e760-f6c0c34e92f7-q-74f05942-r0-probe1/tasksmith-74f059424102__pgYbWa4/result.json" +sha256 = "7611445bc94f3ed130fd48d2d5435b383526ccfc187266268ea08457744a0fe8" +subject_bundle_hash = "sha256:8c0fe08414118cf240f896e3283e31991d063868722a084169be7a39413efe14" +harbor_task_checksum = "432bd4bfb2fad4d2988a1c34f573e82510cfe2312ce4706ea8d193be987ff1a9" + +[[metadata.repo2env.evaluation.evidence]] +kind = "rollout" +path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/f6c0c34e92f7/candidates/74f059424102/quality/trials/r0-rollout/tsbatch-195cc094e760-f6c0c34e92f7-q-74f05942-r0-rollout/tasksmith-74f059424102__y3NeHwW/result.json" +sha256 = "9cffdbd998a3b602338847ac96da288970e8fe90db08f1db9a8e034282b583c8" +subject_bundle_hash = "sha256:745d74181f2aaf6681b26aaf84fa6ac062ab3e52632d9b0e1b57601820922e2c" +harbor_task_checksum = "200433650d2f6a8ee56ebb21da19827c1e6f366661786fd950eb5ae11b2bde95" + +[metadata.repo2env.quality_requirements] +probe_focus = [ + "general", +] + +[environment] +docker_image = "ghcr.io/younesbelkada/hat@sha256:6033c20c5a5b554c3f25d75591d069649104df7913917b3d7a82dab60eea2c53" +cpus = 1 +memory_mb = 2048 +build_timeout_sec = 600 +network_mode = "no-network" + +[agent] +timeout_sec = 600 +user = "learner" +network_mode = "no-network" + +[verifier] +timeout_sec = 90 +user = "root" +network_mode = "no-network" +environment_mode = "separate" + +[verifier.environment] +network_mode = "no-network" +cpus = 1 +memory_mb = 512 + +[[artifacts]] +source = "/workspace/src/pptx" +exclude = [ + "__pycache__", + "*.pyc", + ".pytest_cache", +] diff --git a/tasks/tasksmith-74f059424102/tests/Dockerfile b/tasks/tasksmith-74f059424102/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..00d7eb245e67844473a7ddc5e6f351610c7377b4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3.12-slim +WORKDIR /workspace +RUN python -m pip install --no-cache-dir setuptools==84.2.1 lxml==6.1.3 Pillow==13.0.0 XlsxWriter==3.3.3 pyparsing==3.2.3 pytest==9.2.0 +COPY source /workspace +RUN python -m pip install --no-cache-dir -e . +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 +ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1 +RUN useradd -m -u 1001 grader +COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/ +RUN chmod 755 /tests && chmod 644 /tests/* diff --git a/tasks/tasksmith-74f059424102/tests/contract.json b/tasks/tasksmith-74f059424102/tests/contract.json new file mode 100644 index 0000000000000000000000000000000000000000..c0213bc11fcc39d6cf02311948d5be2a6e81e638 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/contract.json @@ -0,0 +1 @@ +{"expected_passes": ["tests.oxml.test_presentation.DescribeCT_SlideIdList::and_it_chooses_a_valid_slide_id_when_max_slide_id_is_used_for_a_slide[p:sldIdLst/(p:sldId{id=245},p:sldId{id=2147483647},p:sldId{id=256})-257]", "tests.oxml.test_presentation.DescribeCT_SlideIdList::and_it_chooses_a_valid_slide_id_when_max_slide_id_is_used_for_a_slide[p:sldIdLst/(p:sldId{id=256},p:sldId{id=2147483647})-257]", "tests.oxml.test_presentation.DescribeCT_SlideIdList::and_it_chooses_a_valid_slide_id_when_max_slide_id_is_used_for_a_slide[p:sldIdLst/(p:sldId{id=256},p:sldId{id=2147483647},p:sldId{id=257})-258]", "tests.oxml.test_presentation.DescribeCT_SlideIdList::and_it_chooses_a_valid_slide_id_when_max_slide_id_is_used_for_a_slide[p:sldIdLst/p:sldId{id=2147483647}-256]", "tests.oxml.test_presentation.DescribeCT_SlideIdList::and_it_chooses_a_valid_slide_id_when_max_slide_id_is_used_for_a_slide[p:sldIdLst/p:sldId{id=2147483648}-256]", "tests.oxml.test_presentation.DescribeCT_SlideIdList::and_it_chooses_a_valid_slide_id_when_max_slide_id_is_used_for_a_slide[p:sldIdLst/p:sldId{id=2147483646}-2147483647]", "tests.oxml.test_presentation.DescribeCT_SlideIdList::it_can_add_a_sldId_element_as_a_child", "tests.oxml.test_presentation.DescribeCT_SlideIdList::it_knows_the_next_available_slide_id[p:sldIdLst-256]", "tests.oxml.test_presentation.DescribeCT_SlideIdList::it_knows_the_next_available_slide_id[p:sldIdLst/(p:sldId{id=256},p:sldId{id=712})-713]", "tests.oxml.test_presentation.DescribeCT_SlideIdList::it_knows_the_next_available_slide_id[p:sldIdLst/(p:sldId{id=280},p:sldId{id=257})-281]", "tests.oxml.test_presentation.DescribeCT_SlideIdList::it_knows_the_next_available_slide_id[p:sldIdLst/p:sldId{id=256}-257]", "tests.oxml.test_presentation.DescribeCT_SlideIdList::it_knows_the_next_available_slide_id[p:sldIdLst/p:sldId{id=42}-256]"], "immutable_assets": {"src/pptx/templates/default.pptx": "e10cc9e120961f6bd4074a373c9c80d2a06c497157e8f4972977b7bea83a8f34", "src/pptx/templates/docx-icon.emf": "cbfa051aa5f1ec1993f0ce056f67112ce4af3a8c3ac6fccfc219399ed6dc625d", "src/pptx/templates/generic-icon.emf": "e12b5b9555953d6eeef4c24e9c6a3c2a7073e1eaeba8825291ea4b78572b955e", "src/pptx/templates/notes.xml": "a8f14f275cf7616e15c61216afe36aac706c3e7c7c4e987bd433c65809110d03", "src/pptx/templates/notesMaster.xml": "1fb939714ad0571d747d9e573f9a0594062a89e73c6a076d943ba7f541072813", "src/pptx/templates/pptx-icon.emf": "7f976582a6d94fe56b65ce6d3bef5ab5746a6f652718979b1325a31c5a2b4e5d", "src/pptx/templates/theme.xml": "76f7bdf39e5333483e42f9c4f6eba344330617b6e6171b7a4039c239131a9b4d", "src/pptx/templates/xlsx-icon.emf": "14e52936cebdf16e5a6629ce707415c26122fe54af322872a2d25fec618a69ee"}, "optional_files": [], "pytest_args": [], "submitted_files": ["src/pptx/__init__.py", "src/pptx/action.py", "src/pptx/api.py", "src/pptx/chart/__init__.py", "src/pptx/chart/axis.py", "src/pptx/chart/category.py", "src/pptx/chart/chart.py", "src/pptx/chart/data.py", "src/pptx/chart/datalabel.py", "src/pptx/chart/legend.py", "src/pptx/chart/marker.py", "src/pptx/chart/plot.py", "src/pptx/chart/point.py", "src/pptx/chart/series.py", "src/pptx/chart/xlsx.py", "src/pptx/chart/xmlwriter.py", "src/pptx/dml/__init__.py", "src/pptx/dml/chtfmt.py", "src/pptx/dml/color.py", "src/pptx/dml/effect.py", "src/pptx/dml/fill.py", "src/pptx/dml/line.py", "src/pptx/enum/__init__.py", "src/pptx/enum/action.py", "src/pptx/enum/base.py", "src/pptx/enum/chart.py", "src/pptx/enum/dml.py", "src/pptx/enum/lang.py", "src/pptx/enum/shapes.py", "src/pptx/enum/text.py", "src/pptx/exc.py", "src/pptx/media.py", "src/pptx/opc/__init__.py", "src/pptx/opc/constants.py", "src/pptx/opc/oxml.py", "src/pptx/opc/package.py", "src/pptx/opc/packuri.py", "src/pptx/opc/serialized.py", "src/pptx/opc/shared.py", "src/pptx/opc/spec.py", "src/pptx/oxml/__init__.py", "src/pptx/oxml/action.py", "src/pptx/oxml/chart/__init__.py", "src/pptx/oxml/chart/axis.py", "src/pptx/oxml/chart/chart.py", "src/pptx/oxml/chart/datalabel.py", "src/pptx/oxml/chart/legend.py", "src/pptx/oxml/chart/marker.py", "src/pptx/oxml/chart/plot.py", "src/pptx/oxml/chart/series.py", "src/pptx/oxml/chart/shared.py", "src/pptx/oxml/coreprops.py", "src/pptx/oxml/dml/__init__.py", "src/pptx/oxml/dml/color.py", "src/pptx/oxml/dml/fill.py", "src/pptx/oxml/dml/line.py", "src/pptx/oxml/ns.py", "src/pptx/oxml/presentation.py", "src/pptx/oxml/shapes/__init__.py", "src/pptx/oxml/shapes/autoshape.py", "src/pptx/oxml/shapes/connector.py", "src/pptx/oxml/shapes/graphfrm.py", "src/pptx/oxml/shapes/groupshape.py", "src/pptx/oxml/shapes/picture.py", "src/pptx/oxml/shapes/shared.py", "src/pptx/oxml/simpletypes.py", "src/pptx/oxml/slide.py", "src/pptx/oxml/table.py", "src/pptx/oxml/text.py", "src/pptx/oxml/theme.py", "src/pptx/oxml/xmlchemy.py", "src/pptx/package.py", "src/pptx/parts/__init__.py", "src/pptx/parts/chart.py", "src/pptx/parts/coreprops.py", "src/pptx/parts/embeddedpackage.py", "src/pptx/parts/image.py", "src/pptx/parts/media.py", "src/pptx/parts/presentation.py", "src/pptx/parts/slide.py", "src/pptx/presentation.py", "src/pptx/shapes/__init__.py", "src/pptx/shapes/autoshape.py", "src/pptx/shapes/base.py", "src/pptx/shapes/connector.py", "src/pptx/shapes/freeform.py", "src/pptx/shapes/graphfrm.py", "src/pptx/shapes/group.py", "src/pptx/shapes/picture.py", "src/pptx/shapes/placeholder.py", "src/pptx/shapes/shapetree.py", "src/pptx/shared.py", "src/pptx/slide.py", "src/pptx/spec.py", "src/pptx/table.py", "src/pptx/text/__init__.py", "src/pptx/text/fonts.py", "src/pptx/text/layout.py", "src/pptx/text/text.py", "src/pptx/types.py", "src/pptx/util.py"], "submitted_roots": ["src/pptx"], "test_paths": ["tests/oxml/test_presentation.py::DescribeCT_SlideIdList"], "timeout_sec": 60} \ No newline at end of file diff --git a/tasks/tasksmith-74f059424102/tests/grade.py b/tasks/tasksmith-74f059424102/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a803a55bfcc142c8279645ea59cea90b2a90918a --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/grade.py @@ -0,0 +1,196 @@ +"""Standalone trusted entry point; copied into each separate verifier image. + +No Repo2RLEnv installation is needed to grade an exported task. Submitted Python +runs as an unprivileged user; this parent owns the result parser and reward file. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +import signal +import stat +import subprocess +import sys +import tempfile +from pathlib import Path + + +def child_environment(temporary: str) -> dict[str, str]: + """Preserve prepared runtime assets without inheriting controller credentials.""" + return { + **{ + key: os.environ[key] + for key in ( + "LD_LIBRARY_PATH", + "CUDA_VISIBLE_DEVICES", + "NVIDIA_VISIBLE_DEVICES", + "NVIDIA_DRIVER_CAPABILITIES", + "NCCL_SOCKET_IFNAME", + "GLOO_SOCKET_IFNAME", + "HF_HOME", + "HF_HUB_CACHE", + "HF_HUB_OFFLINE", + "TRANSFORMERS_OFFLINE", + "HF_DATASETS_OFFLINE", + ) + if key in os.environ + }, + "PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin", + "HOME": temporary, + "PYTHONDONTWRITEBYTECODE": "1", + "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", + } + + +def validate_submission(workspace: Path, contract: dict) -> None: + """Validate private staging and remove inert backups before importing Python.""" + submitted = set(contract["submitted_files"]) + backups: set[str] = set() + optional = submitted & set(contract.get("optional_files", [])) + paths = submitted - optional + for relative in optional: + path = workspace / relative + if any(component.is_symlink() for component in (path, *path.parents)): + raise ValueError("Submitted source contains a symlink") + # Added standalone modules may be absent in the baseline. If supplied, + # apply the same regular-file and size checks as every required module. + if path.exists(): + paths.add(relative) + roots = contract.get("submitted_roots", []) + immutable = contract.get("immutable_assets", {}) + paths.update(immutable) + for relative in roots: + root = workspace / relative + if root.is_symlink() or not root.is_dir(): + raise ValueError("Submitted source root is missing or linked") + for path in root.rglob("*"): + if path.is_symlink(): + raise ValueError("Submitted source contains a symlink") + if path.is_dir(): + continue + name = path.relative_to(workspace).as_posix() + if path.suffix != ".py" and name not in immutable: + if name not in submitted and path.name.endswith((".py.bak", ".py~")): + backups.add(name) + else: + raise ValueError("Only Python source files may be added") + paths.add(name) + for relative in sorted(paths): + path = workspace / relative + for component in (path, *path.parents): + if component.is_symlink(): + raise ValueError("Submitted source contains a symlink") + if ( + not path.is_file() + or not stat.S_ISREG(path.stat().st_mode) + or path.stat().st_size > 8 * 1024 * 1024 + ): + raise ValueError("Submitted source is not a bounded regular file") + if ( + relative in immutable + and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative] + ): + raise ValueError("Non-Python source assets must remain unchanged") + if relative not in backups: + # os.chown doesn't exist on Windows. This module only ever runs for + # real inside the Linux verifier container (every other path here + # is an absolute container path); the guard exists so the tests + # that call validate_submission() directly can run on a Windows + # host without touching real container-only ownership semantics. + if sys.platform != "win32": + os.chown(path, 0, 0) + path.chmod(0o644) + # Only the verifier's collected copy is cleaned. The learner workspace and + # archived submission retain their bytes. Validate every path first so a + # backup cannot bypass linked, oversized, required, or immutable file checks. + for relative in sorted(backups): + (workspace / relative).unlink() + + +def main() -> None: + directory = Path("/tests") + parser_spec = importlib.util.spec_from_file_location( + "test_results", directory / "test_results.py" + ) + parser = importlib.util.module_from_spec(parser_spec) + sys.modules[parser_spec.name] = parser + parser_spec.loader.exec_module(parser) + contract = json.loads((directory / "contract.json").read_text()) + logs = Path("/logs/verifier") + logs.mkdir(parents=True, exist_ok=True) + logs.chmod(0o755) + reward = logs / "reward.txt" + reward.write_text("0\n") + reward.chmod(0o644) + try: + validate_submission(Path("/workspace"), contract) + except (ValueError, OSError) as exc: + (logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)})) + return + with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary: + working = Path(temporary) + if sys.platform != "win32": # os.chown doesn't exist on Windows; see above + os.chown(working, 1001, 1001) + working.chmod(0o700) + report = working / "results.xml" + command = [ + sys.executable, + "-I", + "/tests/test_driver.py", + *contract["test_paths"], + *contract.get("pytest_args", []), + "-q", + "--tb=short", + "-p", + "no:cacheprovider", + f"--junitxml={report}", + ] + with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr: + process = subprocess.Popen( + command, + cwd="/workspace", + stdout=stdout, + stderr=stderr, + user=1001, + group=1001, + extra_groups=[], + start_new_session=True, + env=child_environment(temporary), + ) + try: + code = process.wait(timeout=contract["timeout_sec"]) + finally: + # Terminate descendants too: they must not keep modifying the + # child-owned report while the trusted parent checks it. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024: + (logs / "result.json").write_text( + json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"}) + ) + return + text = report.read_text() + (logs / "results.xml").write_text(text) + try: + parsed = parser.parse_junit(text, returncode=code) + except ValueError as exc: + (logs / "result.json").write_text( + json.dumps({"passed": False, "returncode": code, "reason": str(exc)}) + ) + return + expected = set(contract["expected_passes"]) + passed = code == 0 and bool(expected) and parsed.passed == expected + (logs / "result.json").write_text( + json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses}) + ) + reward.write_text("1\n" if passed else "0\n") + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-74f059424102/tests/source/.github/workflows/ci.yml b/tasks/tasksmith-74f059424102/tests/source/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..6b14f6cd5b768b1b7820f6b4a58bf2a0ed03e1c9 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/.github/workflows/ci.yml @@ -0,0 +1,36 @@ +name: ci + +on: + pull_request: + branches: [ master ] + push: + branches: + - master + - develop + +permissions: + contents: write + +jobs: + + build: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.9", "3.10", "3.11", "3.12"] + steps: + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Display Python version + run: python -c "import sys; print(sys.version)" + - name: Install test dependencies + run: | + pip install . + pip install -r requirements-test.txt + - name: Test with pytest + run: pytest --cov=pptx --cov-report term-missing tests + - name: Acceptance tests with behave + run: behave --stop diff --git a/tasks/tasksmith-74f059424102/tests/source/.gitignore b/tasks/tasksmith-74f059424102/tests/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c043a21c1daa54380f302dd50215ce88ee04441e --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/.gitignore @@ -0,0 +1,13 @@ +/build/ +.cache +.coverage +/.tox/ +/src/*.egg-info +*.pyc +/dist/ +/docs/.build +out.txt +_scratch/ +/spec/gen_spec/spec*.db +tags +/tests/debug.py diff --git a/tasks/tasksmith-74f059424102/tests/source/.travis.yml b/tasks/tasksmith-74f059424102/tests/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..261be797f6af205681aa33b8c939a6da08df3f86 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/.travis.yml @@ -0,0 +1,13 @@ +language: python +python: + - "3.8" + - "3.6" + - "2.7" + +# ---command to install dependencies, e.g. pip install -r requirements.txt +install: + - pip install -r requirements.txt + +# ---command to run tests, e.g. python setup.py test +sudo: false +script: py.test && behave --stop diff --git a/tasks/tasksmith-74f059424102/tests/source/Dockerfile b/tasks/tasksmith-74f059424102/tests/source/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..de7d17a51a05cfe9f04f7922ddd5627d33e988e8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.12-slim +WORKDIR /workspace +RUN python -m pip install --no-cache-dir setuptools==84.2.1 lxml==6.1.3 Pillow==13.0.0 XlsxWriter==3.3.3 pyparsing==3.2.3 pytest==9.2.0 +COPY . /workspace +RUN python -m pip install --no-cache-dir -e . +RUN rm -rf /workspace/.git /root/.cache/pip +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 +ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1 diff --git a/tasks/tasksmith-74f059424102/tests/source/HISTORY.rst b/tasks/tasksmith-74f059424102/tests/source/HISTORY.rst new file mode 100644 index 0000000000000000000000000000000000000000..6cbff8b3bea3c536fae6cfe2078eb2adfe8349c1 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/HISTORY.rst @@ -0,0 +1,534 @@ +.. :changelog: + +Release History +--------------- + +0.6.24-dev0 ++++++++++++++++++++ + +- fix: #943 remove mention of a Px Length subtype + +0.6.23 (2023-11-02) ++++++++++++++++++++ + +- fix: #912 Pillow<=9.5 constraint entails security vulnerability + + +0.6.22 (2023-08-28) ++++++++++++++++++++ + +- Add #909 Add imgW, imgH params to `shapes.add_ole_object()` +- fix: #754 _Relationships.items() raises +- fix: #758 quote in autoshape name must be escaped +- fix: #746 update Python 3.x support in docs +- fix: #748 setup's `license` should be short string +- fix: #762 AttributeError: module 'collections' has no attribute 'abc' + (Windows Python 3.10+) + + +0.6.21 (2021-09-20) ++++++++++++++++++++ + +- Fix #741 _DirPkgReader must implement .__contains__() + + +0.6.20 (2021-09-14) ++++++++++++++++++++ + +- Fix #206 accommodate NULL target-references in relationships. +- Fix #223 escape image filename that appears as literal in XML. +- Fix #517 option to display chart categories/values in reverse order. +- Major refactoring of ancient package loading code. + + +0.6.19 (2021-05-17) ++++++++++++++++++++ + +- Add shapes.add_ole_object(), allowing arbitrary Excel or other binary file to be + embedded as a shape on a slide. The OLE object is represented as an icon. + + +0.6.18 (2019-05-02) ++++++++++++++++++++ + +- .text property getters encode line-break as a vertical-tab (VT, '\v', ASCII 11/x0B). + This is consistent with PowerPoint's copy/paste behavior and allows like-breaks (soft + carriage-return) to be distinguished from paragraph boundary. Previously, a line-break + was encoded as a newline ('\n') and was not distinguishable from a paragraph boundary. + + .text properties include Shape.text, _Cell.text, TextFrame.text, _Paragraph.text and + _Run.text. + +- .text property setters accept vertical-tab character and place a line-break element in + that location. All other control characters other than horizontal-tab ('\t') and + newline ('\n') in range \x00-\x1F are accepted and escaped with plain-text like + "_x001B" for ESC (ASCII 27). + + Previously a control character other than tab or newline in an assigned string would + trigger an exception related to invalid XML character. + + +0.6.17 (2018-12-16) ++++++++++++++++++++ + +- Add SlideLayouts.remove() - Delete unused slide-layout +- Add SlideLayout.used_by_slides - Get slides based on this slide-layout +- Add SlideLayouts.index() - Get index of slide-layout in master +- Add SlideLayouts.get_by_name() - Get slide-layout by its str name + + +0.6.16 (2018-11-09) ++++++++++++++++++++ + +- Feature #395 DataLabels.show_* properties, e.g. .show_percentage +- Feature #453 Chart data tolerates None for labels + + +0.6.15 (2018-09-24) ++++++++++++++++++++ + +- Fix #436 ValueAxis._cross_xAx fails on c:dateAxis + + +0.6.14 (2018-09-24) ++++++++++++++++++++ + +- Add _Cell.merge() +- Add _Cell.split() +- Add _Cell.__eq__() +- Add _Cell.is_merge_origin +- Add _Cell.is_spanned +- Add _Cell.span_height +- Add _Cell.span_width +- Add _Cell.text getter +- Add Table.iter_cells() +- Move pptx.shapes.table module to pptx.table +- Add user documentation 'Working with tables' + + +0.6.13 (2018-09-10) ++++++++++++++++++++ + +- Add Chart.font +- Fix #293 Can't hide title of single-series Chart +- Fix shape.width value is not type Emu +- Fix add a:defRPr with c:rich (fixes some font inheritance breakage) + + +0.6.12 (2018-08-11) ++++++++++++++++++++ + +- Add Picture.auto_shape_type +- Remove Python 2.6 testing from build +- Update dependencies to avoid vulnerable Pillow version +- Fix #260, #301, #382, #401 +- Add _Paragraph.add_line_break() +- Add Connector.line + + +0.6.11 (2018-07-25) ++++++++++++++++++++ + +- Add gradient fill. +- Add experimental "turbo-add" option for producing large shape-count slides. + + +0.6.10 (2018-06-11) ++++++++++++++++++++ + +- Add `shape.shadow` property to autoshape, connector, picture, and group + shape, returning a `ShadowFormat` object. +- Add `ShadowFormat` object with read/write (boolean) `.inherit` property. +- Fix #328 add support for 26+ series in a chart + + +0.6.9 (2018-05-08) +++++++++++++++++++ + +- Add `Picture.crop_x` setters, allowing picture cropping values to be set, + in addition to interrogated. +- Add `Slide.background` and `SlideMaster.background`, allowing the + background fill to be set for an individual slide or for all slides based + on a slide master. +- Add option `shapes` parameter to `Shapes.add_group_shape`, allowing a group + shape to be formed from a number of existing shapes. +- Improve efficiency of `Shapes._next_shape_id` property to improve + performance on high shape-count slides. + + +0.6.8 (2018-04-18) +++++++++++++++++++ + +- Add `GroupShape`, providing properties specific to a group shape, including + its `shapes` property. +- Add `GroupShapes`, providing access to shapes contained in a group shape. +- Add `SlideShapes.add_group_shape()`, allowing a group shape to be added to + a slide. +- Add `GroupShapes.add_group_shape()`, allowing a group shape to be added to + a group shape, enabling recursive, multi-level groups. +- Add support for adding jump-to-named-slide behavior to shape and run + hyperlinks. + + +0.6.7 (2017-10-30) +++++++++++++++++++ + +- Add `SlideShapes.build_freeform()`, allowing freeform shapes (such as maps) + to be specified and added to a slide. +- Add support for patterned fills. +- Add `LineFormat.dash_style` to allow interrogation and setting of dashed + line styles. + + +0.6.6 (2017-06-17) +++++++++++++++++++ + +- Add `SlideShapes.add_movie()`, allowing video media to be added to a slide. + +- fix #190 Accommodate non-conforming part names having '00' index segment. +- fix #273 Accommodate non-conforming part names having no index segment. +- fix #277 ASCII/Unicode error on non-ASCII multi-level category names +- fix #279 BaseShape.id warning appearing on placeholder access. + + +0.6.5 (2017-03-21) +++++++++++++++++++ + +- #267 compensate for non-conforming PowerPoint behavior on c:overlay element + +- compensate for non-conforming (to spec) PowerPoint behavior related to + c:dLbl/c:tx that results in "can't save" error when explicit data labels + are added to bubbles on a bubble chart. + + +0.6.4 (2017-03-17) +++++++++++++++++++ + +- add Chart.chart_title and ChartTitle object +- #263 Use Number type to test for numeric category + + +0.6.3 (2017-02-28) +++++++++++++++++++ + +- add DataLabel.font +- add Axis.axis_title + + +0.6.2 (2017-01-03) +++++++++++++++++++ + +- add support for NotesSlide (slide notes, aka. notes page) +- add support for arbitrary series ordering in XML +- add Plot.categories providing access to hierarchical categories in an + existing chart. +- add support for date axes on category charts, including writing a dateAx + element for the category axis when ChartData categories are date or + datetime. + +**BACKWARD INCOMPATIBILITIES:** + +Some changes were made to the boilerplate XML used to create new charts. This +was done to more closely adhere to the settings PowerPoint uses when creating +a chart using the UI. This may result in some appearance changes in charts +after upgrading. In particular: + +* Chart.has_legend now defaults to True for Line charts. +* Plot.vary_by_categories now defaults to False for Line charts. + + +0.6.1 (2016-10-09) +++++++++++++++++++ + +- add Connector shape type + + +0.6.0 (2016-08-18) +++++++++++++++++++ + +- add XY chart types +- add Bubble chart types +- add Radar chart types +- add Area chart types +- add Doughnut chart types +- add Series.points and Point +- add Point.data_label +- add DataLabel.text_frame +- add DataLabel.position +- add Axis.major_gridlines +- add ChartFormat with .fill and .line +- add Axis.format (fill and line formatting) +- add ValueAxis.crosses and .crosses_at +- add Point.format (fill and line formatting) +- add Slide.slide_id +- add Slides.get() (by slide id) +- add Font.language_id +- support blank (None) data points in created charts +- add Series.marker +- add Point.marker +- add Marker.format, .style, and .size + + +0.5.8 (2015-11-27) +++++++++++++++++++ + +- add Shape.click_action (hyperlink on shape) +- fix: #128 Chart cat and ser names not escaped +- fix: #153 shapes.title raises on no title shape +- fix: #170 remove seek(0) from Image.from_file() + + +0.5.7 (2015-01-17) +++++++++++++++++++ + +- add PicturePlaceholder with .insert_picture() method +- add TablePlaceholder with .insert_table() method +- add ChartPlaceholder with .insert_chart() method +- add Picture.image property, returning Image object +- add Picture.crop_left, .crop_top, .crop_right, and .crop_bottom +- add Shape.placeholder_format and PlaceholderFormat object + +**BACKWARD INCOMPATIBILITIES:** + +Shape.shape_type is now unconditionally `MSO_SHAPE_TYPE.PLACEHOLDER` for all +placeholder shapes. Previously, some placeholder shapes reported +`MSO_SHAPE_TYPE.AUTO_SHAPE`, `MSO_SHAPE_TYPE.CHART`, +`MSO_SHAPE_TYPE.PICTURE`, or `MSO_SHAPE_TYPE.TABLE` for that property. + + +0.5.6 (2014-12-06) +++++++++++++++++++ + +- fix #138 - UnicodeDecodeError in setup.py on Windows 7 Python 3.4 + + +0.5.5 (2014-11-17) +++++++++++++++++++ + +- feature #51 - add Python 3 support + + +0.5.4 (2014-11-15) +++++++++++++++++++ + +- feature #43 - image native size in shapes.add_picture() is now calculated + based on DPI attribute in image file, if present, defaulting to 72 dpi. +- feature #113 - Add Paragraph.space_before, Paragraph.space_after, and + Paragraph.line_spacing + + +0.5.3 (2014-11-09) +++++++++++++++++++ + +- add experimental feature TextFrame.fit_text() + + +0.5.2 (2014-10-26) +++++++++++++++++++ + +- fix #127 - Shape.text_frame fails on shape having no txBody + + +0.5.1 (2014-09-22) +++++++++++++++++++ + +- feature #120 - add Shape.rotation +- feature #97 - add Font.underline +- issue #117 - add BMP image support +- issue #95 - add BaseShape.name setter +- issue #107 - all .text properties should return unicode, not str +- feature #106 - add .text getters to Shape, TextFrame, and Paragraph + +- Rename Shape.textframe to Shape.text_frame. + **Shape.textframe property (by that name) is deprecated.** + + +0.5.0 (2014-09-13) +++++++++++++++++++ + +- Add support for creating and manipulating bar, column, line, and pie charts +- Major refactoring of XML layer (oxml) +- Rationalized graphical object shape access + **Note backward incompatibilities below** + +**BACKWARD INCOMPATIBILITIES:** + +A table is no longer treated as a shape. Rather it is a graphical object +contained in a GraphicFrame shape, as are Chart and SmartArt objects. + +Example:: + + table = shapes.add_table(...) + + # becomes + + graphic_frame = shapes.add_table(...) + table = graphic_frame.table + + # or + + table = shapes.add_table(...).table + +As the enclosing shape, the id, name, shape type, position, and size are +attributes of the enclosing GraphicFrame object. + +The contents of a GraphicFrame shape can be identified using three available +properties on a shape: has_table, has_chart, and has_smart_art. The enclosed +graphical object is obtained using the properties GraphicFrame.table and +GraphicFrame.chart. SmartArt is not yet supported. Accessing one of these +properties on a GraphicFrame not containing the corresponding object raises +an exception. + + +0.4.2 (2014-04-29) +++++++++++++++++++ + +- fix: issue #88 -- raises on supported image file having uppercase extension +- fix: issue #89 -- raises on add_slide() where non-contiguous existing ids + + +0.4.1 (2014-04-29) +++++++++++++++++++ + +- Rename Presentation.slidemasters to Presentation.slide_masters. + Presentation.slidemasters property is deprecated. +- Rename Presentation.slidelayouts to Presentation.slide_layouts. + Presentation.slidelayouts property is deprecated. +- Rename SlideMaster.slidelayouts to SlideMaster.slide_layouts. + SlideMaster.slidelayouts property is deprecated. +- Rename SlideLayout.slidemaster to SlideLayout.slide_master. + SlideLayout.slidemaster property is deprecated. +- Rename Slide.slidelayout to Slide.slide_layout. Slide.slidelayout property + is deprecated. +- Add SlideMaster.shapes to access shapes on slide master. +- Add SlideMaster.placeholders to access placeholder shapes on slide master. +- Add _MasterPlaceholder class. +- Add _LayoutPlaceholder class with position and size inheritable from master + placeholder. +- Add _SlidePlaceholder class with position and size inheritable from layout + placeholder. +- Add Table.left, top, width, and height read/write properties. +- Add rudimentary GroupShape with left, top, width, and height properties. +- Add rudimentary Connector with left, top, width, and height properties. +- Add TextFrame.auto_size property. +- Add Presentation.slide_width and .slide_height read/write properties. +- Add LineFormat class providing access to read and change line color and + width. +- Add AutoShape.line +- Add Picture.line + +- Rationalize enumerations. **Note backward incompatibilities below** + +**BACKWARD INCOMPATIBILITIES:** + +The following enumerations were moved/renamed during the rationalization of +enumerations: + +- ``pptx.enum.MSO_COLOR_TYPE`` --> ``pptx.enum.dml.MSO_COLOR_TYPE`` +- ``pptx.enum.MSO_FILL`` --> ``pptx.enum.dml.MSO_FILL`` +- ``pptx.enum.MSO_THEME_COLOR`` --> ``pptx.enum.dml.MSO_THEME_COLOR`` +- ``pptx.constants.MSO.ANCHOR_*`` --> ``pptx.enum.text.MSO_ANCHOR.*`` +- ``pptx.constants.MSO_SHAPE`` --> ``pptx.enum.shapes.MSO_SHAPE`` +- ``pptx.constants.PP.ALIGN_*`` --> ``pptx.enum.text.PP_ALIGN.*`` +- ``pptx.constants.MSO.{SHAPE_TYPES}`` --> + ``pptx.enum.shapes.MSO_SHAPE_TYPE.*`` + +Documentation for all enumerations is available in the Enumerations section +of the User Guide. + + +0.3.2 (2014-02-07) +++++++++++++++++++ + +- Hotfix: issue #80 generated presentations fail to load in Keynote and other + Apple applications + + +0.3.1 (2014-01-10) +++++++++++++++++++ + +- Hotfix: failed to load certain presentations containing images with + uppercase extension + + +0.3.0 (2013-12-12) +++++++++++++++++++ + +- Add read/write font color property supporting RGB, theme color, and inherit + color types +- Add font typeface and italic support +- Add text frame margins and word-wrap +- Add support for external relationships, e.g. linked spreadsheet +- Add hyperlink support for text run in shape and table cell +- Add fill color and brightness for shape and table cell, fill can also be set + to transparent (no fill) +- Add read/write position and size properties to shape and picture +- Replace PIL dependency with Pillow +- Restructure modules to better suit size of library + + +0.2.6 (2013-06-22) +++++++++++++++++++ + +- Add read/write access to core document properties +- Hotfix to accomodate connector shapes in _AutoShapeType +- Hotfix to allow customXml parts to load when present + + +0.2.5 (2013-06-11) +++++++++++++++++++ + +- Add paragraph alignment property (left, right, centered, etc.) +- Add vertical alignment within table cell (top, middle, bottom) +- Add table cell margin properties +- Add table boolean properties: first column (row header), first row (column + headings), last row (for e.g. totals row), last column (for e.g. row + totals), horizontal banding, and vertical banding. +- Add support for auto shape adjustment values, e.g. change radius of corner + rounding on rounded rectangle, position of callout arrow, etc. + + +0.2.4 (2013-05-16) +++++++++++++++++++ + +- Add support for auto shapes (e.g. polygons, flowchart symbols, etc.) + + +0.2.3 (2013-05-05) +++++++++++++++++++ + +- Add support for table shapes +- Add indentation support to textbox shapes, enabling multi-level bullets on + bullet slides. + + +0.2.2 (2013-03-25) +++++++++++++++++++ + +- Add support for opening and saving a presentation from/to a file-like + object. +- Refactor XML handling to use lxml objectify + + +0.2.1 (2013-02-25) +++++++++++++++++++ + +- Add support for Python 2.6 +- Add images from a stream (e.g. StringIO) in addition to a path, allowing + images retrieved from a database or network resource to be inserted without + saving first. +- Expand text methods to accept unicode and UTF-8 encoded 8-bit strings. +- Fix potential install bug triggered by importing ``__version__`` from + package ``__init__.py`` file. + + +0.2.0 (2013-02-10) +++++++++++++++++++ + +First non-alpha release with basic capabilities: + +- open presentation/template or use built-in default template +- add slide +- set placeholder text (e.g. bullet slides) +- add picture +- add text box diff --git a/tasks/tasksmith-74f059424102/tests/source/LICENSE b/tasks/tasksmith-74f059424102/tests/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..67ebe716ec4b2d64d6146b5e7cecd77ac7af9b79 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) +Copyright (c) 2013 Steve Canny, https://github.com/scanny + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/tasksmith-74f059424102/tests/source/MANIFEST.in b/tasks/tasksmith-74f059424102/tests/source/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..14688f1e39a4a4dd4dd0a6329d7323d339742b66 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/MANIFEST.in @@ -0,0 +1,5 @@ +include HISTORY.rst LICENSE README.rst tox.ini +recursive-include features * +recursive-include src/pptx/templates * +recursive-include tests *.py +recursive-include tests/test_files * diff --git a/tasks/tasksmith-74f059424102/tests/source/Makefile b/tasks/tasksmith-74f059424102/tests/source/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..94891a89b990cdee3e21957fc7258215ace92050 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/Makefile @@ -0,0 +1,49 @@ +BEHAVE = behave +MAKE = make +PYTHON = python +SETUP = $(PYTHON) ./setup.py +TWINE = $(PYTHON) -m twine + +.PHONY: accept build clean cleandocs coverage docs opendocs + +help: + @echo "Please use \`make ' where is one or more of" + @echo " accept run acceptance tests using behave" + @echo " clean delete intermediate work product and start fresh" + @echo " cleandocs delete cached HTML documentation and start fresh" + @echo " coverage run nosetests with coverage" + @echo " docs build HTML documentation using Sphinx (incremental)" + @echo " opendocs open local HTML documentation in browser" + @echo " readme update README.html from README.rst" + @echo " sdist generate a source distribution into dist/" + @echo " upload upload distribution tarball to PyPI" + +accept: + $(BEHAVE) --stop + +build: + rm -rf dist + $(SETUP) bdist_wheel sdist + +clean: + find . -type f -name \*.pyc -exec rm {} \; + find . -type f -name .DS_Store -exec rm {} \; + rm -rf dist .coverage + +cleandocs: + $(MAKE) -C docs clean + +coverage: + py.test --cov-report term-missing --cov=pptx --cov=tests + +docs: + $(MAKE) -C docs html + +opendocs: + open docs/.build/html/index.html + +test-upload: build + $(TWINE) upload --repository testpypi dist/* + +upload: clean build + $(TWINE) upload dist/* diff --git a/tasks/tasksmith-74f059424102/tests/source/README.rst b/tasks/tasksmith-74f059424102/tests/source/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..24d657b3739cbfcb3954b631ecd527c507cf6072 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/README.rst @@ -0,0 +1,25 @@ +*python-pptx* is a Python library for creating, reading, and updating PowerPoint (.pptx) +files. + +A typical use would be generating a PowerPoint presentation from dynamic content such as +a database query, analytics output, or a JSON payload, perhaps in response to an HTTP +request and downloading the generated PPTX file in response. It runs on any Python +capable platform, including macOS and Linux, and does not require the PowerPoint +application to be installed or licensed. + +It can also be used to analyze PowerPoint files from a corpus, perhaps to extract search +indexing text and images. + +In can also be used to simply automate the production of a slide or two that would be +tedious to get right by hand, which is how this all got started. + +More information is available in the `python-pptx documentation`_. + +Browse `examples with screenshots`_ to get a quick idea what you can do with +python-pptx. + +.. _`python-pptx documentation`: + https://python-pptx.readthedocs.org/en/latest/ + +.. _`examples with screenshots`: + https://python-pptx.readthedocs.org/en/latest/user/quickstart.html diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/LICENSE b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..337e8b2a29dbe0145eb07bcf8dc18ee11b6d420d --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2011 Bay Citizen & Texas Tribune + +Original ReadTheDocs.org code +Copyright (c) 2010 Charles Leifer, Eric Holscher, Bobby Grace + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/layout.html b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/layout.html new file mode 100644 index 0000000000000000000000000000000000000000..d7b8fbb1423d5170167d928cc185bb015efd4720 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/layout.html @@ -0,0 +1,48 @@ +{% extends "basic/layout.html" %} + +{% set script_files = script_files + [pathto("_static/searchtools.js", 1)] %} + +{% block htmltitle %} +{{ super() }} + + + +{% endblock %} + +{% block footer %} + + + +{% if theme_analytics_code %} + + +{% endif %} + +{% endblock %} diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/rtd-themes.conf b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/rtd-themes.conf new file mode 100644 index 0000000000000000000000000000000000000000..5930488d750ff2ee9f1f9bd8f1d8d6fe8ff763bf --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/rtd-themes.conf @@ -0,0 +1,65 @@ +[theme] +inherit = default +stylesheet = rtd.css +pygment_style = default +show_sphinx = False + +[options] +show_rtd = True + +white = #ffffff +almost_white = #f8f8f8 +barely_white = #f2f2f2 +dirty_white = #eeeeee +almost_dirty_white = #e6e6e6 +dirtier_white = #dddddd +lighter_gray = #cccccc +gray_a = #aaaaaa +gray_9 = #999999 +light_gray = #888888 +gray_7 = #777777 +gray = #666666 +dark_gray = #444444 +gray_2 = #222222 +black = #111111 +light_color = #e8ecef +light_medium_color = #DDEAF0 +medium_color = #8ca1af +medium_color_link = #86989b +medium_color_link_hover = #a6b8bb +dark_color = #465158 + +h1 = #000000 +h2 = #465158 +h3 = #6c818f + +link_color = #444444 +link_color_decoration = #CCCCCC + +medium_color_hover = #697983 +green_highlight = #8ecc4c + + +positive_dark = #609060 +positive_medium = #70a070 +positive_light = #e9ffe9 + +negative_dark = #900000 +negative_medium = #b04040 +negative_light = #ffe9e9 +negative_text = #c60f0f + +ruler = #abc + +viewcode_bg = #f4debf +viewcode_border = #ac9 + +highlight = #ffe080 + +code_background = #eeeeee + +background = #465158 +background_link = #ffffff +background_link_half = #ffffff +background_text = #eeeeee +background_text_link = #86989b diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/static/rtd.css_t b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/static/rtd.css_t new file mode 100644 index 0000000000000000000000000000000000000000..578946ab9fe4637f05aecfa6cfa0aa1287582c1e --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/static/rtd.css_t @@ -0,0 +1,781 @@ +/* + * rtd.css + * ~~~~~~~~~~~~~~~ + * + * Sphinx stylesheet -- sphinxdoc theme. Originally created by + * Armin Ronacher for Werkzeug. + * + * Customized for ReadTheDocs by Eric Pierce & Eric Holscher + * + * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* RTD colors + * light blue: {{ theme_light_color }} + * medium blue: {{ theme_medium_color }} + * dark blue: {{ theme_dark_color }} + * dark grey: {{ theme_grey_color }} + * + * medium blue hover: {{ theme_medium_color_hover }}; + * green highlight: {{ theme_green_highlight }} + * light blue (project bar): {{ theme_light_color }} + */ + +@import url("basic.css"); + +/* PAGE LAYOUT -------------------------------------------------------------- */ + +body { + font: 100%/1.5 "ff-meta-web-pro-1","ff-meta-web-pro-2",Arial,"Helvetica Neue",sans-serif; + text-align: center; + color: black; + background-color: {{ theme_background }}; + padding: 0; + margin: 0; +} + +div.document { + text-align: left; + background-color: {{ theme_light_color }}; +} + +div.bodywrapper { + background-color: {{ theme_white }}; + border-left: 1px solid {{ theme_lighter_gray }}; + border-bottom: 1px solid {{ theme_lighter_gray }}; + margin: 0 0 0 16em; +} + +div.body { + margin: 0; + padding: 0.5em 1.3em; + max-width: 55em; + min-width: 20em; +} + +div.related { + font-size: 1em; + background-color: {{ theme_background }}; +} + +div.documentwrapper { + float: left; + width: 100%; + background-color: {{ theme_light_color }}; +} + + +/* HEADINGS --------------------------------------------------------------- */ + +h1 { + margin: 0; + padding: 0.7em 0 0.3em 0; + font-size: 1.5em; + line-height: 1.15; + color: {{ theme_h1 }}; + clear: both; +} + +h2 { + margin: 2em 0 0.2em 0; + font-size: 1.35em; + padding: 0; + color: {{ theme_h2 }}; +} + +h3 { + margin: 1em 0 -0.3em 0; + font-size: 1.2em; + color: {{ theme_h3 }}; +} + +div.body h1 a, div.body h2 a, div.body h3 a, div.body h4 a, div.body h5 a, div.body h6 a { + color: black; +} + +h1 a.anchor, h2 a.anchor, h3 a.anchor, h4 a.anchor, h5 a.anchor, h6 a.anchor { + display: none; + margin: 0 0 0 0.3em; + padding: 0 0.2em 0 0.2em; + color: {{ theme_gray_a }} !important; +} + +h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor, +h5:hover a.anchor, h6:hover a.anchor { + display: inline; +} + +h1 a.anchor:hover, h2 a.anchor:hover, h3 a.anchor:hover, h4 a.anchor:hover, +h5 a.anchor:hover, h6 a.anchor:hover { + color: {{ theme_gray_7 }}; + background-color: {{ theme_dirty_white }}; +} + + +/* LINKS ------------------------------------------------------------------ */ + +/* Normal links get a pseudo-underline */ +a { + color: {{ theme_link_color }}; + text-decoration: none; + border-bottom: 1px solid {{ theme_link_color_decoration }}; +} + +/* Links in sidebar, TOC, index trees and tables have no underline */ +.sphinxsidebar a, +.toctree-wrapper a, +.indextable a, +#indices-and-tables a { + color: {{ theme_dark_gray }}; + text-decoration: none; + border-bottom: none; +} + +/* Most links get an underline-effect when hovered */ +a:hover, +div.toctree-wrapper a:hover, +.indextable a:hover, +#indices-and-tables a:hover { + color: {{ theme_black }}; + text-decoration: none; + border-bottom: 1px solid {{ theme_black }}; +} + +/* Footer links */ +div.footer a { + color: {{ theme_background_text_link }}; + text-decoration: none; + border: none; +} +div.footer a:hover { + color: {{ theme_medium_color_link_hover }}; + text-decoration: underline; + border: none; +} + +/* Permalink anchor (subtle grey with a red hover) */ +div.body a.headerlink { + color: {{ theme_lighter_gray }}; + font-size: 1em; + margin-left: 6px; + padding: 0 4px 0 4px; + text-decoration: none; + border: none; +} +div.body a.headerlink:hover { + color: {{ theme_negative_text }}; + border: none; +} + + +/* NAVIGATION BAR --------------------------------------------------------- */ + +div.related ul { + height: 2.5em; +} + +div.related ul li { + margin: 0; + padding: 0.65em 0; + float: left; + display: block; + color: {{ theme_background_link_half }}; /* For the >> separators */ + font-size: 0.8em; +} + +div.related ul li.right { + float: right; + margin-right: 5px; + color: transparent; /* Hide the | separators */ +} + +/* "Breadcrumb" links in nav bar */ +div.related ul li a { + order: none; + background-color: inherit; + font-weight: bold; + margin: 6px 0 6px 4px; + line-height: 1.75em; + color: {{ theme_background_link }}; + text-shadow: 0 1px rgba(0, 0, 0, 0.5); + padding: 0.4em 0.8em; + border: none; + border-radius: 3px; +} +/* previous / next / modules / index links look more like buttons */ +div.related ul li.right a { + margin: 0.375em 0; + background-color: {{ theme_medium_color_hover }}; + text-shadow: 0 1px rgba(0, 0, 0, 0.5); + border-radius: 3px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; +} +/* All navbar links light up as buttons when hovered */ +div.related ul li a:hover { + background-color: {{ theme_medium_color }}; + color: {{ theme_white }}; + text-decoration: none; + border-radius: 3px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; +} +/* Take extra precautions for tt within links */ +a tt, +div.related ul li a tt { + background: inherit !important; + color: inherit !important; +} + + +/* SIDEBAR ---------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 0; +} + +div.sphinxsidebar { + margin: 0; + margin-left: -100%; + float: left; + top: 3em; + left: 0; + padding: 0 1em; + width: 14em; + font-size: 1em; + text-align: left; + background-color: {{ theme_light_color }}; +} + +div.sphinxsidebar img { + max-width: 12em; +} + +div.sphinxsidebar h3, div.sphinxsidebar h4 { + margin: 1.2em 0 0.3em 0; + font-size: 1em; + padding: 0; + color: {{ theme_gray_2 }}; + font-family: "ff-meta-web-pro-1", "ff-meta-web-pro-2", "Arial", "Helvetica Neue", sans-serif; +} + +div.sphinxsidebar h3 a { + color: {{ theme_grey_color }}; +} + +div.sphinxsidebar ul, +div.sphinxsidebar p { + margin-top: 0; + padding-left: 0; + line-height: 130%; + background-color: {{ theme_light_color }}; +} + +/* No bullets for nested lists, but a little extra indentation */ +div.sphinxsidebar ul ul { + list-style-type: none; + margin-left: 1.5em; + padding: 0; +} + +/* A little top/bottom padding to prevent adjacent links' borders + * from overlapping each other */ +div.sphinxsidebar ul li { + padding: 1px 0; +} + +/* A little left-padding to make these align with the ULs */ +div.sphinxsidebar p.topless { + padding-left: 0 0 0 1em; +} + +/* Make these into hidden one-liners */ +div.sphinxsidebar ul li, +div.sphinxsidebar p.topless { + white-space: nowrap; + overflow: hidden; +} +/* ...which become visible when hovered */ +div.sphinxsidebar ul li:hover, +div.sphinxsidebar p.topless:hover { + overflow: visible; +} + +/* Search text box and "Go" button */ +#searchbox { + margin-top: 2em; + margin-bottom: 1em; + background: {{ theme_dirtier_white }}; + padding: 0.5em; + border-radius: 6px; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; +} +#searchbox h3 { + margin-top: 0; +} + +/* Make search box and button abut and have a border */ +input, +div.sphinxsidebar input { + border: 1px solid {{ theme_gray_9 }}; + float: left; +} + +/* Search textbox */ +input[type="text"] { + margin: 0; + padding: 0 3px; + height: 20px; + width: 144px; + border-top-left-radius: 3px; + border-bottom-left-radius: 3px; + -moz-border-radius-topleft: 3px; + -moz-border-radius-bottomleft: 3px; + -webkit-border-top-left-radius: 3px; + -webkit-border-bottom-left-radius: 3px; +} +/* Search button */ +input[type="submit"] { + margin: 0 0 0 -1px; /* -1px prevents a double-border with textbox */ + height: 22px; + color: {{ theme_dark_gray }}; + background-color: {{ theme_light_color }}; + padding: 1px 4px; + font-weight: bold; + border-top-right-radius: 3px; + border-bottom-right-radius: 3px; + -moz-border-radius-topright: 3px; + -moz-border-radius-bottomright: 3px; + -webkit-border-top-right-radius: 3px; + -webkit-border-bottom-right-radius: 3px; +} +input[type="submit"]:hover { + color: {{ theme_white }}; + background-color: {{ theme_green_highlight }}; +} + +div.sphinxsidebar p.searchtip { + clear: both; + padding: 0.5em 0 0 0; + background: {{ theme_dirtier_white }}; + color: {{ theme_gray }}; + font-size: 0.9em; +} + +/* Sidebar links are unusual */ +div.sphinxsidebar li a, +div.sphinxsidebar p a { + background: {{ theme_light_color }}; /* In case links overlap main content */ + border-radius: 3px; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border: 1px solid transparent; /* To prevent things jumping around on hover */ + padding: 0 5px 0 5px; +} +div.sphinxsidebar li a:hover, +div.sphinxsidebar p a:hover { + color: {{ theme_black }}; + text-decoration: none; + border: 1px solid {{ theme_light_gray }}; +} + +/* Tweak any link appearing in a heading */ +div.sphinxsidebar h3 a { +} + + + + +/* OTHER STUFF ------------------------------------------------------------ */ + +cite, code, tt { + font-family: 'Consolas', 'Deja Vu Sans Mono', + 'Bitstream Vera Sans Mono', monospace; + font-size: 0.95em; + letter-spacing: 0.01em; +} + +tt { + background-color: {{ theme_code_background }}; + color: {{ theme_dark_gray }}; +} + +tt.descname, tt.descclassname, tt.xref { + border: 0; +} + +hr { + border: 1px solid {{ theme_ruler }}; + margin: 2em; +} + +pre, #_fontwidthtest { + font-family: 'Consolas', 'Deja Vu Sans Mono', + 'Bitstream Vera Sans Mono', monospace; + margin: 1em 2em; + font-size: 0.95em; + letter-spacing: 0.015em; + line-height: 120%; + padding: 0.5em; + border: 1px solid {{ theme_lighter_gray }}; + background-color: {{ theme_code_background }}; + border-radius: 6px; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; +} + +pre a { + color: inherit; + text-decoration: underline; +} + +td.linenos pre { + padding: 0.5em 0; +} + +div.quotebar { + background-color: {{ theme_almost_white }}; + max-width: 250px; + float: right; + padding: 2px 7px; + border: 1px solid {{ theme_lighter_gray }}; +} + +div.topic { + background-color: {{ theme_almost_white }}; +} + +table { + border-collapse: collapse; + margin: 0 -0.5em 0 -0.5em; +} + +table td, table th { + padding: 0.2em 0.5em 0.2em 0.5em; +} + + +/* ADMONITIONS AND WARNINGS ------------------------------------------------- */ + +/* Shared by admonitions, warnings and sidebars */ +div.admonition, +div.warning, +div.sidebar { + font-size: 0.9em; + margin: 2em; + padding: 0; + /* + border-radius: 6px; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + */ +} +div.admonition p, +div.warning p, +div.sidebar p { + margin: 0.5em 1em 0.5em 1em; + padding: 0; +} +div.admonition pre, +div.warning pre, +div.sidebar pre { + margin: 0.4em 1em 0.4em 1em; +} +div.admonition p.admonition-title, +div.warning p.admonition-title, +div.sidebar p.sidebar-title { + margin: 0; + padding: 0.1em 0 0.1em 0.5em; + color: white; + font-weight: bold; + font-size: 1.1em; + text-shadow: 0 1px rgba(0, 0, 0, 0.5); +} +div.admonition ul, div.admonition ol, +div.warning ul, div.warning ol, +div.sidebar ul, div.sidebar ol { + margin: 0.1em 0.5em 0.5em 3em; + padding: 0; +} + + +/* Admonitions and sidebars only */ +div.admonition, div.sidebar { + border: 1px solid {{ theme_positive_dark }}; + background-color: {{ theme_positive_light }}; +} +div.admonition p.admonition-title, +div.sidebar p.sidebar-title { + background-color: {{ theme_positive_medium }}; + border-bottom: 1px solid {{ theme_positive_dark }}; +} + + +/* Warnings only */ +div.warning { + border: 1px solid {{ theme_negative_dark }}; + background-color: {{ theme_negative_light }}; +} +div.warning p.admonition-title { + background-color: {{ theme_negative_medium }}; + border-bottom: 1px solid {{ theme_negative_dark }}; +} + + +/* Sidebars only */ +div.sidebar { + max-width: 200px; +} + + + +div.versioninfo { + margin: 1em 0 0 0; + border: 1px solid {{ theme_lighter_gray }}; + background-color: {{ theme_light_medium_color }}; + padding: 8px; + line-height: 1.3em; + font-size: 0.9em; +} + +.viewcode-back { + font-family: 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', + 'Verdana', sans-serif; +} + +div.viewcode-block:target { + background-color: {{ theme_viewcode_bg }}; + border-top: 1px solid {{ theme_viewcode_border }}; + border-bottom: 1px solid {{ theme_viewcode_border }}; +} + +dl { + margin: 1em 0 2.5em 0; +} + +/* Highlight target when you click an internal link */ +dt:target { + background: {{ theme_highlight }}; +} +/* Don't highlight whole divs */ +div.highlight { + background: transparent; +} +/* But do highlight spans (so search results can be highlighted) */ +span.highlight { + background: {{ theme_highlight }}; +} + +div.footer { + background-color: {{ theme_background }}; + color: {{ theme_background_text }}; + padding: 0 2em 2em 2em; + clear: both; + font-size: 0.8em; + text-align: center; +} + +p { + margin: 0.8em 0 0.5em 0; +} + +.section p img { + margin: 1em 2em; +} + + +/* MOBILE LAYOUT -------------------------------------------------------------- */ + +@media screen and (max-width: 600px) { + + h1, h2, h3, h4, h5 { + position: relative; + } + + ul { + padding-left: 1.75em; + } + + div.bodywrapper a.headerlink, #indices-and-tables h1 a { + color: {{ theme_almost_dirty_white }}; + font-size: 80%; + float: right; + line-height: 1.8; + position: absolute; + right: -0.7em; + visibility: inherit; + } + + div.bodywrapper h1 a.headerlink, #indices-and-tables h1 a { + line-height: 1.5; + } + + pre { + font-size: 0.7em; + overflow: auto; + word-wrap: break-word; + white-space: pre-wrap; + } + + div.related ul { + height: 2.5em; + padding: 0; + text-align: left; + } + + div.related ul li { + clear: both; + color: {{ theme_dark_color }}; + padding: 0.2em 0; + } + + div.related ul li:last-child { + border-bottom: 1px dotted {{ theme_medium_color }}; + padding-bottom: 0.4em; + margin-bottom: 1em; + width: 100%; + } + + div.related ul li a { + color: {{ theme_dark_color }}; + padding-right: 0; + } + + div.related ul li a:hover { + background: inherit; + color: inherit; + } + + div.related ul li.right { + clear: none; + padding: 0.65em 0; + margin-bottom: 0.5em; + } + + div.related ul li.right a { + color: {{ theme_white }}; + padding-right: 0.8em; + } + + div.related ul li.right a:hover { + background-color: {{ theme_medium_color }}; + } + + div.body { + clear: both; + min-width: 0; + word-wrap: break-word; + } + + div.bodywrapper { + margin: 0 0 0 0; + } + + div.sphinxsidebar { + float: none; + margin: 0; + width: auto; + } + + div.sphinxsidebar input[type="text"] { + height: 2em; + line-height: 2em; + width: 70%; + } + + div.sphinxsidebar input[type="submit"] { + height: 2em; + margin-left: 0.5em; + width: 20%; + } + + div.sphinxsidebar p.searchtip { + background: inherit; + margin-bottom: 1em; + } + + div.sphinxsidebar ul li, div.sphinxsidebar p.topless { + white-space: normal; + } + + .bodywrapper img { + display: block; + margin-left: auto; + margin-right: auto; + max-width: 100%; + } + + div.documentwrapper { + float: none; + } + + div.admonition, div.warning, pre, blockquote { + margin-left: 0em; + margin-right: 0em; + } + + .body p img { + margin: 0; + } + + #searchbox { + background: transparent; + } + + .related:not(:first-child) li { + display: none; + } + + .related:not(:first-child) li.right { + display: block; + } + + div.footer { + padding: 1em; + } + + .rtd_doc_footer .badge { + float: none; + margin: 1em auto; + position: static; + } + + .rtd_doc_footer .badge.revsys-inline { + margin-right: auto; + margin-bottom: 2em; + } + + table.indextable { + display: block; + width: auto; + } + + .indextable tr { + display: block; + } + + .indextable td { + display: block; + padding: 0; + width: auto !important; + } + + .indextable td dt { + margin: 1em 0; + } + + ul.search { + margin-left: 0.25em; + } + + ul.search li div.context { + font-size: 90%; + line-height: 1.1; + margin-bottom: 1; + margin-left: 0; + } + +} diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/theme.conf b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/theme.conf new file mode 100644 index 0000000000000000000000000000000000000000..5930488d750ff2ee9f1f9bd8f1d8d6fe8ff763bf --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/theme.conf @@ -0,0 +1,65 @@ +[theme] +inherit = default +stylesheet = rtd.css +pygment_style = default +show_sphinx = False + +[options] +show_rtd = True + +white = #ffffff +almost_white = #f8f8f8 +barely_white = #f2f2f2 +dirty_white = #eeeeee +almost_dirty_white = #e6e6e6 +dirtier_white = #dddddd +lighter_gray = #cccccc +gray_a = #aaaaaa +gray_9 = #999999 +light_gray = #888888 +gray_7 = #777777 +gray = #666666 +dark_gray = #444444 +gray_2 = #222222 +black = #111111 +light_color = #e8ecef +light_medium_color = #DDEAF0 +medium_color = #8ca1af +medium_color_link = #86989b +medium_color_link_hover = #a6b8bb +dark_color = #465158 + +h1 = #000000 +h2 = #465158 +h3 = #6c818f + +link_color = #444444 +link_color_decoration = #CCCCCC + +medium_color_hover = #697983 +green_highlight = #8ecc4c + + +positive_dark = #609060 +positive_medium = #70a070 +positive_light = #e9ffe9 + +negative_dark = #900000 +negative_medium = #b04040 +negative_light = #ffe9e9 +negative_text = #c60f0f + +ruler = #abc + +viewcode_bg = #f4debf +viewcode_border = #ac9 + +highlight = #ffe080 + +code_background = #eeeeee + +background = #465158 +background_link = #ffffff +background_link_half = #ffffff +background_text = #eeeeee +background_text_link = #86989b diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/theme.conf.orig b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/theme.conf.orig new file mode 100644 index 0000000000000000000000000000000000000000..a74a8a2cef8ee4bbcdf5e3680c801a5585a136a2 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/.themes/armstrong/theme.conf.orig @@ -0,0 +1,66 @@ +[theme] +inherit = default +stylesheet = rtd.css +pygment_style = default +show_sphinx = False + +[options] +show_rtd = True + +white = #ffffff +almost_white = #f8f8f8 +barely_white = #f2f2f2 +dirty_white = #eeeeee +almost_dirty_white = #e6e6e6 +dirtier_white = #DAC6AF +lighter_gray = #cccccc +gray_a = #aaaaaa +gray_9 = #999999 +light_gray = #888888 +gray_7 = #777777 +gray = #666666 +dark_gray = #444444 +gray_2 = #222222 +black = #111111 +light_color = #EDE4D8 +light_medium_color = #DDEAF0 +medium_color = #8ca1af +medium_color_link = #634320 +medium_color_link_hover = #261a0c +dark_color = rgba(160, 109, 52, 1.0) + +h1 = #1f3744 +h2 = #335C72 +h3 = #638fa6 + +link_color = #335C72 +link_color_decoration = #99AEB9 + +medium_color_hover = rgba(255, 255, 255, 0.25) +medium_color = rgba(255, 255, 255, 0.5) +green_highlight = #8ecc4c + + +positive_dark = rgba(51, 77, 0, 1.0) +positive_medium = rgba(102, 153, 0, 1.0) +positive_light = rgba(102, 153, 0, 0.1) + +negative_dark = rgba(51, 13, 0, 1.0) +negative_medium = rgba(204, 51, 0, 1.0) +negative_light = rgba(204, 51, 0, 0.1) +negative_text = #c60f0f + +ruler = #abc + +viewcode_bg = #f4debf +viewcode_border = #ac9 + +highlight = #ffe080 + +code_background = rgba(0, 0, 0, 0.075) + +background = rgba(135, 57, 34, 1.0) +background_link = rgba(212, 195, 172, 1.0) +background_link_half = rgba(212, 195, 172, 0.5) +background_text = rgba(212, 195, 172, 1.0) +background_text_link = rgba(171, 138, 93, 1.0) diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/Makefile b/tasks/tasksmith-74f059424102/tests/source/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..59efdd9f62869bf2a5c84582d3c6d5e373b78170 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = .build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-pptx.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-pptx.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/python-pptx" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-pptx" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-picture.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-picture.png new file mode 100644 index 0000000000000000000000000000000000000000..f5a02ac229958c261527acf1ac018578fe6e8bbc --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-picture.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a7354647a7f663e4a7e7a9a311b68c24ebdc2d55843e9f93fa5b31ee851b930 +size 48498 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-shape.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-shape.png new file mode 100644 index 0000000000000000000000000000000000000000..2ca1bf978e46c96dc23d45940b24d1e8a130ef46 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-shape.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6c8cf235aa4e7fa7c81f89222f5727f8b100359fcc110220f364991acb5988b +size 12092 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-table.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-table.png new file mode 100644 index 0000000000000000000000000000000000000000..3362c0fe97002e85e9723c52dc1a45e829fc452e --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-table.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:21b8989455f38509560b0b136e0f576a53aeb1d91945172c00797da47de738f4 +size 5233 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-textbox.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-textbox.png new file mode 100644 index 0000000000000000000000000000000000000000..7e824a698ba877b63ee968618a14f8e9169608ce --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/add-textbox.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31760184893901b0a10b40e815ac1d6306c52ae72368bf517a77c3caa80b8cf3 +size 2016 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/bullet-slide.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/bullet-slide.png new file mode 100644 index 0000000000000000000000000000000000000000..dcce1fc0e1036b3c2bc01de038feb928a8823e9f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/bullet-slide.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a7fb009d7017dcfc5d0cf1ea921f6f9b0baff3cd747a91f1c39c2c06b9fd4b6 +size 13969 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-01.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-01.png new file mode 100644 index 0000000000000000000000000000000000000000..f9da3e593900f3baf1c5a823fe0b4b75c1072657 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-01.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fcb998dea219135cb6fa51191601268e5746e5b683327697f430e60334bdccda +size 21878 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-02.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-02.png new file mode 100644 index 0000000000000000000000000000000000000000..c3ec042ca98ed0c225383070aed7841a4f5c8c89 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-02.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b7f946c5ab5aed0cafc8a5c7551c18968dba9f201db14aea7f5380627226eada +size 29666 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-03.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-03.png new file mode 100644 index 0000000000000000000000000000000000000000..ab5a771fef57e4298546decfde0e2b262c2bc44a --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-03.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66a66e6305468a3ca8dfac787f167ec0ce93645529d6986032207518942a83f4 +size 35555 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-04.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-04.png new file mode 100644 index 0000000000000000000000000000000000000000..4c617ec329a3f32d128505443f70af83fdea896e --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-04.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26d0d625518091d4f754f174267747c94634f658490b30e90607601587344a3c +size 35141 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-05.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-05.png new file mode 100644 index 0000000000000000000000000000000000000000..ea14008fa11bafaf236428fb32c4c5df8af7989f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-05.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4a8ddfa3e0bcb1d476ba3124594dcbd12e63613b6178d52bf801f880ca30214 +size 32412 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-06.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-06.png new file mode 100644 index 0000000000000000000000000000000000000000..f39691920dce5dbdb5085366a078d20921fb5f8f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-06.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ff25af7b74fe289a4a65e3d4df612bfb01e6a2793007ebd0e8d012ef508451d +size 22287 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-07.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-07.png new file mode 100644 index 0000000000000000000000000000000000000000..5e430d02b9ffa657ecccd770768d5d0ae018409d --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-07.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89c30bbeae5d65882ac2f778a32c48f36bade519e24d479bef93fc2d4a84632f +size 31478 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-08.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-08.png new file mode 100644 index 0000000000000000000000000000000000000000..2e8bb046d60c16a0f3cab61290c33a05280e1175 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-08.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d149f01f400a57c129970d415f6ae5cd3f89e4fa23655257317ddb5b6cdabdfc +size 9431 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-09.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-09.png new file mode 100644 index 0000000000000000000000000000000000000000..bb8030076785b619d1ea7d3c248f6010303366b8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/chart-09.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3c6f7f14802a106894d6ee7000aa55c98a9c4acce5056c6cd1b502bf52c4d52 +size 16670 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/freeform-01.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/freeform-01.png new file mode 100644 index 0000000000000000000000000000000000000000..e8c4f7b80b8ccaa422b544ce85d7221fcac48e70 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/freeform-01.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e5a23055d55e1dab50c6e4c1268ddc80c40e0f369e368cf25d689348a235565 +size 12485 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/freeform-02.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/freeform-02.png new file mode 100644 index 0000000000000000000000000000000000000000..e462f20d46c680628c87bb9644bea842b3848d9c --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/freeform-02.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0eba9eab1d334ae336a5375c04e2e352f70d4a2ae953e94b69fbb8f86816c6e +size 10869 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/freeform-03.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/freeform-03.png new file mode 100644 index 0000000000000000000000000000000000000000..c005906886bf669bede71e55f95ea89127f0626d --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/freeform-03.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2893e60c84ca71968a2f7caa501fd6377fe0bd44531692008af61096a3ee2140 +size 17488 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/hello-world.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/hello-world.png new file mode 100644 index 0000000000000000000000000000000000000000..bac31f7719794d5b8f66bd5e87cf82506d98e61b --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/hello-world.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdc9a122a1b2eedf14b41ab3890c7cfd32598e0d226017c70df937e8e787296c +size 1526 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-01.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-01.png new file mode 100644 index 0000000000000000000000000000000000000000..0f5ee2bce077782c2a506f30ba5fd11ef6671bf8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-01.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59baff0377172c5ed81875be9380c924a51b489b2a70b757e7186f3aecadb870 +size 18838 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-02.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-02.png new file mode 100644 index 0000000000000000000000000000000000000000..e423bbcb145d6ad4ba9bc011c17b2f334c95e6e6 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-02.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d203af597b52f43f3b54a4d7e441eb3b70b7892c43e160b96bd33de4584f0aa2 +size 4768 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-03.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-03.png new file mode 100644 index 0000000000000000000000000000000000000000..62f9751e68718d4667cc8e8ce1d8a5310977e879 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-03.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e51c57ff3ee527046bcc772986a0ce5ec28f854eb4d65c611d4956b18afc086 +size 13086 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-04.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-04.png new file mode 100644 index 0000000000000000000000000000000000000000..307f47987756ed0874b91fc42aec003b39703906 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-04.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5498b3003e1f99aeb13874ab73d5d72abb815857dd3d78413f2bf57207b1121 +size 11147 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-05.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-05.png new file mode 100644 index 0000000000000000000000000000000000000000..ccdd021e6395a2d9043aa7398e1ad6d57448a4a9 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-05.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e3bdc9d241fe64d0b17ed8a67e3682e6b68d5e82542d16ac38fe8898f700bf7 +size 10168 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-06.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-06.png new file mode 100644 index 0000000000000000000000000000000000000000..b535cd2559ff3bbf2495a8ad1c07183bb60875d7 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-06.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:832750f5239a4a14dc216661836bb14235f816186fb052fc0a12356e2595db12 +size 10687 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-07.png b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-07.png new file mode 100644 index 0000000000000000000000000000000000000000..b557dac0618c56650f3f9126a58498bf279e4f80 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_static/img/table-07.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81a2cb6e0ff7cb12fefe97b26011022423522b040d17dd8f1dd8bc15e27ff0b6 +size 11327 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/_templates/sidebarlinks.html b/tasks/tasksmith-74f059424102/tests/source/docs/_templates/sidebarlinks.html new file mode 100644 index 0000000000000000000000000000000000000000..9f205be1133023b7afeb8f1b7045d73983e61120 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/_templates/sidebarlinks.html @@ -0,0 +1,6 @@ +

Useful Links

+ diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/action.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/action.rst new file mode 100644 index 0000000000000000000000000000000000000000..dda3e1013478afb4ff22672250d2f32af0ec6871 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/action.rst @@ -0,0 +1,26 @@ +.. _action_api: + +Click Action-related Objects +============================ + +The following classes represent click and hover mouse actions, typically +a hyperlink. Other actions such as navigating to another slide in the +presentation or running a macro are also possible. + + +|ActionSetting| objects +----------------------- + +.. autoclass:: pptx.action.ActionSetting() + :members: + :inherited-members: + :undoc-members: + + +|Hyperlink| objects +----------------------- + +.. autoclass:: pptx.action.Hyperlink() + :members: + :inherited-members: + :undoc-members: diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/chart-data.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/chart-data.rst new file mode 100644 index 0000000000000000000000000000000000000000..47e9f407d69af7594c12af5275d1bf1dce54ccd8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/chart-data.rst @@ -0,0 +1,70 @@ +.. _chart-data-api: + +ChartData objects +================= + +A ChartData object is used to specify the data depicted in a chart. It is +used when creating a new chart and when replacing the data for an existing +chart. Most charts are created using a |CategoryChartData| object, however +the data for XY and bubble chart types is different enough that those each +require a distinct chart data object. + +.. autoclass:: pptx.chart.data.ChartData + :members: + :member-order: bysource + :undoc-members: + + +.. autoclass:: pptx.chart.data.CategoryChartData + :members: + :member-order: bysource + :inherited-members: + :exclude-members: + append, categories_ref, count, data_point_offset, index, series_index, + series_name_ref, x_values_ref, xlsx_blob, xml_bytes, y_values_ref + :undoc-members: + +.. autoclass:: pptx.chart.data.Categories + :members: + :member-order: bysource + :inherited-members: + :exclude-members: count + :undoc-members: + +.. autoclass:: pptx.chart.data.Category + :members: + :member-order: bysource + :inherited-members: + :exclude-members: depth, idx, index, leaf_count + :undoc-members: + +.. autoclass:: pptx.chart.data.XyChartData + :members: + :member-order: bysource + :inherited-members: + :exclude-members: + count, data_point_offset, index, series_index, series_name_ref, + x_values_ref, xlsx_blob, xml_bytes, y_values_ref + +.. autoclass:: pptx.chart.data.BubbleChartData + :members: + :member-order: bysource + :inherited-members: + :exclude-members: + count, bubble_sizes_ref, data_point_offset, index, series_index, + series_name_ref, x_values_ref, xlsx_blob, xml_bytes, y_values_ref + +.. autoclass:: pptx.chart.data.XySeriesData + :members: + :member-order: bysource + :inherited-members: + :exclude-members: + count, data_point_offset, name_ref, x_values_ref, y_values_ref + +.. autoclass:: pptx.chart.data.BubbleSeriesData + :members: + :member-order: bysource + :inherited-members: + :exclude-members: + count, bubble_sizes_ref, name_ref, x_values_ref, y_values_ref + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..4719c641a8989de113e45b65c275ed624d05347c --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/chart.rst @@ -0,0 +1,352 @@ +.. _chart-api: + +Charts +====== + +|pp| provides an API for adding and manipulating charts. A chart object, like +a table, is not a shape. Rather it is a graphical object contained in +a |GraphicFrame| shape. The shape API, such as position, size, shape id, and +name, are provided by the graphic frame shape. The chart itself is accessed +using the :attr:`chart` property on the graphic frame shape. + + +|Chart| objects +--------------- + +The |Chart| object is the root of a generally hierarchical graph of component +objects that together provide access to the properties and methods required +to specify and format a chart. + +.. autoclass:: pptx.chart.chart.Chart + :members: + :member-order: bysource + :undoc-members: + +.. autoclass:: pptx.chart.chart.ChartTitle() + :members: + :member-order: bysource + + +|Legend| objects +---------------- + +A legend provides a visual key relating each series of data points to their +assigned meaning by mapping a color, line type, or point shape to each series +name. A legend is optional, but there can be at most one. Most aspects of +a legend are determined automatically, but aspects of its position may be +specified via the API. + +.. autoclass:: pptx.chart.chart.Legend() + :members: + :member-order: bysource + :undoc-members: + + +|Axis| objects +-------------- + +A chart typically has two axes, a category axis and a value axis. In general, +one of these is horizontal and the other is vertical, where which is which +depends on the chart type. For example, the category axis is horizontal on +a column chart, but vertical on a bar chart. + +A chart where the independent variable is in a continuous (numeric) range, +such as an XY/scatter chart, does not have a category axis. Rather it has two +value axes. + +A category is perhaps most commonly a string label, such as ``'East'`` or +``'Revenue'``; however a category can also be a number or a date (although +all categories in a chart must be the same type). + +When a chart's categories are dates, the category axis is generally, but not +necessarily a |DateAxis| object. + +A Chart may have zero to four axes. A pie chart, for example, has neither +a category nor a value axis. + +.. autoclass:: pptx.chart.axis._BaseAxis() + :members: + :member-order: bysource + +.. autoclass:: pptx.chart.axis.CategoryAxis() + :members: + :member-order: bysource + +.. autoclass:: pptx.chart.axis.DateAxis() + :members: + :member-order: bysource + +.. autoclass:: pptx.chart.axis.AxisTitle() + :members: + :member-order: bysource + + +Value Axes +~~~~~~~~~~ + +Some axis properties are only relevant to value axes, in particular, those +related to numeric values rather than text category labels. + +.. autoclass:: pptx.chart.axis.ValueAxis() + :members: + :member-order: bysource + :undoc-members: + + +|MajorGridlines| objects +------------------------ + +Gridlines are the vertical and horizontal lines that extend major tick marks +of an axis across the chart to ease comparison of a data point with the axis +divisions. + +.. autoclass:: pptx.chart.axis.MajorGridlines() + :members: + :member-order: bysource + :undoc-members: + + +|TickLabels| objects +-------------------- + +Tick labels are the numbers appearing on a value axis or the category names +appearing on a category axis. Certain formatting options are available for +changing how these labels are displayed. + +.. autoclass:: pptx.chart.axis.TickLabels() + :members: + :member-order: bysource + :undoc-members: + + +|_BasePlot| objects +------------------- + +A *plot* is a group of series all depicted using the same charting type, e.g. +bar, column, line, etc. Most charts have only a single plot; however, a chart +may have multiple, as in where a line plot appears overlaid on a bar plot in +the same chart. In the Microsoft API, this concept has the name *chart +group*. The term *plot* was chosen for |pp| to avoid the common mistake of +understanding a chart group to be a group of chart objects. + +Certain properties must be set at the plot level. Some of those properties +are not present on plots of all chart types. For example, :attr:`gap_width` +is only present on a bar or column plot. + +.. autoclass:: pptx.chart.plot._BasePlot() + :members: + :member-order: bysource + :undoc-members: + + +|BarPlot| objects +~~~~~~~~~~~~~~~~~ + +The following properties are only present on bar-type plots, which includes +both bar and column charts. + +.. autoclass:: pptx.chart.plot.BarPlot() + :members: + :member-order: bysource + :undoc-members: + + +|BubblePlot| objects +~~~~~~~~~~~~~~~~~~~~ + +The following properties are only present on bubble-type plots. + +.. autoclass:: pptx.chart.plot.BubblePlot() + :members: + :member-order: bysource + :undoc-members: + + +|category.Categories| objects +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Category plots provide access to a |category.Categories| object with their +`.categories` property. + +.. autoclass:: pptx.chart.category.Categories() + :members: + :member-order: bysource + :undoc-members: + + +|category.Category| objects +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: pptx.chart.category.Category() + :members: + :member-order: bysource + :undoc-members: + + +|CategoryLevel| objects +~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: pptx.chart.category.CategoryLevel() + :members: + :member-order: bysource + :undoc-members: + + +|DataLabels| objects +-------------------- + +A *data label* is text that labels a particular data point, usually with its +value, allowing the point to be interpreted more clearly than just visually +comparing its marker with its axis. + +A |DataLabels| object is not a collection, such as a sequence, and it does +not provide access to individual data points. Rather, it provides properties +that allow all the data labels in its scope to be formatted at once. + +.. autoclass:: pptx.chart.datalabel.DataLabels() + :members: + :member-order: bysource + :undoc-members: + +.. autoclass:: pptx.chart.datalabel.DataLabel() + :members: + :member-order: bysource + :undoc-members: + + +|Series| objects +---------------- + +A *series* is a sequence of data points that represent a coherent set of +observations across each of the categories in the chart. For example, on +a chart having regional categories "West", "East", and "Mid-west", a series +might be "Q1 Sales" and have values 42, 120, and 34. The series in this case +coheres around the first quarter time period. + +In general, the type (class) of a series object depends upon the chart type. +The following properties are available on series objects of all types. + +.. autoclass:: pptx.chart.series._BaseSeries() + :members: + :member-order: bysource + :undoc-members: + + +|AreaSeries| objects +~~~~~~~~~~~~~~~~~~~~ + +These properties are available on a series belonging to an area-type plot +such as AREA_STACKED. + +.. autoclass:: pptx.chart.series.AreaSeries() + :inherited-members: + :members: + :member-order: bysource + + +|BarSeries| objects +~~~~~~~~~~~~~~~~~~~ + +These properties are available on a series belonging to a bar-type plot. Note +that column charts are also bar-type charts. + +.. autoclass:: pptx.chart.series.BarSeries() + :inherited-members: + :members: + :member-order: bysource + + +|BubbleSeries| objects +~~~~~~~~~~~~~~~~~~~~~~ + +These properties are available on series belonging to a bubble chart. + +.. autoclass:: pptx.chart.series.BubbleSeries() + :inherited-members: + :members: + :member-order: bysource + + +|LineSeries| objects +~~~~~~~~~~~~~~~~~~~~ + +These properties are available on a series belonging to a line-type plot. + +.. autoclass:: pptx.chart.series.LineSeries() + :inherited-members: + :members: + :member-order: bysource + + +|Marker| objects +~~~~~~~~~~~~~~~~ + +A marker is the small shape (e.g. diamond or circle) that "marks" each +individual data point connected by a series line in a line-type plot. + +.. autoclass:: pptx.chart.marker.Marker() + :inherited-members: + :members: + :member-order: bysource + + +|PieSeries| objects +~~~~~~~~~~~~~~~~~~~ + +These properties are available on a series belonging to a pie chart. + +.. autoclass:: pptx.chart.series.PieSeries() + :inherited-members: + :members: + :member-order: bysource + + +|RadarSeries| objects +~~~~~~~~~~~~~~~~~~~~~ + +These properties are available on a series belonging to a radar chart. + +.. autoclass:: pptx.chart.series.RadarSeries() + :inherited-members: + :members: + :member-order: bysource + + +|XySeries| objects +~~~~~~~~~~~~~~~~~~ + +These properties are available on series belonging to an XY plot. + +.. autoclass:: pptx.chart.series.XySeries() + :members: + :member-order: bysource + :inherited-members: + :undoc-members: + + +|Point| objects +--------------- + +An XY or bubble chart has a :attr:`points` attribute providing access to a +sequence of |Point| objects. That sequence supports iteration, indexed +access, and ``len()``. + +.. autoclass:: pptx.chart.point.CategoryPoints() + :members: + :member-order: bysource + :undoc-members: + +.. autoclass:: pptx.chart.point.BubblePoints() + :members: + :member-order: bysource + :undoc-members: + +.. autoclass:: pptx.chart.point.XyPoints() + :members: + :member-order: bysource + :undoc-members: + +.. autoclass:: pptx.chart.point.Point() + :members: + :member-order: bysource + :undoc-members: diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/dml.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/dml.rst new file mode 100644 index 0000000000000000000000000000000000000000..d96485216976ddac64442e1d53ab05c6b8522061 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/dml.rst @@ -0,0 +1,55 @@ +.. _dml_api: + +DrawingML objects +================= + +Low-level drawing elements like fill and color that appear repeatedly in +various aspects of shapes. + + +|ChartFormat| objects +--------------------- + +.. autoclass:: pptx.dml.chtfmt.ChartFormat + :members: + + +|FillFormat| objects +-------------------- + +.. autoclass:: pptx.dml.fill.FillFormat + :members: + :exclude-members: from_fill_parent + :undoc-members: + + +|LineFormat| objects +-------------------- + +.. autoclass:: pptx.dml.line.LineFormat + :members: + :undoc-members: + + +|ColorFormat| objects +--------------------- + +.. autoclass:: pptx.dml.color.ColorFormat + :members: brightness, rgb, theme_color, type + :undoc-members: + + +|RGBColor| objects +------------------ + +.. autoclass:: pptx.dml.color.RGBColor + :members: from_string + :undoc-members: + + +|ShadowFormat| objects +---------------------- + +.. autoclass:: pptx.dml.effect.ShadowFormat + :members: + :undoc-members: diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/ExcelNumFormat.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/ExcelNumFormat.rst new file mode 100644 index 0000000000000000000000000000000000000000..f8ede063dd17a84d6ea26e87275ad22869130c68 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/ExcelNumFormat.rst @@ -0,0 +1,60 @@ +.. _ExcelNumFormat: + +Excel Number Formats +==================== + +The following integer values correspond to built-in Excel number formats. +While they cannot be used directly in |pp|, this reference can be used to +determine the format strings that can be substituted in +:meth:`.ChartData.add_series` to specify a numeric display format for series +values. + +Further information on string number format codes (such as '#,##0') can be +found on `this web page`_. + +.. _`this web page`: + https://support.office.com/en-GB/article/ + Number-format-codes-5026bbd6-04bc-48cd-bf33-80f18b4eae68 + +---- + +===== ========== ========================== +Value Type Format String +----- ---------- -------------------------- +0 General General +1 Decimal 0 +2 Decimal 0.00 +3 Decimal #,##0 +4 Decimal #,##0.00 +5 Currency $#,##0;$-#,##0 +6 Currency $#,##0;[Red]$-#,##0 +7 Currency $#,##0.00;$-#,##0.00 +8 Currency $#,##0.00;[Red]$-#,##0.00 +9 Percentage 0% +10 Percentage 0.00% +11 Scientific 0.00E+00 +12 Fraction # ?/? +13 Fraction # / +14 Date m/d/yy +15 Date d-mmm-yy +16 Date d-mmm +17 Date mmm-yy +18 Time h:mm AM/PM +19 Time h:mm:ss AM/PM +20 Time h:mm +21 Time h:mm:ss +22 Time m/d/yy h:mm +37 Currency #,##0;-#,##0 +38 Currency #,##0;[Red]-#,##0 +39 Currency #,##0.00;-#,##0.00 +40 Currency #,##0.00;[Red]-#,##0.00 +41 Accounting _ * #,##0_ ;_ * "_ ;_ @_ +42 Accounting _ $* #,##0_ ;_ $* "_ ;_ @_ +43 Accounting _ * #,##0.00_ ;_ * "??_ ;_ @_ +44 Accounting _ $* #,##0.00_ ;_ $* "??_ ;_ @_ +45 Time mm:ss +46 Time h :mm:ss +47 Time mm:ss.0 +48 Scientific ##0.0E+00 +49 Text @ +===== ========== ========================== diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoAutoShapeType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoAutoShapeType.rst new file mode 100644 index 0000000000000000000000000000000000000000..2f3088b1f6dbd46e258a999b653dd4bca3d5126a --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoAutoShapeType.rst @@ -0,0 +1,568 @@ +.. _MsoAutoShapeType: + +``MSO_AUTO_SHAPE_TYPE`` +======================= + +Specifies a type of AutoShape, e.g. DOWN_ARROW + +Alias: ``MSO_SHAPE`` + +Example:: + + from pptx.enum.shapes import MSO_SHAPE + from pptx.util import Inches + + left = top = width = height = Inches(1.0) + slide.shapes.add_shape( + MSO_SHAPE.ROUNDED_RECTANGLE, left, top, width, height + ) + +---- + +ACTION_BUTTON_BACK_OR_PREVIOUS + Back or Previous button. Supports mouse-click and mouse-over actions + +ACTION_BUTTON_BEGINNING + Beginning button. Supports mouse-click and mouse-over actions. + +ACTION_BUTTON_CUSTOM + Button with no default picture or text. Supports mouse-click and mouse-over + action. + +ACTION_BUTTON_DOCUMENT + Document button. Supports mouse-click and mouse-over actions. + +ACTION_BUTTON_END + End button. Supports mouse-click and mouse-over actions. + +ACTION_BUTTON_FORWARD_OR_NEXT + Forward or Next button. Supports mouse-click and mouse-over actions. + +ACTION_BUTTON_HELP + Help button. Supports mouse-click and mouse-over actio. + +ACTION_BUTTON_HOME + Home button. Supports mouse-click and mouse-over actio. + +ACTION_BUTTON_INFORMATION + Information button. Supports mouse-click and mouse-over actions. + +ACTION_BUTTON_MOVIE + Movie button. Supports mouse-click and mouse-over actions. + +ACTION_BUTTON_RETURN + Return button. Supports mouse-click and mouse-over actions. + +ACTION_BUTTON_SOUND + Sound button. Supports mouse-click and mouse-over actions. + +ARC + Arc + +BALLOON + Rounded Rectangular Callout + +BENT_ARROW + Block arrow that follows a curved 90-degree angle + +BENT_UP_ARROW + Block arrow that follows a sharp 90-degree angle. Points up by default. + +BEVEL + Bevel + +BLOCK_ARC + Block arc + +CAN + Can + +CHART_PLUS + Chart Plus + +CHART_STAR + Chart Star + +CHART_X + Chart X + +CHEVRON + Chevron + +CHORD + Geometric chord shape + +CIRCULAR_ARROW + Block arrow that follows a curved 180-degree angle + +CLOUD + Cloud + +CLOUD_CALLOUT + Cloud callout + +CORNER + Corner + +CORNER_TABS + Corner Tabs + +CROSS + Cross + +CUBE + Cube + +CURVED_DOWN_ARROW + Block arrow that curves down + +CURVED_DOWN_RIBBON + Ribbon banner that curves down + +CURVED_LEFT_ARROW + Block arrow that curves left + +CURVED_RIGHT_ARROW + Block arrow that curves right + +CURVED_UP_ARROW + Block arrow that curves up + +CURVED_UP_RIBBON + Ribbon banner that curves up + +DECAGON + Decagon + +DIAGONAL_STRIPE + Diagonal Stripe + +DIAMOND + Diamond + +DODECAGON + Dodecagon + +DONUT + Donut + +DOUBLE_BRACE + Double brace + +DOUBLE_BRACKET + Double bracket + +DOUBLE_WAVE + Double wave + +DOWN_ARROW + Block arrow that points down + +DOWN_ARROW_CALLOUT + Callout with arrow that points down + +DOWN_RIBBON + Ribbon banner with center area below ribbon ends + +EXPLOSION1 + Explosion + +EXPLOSION2 + Explosion + +FLOWCHART_ALTERNATE_PROCESS + Alternate process flowchart symbol + +FLOWCHART_CARD + Card flowchart symbol + +FLOWCHART_COLLATE + Collate flowchart symbol + +FLOWCHART_CONNECTOR + Connector flowchart symbol + +FLOWCHART_DATA + Data flowchart symbol + +FLOWCHART_DECISION + Decision flowchart symbol + +FLOWCHART_DELAY + Delay flowchart symbol + +FLOWCHART_DIRECT_ACCESS_STORAGE + Direct access storage flowchart symbol + +FLOWCHART_DISPLAY + Display flowchart symbol + +FLOWCHART_DOCUMENT + Document flowchart symbol + +FLOWCHART_EXTRACT + Extract flowchart symbol + +FLOWCHART_INTERNAL_STORAGE + Internal storage flowchart symbol + +FLOWCHART_MAGNETIC_DISK + Magnetic disk flowchart symbol + +FLOWCHART_MANUAL_INPUT + Manual input flowchart symbol + +FLOWCHART_MANUAL_OPERATION + Manual operation flowchart symbol + +FLOWCHART_MERGE + Merge flowchart symbol + +FLOWCHART_MULTIDOCUMENT + Multi-document flowchart symbol + +FLOWCHART_OFFLINE_STORAGE + Offline Storage + +FLOWCHART_OFFPAGE_CONNECTOR + Off-page connector flowchart symbol + +FLOWCHART_OR + "Or" flowchart symbol + +FLOWCHART_PREDEFINED_PROCESS + Predefined process flowchart symbol + +FLOWCHART_PREPARATION + Preparation flowchart symbol + +FLOWCHART_PROCESS + Process flowchart symbol + +FLOWCHART_PUNCHED_TAPE + Punched tape flowchart symbol + +FLOWCHART_SEQUENTIAL_ACCESS_STORAGE + Sequential access storage flowchart symbol + +FLOWCHART_SORT + Sort flowchart symbol + +FLOWCHART_STORED_DATA + Stored data flowchart symbol + +FLOWCHART_SUMMING_JUNCTION + Summing junction flowchart symbol + +FLOWCHART_TERMINATOR + Terminator flowchart symbol + +FOLDED_CORNER + Folded corner + +FRAME + Frame + +FUNNEL + Funnel + +GEAR_6 + Gear 6 + +GEAR_9 + Gear 9 + +HALF_FRAME + Half Frame + +HEART + Heart + +HEPTAGON + Heptagon + +HEXAGON + Hexagon + +HORIZONTAL_SCROLL + Horizontal scroll + +ISOSCELES_TRIANGLE + Isosceles triangle + +LEFT_ARROW + Block arrow that points left + +LEFT_ARROW_CALLOUT + Callout with arrow that points left + +LEFT_BRACE + Left brace + +LEFT_BRACKET + Left bracket + +LEFT_CIRCULAR_ARROW + Left Circular Arrow + +LEFT_RIGHT_ARROW + Block arrow with arrowheads that point both left and right + +LEFT_RIGHT_ARROW_CALLOUT + Callout with arrowheads that point both left and right + +LEFT_RIGHT_CIRCULAR_ARROW + Left Right Circular Arrow + +LEFT_RIGHT_RIBBON + Left Right Ribbon + +LEFT_RIGHT_UP_ARROW + Block arrow with arrowheads that point left, right, and up + +LEFT_UP_ARROW + Block arrow with arrowheads that point left and up + +LIGHTNING_BOLT + Lightning bolt + +LINE_CALLOUT_1 + Callout with border and horizontal callout line + +LINE_CALLOUT_1_ACCENT_BAR + Callout with vertical accent bar + +LINE_CALLOUT_1_BORDER_AND_ACCENT_BAR + Callout with border and vertical accent bar + +LINE_CALLOUT_1_NO_BORDER + Callout with horizontal line + +LINE_CALLOUT_2 + Callout with diagonal straight line + +LINE_CALLOUT_2_ACCENT_BAR + Callout with diagonal callout line and accent bar + +LINE_CALLOUT_2_BORDER_AND_ACCENT_BAR + Callout with border, diagonal straight line, and accent bar + +LINE_CALLOUT_2_NO_BORDER + Callout with no border and diagonal callout line + +LINE_CALLOUT_3 + Callout with angled line + +LINE_CALLOUT_3_ACCENT_BAR + Callout with angled callout line and accent bar + +LINE_CALLOUT_3_BORDER_AND_ACCENT_BAR + Callout with border, angled callout line, and accent bar + +LINE_CALLOUT_3_NO_BORDER + Callout with no border and angled callout line + +LINE_CALLOUT_4 + Callout with callout line segments forming a U-shape + +LINE_CALLOUT_4_ACCENT_BAR + Callout with accent bar and callout line segments forming a U-shape + +LINE_CALLOUT_4_BORDER_AND_ACCENT_BAR + Callout with border, accent bar, and callout line segments forming a + U-shape + +LINE_CALLOUT_4_NO_BORDER + Callout with no border and callout line segments forming a U-shape. + +LINE_INVERSE + Straight Connector + +MATH_DIVIDE + Division + +MATH_EQUAL + Equal + +MATH_MINUS + Minus + +MATH_MULTIPLY + Multiply + +MATH_NOT_EQUAL + Not Equal + +MATH_PLUS + Plus + +MOON + Moon + +NO_SYMBOL + "No" symbol + +NON_ISOSCELES_TRAPEZOID + Non-isosceles Trapezoid + +NOTCHED_RIGHT_ARROW + Notched block arrow that points right + +OCTAGON + Octagon + +OVAL + Oval + +OVAL_CALLOUT + Oval-shaped callout + +PARALLELOGRAM + Parallelogram + +PENTAGON + Pentagon + +PIE + Pie + +PIE_WEDGE + Pie + +PLAQUE + Plaque + +PLAQUE_TABS + Plaque Tabs + +QUAD_ARROW + Block arrows that point up, down, left, and right + +QUAD_ARROW_CALLOUT + Callout with arrows that point up, down, left, and right + +RECTANGLE + Rectangle + +RECTANGULAR_CALLOUT + Rectangular callout + +REGULAR_PENTAGON + Pentagon + +RIGHT_ARROW + Block arrow that points right + +RIGHT_ARROW_CALLOUT + Callout with arrow that points right + +RIGHT_BRACE + Right brace + +RIGHT_BRACKET + Right bracket + +RIGHT_TRIANGLE + Right triangle + +ROUND_1_RECTANGLE + Round Single Corner Rectangle + +ROUND_2_DIAG_RECTANGLE + Round Diagonal Corner Rectangle + +ROUND_2_SAME_RECTANGLE + Round Same Side Corner Rectangle + +ROUNDED_RECTANGLE + Rounded rectangle + +ROUNDED_RECTANGULAR_CALLOUT + Rounded rectangle-shaped callout + +SMILEY_FACE + Smiley face + +SNIP_1_RECTANGLE + Snip Single Corner Rectangle + +SNIP_2_DIAG_RECTANGLE + Snip Diagonal Corner Rectangle + +SNIP_2_SAME_RECTANGLE + Snip Same Side Corner Rectangle + +SNIP_ROUND_RECTANGLE + Snip and Round Single Corner Rectangle + +SQUARE_TABS + Square Tabs + +STAR_10_POINT + 10-Point Star + +STAR_12_POINT + 12-Point Star + +STAR_16_POINT + 16-point star + +STAR_24_POINT + 24-point star + +STAR_32_POINT + 32-point star + +STAR_4_POINT + 4-point star + +STAR_5_POINT + 5-point star + +STAR_6_POINT + 6-Point Star + +STAR_7_POINT + 7-Point Star + +STAR_8_POINT + 8-point star + +STRIPED_RIGHT_ARROW + Block arrow that points right with stripes at the tail + +SUN + Sun + +SWOOSH_ARROW + Swoosh Arrow + +TEAR + Teardrop + +TRAPEZOID + Trapezoid + +U_TURN_ARROW + Block arrow forming a U shape + +UP_ARROW + Block arrow that points up + +UP_ARROW_CALLOUT + Callout with arrow that points up + +UP_DOWN_ARROW + Block arrow that points up and down + +UP_DOWN_ARROW_CALLOUT + Callout with arrows that point up and down + +UP_RIBBON + Ribbon banner with center area above ribbon ends + +VERTICAL_SCROLL + Vertical scroll + +WAVE + Wave diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoAutoSize.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoAutoSize.rst new file mode 100644 index 0000000000000000000000000000000000000000..14b9e925ade1560520fb167d62a2d7b249c50ad0 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoAutoSize.rst @@ -0,0 +1,40 @@ +.. _MsoAutoSize: + +``MSO_AUTO_SIZE`` +================= + +Determines the type of automatic sizing allowed. + +The following names can be used to specify the automatic sizing behavior +used to fit a shape's text within the shape bounding box, for example:: + + from pptx.enum.text import MSO_AUTO_SIZE + + shape.text_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE + +The word-wrap setting of the text frame interacts with the auto-size setting +to determine the specific auto-sizing behavior. + +Note that ``TextFrame.auto_size`` can also be set to |None|, which removes +the auto size setting altogether. This causes the setting to be inherited, +either from the layout placeholder, in the case of a placeholder shape, or +from the theme. + +---- + +NONE + No automatic sizing of the shape or text will be done. Text can freely + extend beyond the horizontal and vertical edges of the shape bounding box. + +SHAPE_TO_FIT_TEXT + The shape height and possibly width are adjusted to fit the text. Note + this setting interacts with the TextFrame.word_wrap property setting. If + word wrap is turned on, only the height of the shape will be adjusted; + soft line breaks will be used to fit the text horizontally. + +TEXT_TO_FIT_SHAPE + The font size is reduced as necessary to fit the text within the shape. + +MIXED + Return value only; indicates a combination of automatic sizing schemes are + used. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoColorType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoColorType.rst new file mode 100644 index 0000000000000000000000000000000000000000..f15ea5e4f6cdfd40c75b407640bc1563caa7ae08 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoColorType.rst @@ -0,0 +1,33 @@ +.. _MsoColorType: + +``MSO_COLOR_TYPE`` +================== + +Specifies the color specification scheme + +Example:: + + from pptx.enum.dml import MSO_COLOR_TYPE + + assert shape.fill.fore_color.type == MSO_COLOR_TYPE.SCHEME + +---- + +RGB + Color is specified by an |RGBColor| value + +SCHEME + Color is one of the preset theme colors + +HSL + Color is specified using Hue, Saturation, and Luminosity values + +PRESET + Color is specified using a named built-in color + +SCRGB + Color is an scRGB color, a wide color gamut RGB color space + +SYSTEM + Color is one specified by the operating system, such as the window + background color. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoConnectorType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoConnectorType.rst new file mode 100644 index 0000000000000000000000000000000000000000..971492afa634ef2238391a26eb2e727a247d2f65 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoConnectorType.rst @@ -0,0 +1,33 @@ +.. _MsoConnectorType: + +``MSO_CONNECTOR_TYPE`` +====================== + +Specifies a type of connector. + +Alias: ``MSO_CONNECTOR`` + +Example:: + + from pptx.enum.shapes import MSO_CONNECTOR + from pptx.util import Cm + + shapes = prs.slides[0].shapes + connector = shapes.add_connector( + MSO_CONNECTOR.STRAIGHT, Cm(2), Cm(2), Cm(10), Cm(10) + ) + assert connector.left.cm == 2 + +---- + +CURVE + Curved connector. + +ELBOW + Elbow connector. + +STRAIGHT + Straight line connector. + +MIXED + Return value only; indicates a combination of other states. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoFillType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoFillType.rst new file mode 100644 index 0000000000000000000000000000000000000000..6f7585ee1bff14e2ab186e6583e0b1e3b652d284 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoFillType.rst @@ -0,0 +1,40 @@ +.. _MsoFillType: + +``MSO_FILL_TYPE`` +================= + +Specifies the type of bitmap used for the fill of a shape. + +Alias: ``MSO_FILL`` + +Example:: + + from pptx.enum.dml import MSO_FILL + + assert shape.fill.type == MSO_FILL.SOLID + +---- + +BACKGROUND + The shape is transparent, such that whatever is behind the shape shows + through. Often this is the slide background, but if a visible shape is + behind, that will show through. + +GRADIENT + Shape is filled with a gradient + +GROUP + Shape is part of a group and should inherit the fill properties of the + group. + +PATTERNED + Shape is filled with a pattern + +PICTURE + Shape is filled with a bitmapped image + +SOLID + Shape is filled with a solid color + +TEXTURED + Shape is filled with a texture diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoLanguageId.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoLanguageId.rst new file mode 100644 index 0000000000000000000000000000000000000000..53f3d1c7fe945a5a1fa59c03d6fa3a9e4afa30dd --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoLanguageId.rst @@ -0,0 +1,662 @@ +.. _MsoLanguageId: + +``MSO_LANGUAGE_ID`` +=================== + +Specifies the language identifier. + +Example:: + + from pptx.enum.lang import MSO_LANGUAGE_ID + + font.language_id = MSO_LANGUAGE_ID.POLISH + +---- + +MIXED + More than one language in specified range. + +NONE + No language specified. + +AFRIKAANS + The Afrikaans language. + +ALBANIAN + The Albanian language. + +AMHARIC + The Amharic language. + +ARABIC + The Arabic language. + +ARABIC_ALGERIA + The Arabic Algeria language. + +ARABIC_BAHRAIN + The Arabic Bahrain language. + +ARABIC_EGYPT + The Arabic Egypt language. + +ARABIC_IRAQ + The Arabic Iraq language. + +ARABIC_JORDAN + The Arabic Jordan language. + +ARABIC_KUWAIT + The Arabic Kuwait language. + +ARABIC_LEBANON + The Arabic Lebanon language. + +ARABIC_LIBYA + The Arabic Libya language. + +ARABIC_MOROCCO + The Arabic Morocco language. + +ARABIC_OMAN + The Arabic Oman language. + +ARABIC_QATAR + The Arabic Qatar language. + +ARABIC_SYRIA + The Arabic Syria language. + +ARABIC_TUNISIA + The Arabic Tunisia language. + +ARABIC_UAE + The Arabic UAE language. + +ARABIC_YEMEN + The Arabic Yemen language. + +ARMENIAN + The Armenian language. + +ASSAMESE + The Assamese language. + +AZERI_CYRILLIC + The Azeri Cyrillic language. + +AZERI_LATIN + The Azeri Latin language. + +BASQUE + The Basque language. + +BELGIAN_DUTCH + The Belgian Dutch language. + +BELGIAN_FRENCH + The Belgian French language. + +BENGALI + The Bengali language. + +BOSNIAN + The Bosnian language. + +BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC + The Bosnian Bosnia Herzegovina Cyrillic language. + +BOSNIAN_BOSNIA_HERZEGOVINA_LATIN + The Bosnian Bosnia Herzegovina Latin language. + +BRAZILIAN_PORTUGUESE + The Brazilian Portuguese language. + +BULGARIAN + The Bulgarian language. + +BURMESE + The Burmese language. + +BYELORUSSIAN + The Byelorussian language. + +CATALAN + The Catalan language. + +CHEROKEE + The Cherokee language. + +CHINESE_HONG_KONG_SAR + The Chinese Hong Kong SAR language. + +CHINESE_MACAO_SAR + The Chinese Macao SAR language. + +CHINESE_SINGAPORE + The Chinese Singapore language. + +CROATIAN + The Croatian language. + +CZECH + The Czech language. + +DANISH + The Danish language. + +DIVEHI + The Divehi language. + +DUTCH + The Dutch language. + +EDO + The Edo language. + +ENGLISH_AUS + The English AUS language. + +ENGLISH_BELIZE + The English Belize language. + +ENGLISH_CANADIAN + The English Canadian language. + +ENGLISH_CARIBBEAN + The English Caribbean language. + +ENGLISH_INDONESIA + The English Indonesia language. + +ENGLISH_IRELAND + The English Ireland language. + +ENGLISH_JAMAICA + The English Jamaica language. + +ENGLISH_NEW_ZEALAND + The English NewZealand language. + +ENGLISH_PHILIPPINES + The English Philippines language. + +ENGLISH_SOUTH_AFRICA + The English South Africa language. + +ENGLISH_TRINIDAD_TOBAGO + The English Trinidad Tobago language. + +ENGLISH_UK + The English UK language. + +ENGLISH_US + The English US language. + +ENGLISH_ZIMBABWE + The English Zimbabwe language. + +ESTONIAN + The Estonian language. + +FAEROESE + The Faeroese language. + +FARSI + The Farsi language. + +FILIPINO + The Filipino language. + +FINNISH + The Finnish language. + +FRANCH_CONGO_DRC + The French Congo DRC language. + +FRENCH + The French language. + +FRENCH_CAMEROON + The French Cameroon language. + +FRENCH_CANADIAN + The French Canadian language. + +FRENCH_COTED_IVOIRE + The French Coted Ivoire language. + +FRENCH_HAITI + The French Haiti language. + +FRENCH_LUXEMBOURG + The French Luxembourg language. + +FRENCH_MALI + The French Mali language. + +FRENCH_MONACO + The French Monaco language. + +FRENCH_MOROCCO + The French Morocco language. + +FRENCH_REUNION + The French Reunion language. + +FRENCH_SENEGAL + The French Senegal language. + +FRENCH_WEST_INDIES + The French West Indies language. + +FRISIAN_NETHERLANDS + The Frisian Netherlands language. + +FULFULDE + The Fulfulde language. + +GAELIC_IRELAND + The Gaelic Ireland language. + +GAELIC_SCOTLAND + The Gaelic Scotland language. + +GALICIAN + The Galician language. + +GEORGIAN + The Georgian language. + +GERMAN + The German language. + +GERMAN_AUSTRIA + The German Austria language. + +GERMAN_LIECHTENSTEIN + The German Liechtenstein language. + +GERMAN_LUXEMBOURG + The German Luxembourg language. + +GREEK + The Greek language. + +GUARANI + The Guarani language. + +GUJARATI + The Gujarati language. + +HAUSA + The Hausa language. + +HAWAIIAN + The Hawaiian language. + +HEBREW + The Hebrew language. + +HINDI + The Hindi language. + +HUNGARIAN + The Hungarian language. + +IBIBIO + The Ibibio language. + +ICELANDIC + The Icelandic language. + +IGBO + The Igbo language. + +INDONESIAN + The Indonesian language. + +INUKTITUT + The Inuktitut language. + +ITALIAN + The Italian language. + +JAPANESE + The Japanese language. + +KANNADA + The Kannada language. + +KANURI + The Kanuri language. + +KASHMIRI + The Kashmiri language. + +KASHMIRI_DEVANAGARI + The Kashmiri Devanagari language. + +KAZAKH + The Kazakh language. + +KHMER + The Khmer language. + +KIRGHIZ + The Kirghiz language. + +KONKANI + The Konkani language. + +KOREAN + The Korean language. + +KYRGYZ + The Kyrgyz language. + +LAO + The Lao language. + +LATIN + The Latin language. + +LATVIAN + The Latvian language. + +LITHUANIAN + The Lithuanian language. + +MACEDONINAN_FYROM + The Macedonian FYROM language. + +MALAY_BRUNEI_DARUSSALAM + The Malay Brunei Darussalam language. + +MALAYALAM + The Malayalam language. + +MALAYSIAN + The Malaysian language. + +MALTESE + The Maltese language. + +MANIPURI + The Manipuri language. + +MAORI + The Maori language. + +MARATHI + The Marathi language. + +MEXICAN_SPANISH + The Mexican Spanish language. + +MONGOLIAN + The Mongolian language. + +NEPALI + The Nepali language. + +NO_PROOFING + No proofing. + +NORWEGIAN_BOKMOL + The Norwegian Bokmol language. + +NORWEGIAN_NYNORSK + The Norwegian Nynorsk language. + +ORIYA + The Oriya language. + +OROMO + The Oromo language. + +PASHTO + The Pashto language. + +POLISH + The Polish language. + +PORTUGUESE + The Portuguese language. + +PUNJABI + The Punjabi language. + +QUECHUA_BOLIVIA + The Quechua Bolivia language. + +QUECHUA_ECUADOR + The Quechua Ecuador language. + +QUECHUA_PERU + The Quechua Peru language. + +RHAETO_ROMANIC + The Rhaeto Romanic language. + +ROMANIAN + The Romanian language. + +ROMANIAN_MOLDOVA + The Romanian Moldova language. + +RUSSIAN + The Russian language. + +RUSSIAN_MOLDOVA + The Russian Moldova language. + +SAMI_LAPPISH + The Sami Lappish language. + +SANSKRIT + The Sanskrit language. + +SEPEDI + The Sepedi language. + +SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC + The Serbian Bosnia Herzegovina Cyrillic language. + +SERBIAN_BOSNIA_HERZEGOVINA_LATIN + The Serbian Bosnia Herzegovina Latin language. + +SERBIAN_CYRILLIC + The Serbian Cyrillic language. + +SERBIAN_LATIN + The Serbian Latin language. + +SESOTHO + The Sesotho language. + +SIMPLIFIED_CHINESE + The Simplified Chinese language. + +SINDHI + The Sindhi language. + +SINDHI_PAKISTAN + The Sindhi Pakistan language. + +SINHALESE + The Sinhalese language. + +SLOVAK + The Slovak language. + +SLOVENIAN + The Slovenian language. + +SOMALI + The Somali language. + +SORBIAN + The Sorbian language. + +SPANISH + The Spanish language. + +SPANISH_ARGENTINA + The Spanish Argentina language. + +SPANISH_BOLIVIA + The Spanish Bolivia language. + +SPANISH_CHILE + The Spanish Chile language. + +SPANISH_COLOMBIA + The Spanish Colombia language. + +SPANISH_COSTA_RICA + The Spanish Costa Rica language. + +SPANISH_DOMINICAN_REPUBLIC + The Spanish Dominican Republic language. + +SPANISH_ECUADOR + The Spanish Ecuador language. + +SPANISH_EL_SALVADOR + The Spanish El Salvador language. + +SPANISH_GUATEMALA + The Spanish Guatemala language. + +SPANISH_HONDURAS + The Spanish Honduras language. + +SPANISH_MODERN_SORT + The Spanish Modern Sort language. + +SPANISH_NICARAGUA + The Spanish Nicaragua language. + +SPANISH_PANAMA + The Spanish Panama language. + +SPANISH_PARAGUAY + The Spanish Paraguay language. + +SPANISH_PERU + The Spanish Peru language. + +SPANISH_PUERTO_RICO + The Spanish Puerto Rico language. + +SPANISH_URUGUAY + The Spanish Uruguay language. + +SPANISH_VENEZUELA + The Spanish Venezuela language. + +SUTU + The Sutu language. + +SWAHILI + The Swahili language. + +SWEDISH + The Swedish language. + +SWEDISH_FINLAND + The Swedish Finland language. + +SWISS_FRENCH + The Swiss French language. + +SWISS_GERMAN + The Swiss German language. + +SWISS_ITALIAN + The Swiss Italian language. + +SYRIAC + The Syriac language. + +TAJIK + The Tajik language. + +TAMAZIGHT + The Tamazight language. + +TAMAZIGHT_LATIN + The Tamazight Latin language. + +TAMIL + The Tamil language. + +TATAR + The Tatar language. + +TELUGU + The Telugu language. + +THAI + The Thai language. + +TIBETAN + The Tibetan language. + +TIGRIGNA_ERITREA + The Tigrigna Eritrea language. + +TIGRIGNA_ETHIOPIC + The Tigrigna Ethiopic language. + +TRADITIONAL_CHINESE + The Traditional Chinese language. + +TSONGA + The Tsonga language. + +TSWANA + The Tswana language. + +TURKISH + The Turkish language. + +TURKMEN + The Turkmen language. + +UKRAINIAN + The Ukrainian language. + +URDU + The Urdu language. + +UZBEK_CYRILLIC + The Uzbek Cyrillic language. + +UZBEK_LATIN + The Uzbek Latin language. + +VENDA + The Venda language. + +VIETNAMESE + The Vietnamese language. + +WELSH + The Welsh language. + +XHOSA + The Xhosa language. + +YI + The Yi language. + +YIDDISH + The Yiddish language. + +YORUBA + The Yoruba language. + +ZULU + The Zulu language. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoLineDashStyle.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoLineDashStyle.rst new file mode 100644 index 0000000000000000000000000000000000000000..f7b2941b5a5f82b0e87866d2eeb7ab3a038cbfa5 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoLineDashStyle.rst @@ -0,0 +1,43 @@ +.. _MsoLineDashStyle: + +``MSO_LINE_DASH_STYLE`` +======================= + +Specifies the dash style for a line. + + Alias: ``MSO_LINE`` + + Example:: + + from pptx.enum.dml import MSO_LINE + + shape.line.dash_style = MSO_LINE.DASH_DOT_DOT + +---- + +DASH + Line consists of dashes only. + +DASH_DOT + Line is a dash-dot pattern. + +DASH_DOT_DOT + Line is a dash-dot-dot pattern. + +LONG_DASH + Line consists of long dashes. + +LONG_DASH_DOT + Line is a long dash-dot pattern. + +ROUND_DOT + Line is made up of round dots. + +SOLID + Line is solid. + +SQUARE_DOT + Line is made up of square dots. + +DASH_STYLE_MIXED + Not supported. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoPatternType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoPatternType.rst new file mode 100644 index 0000000000000000000000000000000000000000..61b95ea3c2e7a062299ba47828e7b6283af2de2c --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoPatternType.rst @@ -0,0 +1,183 @@ +.. _MsoPatternType: + +``MSO_PATTERN_TYPE`` +==================== + +Specifies the fill pattern used in a shape. + + Alias: ``MSO_PATTERN`` + + Example:: + + from pptx.enum.dml import MSO_PATTERN + + fill = shape.fill + fill.patterned() + fill.pattern == MSO_PATTERN.WAVE + +---- + +CROSS + Cross + +DARK_DOWNWARD_DIAGONAL + Dark Downward Diagonal + +DARK_HORIZONTAL + Dark Horizontal + +DARK_UPWARD_DIAGONAL + Dark Upward Diagonal + +DARK_VERTICAL + Dark Vertical + +DASHED_DOWNWARD_DIAGONAL + Dashed Downward Diagonal + +DASHED_HORIZONTAL + Dashed Horizontal + +DASHED_UPWARD_DIAGONAL + Dashed Upward Diagonal + +DASHED_VERTICAL + Dashed Vertical + +DIAGONAL_BRICK + Diagonal Brick + +DIAGONAL_CROSS + Diagonal Cross + +DIVOT + Pattern Divot + +DOTTED_DIAMOND + Dotted Diamond + +DOTTED_GRID + Dotted Grid + +DOWNWARD_DIAGONAL + Downward Diagonal + +HORIZONTAL + Horizontal + +HORIZONTAL_BRICK + Horizontal Brick + +LARGE_CHECKER_BOARD + Large Checker Board + +LARGE_CONFETTI + Large Confetti + +LARGE_GRID + Large Grid + +LIGHT_DOWNWARD_DIAGONAL + Light Downward Diagonal + +LIGHT_HORIZONTAL + Light Horizontal + +LIGHT_UPWARD_DIAGONAL + Light Upward Diagonal + +LIGHT_VERTICAL + Light Vertical + +NARROW_HORIZONTAL + Narrow Horizontal + +NARROW_VERTICAL + Narrow Vertical + +OUTLINED_DIAMOND + Outlined Diamond + +PERCENT_10 + 10% of the foreground color. + +PERCENT_20 + 20% of the foreground color. + +PERCENT_25 + 25% of the foreground color. + +PERCENT_30 + 30% of the foreground color. + +PERCENT_40 + 40% of the foreground color. + +PERCENT_5 + 5% of the foreground color. + +PERCENT_50 + 50% of the foreground color. + +PERCENT_60 + 60% of the foreground color. + +PERCENT_70 + 70% of the foreground color. + +PERCENT_75 + 75% of the foreground color. + +PERCENT_80 + 80% of the foreground color. + +PERCENT_90 + 90% of the foreground color. + +PLAID + Plaid + +SHINGLE + Shingle + +SMALL_CHECKER_BOARD + Small Checker Board + +SMALL_CONFETTI + Small Confetti + +SMALL_GRID + Small Grid + +SOLID_DIAMOND + Solid Diamond + +SPHERE + Sphere + +TRELLIS + Trellis + +UPWARD_DIAGONAL + Upward Diagonal + +VERTICAL + Vertical + +WAVE + Wave + +WEAVE + Weave + +WIDE_DOWNWARD_DIAGONAL + Wide Downward Diagonal + +WIDE_UPWARD_DIAGONAL + Wide Upward Diagonal + +ZIG_ZAG + Zig Zag + +MIXED + Mixed pattern. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoShapeType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoShapeType.rst new file mode 100644 index 0000000000000000000000000000000000000000..d8e61db002c98f019905430d1cebc87580c179a5 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoShapeType.rst @@ -0,0 +1,94 @@ +.. _MsoShapeType: + +``MSO_SHAPE_TYPE`` +================== + +Specifies the type of a shape + +Alias: ``MSO`` + +Example:: + + from pptx.enum.shapes import MSO_SHAPE_TYPE + + assert shape.type == MSO_SHAPE_TYPE.PICTURE + +---- + +AUTO_SHAPE + AutoShape + +CALLOUT + Callout shape + +CANVAS + Drawing canvas + +CHART + Chart, e.g. pie chart, bar chart + +COMMENT + Comment + +DIAGRAM + Diagram + +EMBEDDED_OLE_OBJECT + Embedded OLE object + +FORM_CONTROL + Form control + +FREEFORM + Freeform + +GROUP + Group shape + +IGX_GRAPHIC + SmartArt graphic + +INK + Ink + +INK_COMMENT + Ink Comment + +LINE + Line + +LINKED_OLE_OBJECT + Linked OLE object + +LINKED_PICTURE + Linked picture + +MEDIA + Media + +OLE_CONTROL_OBJECT + OLE control object + +PICTURE + Picture + +PLACEHOLDER + Placeholder + +SCRIPT_ANCHOR + Script anchor + +TABLE + Table + +TEXT_BOX + Text box + +TEXT_EFFECT + Text effect + +WEB_VIDEO + Web video + +MIXED + Mixed shape types diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoTextUnderlineType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoTextUnderlineType.rst new file mode 100644 index 0000000000000000000000000000000000000000..3fac11812f4608b8b8a36abbf1a21d13bc8160a6 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoTextUnderlineType.rst @@ -0,0 +1,74 @@ +.. _MsoTextUnderlineType: + +``MSO_TEXT_UNDERLINE_TYPE`` +=========================== + +Indicates the type of underline for text. Used with :attr:`.Font.underline` +to specify the style of text underlining. + +Alias: ``MSO_UNDERLINE`` + +Example:: + + from pptx.enum.text import MSO_UNDERLINE + + run.font.underline = MSO_UNDERLINE.DOUBLE_LINE + +---- + +NONE + Specifies no underline. + +DASH_HEAVY_LINE + Specifies a dash underline. + +DASH_LINE + Specifies a dash line underline. + +DASH_LONG_HEAVY_LINE + Specifies a long heavy line underline. + +DASH_LONG_LINE + Specifies a dashed long line underline. + +DOT_DASH_HEAVY_LINE + Specifies a dot dash heavy line underline. + +DOT_DASH_LINE + Specifies a dot dash line underline. + +DOT_DOT_DASH_HEAVY_LINE + Specifies a dot dot dash heavy line underline. + +DOT_DOT_DASH_LINE + Specifies a dot dot dash line underline. + +DOTTED_HEAVY_LINE + Specifies a dotted heavy line underline. + +DOTTED_LINE + Specifies a dotted line underline. + +DOUBLE_LINE + Specifies a double line underline. + +HEAVY_LINE + Specifies a heavy line underline. + +SINGLE_LINE + Specifies a single line underline. + +WAVY_DOUBLE_LINE + Specifies a wavy double line underline. + +WAVY_HEAVY_LINE + Specifies a wavy heavy line underline. + +WAVY_LINE + Specifies a wavy line underline. + +WORDS + Specifies underlining words. + +MIXED + Specifies a mixed of underline types. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoThemeColorIndex.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoThemeColorIndex.rst new file mode 100644 index 0000000000000000000000000000000000000000..f60518ceea3cd70fb7a5d34cd6f301c994e88442 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoThemeColorIndex.rst @@ -0,0 +1,72 @@ +.. _MsoThemeColorIndex: + +``MSO_THEME_COLOR_INDEX`` +========================= + +Indicates the Office theme color, one of those shown in the color gallery on +the formatting ribbon. + +Alias: ``MSO_THEME_COLOR`` + +Example:: + + from pptx.enum.dml import MSO_THEME_COLOR + + shape.fill.solid() + shape.fill.fore_color.theme_color == MSO_THEME_COLOR.ACCENT_1 + +---- + +NOT_THEME_COLOR + Indicates the color is not a theme color. + +ACCENT_1 + Specifies the Accent 1 theme color. + +ACCENT_2 + Specifies the Accent 2 theme color. + +ACCENT_3 + Specifies the Accent 3 theme color. + +ACCENT_4 + Specifies the Accent 4 theme color. + +ACCENT_5 + Specifies the Accent 5 theme color. + +ACCENT_6 + Specifies the Accent 6 theme color. + +BACKGROUND_1 + Specifies the Background 1 theme color. + +BACKGROUND_2 + Specifies the Background 2 theme color. + +DARK_1 + Specifies the Dark 1 theme color. + +DARK_2 + Specifies the Dark 2 theme color. + +FOLLOWED_HYPERLINK + Specifies the theme color for a clicked hyperlink. + +HYPERLINK + Specifies the theme color for a hyperlink. + +LIGHT_1 + Specifies the Light 1 theme color. + +LIGHT_2 + Specifies the Light 2 theme color. + +TEXT_1 + Specifies the Text 1 theme color. + +TEXT_2 + Specifies the Text 2 theme color. + +MIXED + Indicates multiple theme colors are used, such as in a group shape. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoVerticalAnchor.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoVerticalAnchor.rst new file mode 100644 index 0000000000000000000000000000000000000000..1469a4fbc28c57737e1fb9922afb26bc6d5a4e26 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/MsoVerticalAnchor.rst @@ -0,0 +1,36 @@ +.. _MsoVerticalAnchor: + +``MSO_VERTICAL_ANCHOR`` +======================= + +Specifies the vertical alignment of text in a text frame. Used with the +``.vertical_anchor`` property of the |TextFrame| object. Note that the +``vertical_anchor`` property can also have the value None, indicating +there is no directly specified vertical anchor setting and its effective +value is inherited from its placeholder if it has one or from the theme. +None may also be assigned to remove an explicitly specified vertical +anchor setting. + +Alias: ``MSO_ANCHOR`` + +Example:: + + from pptx.enum.text import MSO_ANCHOR + + cell = table.cell(row_idx=2, col_idx=3) + cell.vertical_anchor = MSO_ANCHOR.BOTTOM + +---- + +TOP + Aligns text to top of text frame and inherits its value from its layout + placeholder or theme. + +MIDDLE + Centers text vertically + +BOTTOM + Aligns text to bottom of text frame + +MIXED + Return value only; indicates a combination of the other states. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpActionType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpActionType.rst new file mode 100644 index 0000000000000000000000000000000000000000..cf043a2ca343ba9948cc74b9428e60192b058cb8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpActionType.rst @@ -0,0 +1,61 @@ +.. _PpActionType: + +``PP_ACTION_TYPE`` +================== + +Specifies the type of a mouse action (click or hover action). + +Alias: ``PP_ACTION`` + +Example:: + + from pptx.enum.action import PP_ACTION + + assert shape.click_action.action == PP_ACTION.HYPERLINK + +---- + +END_SHOW + Slide show ends. + +FIRST_SLIDE + Returns to the first slide. + +HYPERLINK + Hyperlink. + +LAST_SLIDE + Moves to the last slide. + +LAST_SLIDE_VIEWED + Moves to the last slide viewed. + +NAMED_SLIDE + Moves to slide specified by slide number. + +NAMED_SLIDE_SHOW + Runs the slideshow. + +NEXT_SLIDE + Moves to the next slide. + +NONE + No action is performed. + +OPEN_FILE + Opens the specified file. + +OLE_VERB + OLE Verb. + +PLAY + Begins the slideshow. + +PREVIOUS_SLIDE + Moves to the previous slide. + +RUN_MACRO + Runs a macro. + +RUN_PROGRAM + Runs a program. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpMediaType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpMediaType.rst new file mode 100644 index 0000000000000000000000000000000000000000..3019ef5afc88c88e76d5c650963dabea19b6eb7f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpMediaType.rst @@ -0,0 +1,27 @@ +.. _PpMediaType: + +``PP_MEDIA_TYPE`` +================= + +Indicates the OLE media type. + +Example:: + + from pptx.enum.shapes import PP_MEDIA_TYPE + + movie = slide.shapes[0] + assert movie.media_type == PP_MEDIA_TYPE.MOVIE + +---- + +MOVIE + Video media such as MP4. + +OTHER + Other media types + +SOUND + Audio media such as MP3. + +MIXED + Return value only; indicates multiple media types. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpParagraphAlignment.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpParagraphAlignment.rst new file mode 100644 index 0000000000000000000000000000000000000000..47944ca643c6cd689b61896bd8742f445c333101 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpParagraphAlignment.rst @@ -0,0 +1,44 @@ +.. _PpParagraphAlignment: + +``PP_PARAGRAPH_ALIGNMENT`` +========================== + +Specifies the horizontal alignment for one or more paragraphs. + +Alias: ``PP_ALIGN`` + +Example:: + + from pptx.enum.text import PP_ALIGN + + shape.paragraphs[0].alignment = PP_ALIGN.CENTER + +---- + +CENTER + Center align + +DISTRIBUTE + Evenly distributes e.g. Japanese characters from left to right within a + line + +JUSTIFY + Justified, i.e. each line both begins and ends at the margin with spacing + between words adjusted such that the line exactly fills the width of the + paragraph. + +JUSTIFY_LOW + Justify using a small amount of space between words. + +LEFT + Left aligned + +RIGHT + Right aligned + +THAI_DISTRIBUTE + Thai distributed + +MIXED + Return value only; indicates multiple paragraph alignments are present in + a set of paragraphs. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpPlaceholderType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpPlaceholderType.rst new file mode 100644 index 0000000000000000000000000000000000000000..f8ccf604e3a60f5285bf4ef0d170b5d7800cdd83 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/PpPlaceholderType.rst @@ -0,0 +1,74 @@ +.. _PpPlaceholderType: + +``PP_PLACEHOLDER_TYPE`` +======================= + +Specifies one of the 18 distinct types of placeholder. + +Alias: ``PP_PLACEHOLDER`` + +Example:: + + from pptx.enum.shapes import PP_PLACEHOLDER + + placeholder = slide.placeholders[0] + assert placeholder.type == PP_PLACEHOLDER.TITLE + +---- + +BITMAP + Bitmap + +BODY + Body + +CENTER_TITLE + Center Title + +CHART + Chart + +DATE + Date + +FOOTER + Footer + +HEADER + Header + +MEDIA_CLIP + Media Clip + +OBJECT + Object + +ORG_CHART + Organization Chart + +PICTURE + Picture + +SLIDE_NUMBER + Slide Number + +SUBTITLE + Subtitle + +TABLE + Table + +TITLE + Title + +VERTICAL_BODY + Vertical Body + +VERTICAL_OBJECT + Vertical Object + +VERTICAL_TITLE + Vertical Title + +MIXED + Return value only; multiple placeholders of differing types. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlAxisCrosses.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlAxisCrosses.rst new file mode 100644 index 0000000000000000000000000000000000000000..16a8e234022b47a48f996c1f7727a69b993754b3 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlAxisCrosses.rst @@ -0,0 +1,26 @@ +.. _XlAxisCrosses: + +``XL_AXIS_CROSSES`` +=================== + +Specifies the point on the specified axis where the other axis crosses. + +Example:: + + from pptx.enum.chart import XL_AXIS_CROSSES + + value_axis.crosses = XL_AXIS_CROSSES.MAXIMUM + +---- + +AUTOMATIC + The axis crossing point is set automatically, often at zero. + +CUSTOM + The `.crosses_at` property specifies the axis crossing point. + +MAXIMUM + The axis crosses at the maximum value. + +MINIMUM + The axis crosses at the minimum value. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlCategoryType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlCategoryType.rst new file mode 100644 index 0000000000000000000000000000000000000000..6404e5adc59ba50336d85844b132b9c8bff7b334 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlCategoryType.rst @@ -0,0 +1,24 @@ +.. _XlCategoryType: + +``XL_CATEGORY_TYPE`` +==================== + +Specifies the type of the category axis. + +Example:: + + from pptx.enum.chart import XL_CATEGORY_TYPE + + date_axis = chart.category_axis + assert date_axis.category_type == XL_CATEGORY_TYPE.TIME_SCALE + +---- + +AUTOMATIC_SCALE + The application controls the axis type. + +CATEGORY_SCALE + Axis groups data by an arbitrary set of categories + +TIME_SCALE + Axis groups data on a time scale of days, months, or years. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlChartType.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlChartType.rst new file mode 100644 index 0000000000000000000000000000000000000000..0470bf00818f46766b57c75219ef0dae3ced59b0 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlChartType.rst @@ -0,0 +1,233 @@ +.. _XlChartType: + +``XL_CHART_TYPE`` +================= + +Specifies the type of a chart. + +Example:: + + from pptx.enum.chart import XL_CHART_TYPE + + assert chart.chart_type == XL_CHART_TYPE.BAR_STACKED + +---- + +THREE_D_AREA + 3D Area. + +THREE_D_AREA_STACKED + 3D Stacked Area. + +THREE_D_AREA_STACKED_100 + 100% Stacked Area. + +THREE_D_BAR_CLUSTERED + 3D Clustered Bar. + +THREE_D_BAR_STACKED + 3D Stacked Bar. + +THREE_D_BAR_STACKED_100 + 3D 100% Stacked Bar. + +THREE_D_COLUMN + 3D Column. + +THREE_D_COLUMN_CLUSTERED + 3D Clustered Column. + +THREE_D_COLUMN_STACKED + 3D Stacked Column. + +THREE_D_COLUMN_STACKED_100 + 3D 100% Stacked Column. + +THREE_D_LINE + 3D Line. + +THREE_D_PIE + 3D Pie. + +THREE_D_PIE_EXPLODED + Exploded 3D Pie. + +AREA + Area + +AREA_STACKED + Stacked Area. + +AREA_STACKED_100 + 100% Stacked Area. + +BAR_CLUSTERED + Clustered Bar. + +BAR_OF_PIE + Bar of Pie. + +BAR_STACKED + Stacked Bar. + +BAR_STACKED_100 + 100% Stacked Bar. + +BUBBLE + Bubble. + +BUBBLE_THREE_D_EFFECT + Bubble with 3D effects. + +COLUMN_CLUSTERED + Clustered Column. + +COLUMN_STACKED + Stacked Column. + +COLUMN_STACKED_100 + 100% Stacked Column. + +CONE_BAR_CLUSTERED + Clustered Cone Bar. + +CONE_BAR_STACKED + Stacked Cone Bar. + +CONE_BAR_STACKED_100 + 100% Stacked Cone Bar. + +CONE_COL + 3D Cone Column. + +CONE_COL_CLUSTERED + Clustered Cone Column. + +CONE_COL_STACKED + Stacked Cone Column. + +CONE_COL_STACKED_100 + 100% Stacked Cone Column. + +CYLINDER_BAR_CLUSTERED + Clustered Cylinder Bar. + +CYLINDER_BAR_STACKED + Stacked Cylinder Bar. + +CYLINDER_BAR_STACKED_100 + 100% Stacked Cylinder Bar. + +CYLINDER_COL + 3D Cylinder Column. + +CYLINDER_COL_CLUSTERED + Clustered Cone Column. + +CYLINDER_COL_STACKED + Stacked Cone Column. + +CYLINDER_COL_STACKED_100 + 100% Stacked Cylinder Column. + +DOUGHNUT + Doughnut. + +DOUGHNUT_EXPLODED + Exploded Doughnut. + +LINE + Line. + +LINE_MARKERS + Line with Markers. + +LINE_MARKERS_STACKED + Stacked Line with Markers. + +LINE_MARKERS_STACKED_100 + 100% Stacked Line with Markers. + +LINE_STACKED + Stacked Line. + +LINE_STACKED_100 + 100% Stacked Line. + +PIE + Pie. + +PIE_EXPLODED + Exploded Pie. + +PIE_OF_PIE + Pie of Pie. + +PYRAMID_BAR_CLUSTERED + Clustered Pyramid Bar. + +PYRAMID_BAR_STACKED + Stacked Pyramid Bar. + +PYRAMID_BAR_STACKED_100 + 100% Stacked Pyramid Bar. + +PYRAMID_COL + 3D Pyramid Column. + +PYRAMID_COL_CLUSTERED + Clustered Pyramid Column. + +PYRAMID_COL_STACKED + Stacked Pyramid Column. + +PYRAMID_COL_STACKED_100 + 100% Stacked Pyramid Column. + +RADAR + Radar. + +RADAR_FILLED + Filled Radar. + +RADAR_MARKERS + Radar with Data Markers. + +STOCK_HLC + High-Low-Close. + +STOCK_OHLC + Open-High-Low-Close. + +STOCK_VHLC + Volume-High-Low-Close. + +STOCK_VOHLC + Volume-Open-High-Low-Close. + +SURFACE + 3D Surface. + +SURFACE_TOP_VIEW + Surface (Top View). + +SURFACE_TOP_VIEW_WIREFRAME + Surface (Top View wireframe). + +SURFACE_WIREFRAME + 3D Surface (wireframe). + +XY_SCATTER + Scatter. + +XY_SCATTER_LINES + Scatter with Lines. + +XY_SCATTER_LINES_NO_MARKERS + Scatter with Lines and No Data Markers. + +XY_SCATTER_SMOOTH + Scatter with Smoothed Lines. + +XY_SCATTER_SMOOTH_NO_MARKERS + Scatter with Smoothed Lines and No Data Markers. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlDataLabelPosition.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlDataLabelPosition.rst new file mode 100644 index 0000000000000000000000000000000000000000..8d72a8586166afef0ea52430a83e08403085112e --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlDataLabelPosition.rst @@ -0,0 +1,46 @@ +.. _XlDataLabelPosition: + +``XL_DATA_LABEL_POSITION`` +========================== + +Specifies where the data label is positioned. + +Example:: + + from pptx.enum.chart import XL_LABEL_POSITION + + data_labels = chart.plots[0].data_labels + data_labels.position = XL_LABEL_POSITION.OUTSIDE_END + +---- + +ABOVE + The data label is positioned above the data point. + +BELOW + The data label is positioned below the data point. + +BEST_FIT + Word sets the position of the data label. + +CENTER + The data label is centered on the data point or inside a bar or a pie + slice. + +INSIDE_BASE + The data label is positioned inside the data point at the bottom edge. + +INSIDE_END + The data label is positioned inside the data point at the top edge. + +LEFT + The data label is positioned to the left of the data point. + +MIXED + Data labels are in multiple positions. + +OUTSIDE_END + The data label is positioned outside the data point at the top edge. + +RIGHT + The data label is positioned to the right of the data point. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlLegendPosition.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlLegendPosition.rst new file mode 100644 index 0000000000000000000000000000000000000000..fb49eb989910b5f8c66405c21ad016015a6a24d4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlLegendPosition.rst @@ -0,0 +1,33 @@ +.. _XlLegendPosition: + +``XL_LEGEND_POSITION`` +====================== + +Specifies the position of the legend on a chart. + +Example:: + + from pptx.enum.chart import XL_LEGEND_POSITION + + chart.has_legend = True + chart.legend.position = XL_LEGEND_POSITION.BOTTOM + +---- + +BOTTOM + Below the chart. + +CORNER + In the upper-right corner of the chart border. + +CUSTOM + A custom position. + +LEFT + Left of the chart. + +RIGHT + Right of the chart. + +TOP + Above the chart. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlMarkerStyle.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlMarkerStyle.rst new file mode 100644 index 0000000000000000000000000000000000000000..99adde3c4d13a2c875f1aa0dcd30d5d0c90bff14 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlMarkerStyle.rst @@ -0,0 +1,51 @@ +.. _XlMarkerStyle: + +``XL_MARKER_STYLE`` +=================== + +Specifies the marker style for a point or series in a line chart, scatter +chart, or radar chart. + +Example:: + + from pptx.enum.chart import XL_MARKER_STYLE + + series.marker.style = XL_MARKER_STYLE.CIRCLE + +---- + +AUTOMATIC + Automatic markers + +CIRCLE + Circular markers + +DASH + Long bar markers + +DIAMOND + Diamond-shaped markers + +DOT + Short bar markers + +NONE + No markers + +PICTURE + Picture markers + +PLUS + Square markers with a plus sign + +SQUARE + Square markers + +STAR + Square markers with an asterisk + +TRIANGLE + Triangular markers + +X + Square markers with an X diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlTickLabelPosition.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlTickLabelPosition.rst new file mode 100644 index 0000000000000000000000000000000000000000..4d9e19d3dee78b89d06b8fdcd5657d852b258f88 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlTickLabelPosition.rst @@ -0,0 +1,27 @@ +.. _XlTickLabelPosition: + +``XL_TICK_LABEL_POSITION`` +========================== + +Specifies the position of tick-mark labels on a chart axis. + +Example:: + + from pptx.enum.chart import XL_TICK_LABEL_POSITION + + category_axis = chart.category_axis + category_axis.tick_label_position = XL_TICK_LABEL_POSITION.LOW + +---- + +HIGH + Top or right side of the chart. + +LOW + Bottom or left side of the chart. + +NEXT_TO_AXIS + Next to axis (where axis is not at either side of the chart). + +NONE + No tick labels. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlTickMark.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlTickMark.rst new file mode 100644 index 0000000000000000000000000000000000000000..29d2765899f6336267cc9993ae3cc81caa0ef8e6 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/XlTickMark.rst @@ -0,0 +1,26 @@ +.. _XlTickMark: + +``XL_TICK_MARK`` +================ + +Specifies a type of axis tick for a chart. + +Example:: + + from pptx.enum.chart import XL_TICK_MARK + + chart.value_axis.minor_tick_mark = XL_TICK_MARK.INSIDE + +---- + +CROSS + Tick mark crosses the axis + +INSIDE + Tick mark appears inside the axis + +NONE + No tick mark + +OUTSIDE + Tick mark appears outside the axis diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/index.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..e3c465c758e73a019d3fe7c9b98eec70a650cf0a --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/enum/index.rst @@ -0,0 +1,38 @@ + +Enumerations +============ + +Documentation for the various enumerations used for |pp| property settings +can be found here: + +.. toctree:: + :titlesonly: + + MsoAutoShapeType + MsoAutoSize + MsoColorType + MsoConnectorType + MsoFillType + MsoLanguageId + MsoLineDashStyle + MsoPatternType + MsoShapeType + MsoTextUnderlineType + MsoThemeColorIndex + MsoVerticalAnchor + + PpActionType + PpMediaType + PpParagraphAlignment + PpPlaceholderType + + XlAxisCrosses + XlCategoryType + XlChartType + XlDataLabelPosition + XlLegendPosition + XlMarkerStyle + XlTickLabelPosition + XlTickMark + + ExcelNumFormat diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/exc.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/exc.rst new file mode 100644 index 0000000000000000000000000000000000000000..6e30bd13dbb5711a7f88ddd17c3a2b35d9117231 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/exc.rst @@ -0,0 +1,9 @@ +.. _exceptions: + +Exceptions +========== + +.. automodule:: pptx.exc + :members: + :member-order: bysource + :undoc-members: diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/image.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/image.rst new file mode 100644 index 0000000000000000000000000000000000000000..5a986da40494c12b6af9f4aab236f3b15a25d6a5 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/image.rst @@ -0,0 +1,20 @@ +.. _image_api: + +Image +===== + +An image depicted in a |Picture| shape can be accessed using its +:attr:`~.Picture.image` property. The |Image| object provides access to +detailed properties of the image itself, including the bytes of the image +file itself. + + +|Image| objects +--------------- + +The |Image| object is encountered as the :attr:`~Picture.image` property of +|Picture|. + +.. autoclass:: pptx.parts.image.Image() + :members: + :exclude-members: from_blob, from_file diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/placeholders.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/placeholders.rst new file mode 100644 index 0000000000000000000000000000000000000000..d6839dbdf9765cdab3a37e031c0b4330b86951e5 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/placeholders.rst @@ -0,0 +1,99 @@ +.. _placeholder_api: + +Placeholders +============ + +The following classes represent placeholder shapes. A placeholder most +commonly appears on a slide, but also appears on a slide layout and a slide +master. The role of a master placeholder and layout placeholder differs from +that of a slide placeholder and these roles are reflected in the distinct +classes for each. + +There are a larger variety of slide placeholders to accomodate their more +complex and varied behaviors. + + +|MasterPlaceholder| objects +--------------------------- + +.. autoclass:: pptx.shapes.placeholder.MasterPlaceholder() + :members: + :exclude-members: + adjustments, get_or_add_ln, has_chart, has_table, idx, ln, orient, + part, ph_type, shape_type, sz + :inherited-members: + :undoc-members: + + +|LayoutPlaceholder| objects +--------------------------- + +.. autoclass:: pptx.shapes.placeholder.LayoutPlaceholder() + :members: + :undoc-members: + + +ChartPlaceholder objects +------------------------ + +.. autoclass:: pptx.shapes.placeholder.ChartPlaceholder() + :members: + :exclude-members: + has_chart, has_table, has_text_frame, part + :inherited-members: + :undoc-members: + + +PicturePlaceholder objects +-------------------------- + +.. autoclass:: pptx.shapes.placeholder.PicturePlaceholder() + :members: + :exclude-members: + has_chart, has_table, has_text_frame, part + :inherited-members: + :undoc-members: + + +TablePlaceholder objects +------------------------ + +.. autoclass:: pptx.shapes.placeholder.TablePlaceholder() + :members: + :inherited-members: + :exclude-members: + has_chart, has_table, has_text_frame, is_placeholder, + part + :undoc-members: + + +PlaceholderGraphicFrame objects +------------------------------- + +.. autoclass:: pptx.shapes.placeholder.PlaceholderGraphicFrame() + :members: + :inherited-members: + :exclude-members: + chart_part, has_text_frame, is_placeholder, part + :undoc-members: + + +PlaceholderPicture objects +-------------------------- + +.. autoclass:: pptx.shapes.placeholder.PlaceholderPicture() + :members: + :inherited-members: + :exclude-members: + get_or_add_ln, has_chart, has_table, has_text_frame, ln, + part + :undoc-members: + + +_PlaceholderFormat objects +-------------------------- + +.. autoclass:: pptx.shapes.base._PlaceholderFormat() + :members: + :inherited-members: + :undoc-members: diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/presentation.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/presentation.rst new file mode 100644 index 0000000000000000000000000000000000000000..86330c5b01068e08a0dcde0a5bfe0363f95503ab --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/presentation.rst @@ -0,0 +1,142 @@ + +Presentations +============= + +A presentation is opened using the :func:`Presentation` function, provided +directly by the :mod:`pptx` package:: + + from pptx import Presentation + + +This function returns a :class:`.Presentation` object which is the root of +a graph containing the components that constitute a presentation, e.g. +slides, shapes, etc. All existing presentation components are referenced by +traversing the graph and new objects are added to the graph by calling +a method on that object's container. Consequently, |pp| objects are generally +not constructed directly. + +Example:: + + # load a presentation + prs = Presentation(path_to_pptx_file) + + # get reference to first shape in first slide + sp = prs.slides[0].shapes[0] + + # add a picture shape to slide + pic = sld.shapes.add_picture(path, x, y, cx, cy) + + +|Presentation| function +----------------------- + +This function is the only reference that must be imported to work with +presentation files. Typical use interacts with many other classes, but there +is no need to construct them as they are accessed using a property or method +of their containing object. + +.. autofunction:: pptx.Presentation + + +|Presentation| objects +----------------------- + +.. autoclass:: pptx.presentation.Presentation() + :members: + :member-order: bysource + :exclude-members: part + :undoc-members: + + +|CoreProperties| objects +------------------------- + +Each |Presentation| object has a |CoreProperties| object accessed via its +:attr:`core_properties` attribute that provides read/write access to the +so-called *core properties* for the document. The core properties are author, +category, comments, content_status, created, identifier, keywords, language, +last_modified_by, last_printed, modified, revision, subject, title, and +version. + +Each property is one of three types, |str|, |datetime|, or |int|. String +properties are limited in length to 255 characters and return an empty string +('') if not set. Date properties are assigned and returned as |datetime| +objects without timezone, i.e. in UTC. Any timezone conversions are the +responsibility of the client. Date properties return |None| if not set. + +|pp| does not automatically set any of the document core properties other than +to add a core properties part to a presentation that doesn't have one (very +uncommon). If |pp| adds a core properties part, it contains default values for +the title, last_modified_by, revision, and modified properties. Client code +should change properties like revision and last_modified_by explicitly if that +behavior is desired. + +.. class:: pptx.opc.coreprops.CoreProperties + + .. attribute:: author + + *string* -- An entity primarily responsible for making the content of the + resource. + + .. attribute:: category + + *string* -- A categorization of the content of this package. Example + values might include: Resume, Letter, Financial Forecast, Proposal, + or Technical Presentation. + + .. attribute:: comments + + *string* -- An account of the content of the resource. + + .. attribute:: content_status + + *string* -- completion status of the document, e.g. 'draft' + + .. attribute:: created + + *datetime* -- time of intial creation of the document + + .. attribute:: identifier + + *string* -- An unambiguous reference to the resource within a given + context, e.g. ISBN. + + .. attribute:: keywords + + *string* -- descriptive words or short phrases likely to be used as + search terms for this document + + .. attribute:: language + + *string* -- language the document is written in + + .. attribute:: last_modified_by + + *string* -- name or other identifier (such as email address) of person + who last modified the document + + .. attribute:: last_printed + + *datetime* -- time the document was last printed + + .. attribute:: modified + + *datetime* -- time the document was last modified + + .. attribute:: revision + + *int* -- number of this revision, incremented by the PowerPoint® client + once each time the document is saved. Note however that the revision + number is not automatically incremented by |pp|. + + .. attribute:: subject + + *string* -- The topic of the content of the resource. + + .. attribute:: title + + *string* -- The name given to the resource. + + .. attribute:: version + + *string* -- free-form version string diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/shapes.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/shapes.rst new file mode 100644 index 0000000000000000000000000000000000000000..b02c2ee71a1fe8f27a6f25707c3e4a9c0d507568 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/shapes.rst @@ -0,0 +1,154 @@ +.. _shape_api: + +Shapes +====== + +The following classes provide access to the shapes that appear on a slide and +the collections that contain them. + + +|SlideShapes| objects +--------------------- + +The |SlideShapes| object is encountered as the :attr:`~BaseSlide.shapes` +property of |Slide|. + +.. autoclass:: pptx.shapes.shapetree.SlideShapes() + :members: + :inherited-members: + :exclude-members: clone_placeholder, clone_layout_placeholders, + ph_basename + + +|GroupShapes| objects +--------------------- + +The |GroupShapes| object is encountered as the :attr:`~GroupShape.shapes` +property of |GroupShape|. + +.. autoclass:: pptx.shapes.shapetree.GroupShapes() + :members: + :inherited-members: + :exclude-members: clone_placeholder, ph_basename + + +Shape objects in general +------------------------ + +The following properties and methods are common to all shapes. + +.. autoclass:: pptx.shapes.base.BaseShape() + :members: + :exclude-members: part + :member-order: bysource + :undoc-members: + + +|Shape| objects (AutoShapes) +---------------------------- + +The following properties and methods are defined for AutoShapes, which +include text boxes and placeholders. + +.. autoclass:: pptx.shapes.autoshape.Shape() + :members: + :exclude-members: get_or_add_ln, ln + :member-order: bysource + :undoc-members: + + +|AdjustmentCollection| objects +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +An AutoShape is distinctive in that it can have *adjustments*, represented in +the PowerPoint user interface as small yellow diamonds that each allow +a parameter of the shape, such as the angle of an arrowhead, to be adjusted. +The |AdjustmentCollection| object holds these adjustment values for an +AutoShape, each of which is an |Adjustment| instance. + +The |AdjustmentCollection| instance for an AutoShape is accessed using the +``Shape.adjustments`` property (read-only). + +.. autoclass:: pptx.shapes.autoshape.AdjustmentCollection + :members: + :member-order: bysource + :undoc-members: + + +|Adjustment| objects +~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: pptx.shapes.autoshape.Adjustment + :members: + :member-order: bysource + :undoc-members: + + +|Connector| objects +------------------- + +The following properties and methods are defined for Connector shapes: + +.. autoclass:: pptx.shapes.connector.Connector() + :members: + :member-order: bysource + :exclude-members: get_or_add_ln, ln + + +|FreeformBuilder| objects +------------------------- + +The following properties and methods are defined for FreeformBuilder objects. +A freeform builder is used to create a shape with custom geometry: + +.. autoclass:: pptx.shapes.freeform.FreeformBuilder() + :exclude-members: new, shape_offset_x, shape_offset_y + :members: + :member-order: bysource + :undoc-members: + + +``Picture`` objects +------------------- + +The following properties and methods are defined for picture shapes. + +.. autoclass:: pptx.shapes.picture.Picture() + :inherited-members: + :members: + :exclude-members: get_or_add_ln, ln + :member-order: bysource + + +|GraphicFrame| objects +---------------------- + +The following properties and methods are defined for graphic frame shapes. +A graphic frame is the shape containing a table, chart, or smart art. + +.. autoclass:: pptx.shapes.graphfrm.GraphicFrame() + :show-inheritance: + :members: + :exclude-members: + chart_part, has_text_frame, is_placeholder, part, placeholder_format, + shape_type + :inherited-members: + + +|GroupShape| objects +-------------------- + +The following properties and methods are defined for group shapes. A group +shape acts as a container for other shapes. + +Note that: + +* A group shape has no text frame and cannot have one. +* A group shape cannot have a click action, such as a hyperlink. + +.. autoclass:: pptx.shapes.group.GroupShape() + :show-inheritance: + :members: + :exclude-members: + has_chart, has_table, is_placeholder, placeholder_format + :inherited-members: diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/slides.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/slides.rst new file mode 100644 index 0000000000000000000000000000000000000000..1909ecd0898f88856857852f29431c0f5e280c61 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/slides.rst @@ -0,0 +1,110 @@ +.. _slides_api: + +Slides +====== + +|Slides| objects +----------------- + +The |Slides| object is accessed using the +:attr:`~pptx.presentation.Presentation.slides` property of |Presentation|. It +is not intended to be constructed directly. + +.. autoclass:: pptx.slide.Slides() + :members: + :member-order: bysource + :undoc-members: + + +|Slide| objects +--------------- + +An individual |Slide| object is accessed by index from |Slides| or as the +return value of :meth:`add_slide`. + +.. autoclass:: pptx.slide.Slide() + :members: + :exclude-members: part + :inherited-members: + :undoc-members: + + +|SlideLayouts| objects +---------------------- + +The |SlideLayouts| object is accessed using the +:attr:`~pptx.slide.SlideMaster.slide_layouts` property of |SlideMaster|, typically:: + + >>> from pptx import Presentation + >>> prs = Presentation() + >>> slide_layouts = prs.slide_master.slide_layouts + +As a convenience, since most presentations have only a single slide master, the +|SlideLayouts| collection for the first master may be accessed directly from the +|Presentation| object:: + + >>> slide_layouts = prs.slide_layouts + +This class is not intended to be constructed directly. + +.. autoclass:: pptx.slide.SlideLayouts() + :members: + :exclude-members: element, parent + :inherited-members: + :undoc-members: + + +|SlideLayout| objects +--------------------- + +.. autoclass:: pptx.slide.SlideLayout + :members: + :exclude-members: iter_cloneable_placeholders + + +|SlideMasters| objects +---------------------- + +The |SlideMasters| object is accessed using the +:attr:`~pptx.presentation.slide_masters` property of |Presentation|, typically:: + + >>> from pptx import Presentation + >>> prs = Presentation() + >>> slide_masters = prs.slide_masters + +As a convenience, since most presentations have only a single slide master, the +first master may be accessed directly from the |Presentation| object without indexing +the collection:: + + >>> slide_master = prs.slide_master + +This class is not intended to be constructed directly. + +.. autoclass:: pptx.slide.SlideMasters() + :members: + :exclude-members: element, parent + :inherited-members: + :undoc-members: + +|SlideMaster| objects +--------------------- + +.. autoclass:: pptx.slide.SlideMaster + :members: + :exclude-members: related_slide_layout, sldLayoutIdLst + + +|SlidePlaceholders| objects +--------------------------- + +.. autoclass:: pptx.shapes.shapetree.SlidePlaceholders + :members: + + +|NotesSlide| objects +-------------------- + +.. autoclass:: pptx.slide.NotesSlide + :members: + :exclude-members: clone_master_placeholders + :inherited-members: diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/table.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/table.rst new file mode 100644 index 0000000000000000000000000000000000000000..2a666e2467ab0a82165dfc2c3a61f5b13044440a --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/table.rst @@ -0,0 +1,54 @@ +.. _table_api: + +Table-related objects +===================== + + +.. currentmodule:: pptx.table + + +|Table| objects +---------------- + +A |Table| object is added to a slide using the +:meth:`~.SlideShapes.add_table` method on |SlideShapes|. + +.. autoclass:: Table() + :members: + :inherited-members: + :exclude-members: + notify_height_changed, notify_width_changed, part + :undoc-members: + + +|_Column| objects +----------------- + +.. autoclass:: _Column() + :members: + :member-order: bysource + :undoc-members: + + +|_Row| objects +-------------- + +.. autoclass:: _Row() + :members: + :member-order: bysource + :undoc-members: + + +|_Cell| objects +--------------- + +A |_Cell| object represents a single table cell at a particular row/column +location in the table. |_Cell| objects are not constructed directly. A +reference to a |_Cell| object is obtained using the :meth:`Table.cell` method, +specifying the cell's row/column location. A cell object can also be obtained +using the :attr:`_Row.cells` collection. + +.. autoclass:: _Cell + :members: + :member-order: bysource + :undoc-members: diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/text.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/text.rst new file mode 100644 index 0000000000000000000000000000000000000000..77427c605343d879be7f473cf2d8e878bf12b28b --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/text.rst @@ -0,0 +1,46 @@ +.. _text_api: + +Text-related objects +==================== + + +.. currentmodule:: pptx.text.text + + +|TextFrame| objects +-------------------- + +.. autoclass:: TextFrame() + :members: + :member-order: bysource + :undoc-members: + + +|Font| objects +-------------- + +The |Font| object is encountered as a property of |_Run|, |_Paragraph|, and in +future other presentation text objects. + +.. autoclass:: Font() + :members: + :member-order: bysource + :undoc-members: + + +|_Paragraph| objects +-------------------- + +.. autoclass:: _Paragraph() + :members: + :member-order: bysource + :undoc-members: + + +|_Run| objects +-------------- + +.. autoclass:: _Run() + :members: + :member-order: bysource + :undoc-members: diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/api/util.rst b/tasks/tasksmith-74f059424102/tests/source/docs/api/util.rst new file mode 100644 index 0000000000000000000000000000000000000000..827250b6d55ddf90359bcccbfa633083ea6b76df --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/api/util.rst @@ -0,0 +1,12 @@ +.. _util: + +:mod:`util` Module +------------------ + +.. automodule:: pptx.util + :members: + :exclude-members: Collection, lazyproperty, to_unicode + :member-order: bysource + :undoc-members: + :show-inheritance: + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/community/faq.rst b/tasks/tasksmith-74f059424102/tests/source/docs/community/faq.rst new file mode 100644 index 0000000000000000000000000000000000000000..d738b9cd855be34a087eeedfd6c0316d48d0ef13 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/community/faq.rst @@ -0,0 +1,2 @@ +Frequently Asked Questions +========================== diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/community/support.rst b/tasks/tasksmith-74f059424102/tests/source/docs/community/support.rst new file mode 100644 index 0000000000000000000000000000000000000000..c1ee90820ddf3a4cc272bb5c6db7d1e9ae5a0788 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/community/support.rst @@ -0,0 +1,16 @@ +Support +======= + +We'd love to hear from you if you like |pp|, want a new feature, find a bug, +need help using it, or just have a word of encouragement. + +The **mailing list** for |pp| is python-pptx@googlegroups.com + +The **issue tracker** is on github at `scanny/python-pptx`_. + +Feature requests are best broached initially on the mailing list, they can be +added to the issue tracker once we've clarified the best approach, +particularly the appropriate API signature. + +.. _`scanny/python-pptx`: + https://github.com/scanny/python-pptx diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/community/updates.rst b/tasks/tasksmith-74f059424102/tests/source/docs/community/updates.rst new file mode 100644 index 0000000000000000000000000000000000000000..c8be46faf463257459f4625a65c908bae2fbf461 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/community/updates.rst @@ -0,0 +1,7 @@ +.. _updates: + + +Software Updates +================ + +.. include:: ../../HISTORY.rst diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/conf.py b/tasks/tasksmith-74f059424102/tests/source/docs/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..536221211d361ab4308f5143a2a8df089bf4826f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/conf.py @@ -0,0 +1,575 @@ +# -*- coding: utf-8 -*- +# +# python-pptx documentation build configuration file, created by +# sphinx-quickstart on Thu Nov 29 13:59:35 2012. +# +# This file is execfile()d with the current directory set to its containing +# dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import os +import sys + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +from pptx import __version__ # noqa: E402 + + +# -- Allow nonlocal image URI's to accommodate travis-ci status image ------- + +import sphinx.environment # noqa: E402 +from docutils.utils import get_source_line # noqa: E402 + + +def _warn_node(self, msg, node, **kwargs): + if not msg.startswith("nonlocal image URI found:"): + self._warnfunc(msg, "%s:%s" % get_source_line(node), **kwargs) + + +sphinx.environment.BuildEnvironment.warn_node = _warn_node + + +# -- General configuration -------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.doctest", + "sphinx.ext.inheritance_diagram", + "sphinx.ext.intersphinx", + "sphinx.ext.todo", + "sphinx.ext.coverage", + "sphinx.ext.ifconfig", + "sphinx.ext.viewcode", +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix of source filenames. +source_suffix = ".rst" + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"python-pptx" +copyright = u"2012, 2013, Steve Canny" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = __version__ +# The full version, including alpha/beta/rc tags. +release = __version__ + +# A string of reStructuredText that will be included at the end of every source +# file that is read. This is the right place to add substitutions that should +# be available in every file. +rst_epilog = """ +.. |ActionSetting| replace:: :class:`.ActionSetting` + +.. |Adjustment| replace:: :class:`.Adjustment` + +.. |AdjustmentCollection| replace:: :class:`.AdjustmentCollection` + +.. |AreaSeries| replace:: :class:`.AreaSeries` + +.. |AttributeError| replace:: :exc:`.AttributeError` + +.. |Axis| replace:: :class:`.Axis` + +.. |AxisTitle| replace:: :class:`.AxisTitle` + +.. |_Background| replace:: :class:`._Background` + +.. |BarPlot| replace:: :class:`.BarPlot` + +.. |BarSeries| replace:: :class:`.BarSeries` + +.. |BaseFileSystem| replace:: :class:`BaseFileSystem` + +.. |_BaseMaster| replace:: :class:`._BaseMaster` + +.. |BasePlaceholder| replace:: :class:`.BasePlaceholder` + +.. |_BasePlot| replace:: :class:`._BasePlot` + +.. |BaseShape| replace:: :class:`.BaseShape` + +.. |BaseSlidePart| replace:: :class:`.BaseSlidePart` + +.. |BubbleChartData| replace:: :class:`.BubbleChartData` + +.. |BubblePlot| replace:: :class:`.BubblePlot` + +.. |BubblePoints| replace:: :class:`.BubblePoints` + +.. |BubbleSeries| replace:: :class:`.BubbleSeries` + +.. |BubbleSeriesData| replace:: :class:`.BubbleSeriesData` + +.. |category.Categories| replace:: :class:`~.category.Categories` + +.. |data.Categories| replace:: :class:`~.data.Categories` + +.. |category.Category| replace:: :class:`~.category.Category` + +.. |data.Category| replace:: :class:`~.data.Category` + +.. |CategoryAxis| replace:: :class:`.CategoryAxis` + +.. |CategoryChartData| replace:: :class:`.CategoryChartData` + +.. |CategoryLevel| replace:: :class:`.CategoryLevel` + +.. |CategoryPoints| replace:: :class:`.CategoryPoints` + +.. |_Cell| replace:: :class:`_Cell` + +.. |Chart| replace:: :class:`.Chart` + +.. |ChartData| replace:: :class:`.ChartData` + +.. |ChartFormat| replace:: :class:`.ChartFormat` + +.. |ChartPart| replace:: :class:`.ChartPart` + +.. |ChartTitle| replace:: :class:`.ChartTitle` + +.. |ChartXmlWriter| replace:: :class:`.ChartXmlWriter` + +.. |_Close| replace:: :class:`_Close` + +.. |Collection| replace:: :class:`Collection` + +.. |ColorFormat| replace:: :class:`.ColorFormat` + +.. |_Column| replace:: :class:`_Column` + +.. |_ColumnCollection| replace:: :class:`_ColumnCollection` + +.. |Connector| replace:: :class:`.Connector` + +.. |CoreProperties| replace:: :class:`.CoreProperties` + +.. |DataLabel| replace:: :class:`.DataLabel` + +.. |DataLabels| replace:: :class:`.DataLabels` + +.. |DateAxis| replace:: :class:`.DateAxis` + +.. |datetime| replace:: :class:`datetime.datetime` + +.. |DirectoryFileSystem| replace:: :class:`DirectoryFileSystem` + +.. |DrawingOperations| replace:: :class:`.DrawingOperations` + +.. |Emu| replace:: :class:`.Emu` + +.. |False| replace:: :class:`False` + +.. |FileSystem| replace:: :class:`FileSystem` + +.. |FillFormat| replace:: :class:`.FillFormat` + +.. |float| replace:: :class:`float` + +.. |Font| replace:: :class:`.Font` + +.. |FreeformBuilder| replace:: :class:`.FreeformBuilder` + +.. |GradientStops| replace:: :class:`.GradientStops` + +.. |GraphicFrame| replace:: :class:`.GraphicFrame` + +.. |GroupShape| replace:: :class:`.GroupShape` + +.. |GroupShapes| replace:: :class:`.GroupShapes` + +.. |_Hyperlink| replace:: :class:`._Hyperlink` + +.. |Hyperlink| replace:: :class:`.Hyperlink` + +.. |Image| replace:: :class:`.Image` + +.. |ImagePart| replace:: :class:`.ImagePart` + +.. |Inches| replace:: :class:`.Inches` + +.. |int| replace:: :class:`int` + +.. |InvalidXmlError| replace:: :exc:`InvalidXmlError` + +.. |KeyError| replace:: :exc:`KeyError` + +.. |LayoutPlaceholder| replace:: :class:`.LayoutPlaceholder` + +.. |LayoutPlaceholders| replace:: :class:`.LayoutPlaceholders` + +.. |LayoutShapes| replace:: :class:`.LayoutShapes` + +.. |Legend| replace:: :class:`.Legend` + +.. |Length| replace:: :class:`.Length` + +.. |LineFormat| replace:: :class:`.LineFormat` + +.. |_LineSegment| replace:: :class:`._LineSegment` + +.. |LineSeries| replace:: :class:`.LineSeries` + +.. |list| replace:: :class:`list` + +.. |MajorGridlines| replace:: :class:`.MajorGridlines` + +.. |Marker| replace:: :class:`.Marker` + +.. |MasterPlaceholder| replace:: :class:`.MasterPlaceholder` + +.. |MasterPlaceholders| replace:: :class:`.MasterPlaceholders` + +.. |MasterShapes| replace:: :class:`.MasterShapes` + +.. |_MediaFormat| replace:: :class:`._MediaFormat` + +.. |None| replace:: :class:`None` + +.. |NotesMaster| replace:: :class:`.NotesMaster` + +.. |NotesSlide| replace:: :class:`.NotesSlide` + +.. |NotesSlidePlaceholders| replace:: :class:`.NotesSlidePlaceholders` + +.. |NotesSlideShapes| replace:: :class:`.NotesSlideShapes` + +.. |NotImplementedError| replace:: :exc:`NotImplementedError` + +.. |OpcPackage| replace:: :class:`.OpcPackage` + +.. |Package| replace:: :class:`Package` + +.. |PackURI| replace:: :class:`.PackURI` + +.. |_Paragraph| replace:: :class:`_Paragraph` + +.. |Part| replace:: :class:`Part` + +.. |PartTypeSpec| replace:: :class:`PartTypeSpec` + +.. |Picture| replace:: :class:`.Picture` + +.. |PieSeries| replace:: :class:`.PieSeries` + +.. |_PlaceholderFormat| replace:: :class:`._PlaceholderFormat` + +.. |PlaceholderGraphicFrame| replace:: :class:`.PlaceholderGraphicFrame` + +.. |PlaceholderPicture| replace:: :class:`.PlaceholderPicture` + +.. |Plots| replace:: :class:`.Plots` + +.. |Point| replace:: :class:`.Point` + +.. |pp| replace:: `python-pptx` + +.. |Presentation| replace:: :class:`~pptx.presentation.Presentation` + +.. |PresentationPart| replace:: :class:`.PresentationPart` + +.. |Pt| replace:: :class:`.Pt` + +.. |RadarSeries| replace:: :class:`.RadarSeries` + +.. |_Relationship| replace:: :class:`._Relationship` + +.. |_Relationships| replace:: :class:`_Relationships` + +.. |RGBColor| replace:: :class:`.RGBColor` + +.. |_Row| replace:: :class:`_Row` + +.. |_RowCollection| replace:: :class:`_RowCollection` + +.. |_Run| replace:: :class:`_Run` + +.. |Series| replace:: :class:`.Series` + +.. |SeriesCollection| replace:: :class:`.SeriesCollection` + +.. |ShadowFormat| replace:: :class:`.ShadowFormat` + +.. |Shape| replace:: :class:`.Shape` + +.. |ShapeCollection| replace:: :class:`.ShapeCollection` + +.. |Slide| replace:: :class:`.Slide` + +.. |Slides| replace:: :class:`.Slides` + +.. |SlideLayout| replace:: :class:`.SlideLayout` + +.. |SlideLayouts| replace:: :class:`.SlideLayouts` + +.. |SlideLayoutPart| replace:: :class:`.SlideLayoutPart` + +.. |SlideMaster| replace:: :class:`.SlideMaster` + +.. |SlideMasters| replace:: :class:`.SlideMasters` + +.. |SlideMasterPart| replace:: :class:`.SlideMasterPart` + +.. |SlidePlaceholders| replace:: :class:`.SlidePlaceholders` + +.. |SlideShapes| replace:: :class:`.SlideShapes` + +.. |str| replace:: :class:`str` + +.. |Table| replace:: :class:`Table` + +.. |TextFrame| replace:: :class:`.TextFrame` + +.. |TickLabels| replace:: :class:`.TickLabels` + +.. |True| replace:: :class:`True` + +.. |TypeError| replace:: :exc:`TypeError` + +.. |ValueAxis| replace:: :class:`.ValueAxis` + +.. |ValueError| replace:: :exc:`ValueError` + +.. |WorkbookWriter| replace:: :class:`.WorkbookWriter` + +.. |XyChartData| replace:: :class:`.XyChartData` + +.. |XyPoints| replace:: :class:`.XyPoints` + +.. |XySeries| replace:: :class:`.XySeries` + +.. |XySeriesData| replace:: :class:`.XySeriesData` + +.. |ZipFileSystem| replace:: :class:`ZipFileSystem` +""" + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [".build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + + +# -- Options for HTML output ------------------------------------------------ + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "armstrong" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +html_theme_path = [".themes"] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +html_sidebars = { + "**": ["localtoc.html", "relations.html", "sidebarlinks.html", "searchbox.html"] +} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = "python-pptxdoc" + + +# -- Options for LaTeX output ----------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, +# documentclass [howto/manual]). +latex_documents = [ + ( + "index", + "python-pptx.tex", + u"python-pptx Documentation", + u"Steve Canny", + "manual", + ), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output ----------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ("index", "python-pptx", u"python-pptx Documentation", [u"Steve Canny"], 1) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output --------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + "index", + "python-pptx", + u"python-pptx Documentation", + u"Steve Canny", + "python-pptx", + "One line description of project.", + "Miscellaneous", + ), +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + + +# Example configuration for intersphinx: refer to the Python standard library. +# intersphinx_mapping = {'https://docs.python.org/': None} diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-access-xlsx.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-access-xlsx.rst new file mode 100644 index 0000000000000000000000000000000000000000..646b142851635a22d01905ba381832d841f3e401 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-access-xlsx.rst @@ -0,0 +1,137 @@ + +Chart - Embedded Worksheet +========================== + +The data for a chart in PowerPoint is stored in an embedded Excel +spreadsheet. + + +Spike approach +-------------- + +* [ ] driver with one blank slide, builder column chart single series. +* [ ] Can edit Excel data in resulting file +* [ ] resulting file has an embedded Excel package of expected name +* [ ] XML uses worksheet references, not just cached data + + +Proposed protocol +----------------- + +:: + + >>> graphic_frame = prs.slides[0].shapes[0] + >>> chart = graphic_frame.chart + >>> chart_data = chart.chart_data + >>> chart_data + + >>> chart_data.update_from_xlsx_stream(xlsx_stream) + + +MS API Protocol +--------------- + +:: + + >>> chart = prs.Slides(1).Shapes(1).Chart + >>> chart_data = chart.ChartData + >>> workbook = chart_data.Workbook + >>> worksheet = Workbook.Worksheets(1) + + +ChartData objects +~~~~~~~~~~~~~~~~~ + +BreakLink + Removes the link between the data for a chart and a Microsoft Excel + workbook. + +IsLinked + True if the data for the chart is linked to an external Microsoft Excel + workbook. Read-only Boolean. + +Workbook + Returns the workbook that contains the chart data associated with the + chart. Read-only Object. + + +XML specimens +------------- + +.. highlight:: xml + +simple column chart:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-add-chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-add-chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..e3242d65fcc5555cf3c9ef3ec3af6849bde7a3fb --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-add-chart.rst @@ -0,0 +1,176 @@ + +SlideShapes.add_chart() +======================= + +A chart is added to a slide similarly to adding any other shape. Note that +a chart is not itself a shape; the item returned by `.add_shape()` is +a |GraphicFrame| shape which contains a |Chart| object. The actual chart +object is accessed using the :attr:`chart` attribute on the graphic frame +that contains it. + +Adding a chart requires three items, a chart type, the position and size +desired, and a |ChartData| object specifying the categories and series values +for the new chart. + + +Protocol +-------- + +Creating a new chart:: + + >>> chart_data = ChartData() + >>> chart_data.categories = 'Foo', 'Bar' + >>> chart_data.add_series('Series 1', (1.2, 2.3)) + >>> chart_data.add_series('Series 2', (3.4, 4.5)) + + >>> x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4) + >>> graphic_frame = shapes.add_chart( + >>> XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data + >>> ) + >>> chart = graphicFrame.chart + + +Specimen XML +------------ + +.. highlight:: xml + +Chart in a graphic frame:: + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +A ```` element appears in a ``CT_GroupShape`` element, +typically a ```` (shape tree) element:: + + + + + + + + + + + + + + + + + + +Graphic frame-related elements:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-area-chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-area-chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..253328b04c2b6035e33656b98ff49e08c28f30f3 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-area-chart.rst @@ -0,0 +1,287 @@ + +Area Chart +========== + +The area chart is similar to a stacked line chart where the area between the +lines is filled in. + +XML specimens +------------- + +.. highlight:: xml + +XML for default Area chart:: + + + + + + + + + + + + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$6 + + m/d/yy + + + 37261.0 + + + 37262.0 + + + 37263.0 + + + 37264.0 + + + 37265.0 + + + + + + + Sheet1!$B$2:$B$6 + + General + + + 32.0 + + + 32.0 + + + 28.0 + + + 12.0 + + + 15.0 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + Sheet1!$A$2:$A$6 + + m/d/yy + + + 37261.0 + + + 37262.0 + + + 37263.0 + + + 37264.0 + + + 37265.0 + + + + + + + Sheet1!$C$2:$C$6 + + General + + + 12.0 + + + 12.0 + + + 12.0 + + + 21.0 + + + 28.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axes.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axes.rst new file mode 100644 index 0000000000000000000000000000000000000000..e9ab79eb8fdf50d5f74533bc9a1771ea89358419 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axes.rst @@ -0,0 +1,376 @@ + +Chart Axes +========== + +PowerPoint chart axes come in four varieties: category axis, value axis, date +axis, and series axis. A series axis only appears on a 3D chart and is also +known as its depth axis. + +A chart may have two category axes and/or two value axes. The second axis, if +there is one, is known as the *secondary category axis* or *secondary value +axis*. + +A category axis may appear as either the horizontal or vertical axis, +depending upon the chart type. Likewise for a value axis. + + +PowerPoint behavior +------------------- + +Reverse-order +~~~~~~~~~~~~~ + +Normally, categories appear left-to-right in the order specified and values appear +vertically in increasing order. This default ordering can be reversed when desired. + +One common case is for the categories in a "horizontal" bar-chart (as opposed to the +"vertical" column-chart). Because the value axis appears at the bottom, categories +appear from bottom-to-top on the categories axis. For many readers this is odd, perhaps +because we read top-to-bottom. + +The axis "direction" can be switched using the `Axis.reverse_order` property. This +controls the value of the `c:xAx/c:scaling/c:orientation{val=minMax|maxMin}` XML +element/attribute. The default is False. + +MS API protocol:: + + >>> axis = Chart.Axes(xlCategory) + >>> axis.ReversePlotOrder + False + >>> axis.ReversePlotOrder = True + >>> axis.ReversePlotOrder + True + +Proposed python-pptx protocol:: + + >>> axis = chart.category_axis + >>> axis.reverse_order + False + >>> axis.reverse_order = True + >>> axis.reverse_order + True + + +Tick label position +~~~~~~~~~~~~~~~~~~~ + +Proposed python-pptx protocol:: + + >>> axis.tick_label_position + XL_TICK_LABEL_POSITION.NEXT_TO_AXIS + >>> axis.tick_label_position = XL_TICK_LABEL_POSITION.LOW + >>> axis.tick_label_position + XL_TICK_LABEL_POSITION.LOW + +MS API protocol:: + + >>> axis.TickLabelPosition + xlTickLabelPositionNextToAxis + >>> axis.TickLabelPosition = xlTickLabelPositionLow + + c:catAx/c:tickLblPos{val=nextTo} + +Option "none" causes tick labels to be hidden. + +Default when no ```` element is present is nextTo. Same if +element is present with no ``val`` attribute. + + +TickLabels.number_format +~~~~~~~~~~~~~~~~~~~~~~~~ + +Proposed python-pptx protocol:: + + >>> tick_labels = axis.tick_labels + >>> tick_labels.number_format + 'General' + >>> tick_labels.number_format_is_linked + True + >>> tick_labels.number_format = '#,##0.00' + >>> tick_labels.number_format_is_linked = False + +Tick-mark label text for the category axis comes from the name of the +associated category in the chart. The default tick-mark label text for the +category axis is the number that indicates the position of the category +relative to the left end of this axis. To change the number of unlabeled tick +marks between tick-mark labels, you must change the TickLabelSpacing property +for the category axis. + +Tick-mark label text for the value axis is calculated based on the MajorUnit, +MinimumScale, and MaximumScale properties of the value axis. To change the +tick-mark label text for the value axis, you must change the values of these +properties. + +MS API protocol:: + + >>> tick_labels = axis.TickLabels + >>> tick_labels.NumberFormat + 'General' + >>> tick_labels.NumberFormatLinked + True + >>> tick_labels.NumberFormatLinked = False + >>> tick_labels.NumberFormat = "#,##0.00" + + # output of 1234.5678 is '1,234.57' + +When ``sourceLinked`` attribute is True, UI shows "General" number format +category regardless of contents of ``formatCode`` attribute. + +The ``sourceLinked`` attribute defaults to True when the ```` +element is present but that attribute is omitted. + +When the ```` element is not present, the behavior is as though the +element ```` was present. + +The default PowerPoint chart contains this numFmt element:: + + ````. + + +_BaseAxis.visible property +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +```` element + +* when delete element is absent, the default value is True +* when ``val`` attribute is absent, the default value is True + + +XML specimens +------------- + +.. highlight:: xml + +Example axis XML for a single-series line plot:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axis-has-gridlines.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axis-has-gridlines.rst new file mode 100644 index 0000000000000000000000000000000000000000..587f3ba1cf902f812daeed620d65d9fab31459e7 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axis-has-gridlines.rst @@ -0,0 +1,227 @@ + +Chart - BaseAxis.has_gridlines +============================== + +A chart axis can have gridlines that extend the axis tick marks across the +body of the plot area. Gridlines for major and minor tick marks can be +controlled separately. Both vertical and horizontal axes can have gridlines. + + +Candidate protocol +------------------ + +:: + + >>> value_axis = chart.value_axis + >>> value_axis.has_major_gridlines + False + >>> value_axis.has_major_gridlines = True + >>> value_axis.has_major_gridlines + True + >>> category_axis = chart.category_axis + >>> category_axis.has_minor_gridlines + False + >>> category_axis.has_minor_gridlines = True + >>> category_axis.has_minor_gridlines + True + +Can be implemented in BaseAxis since the controlling element appears in +``EG_AxShared``. + + +Microsoft API +------------- + +Axis.HasMajorGridlines + True if the axis has major gridlines. Read/write Boolean. + +Axis.HasMinorGridlines + True if the axis has minor gridlines. Read/write Boolean. + +Axis.MajorGridlines + Returns the major gridlines for the specified axis. Read-only Gridlines. + +Axis.MinorGridlines + Returns the minor gridlines for the specified axis. Read-only Gridlines. + +Gridlines.Border + +Gridlines.Format.Line + +Gridlines.Format.Shadow + + +PowerPoint behavior +------------------- + +* Turning gridlines on and off is controlled from the ribbon (on the Mac at + least) +* Each set of gridlines (horz/vert, major/minor) can be formatted + individually. +* The formatting dialog has panes for Line, Shadow, and Glow & Soft Edges + + +XML Semantics +------------- + +* Each axis can have a ```` and a ```` + element. +* The corresponding gridlines appear if the element is present and not if it + doesn't. +* Line formatting, like width and color, is specified in the child + ```` element. + + +XML specimens +------------- + +.. highlight:: xml + +Example axis XML for a single-series line plot:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axis-title.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axis-title.rst new file mode 100644 index 0000000000000000000000000000000000000000..14e046cb74d8241dd3c3f7e678ff3843704f3da0 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axis-title.rst @@ -0,0 +1,430 @@ +.. _AxisTitle: + + +Axis Title +========== + +A chart axis can have a title. Theoretically, the title text can be drawn +from a cell in the spreadsheet behind the chart; however, there is no +mechanism for specifying this from the PowerPoint 2011 UI (Mac) and there's +no mention of such a procedure I could find on search. So only the "manually +applied" axis title text will be discussed here, other than how to remove any +elements associated with "linked" text, however they may have gotten there. + +The title is a rich text container, and can contain arbitrary text with +arbitrary formatting (font, size, color, etc.). There is little but one thing +to distinquish an axis title from an independent text box; its position is +automatically adjusted by the chart to account for resizing and movement. + +An axis title is visible whenever present. The only way to "hide" it is to +delete it, along with its contents. + +Although it will not be supported, it appears that axis title text can be +specified in the XML as a cell reference in the Excel worksheet. This is +a so-called "linked" title, and in general, any constructive operations on +the axis title will remove any linked title present. + + +Proposed Scope +-------------- + +Completed +~~~~~~~~~ + +* Axis.has_title +* Axis.axis_title +* AxisTitle.has_text_frame +* AxisTitle.text_frame +* AxisTitle.format + +Pending +~~~~~~~ + +* AxisTitle.orientation (this may require text frame rotation) +* XL_ORIENTATION enumeration + + +Candidate protocol +------------------ + +Typical usage +~~~~~~~~~~~~~ + +I expect the most typical use is simply to set the text of the axis title:: + + >>> axis = shapes.add_chart(...).chart.value_axis + >>> axis.axis_title.text_frame.text = 'Foobar' + + +Axis title access +~~~~~~~~~~~~~~~~~~ + +``Axis.has_axis_title`` is used to non-destructively test for the presence of +an axis title and may also be used to add an axis title. + +An axis on a newly created chart has no axis title:: + + >>> axis = shapes.add_chart(...).chart.value_axis + >>> axis.has_title + False + +Assigning |True| to ``.has_title`` causes an empty axis title element to be +added along with its text frame elements (when not already present):: + + >>> axis.has_title = True + >>> axis.has_title + True + +``Axis.axis_title`` is used to access the ``AxisTitle`` object for an axis. +It will always return an ``AxisTitle`` object, but it may be destructive in +the sense that it adds an axis title if there is none:: + + >>> axis = shapes.add_chart(...).chart.value_axis + >>> axis.has_title + False + >>> axis.axis_title + + >>> axis.has_title + True + +Assigning |False| to ``.has_title`` removes the title element from the XML +along with its contents:: + + >>> axis.has_title = False + >>> axis.has_title + False + +Assigning |None| to ``Axis.axis_title`` has the same effect (not sure we'll +actually implement this as a priority):: + + >>> axis.has_title + True + >>> axis.axis_title = None + >>> axis.has_title + False + + +AxisTitle.text_frame +~~~~~~~~~~~~~~~~~~~~ + +According to the schema and the MS API, the ``AxisTitle`` object can contain +either a text frame or an Excel cell reference (````). However, the +only operation on the `c:strRef` element the library will support (for now +anyway) is to delete it when adding a text frame. + +A newly added axis title will already have a text frame, but for the sake of +completeness, ``AxisTitle.has_text_frame`` will allow the client to test for, +add, and remove an axis title text frame. Assigning |True| to +``.has_text_frame`` causes any Excel reference (````) element to be +removed and an empty text frame to be inserted. If a text frame is already +present, no changes are made:: + + >>> axis_title.has_text_frame + False + >>> axis_title.has_text_frame = True + >>> axis_title.has_text_frame + True + +The text frame can be accessed using ``AxisTitle.text_frame``. This call +always returns a text frame object, newly created if not already present:: + + >>> axis_title.has_text_frame + False + >>> axis_title.text_frame + + >>> axis_title.has_text_frame + True + + +AxisTitle.orientation +~~~~~~~~~~~~~~~~~~~~~ + +By default, the PowerPoint UI adds an axis title for a vertical axis at 90° +counterclockwise rotation. The MS API provides for rotation to be specified +as an integer number of degrees between -90 and 90. Positive angles are +interpreted as counterclockwise from the horizontal. Orientation can also be +specified as one of the members of the `XlOrientation` enumeration. The +enumeration includes values for horizontal, 90° (upward), -90° (downward), +and (vertically) stacked:: + + >>> axis = shapes.add_chart(...).chart.value_axis + >>> axis_title.orientation + 90 + >>> axis_title.orientation = XL_ORIENTATION.HORIZONTAL + >>> axis_title.orientation + 0 + + +MS API +-------------- + +Axis object +~~~~~~~~~~~ + +Axis.AxisTitle + Provides access to the AxisTitle object for this axis. + +Axis.HasTitle + Getting indicates presence of axis title. Setting ensures presence or + absence of axis title. + + +AxisTitle object +~~~~~~~~~~~~~~~~ + +AxisTitle.Format + Provides access to fill and line formatting. + +AxisTitle.FormulaLocal + Returns or sets the cell reference for the axis title text. + +AxisTitle.HorizontalAlignment + Not terrifically useful AFAICT unless title extends to multiple lines. + +AxisTitle.IncludeInLayout + Might not be available via UI; no such option present on PowerPoint 2011 + for Mac. + +AxisTitle.Orientation + An integer value from –90 to 90 degrees or one of the XlOrientation + constants. + +AxisTitle.Text + Returns or sets the axis title text. Setting removes any existing + directly-applied formatting, but not title-level formatting. + +AxisTitle.VerticalAlignment + Perhaps not terrifically useful since the textbox is automatically + positioned and sized, so no difference is visible in the typical cases. + + +PowerPoint UI Behaviors +----------------------- + +* To add an axis title from the PowerPoint UI: + + *Chart Layout (ribbon) > Axis Titles > Vertical Axis Title > Rotated Title* + +* The default title "Axis Title" appears when no text has been entered. + +* The default orientation of a vertical axis title inserted by the UI is + rotated 90 degrees counterclockwise. This is initially (before text is + present) implemented using the `c:txPr` element. That element is removed + when explicit title text is added. + + +XlOrientation Enumeration +------------------------- + +https://msdn.microsoft.com/en-us/library/office/ff746480.aspx + +xlDownward (-4170) + Text runs downward. + +xlHorizontal (-4128) + Text runs horizontally. + +xlUpward (-4171) + Text runs upward. + +xlVertical (-4166) + Text runs downward and is centered in the cell. + + +Specimen XML +------------ + +.. highlight:: xml + +Add axis title in UI (but don't set text):: + + + + + + + + + + + + + + + + + + + + + + + + +Edit text directly in UI. Note that `c:txPr` element is removed when text is +added:: + + + + + + + + + + + + + Foobar + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axis-unit.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axis-unit.rst new file mode 100644 index 0000000000000000000000000000000000000000..01c69ad7a751be615f946f428c93d721ae1f5c90 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-axis-unit.rst @@ -0,0 +1,160 @@ + +Chart - ValueAxis.major/minor_unit +================================== + +The value axis has major and minor divisions, corresponding to where tick +marks, tick labels, and gridlines appear, when present. How frequently these +appear is determined by the major/minor units setting, specified as +a floating point number of units to skip between divisions. These settings +may be specified explictly, or PowerPoint can determine a sensible default +based on the chart data. The latter setting is labeled 'Auto' in the UI. By +default, major and minor unit are both set to 'Auto' on new charts. + + +Candidate protocol +------------------ + +The properties ``ValueAxis.major_unit`` and ``ValueAxis.minor_unit`` are used +to access and change this setting. + +|None| is used as an out-of-band value to signify `Auto` behavior. No +separate boolean properties are required. + +:: + + >>> value_axis = chart.value_axis + >>> value_axis.major_unit + None + >>> value_axis.major_unit = 10 + >>> value_axis.major_unit + 10.0 + >>> value_axis.major_unit = -4.2 + Traceback ... + ValueError: must be positive numeric value + >>> value_axis.major_unit = None + >>> value_axis.major_unit + None + + +Microsoft API +------------- + +Axis.MajorUnit + Returns or sets the major units for the value axis. Read/write Double. + +Axis.MinorUnit + Returns or sets the minor units on the value axis. Read/write Double. + +Axis.MajorUnitIsAuto + True if PowerPoint calculates the major units for the value axis. + Read/write Boolean. + +Axis.MinorUnitIsAuto + True if PowerPoint calculates minor units for the value axis. Read/write + Boolean. + + +PowerPoint behavior +------------------- + +Major and minor unit values are viewed and changed using the `Scale` pane of +the `Format Axis` dialog. Checkboxes are used to set a value to `Auto`. +Changing the floating point value causes the `Auto` checkbox to turn off. + + +XML Semantics +------------- + +* Only a value axis axis or date axis can have a ```` or + a ```` element. +* `Auto` behavior is signified by having no element for that unit. + + +XML specimens +------------- + +.. highlight:: xml + +Example value axis XML having an override for major unit:: + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-bar-chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-bar-chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..9f9cd62c4981ab90de4adfce133c6bf97271058f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-bar-chart.rst @@ -0,0 +1,210 @@ + +Bar Chart +========= + +The bar chart is a fundamental plot type, used for both column and bar charts +by specifying the bar direction. It is also used for the clustered, stacked, +and stacked 100% varieties by specifying grouping and overlap. + + +Gap Width +--------- + +A gap appears between the bar or clustered bars for each category on a bar +chart. The default width for this gap is 150% of the bar width. It can be set +between 0 and 500% of the bar width. In the MS API this is set using the +property `ChartGroup.GapWidth`. + +Proposed protocol:: + + >>> assert isinstance(bar_plot, BarPlot) + >>> bar_plot.gap_width + 150 + >>> bar_plot.gap_width = 300 + >>> bar_plot.gap_width + 300 + >>> bar_plot.gap_width = 700 + ValueError: gap width must be in range 0-500 (percent) + + +Overlap +------- + +In a bar chart having two or more series, the bars for each category are +clustered together for ready comparison. By default, these bars are directly +adjacent to each other, visually "touching". + +The bars can be made to overlap each other or have a space between them using +the *overlap* property. Its values range between -100 and 100, representing +the percentage of the bar width by which to overlap adjacent bars. A setting +of -100 creates a gap of a full bar width and a setting of 100 causes all the +bars in a category to be superimposed. The default value is 0. + +Proposed protocol:: + + >>> bar_plot = chart.plots[0] + >>> assert isinstance(bar_plot, BarPlot) + >>> bar_plot.overlap + 0 + >>> bar_plot.overlap = -50 + >>> bar_plot.overlap + -50 + >>> bar_plot.overlap = 200 + ValueError: overlap must be in range -100..100 (percent) + + +XML specimens +------------- + +.. highlight:: xml + +Minimal working XML for a single-series column plot. Note this does not +reference values in a spreadsheet.:: + + + + + + + + + + + + + + + + Foo + + + + + + + + 4.3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-bubble-chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-bubble-chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..9ccfcba60c5fe290d367d510f0bd06e4cfbb04d0 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-bubble-chart.rst @@ -0,0 +1,375 @@ +.. _BubbleChart: + + +Bubble Chart +============ + +A bubble chart is an extension of an X-Y or scatter chart. Containing an +extra (third) series, the size of the bubble is proportional to the value in +the third series. + +The bubble is proportioned to its value by one of two methods selected by the +client: + +* Bubble *width* is proportional to value (linear) +* Bubble *area* is proportional to value (quadratic) + +By default, the scale of the bubbles is determined by setting the largest +bubble equal to a "default bubble size" equal to roughly 25% of the height or +width of the chart area, whichever is less. The default bubble size can be +scaled using a property setting to obtain proportionally larger or smaller +bubbles. + + +PowerPoint UI +------------- + +To create a bubble chart by hand in PowerPoint: + +1. Carts ribbon > Other > Bubble + +A three-row, three-column Excel worksheet opens and the default chart appears. + + +XML semantics +------------- + +* I think this is going to get into blank cells if multiple series are + required. Might be worth checking out how using NA() possibly differs as to + how it appears in the XML. + +* There is a single `c:ser` element. Inside are `c:xVal`, `c:yVal`, and + `c:bubbleSize`, each containing the set of points for that "series". + + +XML specimen +------------ + +.. highlight:: xml + +XML for default bubble chart:: + + + + + + + + + + + + + Sheet1!$B$1 + + + + Y-Value 1 + + + + + + + + Sheet1!$A$2:$A$4 + + General + + + 0.7 + + + 1.8 + + + 2.6 + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 2.7 + + + 3.2 + + + 0.8 + + + + + + + Sheet1!$C$2:$C$4 + + General + + + 10.0 + + + 4.0 + + + 8.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +MS API Protocol +--------------- + +.. highlight:: vb.net + +Create (unconventional) multi-series bubble chart in Excel:: + + If (selection.Columns.Count <> 4 Or selection.Rows.Count < 3) Then + MsgBox "Selection must have 4 columns and at least 2 rows" + Exit Sub + End If + + Dim bubbleChart As ChartObject + Set bubbleChart = ActiveSheet.ChartObjects.Add( + Left:=selection.Left, Width:=600, Top:=selection.Top, Height:=400 + ) + bubbleChart.chart.ChartType = xlBubble + Dim r As Integer + For r = 2 To selection.Rows.Count + With bubbleChart.chart.SeriesCollection.NewSeries + .Name = "=" & selection.Cells(r, 1).Address(External:=True) + .XValues = selection.Cells(r, 2).Address(External:=True) + .Values = selection.Cells(r, 3).Address(External:=True) + .BubbleSizes = selection.Cells(r, 4).Address(External:=True) + End With + Next + + bubbleChart.chart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis) + bubbleChart.chart.Axes(xlCategory, xlPrimary).AxisTitle.Text = "=" & selection.Cells(1, 2).Address(External:=True) + + bubbleChart.chart.SetElement (msoElementPrimaryValueAxisTitleRotated) + bubbleChart.chart.Axes(xlValue, xlPrimary).AxisTitle.Text = "=" & selection.Cells(1, 3).Address(External:=True) + + bubbleChart.chart.SetElement (msoElementPrimaryCategoryGridLinesMajor) + bubbleChart.chart.Axes(xlCategory).MinimumScale = 0 + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +Bubble chart elements:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +References +---------- + +* https://blogs.msdn.microsoft.com/tomholl/2011/03/27/creating-multi-series-bubble-charts-in-excel/ + +* http://peltiertech.com/Excel/ChartsHowTo/HowToBubble.html + +* http://peltiertech.com/Excel/Charts/ControlBubbleSizes.html diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-categories.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-categories.rst new file mode 100644 index 0000000000000000000000000000000000000000..e5b5b7912f2ce8d8516fe18f10dab8c77a60bb43 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-categories.rst @@ -0,0 +1,262 @@ +.. _cht-categories: + +Chart - Categories +================== + +* A category can be |None|, meaning the category exists, but there is no + label for it. + + + The string value of it can be '', since it needs to be a string. But the + .label value will be |None|. + +Caveats +------- + +* Categories are read from the first series in the plot. In all normal + situations I've ever encountered, all series have exactly the same set of + categories. + + I'm not sure why the category labels are redundantly applied to each series, + but the fact that they are leads me to believe I must be missing something; + I don't believe they would repeat them like that if there wasn't a situation + in which they could be different between two series in the same plot. + + Consequently, there might be some edge cases where this won't work quite as + expected. At the same time, I expect it will work exactly as expected for + 99.9% of the cases, maybe 99.99%. + +* Categories are not enforced to be strictly hierarchical. So if a higher-level + category "breaks" (gets a new value) without also a new value at the next + level, the results might be a little weird. Like changing from USA to Canada, + but leaving NY as the state (by leaving that cell blank). + + Basically, the meaning of a structure like this is ambiguous. PowerPoint + interprets it without error and python-pptx interprets it without error, but + the results might not exactly match up. PowerPoint seems to take the senior + category break and show the intermediate category as blank or 'None'. But + I suppose it could be interpreted as the senior category just splits + a subordinate one; it's open to some question. + + +Multilevel Categories +--------------------- + +A category chart can have more than one level of categories, where each +individual category is nested in a higher-level category. + +https://www.youtube.com/watch?v=KbyQpzA7fLo + + +Acceptance Tests +---------------- + +.. highlight:: cucumber + +cht-plot-props.feature:: + + Scenario: Get CategoryPlot.categories + Given a category plot + Then plot.categories is a Categories object + +cht-categories.feature:: + + Scenario: Categories.__len__() + Given a Categories object having 3 categories + Then len(categories) is 3 + + Scenario: Categories.__getitem__() + Given a Categories object having 3 categories + Then categories[2] is a Category object + + Scenario: Categories.__iter__() + Given a Categories object having 3 categories + Then iterating categories produces 3 Category objects + + Scenario: Categories.depth + Given a Categories object having 3 levels of categories + Then categories.depth is 3 + + Scenario: Categories.flattened + Given a Categories object having 3 levels of categories + Then categories.flattened is tuple of 3-tuples + +cht-category.feature:: + + Scenario: Category derives from string + Given a Category object + Then isinstance(category, str) is True + + +XML semantics +------------- + +* The hierarchy of the levels is indicated by their document order. + +* The scope of non-leaf category entries is indicated by the 'idx' attribute + value. A non-leaf category spans from the leaf node having the matching idx + to the last leaf node not contained in its subsequent sibling. + +* The idx value on each `` element identifies the element for possible + overrides, like manual positioning or deletion (hiding). It may also key it + to the values in the series and/or other items; the spec is silent on these + details. + +* I can't find a way to set the `c:noMultiLvlLbl` element truthy using the UI. + I suspect this is only an Excel option. + +* The `c:lvl` element does not appear when there is only a single level of + categories. Also in that case, a `c:strCache` element contains the `c:pt` + elements rather than a `c:multiLvlStrCache` element. + +Q. What behavior is produced by a truthy value in + `c:catAx/c:noMultiLvlLbl/@val` when there are multiple levels of categories + defined? + + + +XML specimens +------------- + +.. highlight:: xml + +Single-level categories (common case):: + + + + Sheet1!$A$2:$A$5 + + + + Category 1 + + + Category 2 + + + Category 3 + + + Category 4 + + + + + +Multi-level categories:: + + + + Sheet1!$C$1:$J$3 + + + + + county one + + + county two + + + county one + + + county two + + + county one + + + county two + + + country one + + + county two + + + + + city one + + + city two + + + city one + + + city two + + + + + UK + + + US + + + + + + + + + ... + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +A ```` element is a child of a ```` (series) element and is of +the ``CT_AxDataSource`` type:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-data.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-data.rst new file mode 100644 index 0000000000000000000000000000000000000000..fe516af2f3e27a33b64fb00fc51ef13aaabaede8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-data.rst @@ -0,0 +1,52 @@ + +Chart Data +========== + +The data behind a chart--its category labels and its series names and +values--turns out to be a pivotal object in both the construction of a new +chart and updating the data behind an existing chart. + +The first role of |ChartData| is to act as a data transfer object, allowing +the data for a chart to be accumulated over multiple calls such as +`.add_series()`. This avoids the need to assemble and send a complex nested +structure of primitives to method calls. + +In addition to this, |ChartData| also takes on the role of broker to +|ChartXmlWriter| and |WorkbookWriter| which know how to assemble the +```` XML and Excel workbook for a chart, respectively. This is +sensible because neither of these objects can operate without a chart data +instance to provide the data they need and doing so concentrates the coupling +to the latter two objects into one place. + + +Protocol +-------- + +A |ChartData| object is constructed directly as needed, and used for either +creating a new chart or for replacing the data behind an existing one. + +Creating a new chart:: + + >>> chart_data = ChartData() + >>> chart_data.categories = 'Foo', 'Bar' + >>> chart_data.add_series('Series 1', (1.2, 2.3)) + >>> chart_data.add_series('Series 2', (3.4, 4.5)) + + >>> x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4) + >>> graphic_frame = shapes.add_chart( + >>> XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data + >>> ) + >>> chart = graphicFrame.chart + +Changing the data behind an existing chart:: + + >>> chart_data = ChartData() + >>> chart_data.categories = 'Foobar', 'Barbaz', 'Bazfoo' + >>> chart_data.add_series('New Series 1', (5.6, 6.7, 7.8)) + >>> chart_data.add_series('New Series 2', (2.3, 3.4, 4.5)) + >>> chart_data.add_series('New Series 3', (8.9, 9.1, 1.2)) + + >>> chart.replace_data(chart_data) + +Note that the dimensions of the replacement data can differ from that of the +existing chart. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-overview.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-overview.rst new file mode 100644 index 0000000000000000000000000000000000000000..3e7465887573b7494259a7153eda72001f18696a --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-overview.rst @@ -0,0 +1,652 @@ + +Charts - Overview +================= + +Adding a new chart - steps and tests +------------------------------------ + +1. Analysis - add chart type page with schema for each new chart element and + see if there's anything distinctive about the chart type series + +2. feature/sld-add-chart .. add new chart types, steps/chart.py + +3. pptx/chart/xmlwriter.py add new type to ChartXmlWriter + +4. pptx/chart/xmlwriter.py add _AreaChartXmlWriter, one per new element type + +5. pptx/chart/series.py add AreaSeries, one per new element type + + +There are 73 different possible chart types, but only 16 distinct XML +chart-type elements. The implementation effort is largely proportional to the +number of new XML chart-type elements. + +Here is an accounting of the implementation status of the 73 chart types: + + +29 - supported for creation so far +++++++++++++++++++++++++++++++++++ + +areaChart +~~~~~~~~~ + +* AREA +* AREA_STACKED +* AREA_STACKED_100 + +barChart +~~~~~~~~ + +* BAR_CLUSTERED +* BAR_STACKED +* BAR_STACKED_100 +* COLUMN_CLUSTERED +* COLUMN_STACKED +* COLUMN_STACKED_100 + +bubbleChart +~~~~~~~~~~~ + +* BUBBLE +* BUBBLE_THREE_D_EFFECT + +doughnutChart +~~~~~~~~~~~~~ + +* DOUGHNUT +* DOUGHNUT_EXPLODED + +lineChart +~~~~~~~~~ + +* LINE +* LINE_MARKERS +* LINE_MARKERS_STACKED +* LINE_MARKERS_STACKED_100 +* LINE_STACKED +* LINE_STACKED_100 + +pieChart +~~~~~~~~ + +* PIE +* PIE_EXPLODED + +radarChart +~~~~~~~~~~ + +* RADAR +* RADAR_FILLED +* RADAR_MARKERS + +scatterChart +~~~~~~~~~~~~ + +* XY_SCATTER +* XY_SCATTER_LINES +* XY_SCATTER_LINES_NO_MARKERS +* XY_SCATTER_SMOOTH +* XY_SCATTER_SMOOTH_NO_MARKERS + +44 remaining: ++++++++++++++ + +area3DChart +~~~~~~~~~~~ + +* THREE_D_AREA +* THREE_D_AREA_STACKED +* THREE_D_AREA_STACKED_100 + +bar3DChart (28 types) +~~~~~~~~~~~~~~~~~~~~~ + +* THREE_D_BAR_CLUSTERED +* THREE_D_BAR_STACKED +* THREE_D_BAR_STACKED_100 +* THREE_D_COLUMN +* THREE_D_COLUMN_CLUSTERED +* THREE_D_COLUMN_STACKED +* THREE_D_COLUMN_STACKED_100 + +* CONE_BAR_CLUSTERED +* CONE_BAR_STACKED +* CONE_BAR_STACKED_100 +* CONE_COL +* CONE_COL_CLUSTERED +* CONE_COL_STACKED +* CONE_COL_STACKED_100 + +* CYLINDER_BAR_CLUSTERED +* CYLINDER_BAR_STACKED +* CYLINDER_BAR_STACKED_100 +* CYLINDER_COL +* CYLINDER_COL_CLUSTERED +* CYLINDER_COL_STACKED +* CYLINDER_COL_STACKED_100 + +* PYRAMID_BAR_CLUSTERED +* PYRAMID_BAR_STACKED +* PYRAMID_BAR_STACKED_100 +* PYRAMID_COL +* PYRAMID_COL_CLUSTERED +* PYRAMID_COL_STACKED +* PYRAMID_COL_STACKED_100 + +line3DChart +~~~~~~~~~~~ + +* THREE_D_LINE + +pie3DChart +~~~~~~~~~~ + +* THREE_D_PIE +* THREE_D_PIE_EXPLODED + +ofPieChart +~~~~~~~~~~ + +* BAR_OF_PIE +* PIE_OF_PIE + +stockChart +~~~~~~~~~~ + +* STOCK_HLC +* STOCK_OHLC +* STOCK_VHLC +* STOCK_VOHLC + +surfaceChart +~~~~~~~~~~~~ + +* SURFACE +* SURFACE_WIREFRAME + +surface3DChart +~~~~~~~~~~~~~~ + +* SURFACE_TOP_VIEW +* SURFACE_TOP_VIEW_WIREFRAME + + +Chart parts glossary +-------------------- + +**data point (point)** + An individual numeric value, represented by a bar, point, column, or pie + slice. + +**data series (series)** + A group of related data points. For example, the columns of a series will + all be the same color. + +**category axis (X axis)** + The horizontal axis of a two-dimensional or three-dimensional chart. + +**value axis (Y axis)** + The vertical axis of a two-dimensional or three-dimensional chart. + +**depth axis (Z axis)** + The front-to-back axis of a three-dimensional chart. + +**grid lines** + Horizontal or vertical lines that may be added to an axis to aid + comparison of a data point to an axis value. + +**legend** + A key that explains which data series each color or pattern represents. + +**floor** + The bottom of a three-dimensional chart. + +**walls** + The background of a chart. Three-dimensional charts have a back wall and + a side wall, which can be formatted separately. + +**data labels** + Numeric labels on each data point. A data label can represent the actual + value or a percentage. + +**axis title** + Explanatory text label associated with an axis + +**data table** + A optional tabular display within the *plot area* of the values on which + the chart is based. Not to be confused with the Excel worksheet holding + the chart values. + +**chart title** + A label explaining the overall purpose of the chart. + +**chart area** + Overall chart object, containing the chart and all its auxiliary pieces + such as legends and titles. + +**plot area** + Region of the chart area that contains the actual plots, bounded by but + not including the axes. May contain more than one plot, each with its own + distinct set of series. A plot is known as a *chart group* in the MS API. + +**axis** + ... may be either a *category axis* or a *value axis* ... on + a two-dimensional chart, either the horizontal (*x*) axis or the vertical + (*y*) axis. A 3-dimensional chart also has a depth (*z*) axis. Pie, + doughnut, and radar charts have a radial axis. + + How many axes do each of the different chart types have? + +**series categories** + ... + +**series values** + ... + + +Chart types +----------- + +* column + + - 2-D column + + + clustered column + + stacked column + + 100% stacked column + + - 3-D column + + + 3-D clustered column + + 3-D stacked column + + 3-D 100% stacked column + + 3-D column + + - cylinder + - cone + - pyramid + +* line + + + 2-D line + + 3-D line + +* pie + + + 2-D pie + + 3-D pie + +* bar + + + 2-D bar + + 3-D bar + + cylinder + + cone + + pyramid + +* area + +* scatter + +* other + + + stock (e.g. open-high-low-close) + + surface + + doughnut + + bubble + + radar + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-shape.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-shape.rst new file mode 100644 index 0000000000000000000000000000000000000000..54872cb9f29aa0f2ad3d6c613008fcc1b3ff6638 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-shape.rst @@ -0,0 +1,57 @@ + +Chart Shape +=========== + +A chart is not actually a shape. It is a graphical object held inside +a graphics frame. The graphics frame is a shape and the chart must be +retrieved from it. + + +Protocol +-------- + +:: + + >>> shape = shapes.add_textbox(0, 0, 0, 0) + >>> shape.has_chart + False + >>> shape.chart + ... + AttributeError: 'Shape' object has no attribute 'chart' + >>> shape = shapes.add_chart(style, type, x, y, cx, cy) + >>> type(shape) + + >>> shape.has_chart + True + >>> shape.chart + + + +Acceptance tests +---------------- + +:: + + Feature: Access chart object + In order to operate on a chart in a presentation + As a developer using python-pptx + I need a way to find and access a chart + + Scenario Outline: Identify a shape containing a chart + Given a + Then the shape a chart + + Examples: Shape types + | shape type | has? | + | shape | does not have | + | graphic frame containing a chart | has | + | picture | does not have | + | graphic frame containing a table | does not have | + | group shape | does not have | + | connector | does not have | + + + Scenario: Access chart object from graphic frame shape + Given a graphic frame containing a chart + When I get the chart from its graphic frame + Then the chart is a ChartPart object diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-title.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-title.rst new file mode 100644 index 0000000000000000000000000000000000000000..5f9b7000d0c9038374ff73f7da0602776da78031 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-title.rst @@ -0,0 +1,228 @@ +.. _ChartTitle: + + +Chart - Chart Title +=================== + +A chart can have a title. The title is a rich text container, and can contain +arbitrary text with arbitrary formatting (font, size, color, etc.). There is +little but one thing to distinquish a chart title from an independent text +box; its position is automatically adjusted by the chart to account for +resizing and movement. + +A title is visible whenever present. The only way to "hide" it is to delete +it, along with its contents. + +Although it will not yet be supported, the chart title can be specified in +the XML as a cell reference in the Excel worksheet. In general, any +constructive operations on the title will remove this. + + +Proposed Scope +-------------- + +* Chart.has_title +* Chart.chart_title +* ChartTitle.has_text_frame +* ChartTitle.text_frame +* ChartTitle.format + + +Candidate protocol +------------------ + +Chart title presence +~~~~~~~~~~~~~~~~~~~~ + +The presence of a chart title is reported by ``Chart.has_title``. Reading +this property is non-destructive. Starting with a newly-created chart, which +has no title:: + + >>> chart = shapes.add_chart(...).chart + >>> chart.has_title + False + +Assigning |True| to ``.has_title`` causes an empty title element to be added +along with its text frame elements (when not already present). This +assignment is idempotent, such that assigning |True| when a chart title is +present leaves the chart unchanged:: + + >>> chart.has_title = True + >>> chart.has_title + True + +Assigning |False| to ``.has_title`` removes the title element from the XML +along with its contents. This assignment is also idempotent:: + + >>> chart.has_title = False + >>> chart.has_title + False + + +Chart title access +~~~~~~~~~~~~~~~~~~ + +Access to the chart title is provided by ``Chart.chart_title``. This property +always provides a |ChartTitle| object; a new one is created if not present. +This behavior produces cleaner code for the common "get or add" case; +``Chart.has_title`` is provided to avoid this potentially destructive +behavior when required:: + + >>> chart = shapes.add_chart(...).chart + >>> chart.has_title + False + >>> chart.chart_title + + >>> chart.has_title + True + + +ChartTitle.text_frame +~~~~~~~~~~~~~~~~~~~~~ + +The ``ChartTitle`` object can contain either a text frame or an Excel cell +reference (````). However, the only operation on the `c:strRef` +element the library will support (for now anyway) is to delete it when adding +a text frame. + +``ChartTitle.has_text_frame`` is used to determine whether a text +frame is present. Assigning |True| to ``.has_text_frame`` causes any Excel +reference to be removed and an empty text frame to be inserted. If a text +frame is already present, no changes are made:: + + >>> chart_title.has_text_frame + False + >>> chart_title.has_text_frame = True + >>> chart_title.has_text_frame + True + +Assigning |False| to ``.has_text_frame`` removes the text frame element from +the XML along with its contents. This assignment is also idempotent:: + + >>> chart.has_text_frame = False + >>> chart.has_text_frame + False + +The text frame can be accessed using ``ChartTitle.text_frame``. This property +always provides a |TextFrame| object; one is added if not present and any +``c:strRef`` element is removed:: + + >>> chart.has_text_frame + False + >>> chart_title.text_frame + + >>> chart.has_text_frame + True + + +XML semantics +------------- + +* ``c:autoTitleDeleted`` set True has no effect on the visibility of a default + chart title (no actual text, 'placeholder' display: 'Chart Title'. It also + seems to have no effect on an actual title, having a text frame and actual + text. + + +XML specimens +------------- + +.. highlight:: xml + +Default when clicking *Chart Title > Title Above Chart* from ribbon (before +changing the text of the title):: + + + + + + + + + ... + + + +Text 'Foobar' typed into chart title just after adding it from ribbon:: + + + + + + + + + + + + + Foobar + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-type.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-type.rst new file mode 100644 index 0000000000000000000000000000000000000000..910b93ca3928ba0a8398bf300a4baece31960e17 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart-type.rst @@ -0,0 +1,438 @@ + +Chart - Chart Type +================== + +There are 73 distinct chart types supported by PowerPoint. + +These are implemented with 16 distinct elements (e.g. c:bar3DChart). Within +an element tag name, they are further differentiated by child elements and +attributes such as c:grouping and c:shape. + +These differentiators are summaried below. + + +c:areaChart +----------- + +* ./c:grouping{val=stacked} => AREA_STACKED +* ./c:grouping{val=percentStacked} => AREA_STACKED_100 +* ./c:grouping{val=standard} => AREA +* . => AREA + + +c:area3DChart +------------- + +* ./c:grouping{val=stacked} => THREE_D_AREA_STACKED +* ./c:grouping{val=percentStacked} => THREE_D_AREA_STACKED_100 +* ./c:grouping{val=standard} => THREE_D_AREA +* . => THREE_D_AREA + + +c:barChart +---------- + +* ./c:barDir{val=bar} + + + ./c:grouping{val=clustered} => BAR_CLUSTERED + + ./c:grouping{val=stacked} => BAR_STACKED + + ./c:grouping{val=percentStacked} => BAR_STACKED_100 + +* ./c:barDir{val=col} + + + ./c:grouping{val=clustered} => COLUMN_CLUSTERED + + ./c:grouping{val=stacked} => COLUMN_STACKED + + ./c:grouping{val=percentStacked} => COLUMN_STACKED_100 + + +c:bar3DChart +------------ + +* ./c:barDir{val=bar} + + + ./c:grouping{val=clustered} + + - ./c:shape{val=box} => THREE_D_BAR_CLUSTERED + - ./c:shape{val=cone} => CONE_BAR_CLUSTERED + - ./c:shape{val=cylinder} => CYLINDER_BAR_CLUSTERED + - ./c:shape{val=pyramid} => PYRAMID_BAR_CLUSTERED + + + ./c:grouping{val=stacked} + + - ./c:shape{val=box} => THREE_D_BAR_STACKED + - ./c:shape{val=cone} => CONE_BAR_STACKED + - ./c:shape{val=cylinder} => CYLINDER_BAR_STACKED + - ./c:shape{val=pyramid} => PYRAMID_BAR_STACKED + + + ./c:grouping{val=percentStacked} + + - ./c:shape{val=box} => THREE_D_BAR_STACKED_100 + - ./c:shape{val=cone} => CONE_BAR_STACKED_100 + - ./c:shape{val=cylinder} => CYLINDER_BAR_STACKED_100 + - ./c:shape{val=pyramid} => PYRAMID_BAR_STACKED_100 + +* ./c:barDir{val=col} + + + ./c:grouping{val=clustered} + + - ./c:shape{val=box} => THREE_D_COLUMN_CLUSTERED + - ./c:shape{val=cone} => CONE_COL_CLUSTERED + - ./c:shape{val=cylinder} => CYLINDER_COL_CLUSTERED + - ./c:shape{val=pyramid} => PYRAMID_COL_CLUSTERED + + + ./c:grouping{val=stacked} + + - ./c:shape{val=box} => THREE_D_COLUMN_STACKED + - ./c:shape{val=cone} => CONE_COL_STACKED + - ./c:shape{val=cylinder} => CYLINDER_COL_STACKED + - ./c:shape{val=pyramid} => PYRAMID_COL_STACKED + + + ./c:grouping{val=percentStacked} + + - ./c:shape{val=box} => THREE_D_COLUMN_STACKED_100 + - ./c:shape{val=cone} => CONE_COL_STACKED_100 + - ./c:shape{val=cylinder} => CYLINDER_COL_STACKED_100 + - ./c:shape{val=pyramid} => PYRAMID_COL_STACKED_100 + + + ./c:grouping{val=standard} + + - ./c:shape{val=box} => THREE_D_COLUMN + - ./c:shape{val=cone} => CONE_COL + - ./c:shape{val=cylinder} => CYLINDER_COL + - ./c:shape{val=pyramid} => PYRAMID_COL + + +c:bubbleChart +------------- + +* ./c:bubble3D{val=0} => BUBBLE +* ./c:bubble3D{val=1} => BUBBLE_THREE_D_EFFECT + + +c:doughnutChart +--------------- + +* . => DOUGHNUT +* ./c:ser/c:explosion{val>0} => DOUGHNUT_EXPLODED + + +c:lineChart +----------- + +* ./c:grouping{val=standard} + + + ./c:ser/c:marker/c:symbol{val=none} => LINE + + ./c:marker{val=1} => LINE_MARKERS + +* ./c:grouping{val=stacked} + + + ./c:marker{val=1} => LINE_MARKERS_STACKED + + ./c:ser/c:marker/c:symbol{val=none} => LINE_STACKED + +* ./c:grouping{val=percentStacked} + + + ./c:marker{val=1} => LINE_MARKERS_STACKED_100 + + ./c:ser/c:marker/c:symbol{val=none} => LINE_STACKED_100 + + +c:line3DChart +------------- + +* . => THREE_D_LINE + + +c:ofPieChart +------------ + +* ./c:ofPieType{val=bar} => BAR_OF_PIE +* ./c:ofPieType{val=pie} => PIE_OF_PIE + + +c:pieChart +---------- + +* . => PIE +* ./c:ser/c:explosion{val>0} => PIE_EXPLODED + + +c:pie3DChart +------------ + +* . => THREE_D_PIE +* ./c:ser/c:explosion{val>0} => THREE_D_PIE_EXPLODED + + +c:radarChart +------------ + +* ./c:radarStyle{val=standard} => RADAR +* ./c:radarStyle{val=filled} => RADAR_FILLED +* ./c:radarStyle{val=marker} => RADAR_MARKERS + + +c:scatterChart +-------------- + +* ./c:scatterStyle{val=lineMarker} => XY_SCATTER +* has to do with ./c:ser/c:spPr/a:ln/a:noFill +* ./c:scatterStyle{val=lineMarker} => XY_SCATTER_LINES +* ./c:scatterStyle{val=line} => XY_SCATTER_LINES_NO_MARKERS +* ./c:scatterStyle{val=smoothMarker} => XY_SCATTER_SMOOTH +* ./c:scatterStyle{val=smooth} => XY_SCATTER_SMOOTH_NO_MARKERS +* check all these to verify + + +c:stockChart +------------ + +* ./? => STOCK_HLC +* ./? => STOCK_OHLC +* ./? => STOCK_VHLC +* ./? => STOCK_VOHLC +* possibly related to 3 vs. 4 series. VOHLC has a second plot and axis for + volume + + +c:surface3DChart +---------------- + +* ./c:wireframe{val=0} => SURFACE_TOP_VIEW +* ./c:wireframe{val=1} => SURFACE_TOP_VIEW_WIREFRAME + + +c:surfaceChart +-------------- + +* ./c:wireframe{val=0} => SURFACE +* ./c:wireframe{val=1} => SURFACE_WIREFRAME + + +XML specimens +------------- + +.. highlight:: xml + +:: + + + + + + + + ... + ... + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..1d55c7056b27c56ecc199acf31d2709a371c54c7 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-chart.rst @@ -0,0 +1,115 @@ +.. _Chart: + +Chart - Main Chart Object +========================= + +Each chart is contained in its own part like `chart1.xml`. + + +`Chart.font` +------------ + +By default, a new chart appears with an 18-point font that is applied to its +axes, the legend, tick labels, etc. The size, color, etc. can be specified +for the chart as a whole by settings attributes on +`/c:chartSpace/c:txPr/a:p/a:pPr/a:defRPr`. + +.. highlight:: xml + + +XML Specimens +------------- + +Default `c:txPr` element:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-data-labels.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-data-labels.rst new file mode 100644 index 0000000000000000000000000000000000000000..b4541a2e2d8a687cba355e27ddfe6dc2a4be7ad4 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-data-labels.rst @@ -0,0 +1,381 @@ + +Chart - Data Labels +=================== + +On a PowerPoint chart, data points may be labeled as an aid to readers. +Typically, the label is the value of the data point, but a data label may +have any combination of its series name, category name, and value. A number +format may also be applied to the value displayed. + + +Object access +------------- + +The `DataLabels` object is not a collection of `DataLabel` objects. +`DataLabels` controls the formatting of the data labels for a whole series, +so "global" settings in a way of thinking. An individual `DataLabel` object +is accessed using it's associated `Point` object:: + + data_label = chart.plot[0].series[0].points[0].data_label + +The two object types share many attributes. + + +DataLabel.font +-------------- + +Proposed protocol:: + + >>> font = data_label.font + >>> font.color.rgb = RGBColor(0x3C, 0xEB, 0x27) + + +Position +-------- + +There are nine choices for where a data label may be positioned relative to +its data point marker, although the available options depend on the chart +type. The options are specified using the :ref:`XlDataLabelPosition` +enumeration. + +**XML Semantics.** The default position when no ```` element is +present (common) depends on the chart type: + ++------------------------------+-------------+ +| barChart (clustered) | OUTSIDE_END | ++------------------------------+-------------+ +| bar3DChart (clustered) | OUTSIDE_END | ++------------------------------+-------------+ +| barChart (stacked) | CENTER | ++------------------------------+-------------+ +| barChart (percent stacked) | CENTER | ++------------------------------+-------------+ +| bar3DChart (stacked) | CENTER | ++------------------------------+-------------+ +| bar3DChart (percent stacked) | CENTER | ++------------------------------+-------------+ +| pieChart | BEST_FIT | ++------------------------------+-------------+ +| pie3DChart | BEST_FIT | ++------------------------------+-------------+ +| ofPieChart | BEST_FIT | ++------------------------------+-------------+ +| areaChart | CENTER | ++------------------------------+-------------+ +| area3DChart | CENTER | ++------------------------------+-------------+ +| doughnutChart | CENTER | ++------------------------------+-------------+ +| radarChart | OUTSIDE_END | ++------------------------------+-------------+ +| all others | RIGHT | ++------------------------------+-------------+ + +http://msdn.microsoft.com/en-us/library/ff535061(v=office.12).aspx + +Proposed protocol:: + + >>> data_labels = plot.data_labels + >>> data_labels.position + OUTSIDE_END (2) + >>> data_labels.position = XL_DATA_LABEL_POSITION.INSIDE_END + >>> data_labels.position + INSIDE_END (3) + + +MS API +------ + +The following properties from the MS API DataLabel object are of most +interest: + +Delete() + Deletes the DataLabel object, which might be useful for "undoing" data + label overrides and restoring inherited behaviors. + +AutoText + True if the object automatically generates appropriate text based on + context. Read/write Boolean. + +Caption + Returns or sets the data label text. Read/write String. + +Format + Returns the line, fill, and effect formatting for the object. Read-only + ChartFormat. + +NumberFormat + Returns or sets the format code for the object. Read/write String. + +NumberFormatLinked + True if the number format is linked to the cells (so that the number + format changes in the labels when it changes in the cells). Read/write + Boolean. + +Orientation + Returns or sets the text orientation. Read/write Long in range -90 to 90 + (degrees). + +Position + Returns or sets the position of the data label. Read/write + XlDataLabelPosition. + +Separator + Returns or sets the separator used for the data labels on a chart. Used + when more than one value is shown, like category+value. Read/write + Variant. + +Shadow + Returns or sets a value that indicates whether the object has a shadow. + Read/write Boolean. + +ShowBubbleSize + True to show the bubble size for the data labels on a chart. False to + hide the bubble size. Read/write Boolean. + +ShowCategoryName + True to display the category name for the data labels on a chart. False + to hide the category name. Read/write Boolean. + +ShowLegendKey + True if the data label legend key is visible. This is a small square of + the series color shown in the legend, and appears adjacent to the data + label. Read/write Boolean. + +ShowPercentage + True to display the percentage value for the data labels on a chart. + False to hide the value. This might only be relevant for pie charts and + similar. Read/write Boolean. + +ShowSeriesName + True to show the series name for the data labels on a chart. False to + hide the series name. Read/write Boolean. + +ShowValue + True to display a specified chart's data label values. False to hide the + values. Read/write Boolean. + +Text + Returns or sets the text for the specified object. Read/write String. + +VerticalAlignment + Returns or sets the vertical alignment of the specified object. + Read/write Variant. + + +PowerPoint behavior +------------------- + +* A default PowerPoint bar chart does not display data labels, but it does + have a ```` child element on its ```` element. + +* Data labels are added to a chart in the UI by selecting the *Data Labels* + drop-down menu in the Chart Layout ribbon. The options include setting the + contents of the data label, its position relative to the point, and + bringing up the *Format Data Labels* dialog. + +* The default number format, when no ```` child element appears, is + equivalent to ```` + + +XML Semantics +------------- + +* A ```` element at the plot level (e.g. ````) is + overridden completely by a ```` element at the series level. + Unless overridden, a ```` element at the plot level determines the + content and formatting for data labels on all the plot's series. + +* A ```` element appears as a child of ```` only when the + data label for its associated data point has overrides. + + +XML specimens +------------- + +.. highlight:: xml + +The ```` element is available on a plot (e.g. ````), +a series (````), and perhaps elsewhere. + +Default ```` element added by PowerPoint when selecting Data Labels +> Value from the Chart Layout ribbon:: + + + + + + + + + + +A ```` element specifying the labels should appear in 10pt Bold +Italic Arial Narrow, color Accent 6, 25% Darker:: + + + + + + + + + + + + + + + + + + + + + + + + + + + +A ```` element having an individual point override for font color +and outline box:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-date-axis.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-date-axis.rst new file mode 100644 index 0000000000000000000000000000000000000000..add900067cb0ee465915ebe888edc8f051453110 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-date-axis.rst @@ -0,0 +1,496 @@ +.. _cht-date-axis: + +Chart - Date Axis +================= + +A date axis maintains a linear relationship between axis distance and elapsed +time in days, months, or years, even if the data items do not include values +for each base time unit. This is in contrast to a category axis, which uses +the independent axis values themselves to determine the discrete set of +categories. + +The date axis does this by essentially creating a "logical category" for each +base time unit in a range, whether the data contains a value for that time +unit or not. + +Variations in the number of days in a month (or year) is also taken care of +automatically. This would otherwise cause month starts to appear at days not +the first of the month. + +This does not make the category axis continuous, however the "grain" of the +discrete units can be quite small in comparison to the axis length. The +individual base unit divisions can but are not typically represented +graphically. The granularity of major and minor divisions is specified as +a property on the date axis. + + +MS API +------ + +* Axis.CategoryType = XL_CATEGORY_TYPE.TIME +* Axis.BaseUnit = XL_TIME_UNIT.DAYS + + +Enumerations +------------ + +XL_CATEGORY_TYPE + * .AUTOMATIC (-4105) + * .CATEGORY (2) + * .TIME (3) + +XL_TIME_UNIT + https://msdn.microsoft.com/en-us/library/office/ff746136.aspx + * .DAYS (0) + * .MONTHS (1) + * .YEARS (2) + + +XML Semantics +------------- + +Changing category axis between `c:catAx` and `c:dateAx` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In the MS API, DateAxis.CategoryType is used to discover the category type, +but is also used to change an axis from a date axis to a category axis and +back. Note the corresponding property in |pp| is read-only for now. + +Changing from a category to date axis leaves the base, major, and minor unit +elements in place. They apply again (instead of the defaults) if the axis is +changed back:: + + + + + + + +Choice of date axis +~~~~~~~~~~~~~~~~~~~ + +PowerPoint automatically uses a `c:dateAx` element if the category labels in +Excel are dates (numbers with date formatting). + +|pp| uses a `c:dateAx` element if the category labels in the chart data +object are datetime.date or datetime.datetime objects. + +Note that |pp| does not change the category axis type when using +`Chart.replace_data()`. + +A date axis is only available on an area, bar (including column), or line +chart. + + +Multi-level categories and date axis +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Multi-level categories are mutually exclusive with a date axis. + +A `c:multiLvlStrRef` element is the only one that can enclose a multi-level +category hierarchy. There is no provision for any or all the levels under +this element to be other than string values (as the 'Str' in its name +implies). + + +Automatic axis type +~~~~~~~~~~~~~~~~~~~ + +The `c:auto` element under `c:catAx` or `c:dateAx` controls whether the +category axis changes automatically between category and date types. + + +Specimen XML +------------ + +.. highlight:: xml + +Series having date categories:: + + + + + + + Sheet1!$B$1 + + + + Buzz + + + + + + + + + + Sheet1!$A$2:$A$520 + + mm\-dd\-yyyy + + + 42156.0 + + + 42157.0 + + + 42158.0 + + + + + + + Sheet1!$B$2:$B$520 + + 0.0 + + + 19.65943065775559 + + + 20.13705095574664 + + + 19.48264757927654 + + + + + +Plot area having date axis:: + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + Sheet1!$A$2:$A$4 + + d\-mmm + + + 42370.0 + + + 42371.0 + + + 42372.0 + + + + + + + Sheet1!$B$2:$B$4 + + General + + + 4.3 + + + 2.5 + + + 3.5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +References +---------- + +* Understanding Date-Based Axis Versus Category-Based Axis in Trend Charts + http://www.quepublishing.com/articles/article.aspx?p=1642672&seqNum=2 + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-doughnut-chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-doughnut-chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..4616fe33f0e30cf1604ea452644248e00c665e6f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-doughnut-chart.rst @@ -0,0 +1,221 @@ + +Doughnut Chart +============== + +A doughnut chart is similar in many ways to a pie chart, except there is +a "hole" in the middle. It can accept multiple series, which appear as +concentric "rings". + + +XML specimens +------------- + +.. highlight:: xml + +XML for default doughnut chart:: + + + + + + + + + + + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Sales + + + + + + + Sheet1!$A$2:$A$5 + + + + 1st Qtr + + + 2nd Qtr + + + 3rd Qtr + + + 4th Qtr + + + + + + + Sheet1!$B$2:$B$5 + + General + + + 8.2 + + + 3.2 + + + 1.4 + + + 1.2 + + + + + + + + + + + Sheet1!$C$1 + + + + Revenue + + + + + + + Sheet1!$A$2:$A$5 + + + + 1st Qtr + + + 2nd Qtr + + + 3rd Qtr + + + 4th Qtr + + + + + + + Sheet1!$C$2:$C$5 + + General + + + 1000.0 + + + 2000.0 + + + 3000.0 + + + 4000.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-invert-if-negative.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-invert-if-negative.rst new file mode 100644 index 0000000000000000000000000000000000000000..db92d3fad36a7203d4dcedc2633c6f33c4ceaee1 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-invert-if-negative.rst @@ -0,0 +1,121 @@ + +Chart - InvertIfNegative +======================== + +Can be set on a bar series or on a data point. It's not clear what its meaning +is on a non-bar data point. ``c:barSer/c:invertIfNegative`` is the target +element. Also valid on a bubble series. + + +Protocol +-------- + +:: + + >>> assert isinstance(plot, pptx.chart.plot.BarPlot) + >>> series = plot.series[0] + >>> series + + >>> series.invert_if_negative + True + >>> series.invert_if_negative = False + >>> series.invert_if_negative + False + + +Semantics +--------- + +* Defaults to |True| if the ```` element is not present. +* Defaults to |True| if the parent element is present but the `val` attribute + is not. + + +PowerPoint® behavior +-------------------- + +In my tests, the ```` element is always present in a new +bar chart and always explicitly initialized to False. + + +XML specimens +------------- + +.. highlight:: xml + +A series element from a simple column chart (single series):: + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-legend.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-legend.rst new file mode 100644 index 0000000000000000000000000000000000000000..47df413843211d3c1b1ecadf4d0ce3edbe5f3ea7 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-legend.rst @@ -0,0 +1,223 @@ + +Chart - Legend +=================== + +A chart may have a legend. The legend may be placed within the plot area or +alongside it. The legend has a fill and font and may be positioned on the +top, right, bottom, left, in the upper-right corner, or in a custom position. +Individual legend entries may be custom specified, but that is not yet in +scope. + + +Candidate protocol +------------------ + +:: + + >>> chart.has_legend + False + >>> chart.has_legend = True + >>> chart.has_legend + True + >>> legend = chart.legend + >>> legend + + + >>> legend.font + + + >>> legend.horz_offset + 0.0 + >>> legend.horz_offset = 0.2 + >>> legend.horz_offset + 0.2 + + >>> legend.include_in_layout + True + >>> legend.include_in_layout = False + >>> legend.include_in_layout + False + + >>> legend.position + XL_LEGEND_POSITION.RIGHT (-4152) + >>> legend.position = XL_LEGEND_POSITION.BOTTOM + >>> legend.position + XL_LEGEND_POSITION.BOTTOM (-4107) + + +Feature Summary +--------------- + +* :attr:`.Chart.has_legend` -- Read/write boolean property +* :attr:`.Chart.legend` -- Read-only |Legend| object or None +* :attr:`.Legend.horz_offset` -- Read/write float (-1.0 -> 1.0). +* :attr:`.Legend.include_in_layout` -- Read/write boolean. +* :attr:`.Legend.position` -- Read/write :ref:`XlLegendPosition` +* :attr:`.Legend.font` -- Read-only |Font| object. + + +Enumerations +------------ + +* :ref:`XlLegendPosition` + + +Microsoft API +------------- + +Chart.HasLegend + True if the chart has a legend. Read/write Boolean. + +Chart.Legend + Returns the legend for the chart. Read-only Legend. + +Legend.IncludeInLayout + True if a legend will occupy the chart layout space when a chart layout + is being determined. The default is True. Read/write Boolean. + +Legend.Position + Returns or sets the position of the legend on the chart. Read/write + XlLegendPosition. + + +XML specimens +------------- + +.. highlight:: xml + +Example legend XML:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Legend having horz_offset == 0.42:: + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-line-chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-line-chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..e796cda86bdee6ec4ca4965c7ee8efc6069acae2 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-line-chart.rst @@ -0,0 +1,149 @@ + +Line Chart +========== + +A line chart is one of the fundamental plot types. + + +XML Semantics +------------- + +* c:lineChart/c:marker{val=0|1} doesn't seem to have any effect one way or + the other. Default line charts inserted using PowerPoint always have it set + to 1 (True). But even if it's set to 0 or removed, markers still appear. + Hypothesis is that c:lineChart/c:ser/c:marker/c:symbol{val=none} and the + like are the operative settings. + + +XML specimens +------------- + +.. highlight:: xml + +Minimal working XML for a line plot. Note this does not reference values in a +spreadsheet.:: + + + + + + + + + + + + Series 1 + + + + + + + + + Category 1 + + + Category 2 + + + + + + + + 4.3 + + + 2.5 + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +Line chart elements:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-marker.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-marker.rst new file mode 100644 index 0000000000000000000000000000000000000000..ca61d854579eb8f3fda02e3aaec064100e3ccf8c --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-marker.rst @@ -0,0 +1,266 @@ + +Chart - Markers +=============== + +A marker is a small geometric shape that explicitly indicates a data point +position on a line-oriented chart. Line, XY, and Radar are the line-oriented +charts. Other chart types do not have markers. + + +PowerPoint behavior +------------------- + +At series level, UI provides property controls for: + +* Marker Fill + + + Solid + + Gradient + + Picture or Texture + + Pattern + +* Marker Line + + + Solid + + - RGBColor (probably HSB too, etc.) + - Transparency + + + Gradient + + Weights & Arrows + +* Marker Style + + + Choice of enumerated shapes + + Size + + +XL_MARKER_STYLE enumeration +--------------------------- + +https://msdn.microsoft.com/en-us/library/bb241374(v=office.12).aspx + ++------------------------+-------+----------------------------------+ +| xlMarkerStyleAutomatic | -4105 | Automatic markers | ++------------------------+-------+----------------------------------+ +| xlMarkerStyleCircle | 8 | Circular markers | ++------------------------+-------+----------------------------------+ +| xlMarkerStyleDash | -4115 | Long bar markers | ++------------------------+-------+----------------------------------+ +| xlMarkerStyleDiamond | 2 | Diamond-shaped markers | ++------------------------+-------+----------------------------------+ +| xlMarkerStyleDot | -4118 | Short bar markers | ++------------------------+-------+----------------------------------+ +| xlMarkerStyleNone | -4142 | No markers | ++------------------------+-------+----------------------------------+ +| xlMarkerStylePicture | -4147 | Picture markers | ++------------------------+-------+----------------------------------+ +| xlMarkerStylePlus | 9 | Square markers with a plus sign | ++------------------------+-------+----------------------------------+ +| xlMarkerStyleSquare | 1 | Square markers | ++------------------------+-------+----------------------------------+ +| xlMarkerStyleStar | 5 | Square markers with an asterisk | ++------------------------+-------+----------------------------------+ +| xlMarkerStyleTriangle | 3 | Triangular markers | ++------------------------+-------+----------------------------------+ +| xlMarkerStyleX | -4168 | Square markers with an X | ++------------------------+-------+----------------------------------+ + +XML specimens +------------- + +.. highlight:: xml + +Marker properties set at the series level, all markers for the series:: + + + + + + + + + + + + + + + + + + + + + + + +Marker properties set on an individual point:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-pie-chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-pie-chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..b3ce4599099bdb2d63d6b641ec4a209a42c4a50a --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-pie-chart.rst @@ -0,0 +1,176 @@ + +Pie Chart +========= + +A pie chart is one of the fundamental plot types. + + +XML specimens +------------- + +.. highlight:: xml + +Minimal working XML for a pie plot. Note this does not reference values in a +spreadsheet.:: + + + + + + + + + + + Sales + + + + + + 1st Qtr + + + 2nd Qtr + + + 3rd Qtr + + + 4th Qtr + + + + + + + + 8.2 + + + 3.2 + + + 1.4 + + + 1.2 + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +Pie chart elements:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-plot-data.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-plot-data.rst new file mode 100644 index 0000000000000000000000000000000000000000..43227662bb600a67a5012a59f4a0cf98b45e4837 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-plot-data.rst @@ -0,0 +1,198 @@ + +Chart - Plot Data +================= + +The values and categories of each plot is specified by a data set. In the +typical case, that data is composed of a sequence of categories and +a sequence of series, where each series has a numeric value corresponding to +each of the categories. + + +Candidate protocol +------------------ + +:: + + >>> plot = chart.plots[0] + >>> plot.categories + ('Foo', 'Bar', 'Baz') + >>> len(plot.series) + 3 + >>> series = iter(plot.series) + >>> next(series).values + (1.2, 2.3, 3.4) + >>> next(series).values + (4.5, 5.6, 6.7) + >>> next(series).values + (7.8, 8.9, 9.0) + + +Feature Summary +--------------- + +* **Plot.categories** -- Read/only for now. Returns tuple of string. +* **Series.values** -- Read/only for now. Returns tuple of float. + + +Microsoft API +------------- + +ChartGroup.CategoryCollection + Returns all the visible categories in the chart group, or the specified + visible category. + +ChartGroup.SeriesCollection + Returns all the series in the chart group. + +Series.Values + Returns or sets a collection of all the values in the series. Read/write + Variant. Returns an array of float; accepts a spreadsheet formula or an + array of numeric values. + +Series.Formula + Returns or sets the object's formula in A1-style notation. Read/write + String. + + +XML specimens +------------- + +.. highlight:: xml + +Example series XML:: + + + + + + Sheet1!$A$2:$A$4 + + + + Foo + + + Bar + + + Baz + + + + + + + Sheet1!$B$2:$B$4 + + + + 1.2 + + + 2.3 + + + 3.4 + + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-plots.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-plots.rst new file mode 100644 index 0000000000000000000000000000000000000000..e0ea8c23a89111a51bcb96a6e9ff018960ec1a96 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-plots.rst @@ -0,0 +1,335 @@ + +Chart - Plots +============= + +Within the ``c:chartSpace/c:chart/c:plotArea`` element may occur 0..n +`xChart` elements, each containing 0..n series. + +`xChart` here is a placeholder name for the various plot elements, each of +which ends with `Chart`: + +* ```` +* ```` +* ```` +* ```` +* etc. ... + +In the Microsoft API, the term *chart group* is used for the concept these +elements represent. Rather than a group of charts, their role is perhaps +better described as a *series group*. The terminology is a bit vexed when it +comes down to details. The term *plot* was chosen for the purposes of this +library. + +The reason the concept of a plot is required is that more than one type of +plotting may appear on a single chart. For example, a line chart can appear +on top of a column chart. To be more precise, one or more series can be +plotted as lines superimposed on one or more series plotted as columns. + +The two sets of series both belong to a single chart, and there is only +a single data source to define all the series in the chart. The Excel +workbook that provides the chart data uses only a single worksheet. + +Individual series can be assigned a different *chart type* using the +PowerPoint UI; this operation causes them to be placed in a distinct `xChart` +element of the corresponding type. During this operation, PowerPoint adds +`xChart` elements in an order that seems to correspond to logical viewing +order, without respect to the sequence of the series chosen. It appears area +plots are placed in back, bar next, and line in front. This prevents plots of +one type from obscuring the others. + +Note that not all combinations of chart types are possible. I've seen area +overlaid with column overlaid with line. Bar cannot be combined with line, +which seems sensible because their axes locations differ (switched +horizontal/vertical). + + +Feature Summary +--------------- + +Most plot-level properties are particular to a chart type. One so far is +shared by plots of almost all chart types. + +* **Plot.vary_by_categories** -- Read/write boolean determining whether point + markers for each category have a different color. A point marker here means + a bar for a bar chart, a pie section, etc. This setting is only operative + when the plot has a single series. A plot with multiple series uses varying + colors to distinguish series rather than categories. + + +Candidate protocol +------------------ + +Plot.vary_by_categories:: + + >>> plot = chart.plots[0] + >>> plot.vary_by_categories + True + >>> plot.vary_by_categories = False + >>> plot.vary_by_categories + False + + +XML Semantics +------------- + +* The value of ``c:xChart/c:varyColors`` defaults to |True| when the element + is not present or when the element is present but its ``val`` attribute is + not. + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-points.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-points.rst new file mode 100644 index 0000000000000000000000000000000000000000..5bb3e5215334f2dac193a234724a09dfdebdb743 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-points.rst @@ -0,0 +1,345 @@ + +Chart - Points +============== + +A chart may be understood as a graph of a function, formed by rendering +a finite number of ordered pairs (e.g. (x, y)) in one of several graphical +formats such as bar, pie, or bubble. + +A functon can be expressed as:: + + y = f(x) + +where *x* is the input to the function and *y* is the output. *x* is known +more formally as the function's *argument*, and *y* as its *value*. The set +of possible input (x) values is the *domain* of the function. The set of +possible output (y) values is the function's *range*. + +In PowerPoint, the function is perhaps rarely mathematical; perhaps more +commonly, the x and y values are correlated observations, facts to be +communicated graphically as a set. Still these terms borrowed from +mathematics provide convenient language for describing aspects of PowerPoint +charts. + +PowerPoint charts can be divided broadly into *category* types, which take +a discrete argument, and *XY* (aka. scatter) types which take a continuous +argument. For category types, the argument is one of a discrete set of +categories, expressed as a label, such as "Blue", "Red", and "Green". The +argument for an XY type is a real number. In both cases, the *value* of each +data point is a real number. + +The argument is commonly associated with the horizontal axis of the chart and +the value with the vertical axis; these would be the X and Y axis +respectively on an XY chart. However the 2D orientation of the axes is +reversed in some char types (bar charts in particular) and takes other forms +in chart types such as radar and doughnut. In the MS API, the axis associated +with the argument is known as the *category axis* and the other is the *value +axis*. This terminology is used across all chart types (including XY) as +a matter of convention. + + +Series +------ + +A chart can have one or more series. A series is a set of ordered pairs that +are related in some way and meant to be distinguished graphically on the +chart, often so they can be compared. For example, one series could represent +Q1 financial results, depicted as a blue line, and a second series represent +Q2 financial results with a red line. + +In a standard chart, all series share the same domain (e.g. the same X axis). +In a category chart, all series also share the same set of categories. In an +XY chart, the domain values are continuous; so in general, each data point in +each XY series will in have a distinct argument (x value). + +In the MS API, there are multiple members on Series related to data points: + +* Values +* XValues +* Points + +Note that *Categories* is not in this set. ``CategoryCollection`` is a member +of ``ChartGroup`` (named Plot in |pp|) in the MS API. + +**Values** is the Excel range address at which the series values are stored. +A set of constant values can be assigned in the MS API but this is not +supported in |pp|. + +**XValues** is the Excel range address at which the series arguments are +stored when the chart is one of the XY types. X values replace categories for +an XY chart. + +**Points** is a sequence of Point objects, each of which provides access to +the formatting of the graphical representation of the data point. Notably, it +does not allow changing the category, x or y value, or size (for a bubble +chart). + +Every chart type supported by MS Office charts has the concept of data +points. + +Informally, a data point is an atomic element of the content depicted by the +chart. + +MS Office charts do not have a firm distinction for data points. + +In all cases, points belong to a *series*. + +There is some distinction between a data point for a category chart and one +for an XY (scatter) chart. + +The API + + +Functions +--------- + +:: + + data_point_count = min( + xVal.ptCount_val, yVal.ptCount_val, bubbleSize.ptCount_val + ) + + invariant(ptCount_val > max(pt.idx)) + + @property + def pt_v(self, parent, idx): + pts = parent.xpath('.//c:pt[@val=%s]' % idx) + if pts is None: + return None + pt = pts[0] + return pt.v + + points[i] ~= Point(xVal.pts[i], yVal.pts[i], bubbleSize.pts[i]) + + +Point membership hypothesis: +---------------------------- + +* Visual alignment is not significant. A range may be anywhere in relation to + the other data point ranges. + +* Sequence is low row/col to high row/col in the Excel range, regardless of + the "direction" in which the cells are selected. This seems to be enforced + by a validation "correction" of the range string in the UI 'Select Data' + dialog. + +* The number (count) of x, y, or size values is the number of cells in the + range. This corresponds directly to ptCount/@val for that data source + sequence. + +* The number of points in the series is the minimum of the x, y, and size + value counts (ptCount). + +* The ordered set of values for a point is formed by simple indexing within + each value sequence. For example:: + + point[3] = (x_values[3], y_values[3], sizes[3]) + + When any value sequence in the set runs out of elements, no further points + are formed. + + All values of each data source sequence are written to the XML; values are + not truncated because they lack a counter part in one of the other + sequences. Consequently, the ptCount values will not necessarily match. + + +Experiment (IronPython): +------------------------ + +* Create a chart with three X-values and four Y-values. .XValues has three + and .Values has four members. How many points are in Series.Points? + +Observations: + +* 4 X, 4 Y, 4 size -- 4 points +* 3 X, 4 Y, 4 size -- 3 points +* 4 X, 3 Y, 4 size -- 3 points +* 4 X, 4 Y, 3 size -- 3 points + +Points with blank (y) values still count as a point. +Points with blank (y) values still count as a point. + +Explain how ... + +Hypothesis: An x, y, or size value index always starts at zero, at the +beginning of the range, and increments to ptCount-1. + +Hypothesis: ptCount is always based on the number of cells in the Excel +range, including blank cells at the start and end. + +ptCount and pt behavior on range including blank cell at end. + +xVal//ptCount can be different than yVal//ptCount + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +Point-related elements are stored under `c:ser`:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-radar-chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-radar-chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..42f960ca8e4436f3c10944951ae816bead423096 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-radar-chart.rst @@ -0,0 +1,370 @@ +.. _RadarChart: + + +Radar Chart +=========== + +A radar chart is essentially a line chart wrapped around on itself. + +It's worth a try to see if inheriting from LineChart would work. + + +PowerPoint UI +------------- + +* Insert > Chart ... > Other > Radar + +* Default Radar uses 5 categories, 2 series, points connected with lines, no + data point markers. Other radar options can add markers or fill. + +* Layout seems an awful lot like a line chart + +* Supports data labels, but only with data point value, not custom text (from + UI). + + +XML semantics +------------- + +* There is one `c:ser` element for each series. Each `c:ser` element contains + both the categories and the values (even though that is often redundant). + +* ? What happens if the category items in a radar chart don't match? + Inside are `c:xVal`, `c:yVal`, and + `c:bubbleSize`, each containing the set of points for that "series". + + +XML specimen +------------ + +.. highlight:: xml + +XML for default radar chart (simplified):: + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Series 1 + + + + + + + + + + Sheet1!$A$2:$A$6 + + m/d/yy + + + 37261.0 + + + 37262.0 + + + 37263.0 + + + 37264.0 + + + 37265.0 + + + + + + + Sheet1!$B$2:$B$6 + + General + + + 32.0 + + + 32.0 + + + 28.0 + + + 12.0 + + + 15.0 + + + + + + + + + + + Sheet1!$C$1 + + + + Series 2 + + + + + + + + + + Sheet1!$A$2:$A$6 + + m/d/yy + + + 37261.0 + + + 37262.0 + + + 37263.0 + + + 37264.0 + + + 37265.0 + + + + + + + Sheet1!$C$2:$C$6 + + General + + + 12.0 + + + 12.0 + + + 12.0 + + + 21.0 + + + 28.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +MS API Protocol +--------------- + +.. highlight:: vb.net + +Make a radar chart:: + + Public Sub MakeGraph() + + Dim title As String = "Title" + Dim x_label As String = "X Axis Label" + Dim y_label As String = "Y Axis Label" + Dim new_chart As Chart + + ' Make the chart. + Set new_chart = Charts.Add() + ActiveChart.ChartType = xlRadar + ActiveChart.SetSourceData _ + Source:=sheet.Range("A1:A" & UBound(values)), _ + PlotBy:=xlColumns + + ' Set the chart's title abd axis labels. + With ActiveChart + .HasTitle = True + .ChartTitle.Characters.Text = title + + .Axes(xlCategory, xlPrimary).HasTitle = True + .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = x_label + + .Axes(xlValue, xlPrimary).HasTitle = True + .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = y_label + End With + End Sub + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +Radar chart elements:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-series.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-series.rst new file mode 100644 index 0000000000000000000000000000000000000000..9a9b951b7c5197e600982acaf6d196c78d2efaad --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-series.rst @@ -0,0 +1,360 @@ + +Chart - Series +============== + +A series in a sequence of *points* that correspond to the categories of +a plot. A chart may have more than one series, which gives rise, for example, +to a *clustered column chart* or a line chart with multiple lines plotted. + +A series belongs to a *plot*. When a chart has multiple plots, such as a bar +chart with a superimposed line plot, each of the series in the chart belong to +one plot or the other. + +Although the Microsoft API has a method on Chart to access all the series in +a chart, it also has the same method for accessing the series of a plot +(ChartGroup in MS API). + +There are eight distinct series types, corresponding to major chart types. +They all share a common base of attributes and others appear on one or more +of the types. + + +Series Access +------------- + +Series are perhaps most naturally accessed from a plot, to which they +belong:: + + >>> plot.series + + +However, there is also a property on |Chart| which allows access to all +the series in the chart:: + + >>> chart.series + + +Each series in a chart has an explicit sequence indicator, the value of its +required `c:order` child element. The series for a plot appear in order of +this value. The series for a chart appear in plot order, then their order +within that plot, such that all series for the first plot appear before those +in the next plot, and so on. + +Properties +---------- + +Series.format +~~~~~~~~~~~~~ + +All series have an optional `c:spPr` element that control the drawing shape +properties of the series such as fill and line, including transparency and +shadow. + +Series.points +~~~~~~~~~~~~~ + +Perhaps counterintuitively, a Point object does not provide access to all the +attributes one might think. It only provides access to attributes of the +visual representation of the point in that chart, such as the color, datum +label, or marker. It does not provide access to the data point values, such +as the Y value or the bubble size. + +Surface charts do not have a distinct data point representation (rather just +an inflection in the surface. So series of surface charts will not have the +.points member. Since surface charts are not yet implemented, this will come +into play sometime later. + +Note that bubble and XY have a different way of organizing their data points +so have a distinct implementation from that of category charts. + +**Implementation notes:** + +* Introduce _BaseCategorySeries and subclass all category series types from + it. Add tests to test inheritance. No acceptance test since this is + internals-only. + +* It's possible the only requirement is to create CategoryPoints. The rest of + the implementation might work all on its own. Better spike it and see. + + +Protocol +-------- + +:: + + >>> assert isinstance(chart, pptx.chart.chart.Chart) + >>> plot = chart.plots[0] + >>> plot + + >>> series = plot.series[0] + >>> series + + >>> fill = series.format.fill + >>> fill + + >>> fill.type + None + >>> fill.solid() + >>> fill.fore_color.rgb = RGB(0x3F, 0x2C, 0x36) + # also available are theme_color and brightness + + +XML specimens +------------- + +.. highlight:: xml + +A series element from a simple column chart (single series):: + + + + + + + Sheet1!$A$2 + + + + Base + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Sheet1!$B$1:$F$1 + + + + Très probable + + + Plutôt probable + + + Plutôt improbable + + + Très improbable + + + Je ne sais pas + + + + + + + Sheet1!$B$2:$F$2 + + 0 + + + 19.0 + + + 13.0 + + + 10.0 + + + 46.0 + + + 12.0 + + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-tick-labels.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-tick-labels.rst new file mode 100644 index 0000000000000000000000000000000000000000..5c0cafb18990c395408ed5e4878698fd8ebe2a72 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-tick-labels.rst @@ -0,0 +1,208 @@ + +Chart - Tick Labels +=================== + +The vertical and horizontal divisions of a chart axis may be labeled with +*tick labels*, text that describes the division, most commonly its category +name or value. A tick labels object is not a collection. There is no object +that represents in individual tick label. + +Tick label text for a category axis comes from the name of each category. The +default tick label text for a category axis is the number that indicates the +position of the category relative to the low end of this axis. To change the +number of unlabeled tick marks between tick-mark labels, you must change the +TickLabelSpacing property for the category axis. + +Tick label text for the value axis is calculated based on the `major_unit`, +`minimum_scale`, and `maximum_scale` properties of the value axis. To change +the tick label text for the value axis, you must change the values of these +properties. + + +Candidate protocol +------------------ + +:: + + >>> tick_labels = value_axis.tick_labels + + >>> tick_labels.font + + + >>> tick_labels.number_format + 'General' + >>> tick_labels.number_format = '0"%"' + >>> tick_labels.number_format + '0"%"' + + >>> tick_labels.number_format_is_linked + True + >>> tick_labels.number_format_is_linked = False + >>> tick_labels.number_format_is_linked + False + + # offset property is only available on category axis + >>> tick_labels = category_axis.tick_labels + >>> tick_labels.offset + 100 + >>> tick_labels.offset = 250 + >>> tick_labels.offset + 250 + + +Feature Summary +--------------- + +* **TickLabels.font** -- Read/only Font object for tick labels. +* **TickLabels.number_format** -- Read/write string. +* **TickLabels.number_format_is_linked** -- Read/write boolean. +* **TickLabels.offset** -- Read/write int between 0 and 1000, inclusive. + + +Microsoft API +------------- + +Font + Returns the font of the specified object. Read-only ChartFont. + +NumberFormat + Returns or sets the format code for the object. Read/write String. + +NumberFormatLinked + True if the number format is linked to the cells (so that the number + format changes in the labels when it changes in the cells). Read/write + Boolean. + +Offset + Returns or sets the distance between the levels of labels, and the + distance between the first level and the axis line. Read/write Long. + + +XML specimens +------------- + +.. highlight:: xml + +Example category axis XML showing tick label-related elements:: + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-xy-chart.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-xy-chart.rst new file mode 100644 index 0000000000000000000000000000000000000000..06050f603867ce9a8ff922cd372cc3eee65118d3 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/cht-xy-chart.rst @@ -0,0 +1,394 @@ +.. _XyChart: + + +X-Y Chart +========= + +An X-Y chart, also known as a *scatter* chart, depending on the version of +PowerPoint, is distinguished by having two value axes rather than one +category axis and one value axis. + + + +XML specimen +------------ + +.. highlight:: xml + +XML for default XY chart:: + + + + + + + + + + + + + + + + Sheet1!$B$1 + + + + Red Bull + + + + + + + + + + + + Sheet1!$A$2:$A$7 + + General + + + 0.7 + + + 1.8 + + + 2.6 + + + 0.8 + + + 1.7 + + + 2.5 + + + + + + + Sheet1!$B$2:$B$7 + + General + + + 2.7 + + + 3.2 + + + 0.8 + + + + + + + + + + + + Sheet1!$C$1 + + + + Monster + + + + + + + + + + + + Sheet1!$A$2:$A$7 + + General + + + 0.7 + + + 1.8 + + + 2.6 + + + 0.8 + + + 1.7 + + + 2.5 + + + + + + + Sheet1!$C$2:$C$7 + + General + + + 3.2 + + + 4.3 + + + 1.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +XY (scatter) chart elements:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-color.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-color.rst new file mode 100644 index 0000000000000000000000000000000000000000..69f3bed74132d36c7f4642311b04b348e70c206e --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-color.rst @@ -0,0 +1,150 @@ + +Color +===== + +ColorFormat object ... + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-fill.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-fill.rst new file mode 100644 index 0000000000000000000000000000000000000000..f0b4c5b544571183f6756bc72f830a8afa435f63 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-fill.rst @@ -0,0 +1,366 @@ + +Fill (for shapes) +================= + +Overview +-------- + +In simple terms, *fill* is the color of a shape. The term *fill* is used to +distinguish from *line*, the border around a shape, which can have a different +color. It turns out that a line has a fill all its own, but that's another +topic. + +While having a solid color fill is perhaps most common, it is just one of +several possible fill types. A shape can have the following types of fill: + +* solid (color) +* gradient -- a smooth transition between multiple colors (see + :ref:`gradientfill`) +* picture -- in which an image "shows through" and is cropped by the boundaries + of the shape +* pattern -- in which a small square of pixels (tile) is repeated to fill the + shape +* background (no fill) -- the body of the shape is transparent, allowing + whatever is behind it to show through. + +Elements that can have a fill include autoshape, line, text (treating each +glyph as a shape), table, table cell, and slide background. + + +Scope +----- + +This analysis initially focused on solid fill for an autoshape (including +text box). Later, pattern fills were added and then analysis for gradient +fills. Picture fills are still outstanding. + +* ``FillFormat.type`` -- ``MSO_FILL.SOLID`` or |None| for a start +* ``FillFormat.solid()`` -- changes fill type to `` +* ``FillFormat.patterned()`` -- changes fill type to `` +* ``FillFormat.fore_color`` -- read/write foreground color + +**maybe later:** + +* ``FillFormat.transparency`` -- adds/changes or something + + +Protocol +-------- + +**Accessing fill.** A shape object has a `.fill` property that returns +a `FillFormat` object. The `.fill` property is idempotent; it always returns +the same `FillFormat` object for a given shape object:: + + >>> fill = shape.fill + >>> assert(isinstance(fill, FillFormat) + +**Fill type.** A fill has a type, indicated by a member of `MSO_FILL` on +`FillFormat.type`:: + + >>> fill.type + MSO_FILL.SOLID (1) + +The fill type may also be |None|, indicating the shape's fill is inherited +from the style hierarchy (generally the theme linked to the slide master). +This is the default for a new shape:: + + >>> shape = shapes.add_shape(...) + >>> shape.fill.type + None + +The fill type partially determines the valid calls on the fill:: + + >>> fill.solid() + >>> fill.type + 1 # MSO_FILL.SOLID + + >>> fill.fore_color = 'anything' + AttributeError: can't set attribute # .fore_color is read-only + >>> fore_color = fill.fore_color + >>> assert(isinstance(fore_color, ColorFormat)) + + >>> fore_color.rgb = RGBColor(0x3F, 0x2c, 0x36) + >>> fore_color.theme_color = MSO_THEME_COLOR.ACCENT_1 + >>> fore_color.brightness = -0.25 + + >>> fill.transparency + 0.0 + >>> fill.transparency = 0.25 # sets opacity to 75% + + >>> sp.fill = None # removes any fill, fill is inherited from theme + + fill.solid() + fill.fore_color.rgb = RGBColor(0x01, 0x23, 0x45) + fill.fore_color.theme_color = MSO_THEME_COLOR.ACCENT_1 + fill.fore_color.brightness = 0.25 + fill.transparency = 0.25 + shape.fill = None + fill.background() # is almost free once the rest is in place + +**Pattern Fill.** :: + + >>> fill = shape.fill + >>> fill.type + None + >>> fill.patterned() + >>> fill.type + 2 # MSO_FILL.PATTERNED + >>> fill.fore_color.rgb = RGBColor(79, 129, 189) + >>> fill.back_color.rgb = RGBColor(239, 169, 6) + + +Related items from Microsoft VBA API +------------------------------------ + +* `MSDN FillFormat Object`_ + +.. _`MSDN FillFormat Object`: + https://msdn.microsoft.com/en-us/vba/powerpoint-vba/articles/fillformat-o + bject-powerpoint + + +Enumerations +------------ + +MsoFillType +~~~~~~~~~~~ + +http://msdn.microsoft.com/EN-US/library/office/ff861408.aspx + +**msoFillBackground** + 5 -- Fill is the same as the background. + +**msoFillGradient** + 3 -- Gradient fill. + +**msoFillPatterned** + 2 -- Patterned fill. + +**msoFillPicture** + 6 -- Picture fill. + +**msoFillSolid** + 1 -- Solid fill. + +**msoFillTextured** + 4 -- Textured fill. + +**msoFillMixed** + -2 -- Mixed fill. + + +XML specimens +------------- + +.. highlight:: xml + +Inherited fill on autoshape:: + + + ... + + + + + + +Solid RGB color on autoshape:: + + + ... + + + + + + + + +Patterned fill:: + + + + + + + + + + + + +XML semantics +------------- + +* **No `prst` attribute.** When an `a:pattFill` element contains no `prst` + attribute, the pattern defaults to 5% (dotted). This is the first one in + the pattern gallery in the PowerPoint UI. + +* **No `fgClr` or `bgClr` elements.** When an `a:pattFill` element contains + no `fgClr` or `bgClr` chile elements, the colors default to black and white + respectively. + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-gradient.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-gradient.rst new file mode 100644 index 0000000000000000000000000000000000000000..ea66829ee3f9a87ab48137bc00e147694f4d0cfa --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-gradient.rst @@ -0,0 +1,498 @@ +.. _gradientfill: + +Gradient Fill +============= + +A gradient fill is a smooth gradual transition between two or more colors. +A gradient fill can mimic the shading of real-life objects and allow +a graphic to look less "flat". + +Each "anchor" color and its relative location in the overall transition is +known as a *stop*. A gradient definition gathers these in a sequence known as +the *stop list*, which contains two or more stops (a gradient with only one +stop would be a solid color). + +A gradient also has a *path*, which specifies the direction of the color +transition. Perhaps most common is a *linear path*, where the transition is +along a straight line, perhaps top-left to bottom-right. Other gradients like +*radial* and *rectangular* are possible. The initial implementation supports +only a linear path. + + +Protocol +-------- + +**Staring with a newly-created shape** A newly created shape has a fill of +|None|, indicating it's fill is inherited:: + + >>> shape = shapes.add_shape(...) + >>> fill = shape.fill + >>> fill + + >>> fill.type + None + +**Apply a gradient fill** A gradient fill is applied by calling the +`.gradient()` method on the `FillFormat` object. This applies a two-stop +linear gradient in the bottom-to-top direction (90-degrees in UI):: + + >>> fill.gradient() + >>> fill._fill.xml + + + + + + + + + + + + + + + + + + + + +**Change angle of linear gradient.**:: + + >>> fill.gradient_angle + 270.0 + >>> fill.gradient_angle = 45 + >>> fill.gradient_angle + 45.0 + +**Access a stop.** The `GradientStops` sequence provides access to an +individual gradient stop.:: + + >>> gradient_stops = fill.gradient_stops + >>> gradient_stops + + + >>> len(gradient_stops) + 3 + + >>> gradient_stop = gradient_stops[0] + >>> gradient_stop + + +**Manipulate gradient stop color.** The `.color` property of a gradient stop +is a `ColorFormat` object, which may be manipulated like any other color to +achieve the desired effect:: + + >>> color = gradient_stop.color + >>> color + + >>> color.theme_color = MSO_THEME_COLOR.ACCENT_2 + +**Manipulate gradient stop position.**:: + + >>> gradient_stop.position + 0.8 # ---represents 80%--- + >>> gradient_stop.position = 0.5 + >>> gradient_stop.position + 0.5 + +**Remove a gradient stop position.**:: + + >>> gradient_stops[1].remove() + >>> len(gradient_stops) + 2 + + +PowerPoint UI features and behaviors +------------------------------------ + +* Gradient dialog enforces a two-stop minimum in the stops list. A stop that + is one of only two stops cannot be deleted. + +* Gradient Gallery ... + + +Related items from Microsoft VBA API +------------------------------------ + +* `GradientAngle`_ +* `GradientColorType`_ +* `GradientDegree`_ +* `GradientStops`_ +* `GradientStyle`_ +* `GradientVariant`_ + +* `OneColorGradient()`_ + +* `PresetGradient()`_ + +* `TwoColorGradient()`_ + +.. _`GradientAngle`: + https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/fillformat-gradientangle-property-powerpoint + +.. _`GradientColorType`: + https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/fillformat-gradientcolortype-property-powerpoint + +.. _`GradientDegree`: + https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/fillformat-gradientdegree-property-powerpoint + +.. _`GradientStops`: + https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/fillformat-gradientstops-property-powerpoint + +.. _`GradientStyle`: + https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/fillformat-gradientstyle-property-powerpoint + +.. _`GradientVariant`: + https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/fillformat-gradientvariant-property-powerpoint + +.. _`OneColorGradient()`: + https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/fillformat-p + resetgradient-method-powerpoint + +.. _`PresetGradient()`: + https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/fillformat-o + necolorgradient-method-powerpoint + +.. _`TwoColorGradient()`: + https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/fillformat-p + resetgradient-method-powerpoint + + +Enumerations +------------ + +MsoFillType +~~~~~~~~~~~ + +http://msdn.microsoft.com/EN-US/library/office/ff861408.aspx + +**msoFillBackground** + 5 -- Fill is the same as the background. + +**msoFillGradient** + 3 -- Gradient fill. + +**msoFillPatterned** + 2 -- Patterned fill. + +**msoFillPicture** + 6 -- Picture fill. + +**msoFillSolid** + 1 -- Solid fill. + +**msoFillTextured** + 4 -- Textured fill. + +**msoFillMixed** + -2 -- Mixed fill. + + +MsoGradientStyle +~~~~~~~~~~~~~~~~ + +https://msdn.microsoft.com/en-us/vba/office-shared-vba/articles/msogradient\ +style-enumeration-office + +**msoGradientDiagonalDown** + 4 Diagonal gradient moving from a top corner down to the opposite corner. + +**msoGradientDiagonalUp** + 3 Diagonal gradient moving from a bottom corner up to the opposite corner. + +**msoGradientFromCenter** + 7 Gradient running from the center out to the corners. + +**msoGradientFromCorner** + 5 Gradient running from a corner to the other three corners. + +**msoGradientFromTitle** + 6 Gradient running from the title outward. + +**msoGradientHorizontal** + 1 Gradient running horizontally across the shape. + +**msoGradientVertical** + 2 Gradient running vertically down the shape. + +**msoGradientMixed** + \-2 Gradient is mixed. + + +MsoPresetGradientType +~~~~~~~~~~~~~~~~~~~~~ + +**msoGradientBrass** + 20 Brass gradient. + +**msoGradientCalmWater** + 8 Calm Water gradient. + +**msoGradientChrome** + 21 Chrome gradient. + +**msoGradientChromeII** + 22 Chrome II gradient. + +**msoGradientDaybreak** + 4 Daybreak gradient. + +**msoGradientDesert** + 6 Desert gradient. + +**msoGradientEarlySunset** + 1 Early Sunset gradient. + +**msoGradientFire** + 9 Fire gradient. + +**msoGradientFog** + 10 Fog gradient. + +**msoGradientGold** + 18 Gold gradient. + +**msoGradientGoldII** + 19 Gold II gradient. + +**msoGradientHorizon** + 5 Horizon gradient. + +**msoGradientLateSunset** + 2 Late Sunset gradient. + +**msoGradientMahogany** + 15 Mahogany gradient. + +**msoGradientMoss** + 11 Moss gradient. + +**msoGradientNightfall** + 3 Nightfall gradient. + +**msoGradientOcean** + 7 Ocean gradient. + +**msoGradientParchment** + 14 Parchment gradient. + +**msoGradientPeacock** + 12 Peacock gradient. + +**msoGradientRainbow** + 16 Rainbow gradient. + +**msoGradientRainbowII** + 17 Rainbow II gradient. + +**msoGradientSapphire** + 24 Sapphire gradient. + +**msoGradientSilver** + 23 Silver gradient. + +**msoGradientWheat** + 13 Wheat gradient. + +**msoPresetGradientMixed** + -2 Mixed gradient. + + +XML specimens +------------- + +.. highlight:: xml + +Gradient fill (preset selected from gallery on PowerPoint 2014):: + + + + + + + + + + + + + + + + + + + + + + + + + + +Gradient fill (simple created with gradient dialog):: + + + + + + + + + + + + + + + + + + + + + +XML semantics +------------- + +* Each `a:gs` element is a fill format + +* `a:lin@ang` is angle in 1/60,000ths of a degree. Zero degrees is the vector + (1, 0), pointing directly to the right. Degrees are measured + **counter-clockwise** from that origin. + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-line.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-line.rst new file mode 100644 index 0000000000000000000000000000000000000000..a0d3b7283a7cdeafa22bfa116c8c00f38b65f95f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/dml-line.rst @@ -0,0 +1,241 @@ + +Line format +=========== + + +Intial scope +------------ + +* Shape.line, Connector.line to follow, then Cell.border(s).line, possibly + text underline and font.line (character outline) + + +Protocol +-------- + +:: + + >>> shape.line + + >>> shape.fore_color + + + +Notes +----- + +definitely spike on this one. + +start with line.color, first an object to hang members off of + + +Issue: How to accommodate these competing requirements: + +* Polymorphism in parent shape. More than one type of shape can have a line + and possibly several (table cell border, Run/text, and text underline use + the same CT_LineProperties element, and perhaps others). + +* The line object cannot hold onto a `` element, even if that was + a good idea, because it is an optional child; not having an `` + element is a legitimate and common situation, indicating line formatting + should be inherited from the theme or perhaps a layout placeholder. + +* Needing to accommodate XML changing might not be important, could make that + operation immutable, such that changing the shape XML returns a new shape, + not changing the existing one in-place. + +* maybe having the following 'line_format_owner_interface', delegating + create, read, and delete of the `` element to the parent, and + allowing LineFormat to take responsibility for update. + + + line.parent has the shape having the line format + + parent.ln has the `` element or None, delegating access to the parent + + ln = parent.add_ln() + + parent.remove_ln() + + +MS API +------ + +* | LineFormat + | https://msdn.microsoft.com/en-us/vba/powerpoint-vba/articles/lineformat-object-powerpoint + +* | LineFormat.DashStyle + | https://msdn.microsoft.com/en-us/vba/powerpoint-vba/articles/lineformat-dashstyle-property-powerpoint + +* | MsoLineDashStyle Enumeration + | https://msdn.microsoft.com/en-us/library/aa432639(v=office.12).aspx + + +-----------------------+-------+----------------------------------+ + | Name | Value | Description | + +-----------------------+-------+----------------------------------+ + | msoLineDash | 4 | Line consists of dashes only. | + +-----------------------+-------+----------------------------------+ + | msoLineDashDot | 5 | Line is a dash-dot pattern. | + +-----------------------+-------+----------------------------------+ + | msoLineDashDotDot | 6 | Line is a dash-dot-dot pattern. | + +-----------------------+-------+----------------------------------+ + | msoLineDashStyleMixed | -2 | Not supported. | + +-----------------------+-------+----------------------------------+ + | msoLineLongDash | 7 | Line consists of long dashes. | + +-----------------------+-------+----------------------------------+ + | msoLineLongDashDot | 8 | Line is a long dash-dot pattern. | + +-----------------------+-------+----------------------------------+ + | msoLineRoundDot | 3 | Line is made up of round dots. | + +-----------------------+-------+----------------------------------+ + | msoLineSolid | 1 | Line is solid. | + +-----------------------+-------+----------------------------------+ + | msoLineSquareDot | 2 | Line is made up of square dots. | + +-----------------------+-------+----------------------------------+ + + +Specimen XML +------------ + +.. highlight:: xml + +solid line color:: + + + + + + + + + + + + + + + + +little bit of everything:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/enumerations.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/enumerations.rst new file mode 100644 index 0000000000000000000000000000000000000000..b42c5b653fee92de8a16c148649be2aa1bb687d8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/enumerations.rst @@ -0,0 +1,255 @@ + +Enumerations +============ + +Overview +-------- + +A large number of settings in PowerPoint are a selection between a small, +finite set of discrete choices. Often, in the XML, these are represented by +a simple type defined as an enumeration of a set of short string values. This +page describes the strategy for providing access to these sets of values in +the various parts of the library that require them. + + +Notes +----- + +* The general strategy is to provide a set of classes, one for each + enumeration, that serves as the single source for all reference and + behavior for that enumeration. +* These enumerations correspond one-to-one with Microsoft API enumerations. +* The naming is based on the Microsoft enumeration. .. all-caps snake case + from the original mixed-case. + + +Definitions +----------- + +member + What constitutes a member of an enumeration? What attributes do all + members have in common? + +out-of-band member + Is there such a thing? Or is there just an out-of-band value? + +get-value + ... value returned to indicate the current state of a property + +set-value + ... value passed to indicate the desired state of a property + + +Feature requirements +-------------------- + +Design principle: All required values and mappings are defined in the +enumeration class. All required names, data structures, and methods are +generated by the metaclass. They don't have to be generated manually. + +* [X] feature: dotted name access + + enumeration values can be accessed from an enumeration class with + dotted notation, e.g. ``MSO_FOO.BAR_BAZ`` + +* [X] feature: enumeration value behaves as an int + +* [X] feature: __str__ value of enum member is the member name and int value + + In order to provide the developer with a directly readable name for an + enumeration value (rather than a raw int), each enum values shall have + a __str__ method that returns the member name. E.g.:: + + >>> print("text_frame.auto_size is '%s'" % text_frame.auto_size) + text_frame.auto_size is 'SHAPE_TO_FIT_TEXT (2)' + +* [X] feature: out-of-band values -- like None, True, and False + + From time to time it is desireable to allow return and setting values + that are not named members of the enumeration to provide a more + Pythonic protocol for a property that uses the enumeration. For + example:: + + >>> run.underline + None + >>> run.underline = True + >>> str(run.underline) + 'SINGLE' + >>> run.underline = False + >>> str(run.underline) + 'NONE' + >>> run.underline = WD_UNDERLINE.DOUBLE + >>> str(run.underline) + 'DOUBLE' + +* [X] feature: alias decorator + + one or more convenience aliases can be declared for an Enumeration + subclass by use of an @alias decorator + +* [X] feature: setting validation + + In order to allow invalid input values to raise ValueError exceptions + at the API method level, the enumeration shall provide an + is_valid_setting() class method that returns False if the value passed + as an argument is not a member of the enumeration. E.g.:: + + assert MSO_AUTO_SIZE.is_member('foobar') is False + +* [X] feature: to_XML translation + + + [X] issue: Not all enumerations have mappings to XML attribute values. + Consider creating an XmlEnumeration subclass that provides this extra + feature. + + + [X] issue: There exist 'return-only' enumeration values, out-of-band + values used to indicate none of the other values apply, for example + MIXED = -2 to indicate the call was made on a range that contains + items not all having the same value. + + To provide a single authoritative mapping from enumeration member + values and the XML attribute values they correspond to, the Enumeration + class shall provide a to_xml(member_value) method that returns the XML + value corresponding to the passed member value. + + The method shall raise ValueError if the passed value is not a member + of the enumeration. + + The special XML value |None| indicates the attribute should be removed + altogether and should be returned where that is the appropriate + behavior. + + Where the Python value is an out-of-band value such as |None|, |True|, + or |False|, there must be a valid XML value or |None| as the mapping. + +* [X] feature: docstrings + + To provide built-in documentation for different options and to provide + a source for option descriptions for a generated documentation page, + each enumeration member shall have as its docstring a description of + the member and the behavior that setting specifies in its context. + +* [X] feature: auto-generate documentation + + + [X] add __ms_name__ var => 'MsoAutoSize' + + [X] add __url__ var => 'http:// ...' + + In order to provide single-source for both code and documentation, the + Enumeration class shall provide a documentation page generation method + that generates Sphinx RST source for a documentation page for the + enumeration. This page source shall be available as either the + docstring (__doc__) value of the class or its __str__ value. The + supplied docstring shall be pre-pended to the generated portion after + the top matter such as page title and reference link are generated. + +* [X] convert all existing enums to new type to make sure they all work + + + [X] MSO_AUTO_SIZE + + [X] MSO_VERTICAL_ANCHOR (__init__ -> enum.text) + + [X] MSO_FILL_TYPE (__init__ -> enum.dml) + + [X] MSO_COLOR_TYPE (__init__ -> enum.dml) + + [X] others ... + + [>] PP_PARAGRAPH_ALIGNMENT (constants -> enum.text) + + [X] TEXT_ALIGN_TYPE (constants -> delete) + + [X] TEXT_ANCHORING_TYPE (constants -> delete) + + [X] MSO_SHAPE_TYPE (constants.MSO -> enum.shapes.MSO_SHAPE_TYPE) + + [X] MSO.ANCHOR_* (constants -> MSO_VERTICAL_ANCHOR) + + [X] PP_PLACEHOLDER_TYPE: PH_TYPE_* in spec.py PpPlaceholderType + + [X] ST_Direction: PH_ORIENT_* + + [X] ST_PlaceholderSize: PH_SZ_* + + [X] MSO_AUTO_SHAPE_TYPE (constants -> enum.shapes) + + [X] What is pml_parttypes doing in spec? I thought that went a long time + ago? must be dead code now. + + [X] fix all enum references in documentation + + [X] adjust all examples that use enum or constants + + [X] spec: pretty sure default content types belong in opc somewhere + +* [ ] ... starting to think that combining to_xml() and from_xml() into enums + is not the best idea: + + + [ ] There are two separate concerns: (1) provide a symbolic reference for + use in the API to specify an enumerated option. (2) provide one of + potentially several mappings between that value and values in + different domains. + + + [ ] could create custom Enumeration subclasses to accommodate special + cases where there are mappings beyond to and from an XML attribute + value. + + + [ ] could create value objects that perhaps encapsulate those mappings. + I suppose that's what Enumeration is now. + +* [X] issue: does to/from XML translation replace an ST_* class in oxml? + (Probably can't fully replace, need validation and other bits as well. + Might be best to wait until a few examples have accumulated.) + + In order to support DRY translation between enumeration values and XML + simple type (ST_*) attribute values, the Enumeration class shall + provide both to_xml(enum_value) and from_xml(attr_value) methods where + enumeration values map to XML attribute values. + +* [ ] issue: how handle case where more than one XML to name mapping is + possible? Like both True and SINGLE set underline to 'single'? Where if + anywhere does that cause a conflict? + + The other direction of this is when more than one XML value should map + to None. + +* [ ] issue: how add clsdict._xml_to_member dict unconditionally to + subclasses of XmlEnumeration? use __init__ instead of __new__ for that + part:: + + def __init__(cls, clsname, bases, clsdict): + cls._collect_valid_settings = [] + + - init time might be too late, no handy ref to metaclass? + - could catch __new__ on separate XmlMappedEnumMember metaclass and add + the attribute(s) then. + +* [ ] deprecate prior versions: + + + [ ] MSO_VERTICAL_ANCHOR from enum/__init__.py + +* [ ] consider adding a feature whereby aliases can be defined for an enum + member name + +* [ ] consider what requirements an ST_* enumeration might have, aside from + or in addition to an API enumeration + +* [ ] need a page or whatever in the user guide to talk about how fills are + applied and give example code + +* [ ] how could enumeration documentation be generated automatically from + enumerations as part of the Sphinx run? + + +Code Sketches +------------- + +enabling an @alias decorator to define aliases for an enumeration class:: + + #!/usr/bin/env python + + from __future__ import absolute_import, print_function + + + def alias(*aliases): + """ + Decorating a class with @alias('FOO', 'BAR', ..) allows the class to + be referenced by each of the names provided as arguments. + """ + def decorator(cls): + for alias in aliases: + globals()[alias] = cls + return cls + return decorator + + + @alias('BAR', 'BAZ') + class FOO(object): + BAR = 'Foobarish' + + + print("FOO.BAR => '%s'" % FOO.BAR) + print("BAR.BAR => '%s'" % BAR.BAR) # noqa + print("BAZ.BAR => '%s'" % BAZ.BAR) # noqa diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/index.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..028b113b825437c642d2b92c39860c1ee97f98f8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/index.rst @@ -0,0 +1,156 @@ + +Analysis +======== + +Documentation of studies undertaken in support of API and code design. + +Feature Analysis +---------------- + +Roughly in reverse chronological order of creation: + + +Slides +~~~~~~ + +.. toctree:: + :maxdepth: 1 + + sld-background + sld-notes-slide + sld-notes-master + sld-base + sld-slide + sld-master + sld-layout + + +Chart +~~~~~ + +.. toctree:: + :maxdepth: 1 + + cht-chart + cht-chart-title + cht-axis-title + cht-data-labels + cht-date-axis + cht-categories + cht-marker + cht-chart-overview + cht-area-chart + cht-doughnut-chart + cht-points + cht-radar-chart + cht-bubble-chart + cht-xy-chart + cht-line-chart + cht-pie-chart + cht-bar-chart + cht-plots + cht-legend.rst + cht-add-chart.rst + cht-chart-data.rst + cht-tick-labels.rst + cht-plot-data.rst + cht-axis-unit.rst + cht-chart-type + cht-invert-if-negative + cht-axis-has-gridlines + cht-series + cht-access-xlsx + cht-axes + cht-chart-shape + + +Table +~~~~~ + +.. toctree:: + :titlesonly: + + tbl-merge + tbl-table + tbl-table-style + + +Shape +~~~~~ + +.. toctree:: + :titlesonly: + + sld-slide-shapes + shp-shapes + shp-pos-and-size + shp-autofit + shp-group-shape + shp-autoshape + shp-shadow + shp-freeform + shp-connector + shp-picture + shp-graphfrm + shp-ole-object + shp-movie + shp-hyperlink + placeholders/index + shp-preset-geom + + +Text +~~~~ + +.. toctree:: + :maxdepth: 1 + + txt-para-spacing + txt-fit-text + txt-autofit-text + txt-text + txt-font-underline + txt-font-color + txt-font-typeface + txt-hyperlink + + +Presentation +~~~~~~~~~~~~ + +.. toctree:: + :maxdepth: 1 + + prs-properties + + +DrawingML +~~~~~~~~~ + +.. toctree:: + :maxdepth: 1 + + dml-color + dml-fill + dml-gradient + dml-line + + +Package +~~~~~~~ + +.. toctree:: + :maxdepth: 1 + + pkg-coreprops + enumerations + + +Major discovery sources +----------------------- + +* ISO/IEC 29500 Open XML specification +* XSD schemas for Open XML +* MSDN PowerPoint® API documentation +* Inspection of XML generated by PowerPoint® client +* Inspection of PowerPoint® client GUI diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/pkg-coreprops.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/pkg-coreprops.rst new file mode 100644 index 0000000000000000000000000000000000000000..016ed84f741bc21abcf4baa5e0099f77dabe170d --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/pkg-coreprops.rst @@ -0,0 +1,132 @@ +######################## +Core Document Properties +######################## + +:Updated: 2013-06-22 +:Author: Steve Canny +:Status: **WORKING DRAFT** + + +Introduction +============ + +The 'Core' in core document properties refers to `Dublin Core`_, a metadata +standard that defines a core set of elements to describe resources. + +ISO/IEC 29500-2 Section 11 + + +API Sketch +========== + +Presentation.core_properties + +_CoreProperties(): + +All string values are limited to 255 chars (unicode chars, not bytes) + +* title +* subject +* author +* keywords +* comments +* last_modified_by +* revision (integer) +* created (date in format: '2013-04-06T06:03:36Z') +* modified (date in same format) +* category + + +Status and company (and many others) are custom properties, held in +``app.xml``. + + +XML produced by PowerPoint® client +================================== + +.. highlight:: xml + +:: + + + + Core Document Properties Exploration + PowerPoint core document properties + Steve Canny + powerpoint; open xml; dublin core; microsoft office + One thing I'd like to discover is just how line wrapping is handled in the comments. This paragraph is all on a single line._x000d__x000d_This is a second paragraph separated from the first by two line feeds. + Steve Canny + 2 + 2013-04-06T06:03:36Z + 2013-06-15T06:09:18Z + analysis + + + +Schema +====== + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +.. _Dublin Core: + http://en.wikipedia.org/wiki/Dublin_Core diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/index.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..22a04d776c8641ff00f395798f63a49a1b4a79aa --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/index.rst @@ -0,0 +1,286 @@ +.. _placeholder: + +Placeholders +============ + +.. toctree:: + :titlesonly: + + slide-placeholders/index + layout-placeholders + master-placeholders + +From a user perspective, a placeholder is a container into which content can +be inserted. The position, size, and formatting of content inserted into the +placeholder is determined by the placeholder, allowing those key presentation +design characteristics to be determined at design time and kept consistent +across presentations created from a particular template. + +The placeholder appearing on a slide is only part of the overall placeholder +mechanism however. Placeholder behavior requires three different categories +of placeholder shape; those that exist on a slide master, those on a slide +layout, and those that ultimately appear on a slide in a presentation. + +These three categories of placeholder participate in a property inheritance +hierarchy, either as an inheritor, an inheritee, or both. Placeholder shapes +on masters are inheritees only. Conversely placeholder shapes on slides are +inheritors only. Placeholders on slide layouts are both, a possible inheritor +from a slide master placeholder and an inheritee to placeholders on slides +linked to that layout. + +A layout inherits from its master differently than a slide inherits from +its layout. A layout placeholder inherits from the master placeholder sharing +the same type. A slide placeholder inherits from the layout placeholder +having the same `idx` value. + +Glossary +-------- + +placeholder shape + A shape on a slide that inherits from a layout placeholder. + +layout placeholder + a shorthand name for the placeholder shape on the slide layout from which + a particular placeholder on a slide inherits shape properties + +master placeholder + the placeholder shape on the slide master which a layout placeholder + inherits from, if any. + + +Schema excerpt +-------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Notes on footer item placeholders +--------------------------------- + +Recommendation and Argumentation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Place page number (and perhaps copyright, date) on master in plain text boxes. +Use "Hide Background Graphics" option on title slide to prevent them showing +there if desired. + +* In the slide placeholder method, an individually selectable footer item + placeholder is present on the slide: + + + It can be moved accidentally, losing the placement consistency originally + imposed by the master. Recovering exact placement requires reapplying the + layout which may make other, unwanted changes. + + It can be deleted, which could be a plus or minus depending. + + It can be formatted inconsistently. + + In can be accidentally selected and generally pollutes the shape space of + the slide. + +* I'm not sure python-pptx does the right thing when adding slides from layouts + containing footer items, at least not the same thing as PowerPoint does in + automatically working out which footer items to copy over. + + Also, there's no method to copy over footer items from the layout. + +* Alternatives: + + 1. A page number can be placed on the master as a text box. This causes it to + appear on every layout and every slide. No refreshing is necessary as this + item is inherited, not copied at slide or layout create time. + + It can be excluded from an individual layout (such as a title slide + layout) by setting the `Hide Background Graphics` flag on + a layout-by-layout basis. Unfortunately, this also hides other items such + as a logo, copyright text, and slide background, but these can be + reapplied individually directly to that slide layout. Since the title + slide layout is generally the only one folks want to hide a slide number + from, this is perhaps not a great burden. Others, like perhaps closing + slides, might have their own background anyway. + + +Hypothesis: +~~~~~~~~~~~ + +* There is a class of placeholders known as "footer elements", comprising date + and time, footer text, and slide number. + +* These placeholders can only be directly added to a master. They are not + available as options to add directly to a layout or to a slide. + +* In every case, these placeholders are copied, although some attributes may be + inherited at run time (not sure). Footer items are copied from the master to + a new layout. Likewise, items are copied from a layout to a slide, but only + when explicitly asked for using Insert > Header and Footer. PowerPoint + sometimes adds these automatically when they're already present on other + slides (don't know the rules it uses). + + +Intended procedure +~~~~~~~~~~~~~~~~~~ + +This is how slide footer items are designed to be used: + +* Add footer placeholders to master with intended standard position and + formatting. + +* Available by default on each layout. Can be disabled for individual layouts, + for example, the title slide layout using the Slide Master Ribbon > Edit + Layout > Allow Footers checkbox. Also can be deleted and formatting changed + individually on a layout-by-layout basis. + +* Hidden by default on new slides. Use Insert > Header and Footer dialog to add + which items to show. Can be applied to all slides. Under certain + circumstances, PowerPoint adds selected footer items to new slides + automatically, based on them being present on other slides already in the + presentation. + + +PowerPoint Behaviors +~~~~~~~~~~~~~~~~~~~~ + +* Layout: Slide Master (ribbon) > Edit Layout > Allow Footers (checkbox) + + + Adding or removing a footer item from a layout, does not automatically + reflect that change on existing slides based on that layout. The change is + also not reflected when you reapply the layout, at least for deleting case. + + - It does not appear when you reapply the layout ('Reset Layout to Default + Settings' on Mac) + +* Position appears to be inherited as long as you haven't moved the placeholder + on the slide. This applies at master -> layout as well as layout -> slide + level. + + + Refreshing the layout after the page number item has been deleted leaves + the page number item, but repositions it to a default (right justified to + right slide edge) position. Apparently it attempts to inherit the position + from the layout but not presence (or not). + +* The `Allow Footers` checkbox is inactive (not greyed out but can't be set on) + when there are no footer placeholder items on the master. + +* Allow footers seems to be something of a one-way street. You can't clear the + checkbox once it's set. However, if you delete the footer placeholder(s), the + checkbox clears all by itself. + +* The placeholder copied from master to layout can be repositioned and + formatted (font etc.). + +* Menu > Insert > Header and Footer ... Is available on individual slides and + can be applied to all slides. It also works for removing footer items. This + applies to *slides*, not to slide layouts. + + This dialog is also available from the Page Setup dialog. + +* Hide background graphics flag does not control footer items. It does however + control visibility of all non-placeholder items on the layout (or slide). + It's available at both the layout and slide level. Not sure how that's + reflected in the XML. + +* When creating a new slide layout, the footer placeholders from the master are + all automatically shown. This is to say that the "Allow Footers" ribbon + option defaults to True when adding a new slide layout. + + Clicking Allow Footers off hides all the footer items. They can also be + deleted or formatted individually. + +* In order to appear (at create time anyway), footer items need to be: + + 1. Present on the master + 2. Present on the layout ('Allow Footers' turned on, ph not deleted) + 3. Insert Header and Footer turned on for each ph element to be shown. This + is applied on a slide-by-slide basis. + + +Notes +~~~~~ + +* Header is a misnomer as far as slides are concerned. There are no header + items for a slide. A notes page can have a header though, which I expect is + why it appears, since the same dialog is used for slides and notes pages (and + handouts). + +* A master is intended only to contain certain items: + + + Title + + Body + + Footer placeholders (date/time, footer text, slide number) + + Background and theme items, perhaps logos and static text + + +* http://www.powerpointninja.com/templates/powerpoint-templates-beware-of-the-footers/ + +* https://github.com/scanny/python-pptx/issues/64 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/layout-placeholders.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/layout-placeholders.rst new file mode 100644 index 0000000000000000000000000000000000000000..e2383e0bb8e468732436db0ac446d45eebbba5f8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/layout-placeholders.rst @@ -0,0 +1,128 @@ + +Layout Placeholders +=================== + + +Candidate protocol +------------------ + +:: + + >>> slide_layout = prs.slide_layouts[0] + >>> slide_layout + + >>> slide_layout.shapes + + >>> slide_layout.shapes[0] + + >>> layout_placeholders = slide_layout.placeholders + >>> layout_placeholders + + >>> len(layout_placeholders) + 5 + >>> layout_placeholders[1].type + 'body' + >>> layout_placeholders[2].idx + 10 + >>> layout_placeholders.get(idx=0) + + >>> layout_placeholders.get(idx=666) + None + >>> layout_placeholders[1]._sp.spPr.xfrm + None + >>> layout_placeholders[1].width # should inherit from master placehldr + 8229600 + + +Example XML +----------- + +Slide layout placeholder:: + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + ... and others through lvl="4", five total + + + + + +Behaviors +--------- + +* Hypothesis: + + + Layout inherits properties from master based only on type (e.g. body, + dt), with no bearing on idx value. + + Slide inherits from layout strictly on idx value. + + + Need to experiment to see if position and size are inherited on body + placeholder by type or if idx has any effect + + - expanded/repackaged, change body ph idx on layout and see if still + inherits position. + - result: slide layout still appears with the proper position and size, + however the slide placeholder appears at (0, 0) and apparently with + size of (0, 0). + + + What behavior is exhibited when a slide layout contains two body + placeholders, neither of which has a matching idx value and neither of + which has a specified size or position? + + - result: both placeholders are present, directly superimposed upon each + other. They both inherit position and fill. + + +Layout placeholder inheritance +------------------------------ + +Objective: determine layout placeholder inheritee for each ph type + +Observations: + +Layout placeholder with *lyt-ph-type* inherits color from master placeholder +with *mst-ph-type*, noting idx value match. + +=========== =========== =================================================== +lyt-ph-type mst-ph-type notes +=========== =========== =================================================== +ctrTitle title title layout - idx value matches (None, => 0) +subTitle body title layout - idx value matches (1) +dt dt title layout - idx 10 != 2 +ftr ftr title layout - idx 11 != 3 +sldNum sldNum title layout - idx 12 != 4 +title title bullet layout - idx value matches (None, => 0) +None (obj) body bullet layout - idx value matches (1) +body body sect hdr - idx value matches (1) +None (obj) body two content - idx 2 != 1 +body body comparison - idx 3 != 1 +pic body picture - idx value matches (1) +chart body manual - idx 9 != 1 +clipArt body manual - idx 9 != 1 +dgm body manual - idx 9 != 1 +media body manual - idx 9 != 1 +tbl body manual - idx 9 != 1 + +hdr repair err valid only in Notes and Handout Slide +sldImg repair err valid only in Notes and Handout Slide +=========== =========== =================================================== diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/master-placeholders.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/master-placeholders.rst new file mode 100644 index 0000000000000000000000000000000000000000..023eb82091175f95deac78878058e5afa3ef9c7f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/master-placeholders.rst @@ -0,0 +1,114 @@ + +Master Placeholders +=================== + + +Candidate protocol +------------------ + +:: + + >>> slide_master = prs.slide_master + >>> slide_master.shapes + + + >>> slide_master.shapes[0] + + >>> master_placeholders = slide_master.placeholders + >>> master_placeholders + + >>> len(master_placeholders) + 5 + >>> master_placeholders[0].type + 'title' + >>> master_placeholders[0].idx + 0 + >>> master_placeholders.get(type='body') + + >>> master_placeholders.get(idx=666) + None + + +Example XML +----------- + +Slide master placeholder:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + ... and others through lvl="4", five total + + + + + +Behaviors +--------- + +* Master placeholder specifies size, position, geometry, and text body + properties, such as margins (inset) and autofit + +* It appears a slide master permits at most five placeholders, at most one + each of title, body, date, footer, and slide number + +* A master placeholder is always a `` (autoshape) element. It does not + allow the insertion of content, although text entered in the shape somehow + becomes the prompt text for inheriting placeholders. + +* Hypothesis: + + + Layout inherits properties from master based only on type (e.g. body, + dt), with no bearing on idx value. + + Slide inherits from layout strictly on idx value. + + + Need to experiment to see if position and size are inherited on body + placeholder by type or if idx has any effect + + - expanded/repackaged, change body ph idx on layout and see if still + inherits position. + - result: slide layout still appears with the proper position and size, + however the slide placeholder appears at (0, 0) and apparently with + size of (0, 0). + + + What behavior is exhibited when a slide layout contains two body + placeholders, neither of which has a matching idx value and neither of + which has a specified size or position? + + - result: both placeholders are present, directly superimposed upon each + other. They both inherit position and fill. + +* GUI doesn't seem to provide a way to add additional "footer" placeholders + +* Does the MS API include populated object placeholders in the Placeholders + collection? diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/index.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..6b8f067b033b1ccbe00f167d2b5fba0c8af7b8ef --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/index.rst @@ -0,0 +1,268 @@ + +Slide Placeholders +================== + +.. toctree:: + :titlesonly: + + picture-placeholder + table-placeholder + placeholders-in-new-slide + + +Candidate protocol +------------------ + +:: + + >>> slide = prs.slides[0] + >>> slide.shapes + + >>> slide.shapes[0] + + >>> slide_placeholders = slide.placeholders + >>> slide_placeholders + + >>> len(slide_placeholders) + 2 + >>> slide_placeholders[1] + + >>> slide_placeholders[1].type + 'body' + >>> slide_placeholders.get(idx=1) + AttributeError ... + >>> slide_placeholders[1]._sp.spPr.xfrm + None + >>> slide_placeholders[1].width # should inherit from layout placeholder + 8229600 + >>> table = slide_placeholders[1].insert_table(rows=2, cols=2) + >>> len(slide_placeholders) + 2 + + +Inheritance behaviors +--------------------- + +A placeholder shape on a slide is initially little more than a reference to +its "parent" placeholder shape on the slide layout. If it is a placeholder +shape that can accept text, it contains a `` element. Position, +size, and even geometry are inherited from the layout placeholder, which may +in turn inherit one or more of those properties from a master placeholder. + + +Substitution behaviors +---------------------- + +Content may be placed into a placeholder shape two ways, by *insertion* and +by *substitution*. Insertion is simply placing the text insertion point in +the placeholder and typing or pasting in text. Substitution occurs when an +object such as a table or picture is inserted into a placeholder by clicking +on a placeholder button. + +An empty placeholder is always a `` (autoshape) element. When an object +such as a table is inserted into the placehoder by clicking on a placeholder +button, the `` element is replaced with the appropriate new shape +element, a table element in this case. The `` element is retained in +the new shape element and preserves the linkage to the layout placeholder +such that the 'empty' placeholder shape can be restored if the inserted +object is deleted. + + +Operations +---------- + +* clone on slide create +* query inherited property values +* substitution + + +Example XML +----------- + +.. highlight:: xml + +Baseline textbox shape:: + + + + + + + + + + + + + + + + + + + + + + + + + + Some text + + + + + + + +Content placeholder:: + + + + + + + + + + + + + + + + + + + + + + +Notable differences: + +* placeholder has `` element +* placeholder has `` element +* placeholder has no `` child elements, implying both that: + + + all shape properties are initially inherited from the layout placeholder, + including position, size, and geometry + + any specific shape property value may be overridden by specifying it on + the inheriting shape + + +Matching slide layout placeholder:: + + + + + + + + + + + + + + + + + + + + Click to edit Master text styles + + + + ... and others through lvl="4", five total + + + + + +Behaviors +--------- + +* A placeholder is accessed through a slide-type object's shape collection, + e.g. ``slide.shapes.placeholders``. The contents of the placeholders + collection is a subset of the shapes in the shape collection. + +* The title placeholder, if it exists, always appears first in the + placeholders collection. + +* Placeholders can only be top-level shapes, they cannot be nested in a group + shape. + +* A slide placeholder may be either an `` (autoshape) element or + a `` or `` element. In either case, its relationship + to its layout placeholder is preserved. + +* Slide inherits from layout strictly on idx value. + +* The placeholder with idx="0" is the title placeholder. "0" is the default + for the *idx* attribute on , so one with no idx attribute is the + title placeholder. + +* The document order of placeholders signifies their z-order and has no + bearing on their index order. :attr:`_ShapeCollection.placeholders` contains + the placeholders in order of *idx* value, which means the title placeholder + always appears first in the sequence, if it is present. + +Automatic naming +~~~~~~~~~~~~~~~~ + +* Most placeholders are automatically named '{root_name} Placeholder {num}' + where *root_name* is something like ``Chart`` and num is a positive integer. + A typical example is ``Table Placeholder 3``. + +* A placeholder with vertical orientation, i.e. ````, is + prefixed with ``'Vertical '``, e.g. ``Vertical Text Placeholder 2``. + +* The word ``'Placeholder'`` is omitted when the type is 'title', 'ctrTitle', + or 'subTitle'. + +On slide creation +~~~~~~~~~~~~~~~~~ + +When a new slide is added to a presentation, empty placeholders are added to +it based on the placeholders present in the specified slide layout. + +Only content placeholders are created automatically. Special placeholders +must be created individually with additional calls. Special placeholders +include header, footer, page numbers, date, and slide number; and perhaps +others. In this respect, it seems like special placeholders on a slide layout +are simply default settings for those placeholders in case they are added +later. + +During slide life-cycle +~~~~~~~~~~~~~~~~~~~~~~~ + +* Placeholders can be deleted from slides and can be restored by calling + methods like AddTitle on the shape collection. AddTitle raises if there's + already a title placeholder, so need to call .hasTitle() beforehand. + + +Experimental findings -- Applying layouts +----------------------------------------- + +* Switching the layout of an empty title slide to the blank layout resulted + in the placeholder shapes (title, subtitle) being removed. +* The same switch when the shapes had content (text), resulted in the shapes + being preserved, complete with their `` element. Position and + dimension values were added that preserve the height, width, top position + but set the left position to zero. +* Restoring the original layout caused those position and dimension values to + be removed (and "re-inherited"). +* Applying a new (or the same) style to a slide appears to reset selected + properties such that they are re-inherited from the new layout. Size and + position are both reset. Background color and font, at least, are not + reset. +* The "Reset Layout to Default Settings" option appears to reset all shape + properties to inherited, without exception. +* Content of a placeholder shape is retained and displayed, even when the + slide layout is changed to one without a matching layout placeholder. +* The behavior when placeholders are added to a slide layout (from the slide + master) may also be worth characterizing. + + + ... show master placeholder ... + + ... add (arbitrary) placeholder ... diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/picture-placeholder.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/picture-placeholder.rst new file mode 100644 index 0000000000000000000000000000000000000000..fceaf28f4516ee9224e4070e2ae933856106822b --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/picture-placeholder.rst @@ -0,0 +1,109 @@ + +Picture placeholder +=================== + +A picture placeholder is an unpopulated placeholder into which an image can +be inserted. This comprises three concrete placeholder types, a picture +placeholder, a clip art placeholder, and a content placeholder. Each of +these, and indeed any unpopulated placeholder, take the form of a `p:sp` +element in the XML. Once populated with an image, these placeholders become +a *placeholder picture* and take the form of a `p:pic` element. + + +Candidate protocol +------------------ + +Placeholder access:: + + >>> picture_placeholder = slide.placeholders[1] # keyed by idx, not offset + >>> picture_placeholder + + >>> picture_placeholder.shape_type + MSO_SHAPE_TYPE.PLACEHOLDER (14) + +PicturePlaceholder.insert_picture():: + + >>> placeholder_picture = picture_placeholder.insert_picture('image.png') + >>> placeholder_picture + + >>> placeholder_picture.shape_type + MSO_SHAPE_TYPE.PLACEHOLDER (14) + + +Example XML +----------- + +.. highlight:: xml + +A picture-only layout placholder:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + +An unpopulated picture-only placeholder on a slide:: + + + + + + + + + + + + + + +A picture-only placeholder populated with an image:: + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/placeholders-in-new-slide.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/placeholders-in-new-slide.rst new file mode 100644 index 0000000000000000000000000000000000000000..d10bdefe21c0e21caa204ecac0b9b9e9d06623b8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/placeholders-in-new-slide.rst @@ -0,0 +1,216 @@ +========================= +Placeholders in new slide +========================= + +Topic of inquiry +================ + +What placeholder shapes are added to a new slide when it is added to a +presentation? + + +Abstract +======== + +Slides were created based on a variety of slide layouts so their placeholder +elements could be inspected to reveal slide construction behaviors that depend +on the slide layout chosen. A placeholder shape appeared in each slide +corresponding to each of the placeholder shapes in the slide layout, excepting +those of footer, date, and slide number type. Placeholder shapes were +```` elements for all placeholder types rather than matching the element +type of the shape they hold a place for. Each slide-side placeholder had a +```` element that exactly matched the corresponding element in the slide +layout, with the exception that a *hasCustomPrompt* attribute, if present in +the slide layout, did not appear in the slide. Placeholders in the slide were +named and numbered differently. All placeholders in the slide layout had a +```` element, but only certain types had one in the slide. All +placeholders were locked against grouping. + + +Procedure +========= + +This procedure was run using PowerPoint for Mac 2011 running on an Intel-based +Mac Pro running Mountain Lion 10.8.2. + +1. Create a new presentation based on the "White" theme. + +#. Add a new slide layout and add placeholders of the following types. The + new slide layout is (automatically) named *Custom Layout*. + + * Chart + * Table + * SmartArt Graphic + * Media + * Clip Art + +#. Add a new slide for each of the following layouts. Do not enter any content + into the placeholders. + + * Title Slide (added automatically on File > New) + * Title and Content + * Two Content + * Comparison + * Content with Caption + * Picture with Caption + * Vertical Title and Text + * Custom Layout + +#. Save and unpack the presentation. This command works on OS X: ``unzip + white.pptx -d white`` + +#. Inspect the slide.xml files and compare placeholders with those present in + their corresponding slideLayout.xml file. + + +Observations +============ + +Typical XML for a placeholder:: + + + + + + + + + + + + + + + + + + + + + + +elements +^^^^^^^^ + +* Placeholder shapes **WERE** created corresponding to layout placeholders of + the following types in the slide layout: + + * ``'title'`` + * ``'body'`` + * ``'ctrTitle'`` + * ``'subTitle'`` + * ``'obj'`` + * ``'chart'`` + * ``'tbl'`` + * ``'clipArt'`` + * ``'dgm'`` (SmartArt Graphic, perhaps abbreviation of 'diagram') + * ``'media'`` + * ``'pic'`` + * ``None`` (type attribute default is ``'obj'``) + +* Placeholder shapes **WERE NOT** created corresponding to layout placeholders + of these types in the slide layout: + + * ``'dt'`` (date) + * ``'sldNum'`` (slide number) + * ``'ftr'`` (footer) + +* The following placeholder types do not apply to slides (they apply to notes + pages and/or handouts). + + * ``'hdr'`` + * ``'sldImg'`` + +* ** element**. Placeholder shapes of the following types had a + ```` element. Placeholders of all other types did not have a + ```` element. + + * ``'title'`` + * ``'body'`` + * ``'ctrTitle'`` + * ``'subTitle'`` + * ``'obj'`` (and those without a ``type`` attribute) + +* ** element**. Each placeholder shape in each slide had a + ```` element (it is a required element) populated with *id* and + *name* attributes. + + * The value of the *id* attribute of ``p:cNvPr`` does not correspond to its + value in the slide layout. Shape ids were renumbered starting from 2 and + proceeding in sequence (e.g. 2, 3, 4, 5, ...). Note that id="1" belongs to + the spTree element, at ``/p:sld/p:cSld/p:spTree/p:nvGrpSpPr/p:cNvPr@id``. + + * The value of the *name* attribute is of the form '%s %d' % (type_name, + num), where type_name is determined by the placeholder type (e.g. 'Media + Placeholder') and num appears to default to ``id - 1``. The assigned name + in each case was similar to its counterpart in the slide layout (same + *type_name*), but its number was generally different. + +* **** element. Placeholder shapes of all types had the element + ```` specifying the placeholder could not be grouped + with any other shapes. + +* **** element. All placeholder shapes had an empty ```` + element. + + +attributes +^^^^^^^^^^ + +* **type**. The ``type`` attribute of the ```` element was copied + without change. Where no ``type`` attribute appeared (defaults to "obj", + indicating a "content" placeholder), no ``type`` attribute was added to the + ```` element. + +* **orient**. The ``orient`` attribute of the ```` element was copied + without change. Where no ``orient`` attribute appeared (defaults to "horz"), + no ``orient`` attribute was added to the ```` element. + +* **sz**. The ``sz`` (size) attribute of the ```` element was copied + without change. Where no ``sz`` attribute appeared (defaults to "full"), no + ``sz`` attribute was added to the ```` element. + +* **idx**. The ``idx`` attribute of the ```` element was copied without + change. Where no ``idx`` attribute appeared (defaults to "0", indicating the + singleton title placeholder), no ``idx`` attribute was added to the + ```` element. + +* **hasCustomPrompt**. The ``hasCustomPrompt`` attribute of the ```` + element was NOT copied from the slide layout to the slide. + + +Other observations +================== + +Placeholders created from the slide layout were always ```` elements, +even when they were a placeholder for a shape of another type, e.g. +````. When the on-screen placeholder for a table was clicked +to add a table, the ```` +element containing the table. The ```` element was retained in the new +shape. Reapplying the layout to the slide caused the table to move to the +original location of the placeholder (the idx may have been used for +matching). Deleting the table caused the original placeholder to reappear in +its original position. + + +Conclusions +=========== + +* Placeholder shapes are added to new slides based on the placeholders present + in the slide layout specified on slide creation. +* Placeholders for footer, slide number, and date are excluded. +* Each new placeholder is assigned an id starting from 2 and proceeding in + increments of 1 (e.g. 2, 3, 4, ...). +* Each new placeholder is named based on its type and the id assigned. +* Placeholders are locked against grouping. +* Placeholders of selected types get a minimal ```` element. +* Slide placeholders receive an exact copy of the ```` element in the + corresponding slide layout placeholder, except that the optional + ``hasCustomPrompt`` attribute, if present, is not copied. + +Open Questions +============== + +None. + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/table-placeholder.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/table-placeholder.rst new file mode 100644 index 0000000000000000000000000000000000000000..0b4615e1b985c3fee65e40bc9eda2a5a0e7fd34e --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/placeholders/slide-placeholders/table-placeholder.rst @@ -0,0 +1,132 @@ + +Table placeholder +================= + +A table placeholder is an unpopulated placeholder into which a table can be +inserted. This comprises two concrete placeholder types, a table placeholder +and a content placeholder. Both take the form of a `p:sp` element in the XML. +Once populated with a table, these placeholders become a *placeholder graphic +frame* and take the form of a `p:graphicFrame` element. + + +Candidate protocol +------------------ + +Placeholder access:: + + >>> table_placeholder = slide.placeholders[10] # keyed by idx, not offset + >>> table_placeholder + + >>> table_placeholder.shape_type + MSO_SHAPE_TYPE.PLACEHOLDER (14) + +TablePlaceholder.insert_table():: + + >>> ph_graphic_frame = table_placeholder.insert_table(rows=2, cols=2) + >>> ph_graphic_frame + + >>> ph_graphic_frame.shape_type + MSO_SHAPE_TYPE.PLACEHOLDER (14) + >>> ph_graphic_frame.has_table + True + >>> table = ph_graphic_frame.table + >>> len(table.rows), len(table.columns) + (2, 2) + + +Example XML +----------- + +.. highlight:: xml + +A table-only layout placholder:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +An unpopulated table-only placeholder on a slide:: + + + + + + + + + + + + + + +A table-only placeholder populated with a table:: + + + + + + + + + + + + + + + + + + + + + + + + + {5C22544A-7EE6-4342-B048-85BDC9FD1C3A} + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/prs-properties.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/prs-properties.rst new file mode 100644 index 0000000000000000000000000000000000000000..2ac188988d9276ae4ef649c7d0e155046984e619 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/prs-properties.rst @@ -0,0 +1,140 @@ + +Presentation properties +======================= + + +Overview +-------- + +The presentation object has a few interesting properties. Right now I'm +interested in slide size. + + + +Protocol +-------- + +:: + + >>> assert isinstance(prs, pptx.parts.presentation.PresentationPart) + >>> prs.slide_width + 9144000 + >>> prs.slide_height + 6858000 + >>> prs.slide_width = 11887200 # 13 inches + >>> prs.slide_height = 6686550 # 7.3125 inches + >>> prs.slide_width, prs.slide_height + (11887200, 6686550) + + +XML specimens +------------- + +.. highlight:: xml + +Example presentation.xml contents:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-autofit.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-autofit.rst new file mode 100644 index 0000000000000000000000000000000000000000..017acb6b96519922b95fdbcc4a3ae8bcf65b5f8f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-autofit.rst @@ -0,0 +1,156 @@ + +Autofit setting +=============== + +Overview +-------- + +PowerPoint provides the *autofit* property to specify how to handle text that +is too big to fit within its shape. The three possible settings are: + +* resize shape to fit text +* resize text to fit shape +* resize neither the shape nor the text, allowing the text to extend beyond + the bounding box + +Auto size is closely related to word wrap. + +There are certain constraining settings for resizing the text, not sure if +those are supported in PowerPoint or not. + + +Protocol +-------- + +:: + + >>> text_frame = shape.text_frame + >>> text_frame.auto_size + None + >>> text_frame.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT + >>> text_frame.auto_size + 1 + >>> text_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE + >>> text_frame.auto_size + 2 + >>> str(text_frame.auto_size) + 'MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE' + >>> text_frame.auto_size = MSO_AUTO_SIZE.NONE + >>> text_frame.auto_size + 0 + >>> text_frame.auto_size = None + >>> text_frame.auto_size + None + + +Scenarios +--------- + +**Default new textbox.** When adding a new texbox from the PowerPoint +toolbar, the new textbox sizes itself to fit the entered text. This +corresponds to the setting MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT and ``word_wrap += None``. + +``MSO_AUTO_SIZE.NONE``, ``word_wrap = False``. Text is free form, with +PowerPoint exhibiting no formatting behavior. Text appears just as entered +and lines are broken only where hard breaks are inserted. + +``MSO_AUTO_SIZE.NONE``, ``word_wrap = True``. Text is wrapped into +a column the width of the shape, but is not constrained vertically. + +``MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT``, ``word_wrap = False``. The width of +the shape expands as new text is entered. Line breaks occur only where hard +breaks are entered. The height of the shape grows to accommodate the number +of lines of entered text. Width and height shrink as extents of the text are +reduced by deleting text or reducing font size. + +``MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT``, ``word_wrap = True``. Text is +wrapped into a column the width of the shape, with the height of the shape +growing to accommodate the resulting number of lines. + +``MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE``, ``word_wrap = False``. Experiment +... + +``MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE``, ``word_wrap = True``. Experiment ... + + +XML specimens +------------- + +.. highlight:: xml + +Default new textbox:: + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-autoshape.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-autoshape.rst new file mode 100644 index 0000000000000000000000000000000000000000..5695793a685eb2e85d5ff05b5835eb894d5c8484 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-autoshape.rst @@ -0,0 +1,181 @@ +.. _autoshape: + +Auto Shape +========== + + +Summary +------- + +*AutoShape* is the name the MS Office API uses for a shape with preset +geometry, those referred to in the PowerPoint UI simply as *shape*. Typical +examples are a rectangle, a circle, or a star shape. An auto shape has a type +(preset geometry), an outline line style, a fill, and an effect, in addition to +a position and size. The outline, fill, and effect can each be None. + +Each auto shape is contained in an ```` element. + + +Auto shape type +--------------- + +There are 187 pre-defined auto shape types, each corresponding to a distinct +preset geometry. Some types have one or more *adjustment value*, which +corresponds to the position of an adjustment handle (small yellow diamond) on +the shape in the UI that changes an aspect of the shape geometry, for example +the corner radius of a rounded rectangle. + +* `MsoAutoShapeType Enumeration`_ page on MSDN + + +Adjustment values +----------------- + +Many auto shapes may be adjusted to change their shape beyond just their width, +height, and rotation. In the PowerPoint application, this is accomplished by +dragging small yellow diamond-shaped handles that appear on the shape when it +is selected. + +In the XML, the position of these adjustment handles is reflected in the +contents of the ```` element:: + + + + + + + +The |avLst| element can be empty, even if the shape has available adjustments. + +guide + a guide is essentially a variable within DrawingML. Its value is the result + of a simple expression like ``"*/ 100000 w ss"``. Its value may then be used + in other expressions or directly to specify a point, by referring to it by + name. + +```` stands for *guide* ... + +Where are the custom geometries defined? + The geometries for autoshapes are defined in ``presetShapeDefinitions.xml``, + located in: + + ``pptx/ref/ISO-IEC-29500-1/schemas/dml-geometries/OfficeOpenXML-DrawingMLGeometries/``. + +What is the range of the formula values? + In general, the nominal adjustment value range for the preset shapes is 0 to + 100000. However, the actual value stored can be outside that range, + depending on the formulas involved. For example, in the case of the chevron + shape, the range is from 0 to 100000 * width / short-side. When the shape is + taller than it is wide, width is the short side and the range is 0 to + 100000. However, when the shape is wider than it is tall, the range can be + much larger. Required values are probably best discovered via + experimentation or calculation based on the preset formula. + +The |gd| element does not appear initially when the shape is inserted. However, +if the adjustment handle is moved and then moved back to the default value, the +|gd| element is not removed. The default value becomes the effective value for +the guide if the |gd| element is not present. + +The adjustment value is preserved over scaling of the object. Its effective +value can change however, depending on the formula. In the case of the chevron +shape, the effective value is a function of ``ss``, the "short side", and the +adjustment handle moves on screen when the chevron is made wider than it is +tall. + +A certain level of documentation for auto shapes could be generated from the +XML shape definition file. The preset name and the number of adjustment values +it has (guide definitions) and the adjustment value name can readily be +determined by inspection of the XML. + +What coordinate system are the formula values expressed in? + There appear to be two coordinate systems at work. The 0 to 100000 bit the + adjustment handles are expressed in appears to be the (arbitrary) shape + coordinate system. The built-in values like ``w``, ``ss``, etc., appear to + be in the slide coordinate system, the one the ``xfrm`` element traffics in. + + Probably worth experimenting with some custom shapes to find out (edit and + rezip with bash one-liner). + +useful web resources + What useful web resources are out there on DrawingML? + + http://officeopenxml.com/drwSp-custGeom.php + + +XML produced by PowerPoint® client +---------------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is text inside a rounded rectangle + + + + + + + +Resources +--------- + +* `DrawingML Shapes`_ on officeopenxml.com + +* `Shape Object MSDN page`_ + +* `MsoShapeType Enumeration`_ + +.. _DrawingML Shapes: + http://officeopenxml.com/drwShape.php + +.. _Shape Object MSDN page: + http://msdn.microsoft.com/en-us/library/office/ff744177(v=office.14).aspx + +.. _MsoShapeType Enumeration: + http://msdn.microsoft.com/en-us/library/office/aa432678(v=office.14).aspx + +.. _`MsoAutoShapeType Enumeration`: + http://msdn.microsoft.com/en-us/library/office/aa432469(v=office.14).aspx + +.. |avLst| replace:: ```` + +.. |gd| replace:: ```` diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-connector.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-connector.rst new file mode 100644 index 0000000000000000000000000000000000000000..56b60a16cade22ed2d41cff8f2c736875a5916f8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-connector.rst @@ -0,0 +1,620 @@ + +Line/Connector Shape +==================== + +Lines are a sub-category of auto shape that differ in certain properties and +behaviors. In particular, they have a start point and end point in addition +to extents (left, top, width, height). + +Connectors are based on the ```` element and have one of a handful +of different preset geometry values, such as ``line``. Freeform connectors, +despite the name, are not connectors, and are a custom geometry shape based +on the p:sp element. + +Connectors can be "connected" to an auto shape such that a connected end +point remains connected when the auto shape is moved. This relies on +a concept of "connection points" on the auto shape. These connections points +are preset features of the auto shape, similar to how adjustment points are +pre-defined. Connection points are identified by index. + +Connector shapes do not have a text frame and cannot have text that is +anchored to the shape. + + +Design Issues +------------- + +* See how PowerPoint interprets the remaining connector types like + bentConnector2 + + +Unimplemented Scope +------------------- + +* Connector.shape_type = MSO_LINE +* BaseShape.is_connector + ConnectorShape.is_connector (not yet implemented) + +* [ ] see how a connector returns for `connector.AutoShapeType` in MS API. + + +PowerPoint behaviors +-------------------- + +* Once connected, moving the target shape moves the connector the same + amount, however, the relative position of the connector end-point is not + adjusted to align to the connection point; rather, the relative offset is + maintained. + + Also, when the connector is selected, the connected point is highlighted in + red, even though it is not coincident with the connection point. + +* Arrow heads are not a direct property of a connector, despite perhaps + appearing so in the UI. Line endings are a property of the line style of + the connector (and other shapes). + + +MS API +------ + +`Shapes Object Members `_ + +* AddConnector(Type, BeginX, BeginY, EndX, EndY) + + +`MsoConnectorType Enumeration `_ + ++-----------------------+----+-----------------------------------------------+ +| msoConnectorCurve | 3 | Curved connector. | ++-----------------------+----+-----------------------------------------------+ +| msoConnectorElbow | 2 | Elbow connector. | ++-----------------------+----+-----------------------------------------------+ +| msoConnectorStraight | 1 | Straight line connector. | ++-----------------------+----+-----------------------------------------------+ +| msoConnectorTypeMixed | -2 | Return only; indicates combination of states. | ++-----------------------+----+-----------------------------------------------+ + + +Protocols +--------- + +Properties:: + + >>> connector.is_connector + True + >>> connector.type + MSO_SHAPE_TYPE.LINE + >>> connector.start_x + 914400 + >>> connector.end_y + 914400 + >>> connector.adjustments + + +Creation protocol:: + + >>> line = shapes.add_connector( + ... MSO_CONNECTOR.STRAIGHT, start_x, start_y, end_x, end_y + ... ) + + +MS API Protocol +--------------- + + +Behaviors +--------- + +UI display +~~~~~~~~~~ + +Connector shapes do not display a bounding box when selected in the UI. Rather +their start and end points are highlighted with a small gray circle that can be +moved. If there is an adjustment, such as a mid-point, it is indicated in the +normal way with a small yellow diamond. These endpoints and adjustment diamond +cannot be individually selected. + + +Naming +~~~~~~ + +What determines the name automatically applied to a line or connector shape? +Can it change after shape creation, for example by applying an arrowhead? + + +Enumerations +------------ + +MsoConnectorType + +http://msdn.microsoft.com/en-us/library/office/ff860918(v=office.15).aspx + +===================== ===== =============================================== +Name Value Description +===================== ===== =============================================== +msoConnectorCurve 3 Curved connector. +msoConnectorElbow 2 Elbow connector. +msoConnectorStraight 1 Straight line connector. +msoConnectorTypeMixed -2 Return value only; indicates a combination of + the other states. +===================== ===== =============================================== + + +Specimen XML +------------ + +.. highlight:: xml + +Default connector shapes inserted from PowerPoint UI. + +Straight line (Connector):: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Straight arrow Connector:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Straight segment jointed connector:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Curved (S-like) connector:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Freeform connector:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Completely free-form line:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Analysis +-------- + +* The p:style element represents indirection of the connector visual + attributes to the theme part. + +* What's up with the p:style element? Does that have to be there? What + happens if we just leave that out? Is the `accent1` default universal + enough to pop in there without consideration? + +* Seems like the most common lines are connectors +* Connectors are a distinct shape type. They are very similar to + regular ````-based auto shapes, but lack a text frame. +* Hypothesis: There are really two types, connectors and free-form. + + + Connectors are based on the ```` element and have a preset + geometry (```` child of ````). + + Free-form lines are based on the ```` element and have a custom + geometry (```` child of ````). + +* Connectors don't have a fill. Free-form shapes do. Fill of free-form shapes + extends between the line and a line connecting the end points, whether + present or not. Since the lines can cross, this produces some possibly + surprising fill behaviors; there is no clear concept of inside and outside + for such a shape. + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ... other shape types removed ... + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-freeform.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-freeform.rst new file mode 100644 index 0000000000000000000000000000000000000000..12f3bcaa17e825981d0098206712f4fe4cd01672 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-freeform.rst @@ -0,0 +1,883 @@ + +Freeform Shapes +=============== + +PowerPoint AutoShapes, such as rectangles, circles, and triangles, have +a *preset* geometry. The user simply picks from a selection of some 160 +pre-defined shapes to place one on the slide, at which point they can be +scaled. Many shapes allow their geometry to be adjusted in certain ways using +adjustment points (by dragging the small yellow diamonds). + +PowerPoint also supports a much less commonly used but highly flexible sort +of shape having *custom geometry*. Whereas a shape with preset geometry has +that geometry defined internally to PowerPoint and simply referred to by +a keyname (such as 'rect'), a shape with custom geometry spells out the +custom geometry step-by-step in an XML subtree, using a sequence of moveTo, +lineTo, and other drawing commands. + + +Vocabulary +---------- + +* A freeform shape is composed of one or more *paths*. Each path may be + configured to get a stroke, a fill, both, or neither. This allows drawing + some shapes such as call-outs where, say, a reference line should be + stroked but not filled, and the callout balloon contour should be filled + but not stroked. + + Each path also has its own local coordinate system, which may come in handy + when using guides. I haven't seen any clear examples of this yet but + I haven't gone looking either. + + In any case, only a single path will be supported in the initial + implementation. + +* A path is composed of one or more *contours*. A contour can be a *closed + contour* or and *open contour*. The closure state only affects the + continuity of the contour outline (although it also adds a straight line + between start and end if needed). + +* A contour is specified by a starting point (``) followed by + a sequence of line segments, each of which can be a straight or curved. + Curve segments will not be supported in the initial implementation. + + The term *contour* is not "official", but there are behaviors that depend + on "continuous pen-down strokes", such as "cut-out" behavior. Consequently, + a term is needed. + + +Scope +----- + +* Move to, line to, and close, initially. +* Line style (solid, dashed, etc.) +* Fill pattern (solid, dashed, etc.) + +Limits of scope +~~~~~~~~~~~~~~~ + +* Curve segments will not be implemented initially. + + Curves wouldn't be that hard to add, but until anyone cares about the + control points and we have some live example about how those would be + calculated etc., we don't have a requirement to design to. + +* Multiple-path freeforms are out of scope for now. + + It's not immediately apparent what they would be good for, and they don't + seem to be required to fulfill present requirements. + + +Use Case 1 - Specify all points in slide coordinates +---------------------------------------------------- + +A very simple case can be had by specifying the verticies in slide +coordinates:: + + >>> freeform_builder = shapes.build_freeform(Inches(1.5), Inches(1)) + >>> freeform_builder.add_line_segments(( + ... (Inches(2), Inches(2)), + ... (Inches(1), Inches(2)), + ... (Inches(1.5), Inches(1)), + ... )) + >>> freeform_shape = freeform_builder.convert_to_shape() + >>> freeform_shape.left.inches, freeform_shape.top.inches + 1.0, 1.0 + >>> freeform_shape.width.inches, freeform_shape.height.inches + 1.0, 1.0 + +This method may be used to place a freeform shape when you know exactly where +you want the vertices to be positioned on the slide. The position and size of +the shape (its bounding box) is worked out automatically from the minimum and +maximum x and y positions of the points specified. + +The shape is automatically closed if the last vertex is the same as the +beginning vertex; otherwise the shape is left open. + +The library automatically subtracts the top-left corner (origin) coordinates +from each point to write the XML. + + +Use Case 2 - Specify points in custom coordinates +------------------------------------------------- + +The next step up in complexity is where a custom coordinate system is to be +used to specify vertices for a single shape. + +In this alternative, all the verticies are specified in custom coordinates +and a scaling factor is provided:: + + >>> freeform_builder = shapes.build_freeform( + ... 1500, 1000, scale=1000/Inches(1) + ... ) + >>> freeform_builder.add_line_segments(( + ... (2000, 2000), + ... (1000, 2000), + ... (1500, 1000), + ... )) + >>> freeform_shape = freeform_builder.convert_to_shape() + >>> freeform_shape.left.inches, freeform_shape.top.inches + 1.0, 1.0 + >>> freeform_shape.width.inches, freeform_shape.height.inches + 1.0, 1.0 + +This method creates a shape of exactly the same appearance as the prior +example. It's probably not the most natural approach because all coordinates +have to be translated to their position on the slide. However, it is an +option and it's more compact. It could also be made to work with floating +point values. + +This could also work by creating the shape at (0, 0) on the slide and then +simply moving the shape to where you wanted using its `.top` and `.left` +properties. + + +Use Case 3 - Specify origin for custom coordinates +-------------------------------------------------- + +This is perhaps the most natural approach for doing something fancy, like +creating individual shapes for each of the 50 US states within a particular +area of the slide such that their boundaries all align with adjacent states +to make a map of the United States. + +Like in the prior use case, verticies are specified in custom coordinates +and a scaling factor is provided. In addition, an origin in provided in slide +coordinates (EMU). This would correspond to the origin of the entire map of +the US in our example and represents where you want the top-left corner of +the map to be on the slide. + +It is up to the client code to adjust the vertices provided such that they +represent their position relative to this origin in the custom coordinates +provided. It is also up to the client to get the scaling factor right such +that the entire map fits in the intended area of the slide. + +In this scenario, `top` and `left` arguments are added to the +`.build_freeform()` call. These arguments should be given the same values for +each of the "interlocking" shapes. These two arguments each independently +take on the value of zero when omitted, which produces the behavior of the +prior use case:: + + >>> freeform_builder = shapes.build_freeform( + ... start_x=1500, start_y=1000, scale=1000/Inches(1), + ... top=Inches(1), left=Inches(2) + ... ) + >>> freeform_builder.add_line_segments(( + ... (2000, 2000), + ... (1000, 2000), + ... (1500, 1000), + ... )) + >>> freeform_shape = freeform_builder.convert_to_shape() + >>> freeform_shape.left.inches, freeform_shape.top.inches + 3.0, 2.0 + >>> freeform_shape.width.inches, freeform_shape.height.inches + 1.0, 1.0 + +As we can see here, the size of the shape is exactly the same, but it has +been translated to be relative to the slide coordinates provided in the +`.build_freeform()` call. + + +Use Case 4 - Specify position on conversion +------------------------------------------- + +Another use case is where you want to specify a shape entirely in terms of +its local coordinates, relative to its local origin (top-left corner). This +might be used when you want a custom shape that is not one of the 168 +provided preset geometry shapes, say an orthoganal projection cube or +something like that, and then place that in a variety of locations around the +slide. + +For this you build the shape as in Use Case 2, allowing the origin to default +to (0, 0), and then specify a position for the shape in the +`.convert_to_shape()` call. You can even call `.convert_to_shape()` multiple +times to "rubber stamp" the shape in various positions around the slide. + +Can you call `.convert_to_shape()` multiple times? Maybe that would be good! + + +Usage Notes +----------- + +**Closing a contour.** A contour is only *truly* closed if it ends with +a `` element. It can *appear* closed if its end point is the same as +its start point, but close inspection of the line-ends will reveal there is +no smooth transition around the starting corner. This is more apparent when +a wide line style is used for the outline. + +A `` element will cause a straight line segment to be drawn between +the last point point of the contour and the first. So it's not necessary to +repeat the first point as the last one if a straight line segment suits. The +advantage is small however, and might only be an optimization to consider +when thousands of freeform shapes were being drawn in a single presentation. + + +Candidate Protocol +------------------ + +Obtain a FreeformBuilder object:: + + >>> freeform_builder = shapes.build_freeform(50, 0, scale=100/Inches(1)) + >>> freeform_builder + + +The `x` and `y` arguments specify the starting pen location in local +coordinates. The `scale` argument determines the rendered size of the shape +relative to the values specified for the vertices. The `scale` argument can +be an `(x_scale, y_scale)` pair to specify a shape coordinate system that is +rectangular rather than square. + +**Add vertices to the freeform shape** an arbitrary number of straight line +segments can be added to the shape using the `add_line_segments()` method:: + + >>> vertices = ((100, 200), (200, 300), (300, 400)) + >>> freeform_builder.add_line_segments(vertices, close=True) + +The method also specifies whether the contour so generated should be closed +(`True` by default). Closing a contour causes its end point to be connected +to its starting point with a straight line segment. It also causes the +contour to form a smooth perimeter outline. A contour that is not closed will +have line end caps and may be assigned line ends like arrowheads. + +Although PowerPoint supports a variety of curved line segments, those will +not be implemented in this initial effort. + +**Add second and further contours** A path can have multiple distinct +contours. These contours can be separate and distinct or they can overlap. +A contour that is completely enclosed by another contour forms a "cutout" in +the enclosing contour. Where two contours partially overlap, the fill begins +at the outermost boundary and stops when it reaches another boundary. + +.. image:: /_static/img/freeform-03.png + +A new contour is begun by calling the `.move_to()` method:: + + >>> freeform_builder.move_to(x, y) + +* Set freeform coordinate system (extents) + + There is no need to explicitly specify the extents of the coordinate + system. The position and size of the shape can be calculated from the + origin provided and the maxima and minima of the vertices provided. + +* Specify the scaled size of the freeform shape + + This is also unnecessary to specify as it is implied by the scaling factor + provided and the maxima and minima of the vertices specified. + + +**Possible approach:** + +Optionally specify an alternate coordinate system in the initial call such +that parameters are: + +* `x, y` - X and Y coordinates of initial pen position. If no scaling factor + is provided, these are interpreted as `Length` values from the top-left + corner of the slide. + +* `scale=1.0` (*optional*) - Determines the scaling of the x and y values + used to specify the vertices. This is a proportion to a `Length` unit, + which is an `Emu`, 914400 to the inch. This value is conveniently formed by + division with a `Length` subclass, like `1000/Inches(1)` to give "1000 + units per inch" in that case. This could just as easily be `2142/Cm(1)` to + give "2142 units per centimeter". The default value of 1.0 means "1 unit + per Emu". + +* `left` (*optional*) - X-axis position of top-left corner of freeform shape + bounding box, specified as a `Length` (not scaled) value relative to + left edge of slide. If this value is not specified, it is calculated + from the minimum x position of the points in the shape. + +* `top` (*optional*) - Y-axis position of top-left corner of freeform shape + bounding box, specified as a `Length` (not scaled) value relative to + top edge of the slide. If this value is not specified, it is calculated + from the minimum y position of the points in the shape. + +* `y_scale=None` (*optional, not implemented*) - Y-axis scaling factor + (defaults to same as X-axis scaling factor) + +The shape size (extents) are calculated from max_X and max_Y in given +coordinates, multiplied by the scaling factor. + + +Experimentation +--------------- + +Q. How does PowerPoint behave if we leave out all the "guides" and connection + points, i.e. if the `a:gdLst` and `a:cxnLst` elements are empty? + +A. It likes it just fine. Might not be a bad idea to leave empty `a:gdLst` + and `a:cxnLst` elements in there though, when creating a new freeform XML + subtree, just to be a little safer compatibility-wise since PowerPoint + seems to always put them in there. + +---- + +Q. What happens if there's no `a:moveTo` element at the start of a path? + +A. The path does not appear; it is not drawn. Note this is contrary to the + (unofficial) documentation indicating that (0, 0) is used as the starting + pen location. + +---- + +Q. What happens if a second path overlaps the first one, i.e. partly in and + partly out? + +A. The "outside" portion of the overlapping contour becomes the outside of + the shape and the region between that contour and the boundary of the + first shape is shaded. This produces two (or more) "point" areas on the + perimeter of the first shape where the width is zero. + +---- + +Q. What happens if the last point is not the same as the first point and the + path is closed? + +A. A straight-line segment is added between the last point and the starting + point. The appearance is just as it is when the last point is the same as + the starting point. + +---- + +Q. What happens if you do a shape with an `a:moveTo` in the middle (producing + a gap in the outline) but then close the shape? Does it still get a fill + or is it considered open then? + +A. The `moveTo` operation essentially resets the "starting" point for closure + purposes. The remainder of the path is closed, but the part before the + `moveTo` remains an open contour. + +---- + +Q. What happens when the last point is the same as the first point but there + is no `a:close` element? + +A. The shape outline is discontinuous at the start/end point and does not + form a smooth contour at that point. The visual appearance depends on the + line ends and line end caps chosen. + +---- + +* [ ] What happens when negative coordinate values are used? + +* [ ] What happens when you close a contour right after an `a:moveTo`? + +* [ ] What is the point of having multiple paths? The only difference I can + see is that overlapping areas are not "subtracted" and you can have + a different coordinate system. I'm inclined to think it's all about + needing distinct coordinate systems for some reason, perhaps when + variables (guides ``) are used. + +* [ ] What is the purpose of the boolean `stroke` attribute on path? + + +PowerPoint UI behaviors +----------------------- + +* A freeform shape can be created using the ribbon Shape > Lines and + Connectors > Freeform command. There is also a "Curve" and "Scribble" + option. + +* A shape is then created by placing points with the mouse. In the freeform + case, each vertex defines a line segment. In the case of a curve freeform, + the vertices are control points. + +* Clicking close to the starting point closes the shape. Double-clicking also + ends the drawing, leaving the shape open. + +* Once created, an "Edit Points" option appears on the context menu when + right-clicking the shape. This allows the points to be fine-tuned. + +* Hypothesis: PowerPoint uses an arbitrary scale of 10,000 (period, not per + inch) as the coordinate space for a freeform shape added or edited using + the UI. The rules are more complicated, not sure what they are, but it + seems to start with a square of about that and move from there. + + +MS API +------ + +MS API protocol +~~~~~~~~~~~~~~~ + +.. highlight:: vbnet + +Example:: + + Set myDocument = ActivePresentation.Slides(1) + + With myDocument.Shapes.BuildFreeform(msoEditingCorner, 360, 200) + .AddNodes msoSegmentCurve, msoEditingCorner, _ + 380, 230, 400, 250, 450, 300 + .AddNodes msoSegmentCurve, msoEditingAuto, 480, 200 + .AddNodes msoSegmentLine, msoEditingAuto, 480, 40 + .AddNodes msoSegmentLine, msoEditingAuto, 360, 200 + .ConvertToShape + End With + +* Specify pen starting point in initial `BuildFreeform` call. + +* All points are specified in slide coordinates. + +* Specify each vertex separately in an `.AddNodes()` method call. It seems + like it should actually be named `.AddNode()`, but perhaps they consider + control points to be nodes separate from the vertex point. + + A line segment can be specified by specifying the x, y vertex of the ending + point. + + A curve segment can be specified by specifying additional control points + (nodes). The vertex can be specified to be a corner (one control point on + starting vertex), smooth (tangent at the vertex), or symmetric (we'd have + to experiment to see what that does exactly, no ready available + documentation). + +* The path is closed (or not) when the `.ConvertToShape()` method is called + on the `FreeformBuilder` object. It looks like it's closed if the last + point is coincident with the first and open otherwise. + +* There is no way to make a multi-path shape as far as I can tell. + +* The MS API provides no way to "lift the pen" to make a discontinuous path + as far as I can tell. (And so does not provide a way to make "cutouts" like + a lake within a landmass shape.) + + +MS API Objects +~~~~~~~~~~~~~~ + +* | Shapes.BuildFreeform(x, y) + | https://msdn.microsoft.com/VBA/PowerPoint-VBA/articles/shapes-buildfreeform-method-powerpoint + +* | FreeformBuilder + | https://msdn.microsoft.com/VBA/PowerPoint-VBA/articles/freeformbuilder-object-powerpoint + +* | FreeformBuilder.AddNodes() + | https://msdn.microsoft.com/en-us/vba/powerpoint-vba/articles/freeformbuilder-addnodes-method-powerpoint + +* | FreeformBuilder.ConvertToShape() + | https://msdn.microsoft.com/VBA/PowerPoint-VBA/articles/freeformbuilder-converttoshape-method-powerpoint + | Cannot be called before adding at least one segment to the shape. + +* | Shape.Nodes + | + +* | MsoSegmentType enumeration + | https://msdn.microsoft.com/VBA/Office-Shared-VBA/articles/msosegmenttype-enumeration-office + + +---------------------+-------+-----------------+ + | Name | Value | Description | + +---------------------+-------+-----------------+ + | msoSegmentCurve | 1 | Curve. | + +---------------------+-------+-----------------+ + | msoSegmentLine | 0 | Line. | + +---------------------+-------+-----------------+ + +* | MsoEditingType enumeration + | https://msdn.microsoft.com/VBA/Office-Shared-VBA/articles/msoeditingtype-enumeration-office + + +---------------------+-------+---------------------------------------------+ + | Name | Value | Description | + +---------------------+-------+---------------------------------------------+ + | msoEditingAuto | 0 | Editing type is appropriate to the segments | + | | | being connected. | + +---------------------+-------+---------------------------------------------+ + | msoEditingCorner | 1 | Corner node. | + +---------------------+-------+---------------------------------------------+ + | msoEditingSmooth | 2 | Smooth node. | + +---------------------+-------+---------------------------------------------+ + | msoEditingSymmetric | 3 | Symmetric node. | + +---------------------+-------+---------------------------------------------+ + + +XML Semantics +------------- + +* The `w` and `h` attributes of a `a:path` element specify size of the shape + canvas in local coordinates. + + + The **origin of the shape canvas** is at its top left corner and has the + value (0, 0) in local coordinates. The vertices must be translated by the + X and Y minima to place the bounding box tightly around the shape. + +* The `a:rect` element specifies the text-box extents for the shape. + +* The `a:pathLst` element contains zero or more `a:path` elements, each of + which specify a *path*. + +* A path has a *private* and *arbitrary* *integral* coordinate system defined + by the `w` and `h` attributes on the `a:path` element. This means that each + path in an `a:custGeom/a:pathLst` has an independent scaling for its + coordinate system. + +* A path is composed of a sequence of the following possible elements: + + + `a:moveTo` + + `a:lnTo` + + `a:arcTo` + + `a:quadBezTo` + + `a:cubicBezTo` + + `a:close` + + A path may begin with an `a:moveTo` element. This essentially locates the + starting location of the "pen". Each subsequent drawing command extends the + shape by adding a line segment. If the path does not begin with an + `a:moveTo` element, the path does not appear (it is not drawn). Note this + is contrary to the (unofficial) documentation indicating that (0, 0) is + used as the default starting pen location. + + A path can be open or closed. If an `a:close` element is added, a straight + line segment is drawn from the current pen location to the initial location + of the drawing sequence and the shape appears with a fill. If the pen is + already at the starting location, no additional line segment appears. If no + `a:close` element is added, the shape remains "open" and only the path + appears (no fill). + + A path can contain more than one drawing sequence, i.e. one sequence can be + "closed" and another sequence started. If a subsequent drawing sequence is + entirely enclosed within a prior sequence, it appears as a "cutout", or an + interior boundary. This behavior does not occur when the two drawing + sequences are in separate paths, even within the same shape. + + The pen can be "lifted" using an `a:moveTo` element, in which case no line + segment is drawn between the prior location and the new location. This can + be used to produce a discontinuous outline. + + A path has a boolean `stroke` attribute (default True) that specifies + whether a line should appear on the path. + +* The `a:pathLst` element can contain multiple `a:path` elements. In this + case, each path is essentially a "sub-shape", such as a shape that depicts + the islands of Hawaii. + + If a prior path is not closed, its end point path will be connected to the + first point of the subsequent path. + + The paths within a shape all have the same z-position, i.e. they appear on + a single plane such that all outlines appear, even when they intersect. + There is no cropping behavior such as occurs for individual shapes on + a slide. + + +Fill behavior +~~~~~~~~~~~~~ + +Hypothesis: Any shape can have a fill, even an "open" shape. The question of +whether a shape has a fill is not determined by whether it is closed, but by +whether a fill is *applied* to the shape. + +In the PowerPoint UI, a closed shape is automatically assigned a fill when it +is drawn. Conversely, an open shape is not assigned a fill. This behavior is +built into the drawing code and is not dependent solely on the "closed-ness" +of the shape. + +The XML template for a freeform shape (as of this writing) includes an +element for a fill and effect, consistent with the PowerPoint defaults for +a closed shape. The fill would need to be removed from an open shape if the +user didn't want it. + + +Coordinate system +~~~~~~~~~~~~~~~~~ + +* Each path has its own local coordinate system, distinct both from the + *shape* coordinate system and the coordinate systems of the other paths in + the shape. + +* The x and y extents of a path coordinate system are specified by the `w` + and `h` attributes on the `a:path` element, respectively. The top, left + corner of the path bounding box is (0, 0) and the bottom, right corner is + at (`h`, `w`). Coordinates are positive integers in the range 0 to + 27,273,042,316,900 (about 2^44.63). + + +Resources +--------- + +* Office Open XML - Custom Geometry + http://officeopenxml.com/drwSp-custGeom.php + + +XML Specimens +------------- + +.. highlight:: xml + +Hand-built, as-written by PowerPoint +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. image:: /_static/img/freeform-01.png + +This triangle is hand-built using the 'Freeform' shape tool in the PowerPoint +UI. A couple things to notice: + +* The shape includes a full complement of `` and `` elements. + The shape works fine without these and providing a way to specify these is + out of scope for the current effort. + +* The freeform shape itself is specified in `p:sp/p:spPr/a:custGeom`. That's + a little interesting that the geometry is considered a shape property + (spPr) rather than somehow more core to the shape. + +* The `` element contains only a single path. I haven't yet + discovered how to add a second path to a shape using the UI. + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +The rest of these shape subtrees have the `` and `` +elements removed for brevity and many focus simply on the `a:pathLst` element +for compact presentation. + + +Effect of `` element +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. image:: /_static/img/freeform-02.png + +This one is a little tricky to see, but if you look closely, you'll see that +the outline at the apex of the triangle is not "closed". This behavior arises +when there is no `` element at the end of the path, even when the +end-point is the same as the start-point:: + + + + + + + + + + + +XML Schema excerpt +------------------ + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-graphfrm.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-graphfrm.rst new file mode 100644 index 0000000000000000000000000000000000000000..2c5bb233ca1ce0b5556172bf4d40673709f25d69 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-graphfrm.rst @@ -0,0 +1,217 @@ + +Graphic Frame +============= + +A *graphic frame* is a shape that contains a graphical object such as a table, +chart, or SmartArt object. While often referred to as a shape in common +parlance, a table or chart is not a shape. The graphic frame container is the +shape and the table, chart, or SmartArt object is a DrawingML (DML) object +within it. + +A chart, for example, is a shared DML object. It can appear in a Word, Excel, +or PowerPoint file, virtually unchanged except for the container in which it +appears. + +The graphical content is contained in the +``p:graphicFrame/a:graphic/a:graphicData`` grandchild element. The type of +graphical object contained is specified by an XML namespace contained in the +``uri`` attribute of the ```` element. The graphical content may +appear directly in the ```` element or may be in a separate +part related by an rId. XML for a table is embedded inline. Chart XML is stored +in a related Chart part. + + +Protocol +-------- + +:: + + >>> shape = shapes.add_chart(style, type, x, y, cx, cy) + >>> type(shape) + + >>> shape.has_chart + True + >>> shape.has_table + False + >>> shape.chart + + + >>> shape = shapes.add_table(rows=2, cols=2, x, y, cx, cy) + >>> type(shape) + + >>> shape.has_chart + False + >>> shape.has_table + True + >>> shape.table + + + +Specimen XML +------------ + +.. highlight:: xml + +Table in a graphic frame:: + + + + + + + + + + + + + + + + + ... remaining table XML ... + + + + + + +Chart in a graphic frame:: + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +A ```` element appears in a ``CT_GroupShape`` element, +typically a ```` (shape tree) element:: + + + + + + + + + + + + + + + + + + +Graphic frame-related elements:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-group-shape.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-group-shape.rst new file mode 100644 index 0000000000000000000000000000000000000000..6099c9f86fc82d69982d449bf2bac26f31b1d970 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-group-shape.rst @@ -0,0 +1,250 @@ +.. _GroupShape: + + +Group Shape +=========== + +A *group shape* is a container for other shapes. + +In the PowerPoint UI, a group shape may be selected and moved as a unit, such +that the contained shapes retain their relative position to one another. + +Certain operations can also be applied to all the shapes in a group by +applying that operation to the group shape. + +The *grouping* notion is *recursive*; a group shape can itself contain one or +more group shapes. The "root" shape tree of a slide is itself a group, +although it has a few distinctive behaviors. The XML element for a slide's +shape tree (`p:spTree`) is the same XML type as that for a group shape +(`p:grpSp`), namely `CT_GroupShape`. + + +PowerPoint Behaviors +-------------------- + +* A group shape can have no click action. + + +XML Semantics +------------- + +* `chOff` and `chExt` represent child offset and child extents, respectively. + These are used if the group itself is transformed, in particular when it is + scaled. + + +MS API +------ + +* `Shape.GroupItems` - corresponds to `GroupShape.shapes` + + +XML Specimens +------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-hyperlink.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-hyperlink.rst new file mode 100644 index 0000000000000000000000000000000000000000..c6ed50b6bfbc064ec80a6c1602d82abcd03acc5c --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-hyperlink.rst @@ -0,0 +1,653 @@ + +Shape hyperlink +=============== + +In addition to hyperlinks in text, PowerPoint supports hyperlinks on shapes. +This feature is a subset of the more general *click action* functionality on +shapes. + +A run or shape can have two distinct mouse event behaviors, one for (left) +clicking and another for rolling over with the mouse (hover). These are +independent; a run or shape can have one, the other, both, or neither. + +A "true" hyperlink in PowerPoint is indicated by having no `action` attribute +on the `a:hlinkClick` element. The general hyperlink mechanism of storing +a URL in a mapped relationship is used by other verbs such as `hlinkfile` and +`program`, but these are considered distinct from hyperlinks for the sake of +this analysis. That distinction is reflected in the API. + +See also: _Run.hyperlink, `pptx.text._Hyperlink` + + +Candidate Protocol +------------------ + +.. highlight:: python + +* `Shape` + + + `.click_action` - unconditionally returns an `ActionSetting` object, + regardless of whether a click action is defined. Returns an + `ActionSetting` object even when the shape type does not support a click + action (such as a table). + +* `ActionSetting` + + + `.action` - returns a member of the `PP_ACTION_TYPE` (`PP_ACTION`) + enumeration + + + `.action_url` - returns the `ppaction://` URL as a string, in its + entirety, or None if no action attribute is present. Maybe this should + do XML character entity decoding. + + + `.action_verb` - returns the verb in the `ppaction://` URL, or None if no + action URL is present. e.g. `'hlinksldjump'` + + + `.action_fields` - returns a dictionary containing the fields in the query + string of the action URL. + + + `.hyperlink` - returns a Hyperlink object that represents the hyperlink + defined for the shape. A Hyperlink object is always returned. + + + `.target_slide` - returns a Slide object when the action is a jump to + another slide in the same presentation. This is the case when action is + `FIRST_SLIDE`, `LAST_SLIDE`, `PREVIOUS_SLIDE`, `NEXT_SLIDE`, or + `NAMED_SLIDE`. + + Supports assignment of a slide object, after which `.action` returns + `NAMED_SLIDE`. + +* Hyperlink + + + `.address` - returns the URL contained in the relationship for this + hyperlink. + + + `.screen_tip` - tool-tip text displayed on mouse rollover is slideshow + mode. Put in the XML hooks for this but API call is second priority + +Detect that a shape has a hyperlink:: + + for shape in shapes: + click_action = shape.click_action + if click_action.action == PP_ACTION.HYPERLINK: + print(click_action.hyperlink) + + +Add a hyperlink:: + + p = shape.text_frame.paragraphs[0] + r = p.add_run() + r.text = 'link to python-pptx @ GitHub' + hlink = r.hyperlink + hlink.address = 'https://github.com/scanny/python-pptx' + +Delete a hyperlink:: + + r.hyperlink = None + + # or ----------- + + r.hyperlink.address = None # empty string '' will do it too + +A Hyperlink instance is lazy-created on first reference. The object persists +until garbage collected once created. The link XML is not written until +.address is specified. Setting ``hlink.address`` to None or '' causes the +`hlink` entry to be removed if present. + +Add "Jump to slide" click action:: + + >>> click_action = shape.click_action + >>> click_action.target_slide = slides[4] + >>> click_action.action + NAMED_SLIDE (101) + + +Future Scope +------------ + +`ActionSetting.action` supports these alternate assignments:: + + # ---Shape.click_action is an ActionSetting object--- + ActionSetting.action = ( + PP_ACTION.FIRST_SLIDE or + PP_ACTION.LAST_SLIDE or + PP_ACTION.NEXT_SLIDE or + PP_ACTION.PREVIOUS_SLIDE + ) + +Each of these assignments takes immediate effect and is "self-contained"; no +further assignments are necessary to produce the specified behavior. + +Assigning `NAMED_SLIDE` to `ActionSetting.action` raises an exception. This +action is created by assigning a `Slide` object. + + +Glossary +-------- + +**click action** + The behavior to be executed when the user clicks on a shape. There are 14 + possible behaviors, such as navigate to a different slide, open a web + page, and run a macro. The possible behaviors are described by the + members of the `PP_ACTION_TYPE` enumeration. + +**hover action** + All click action behaviors can also be triggered by a mouse-over (hover) + event. + +**hyperlink** + A hyperlink is a particular class of click action that roughly + corresponds to opening a web page, although it can also be used to send + an email. While a similar mechanism is used to specify other actions, + such as open a file, this term here is reserved for the action of + navigating to a web URL (including `mailto://`). + +**action** + The click or hover action is specified in the XML using a URL on the + `ppaction://` protocol contained in the `action` attribute of the + `a:hlinkClick` (or `a:hlinkHover`) element. A hyperlink action is implied + when no `action` attribute is present. + +**action verb** + The specific action to be performed is contained in the *host* field of + the `ppaction://` URL. For instance, `customshow` appears in + `ppaction://customshow?id=0&return=true` to indicate + a `PP_ACTION.NAMED_SLIDE_SHOW` action. + +**OLE verb** + The term *verb* also appears in this context to indicate an OLE verb such + as `Open` or `Edit`. This is not to be confused with an `action verb`. + + +`PP_ACTION_TYPE` mapping logic +------------------------------ + +:: + + # _ClickAction.action property + + hlinkClick = shape_elm.hlinkClick + + if hlinkClick is None: + return PP_ACTION.NONE + + action_verb = hlinkClick.action_verb + + if action_verb == 'hlinkshowjump': + relative_target = hlinkClick.action_fields['jump'] + return { + 'firstslide': PP_ACTION.FIRST_SLIDE, + 'lastslide': PP_ACTION.LAST_SLIDE, + 'lastslideviewed': PP_ACTION.LAST_SLIDE_VIEWED, + 'nextslide': PP_ACTION.NEXT_SLIDE, + 'previousslide': PP_ACTION.PREVIOUS_SLIDE, + 'endshow': PP_ACTION.END_SHOW, + }[relative_target] + + return { + None: PP_ACTION.HYPERLINK, + 'hlinksldjump': PP_ACTION.NAMED_SLIDE, + 'hlinkpres': PP_ACTION.PLAY, + 'hlinkfile': PP_ACTION.OPEN_FILE, + 'customshow': PP_ACTION.NAMED_SLIDE_SHOW, + 'ole': PP_ACTION.OLE_VERB, + 'macro': PP_ACTION.RUN_MACRO, + 'program': PP_ACTION.RUN_PROGRAM, + }[action_verb] + + +PowerPoint® application behavior +-------------------------------- + +The general domain here is mouse event behaviors, with respect to a shape. +So far, the only two mouse events are (left) click and hover (mouse over). +These can trigger a variety of actions. I'm not sure if all actions can be +triggered by either event, but the XML appears to support it. + +Action inventory +~~~~~~~~~~~~~~~~ + +The following behaviors can be triggered by a click: + +* Jump to a relative slide in same presentation (first, last, next, previous, + etc.). +* Jump to specific slide in same presentation (by slide index, perhaps title + as fallback) +* Jump to a slide in different presentation (by slide index) +* End the slide show +* Jump to bookmark in Microsoft Word document +* Open an arbitrary file on the same computer +* Web link - Open a browser and navigate to a specified web page +* Run a macro +* Run an arbitrary program +* Execute an OLE action + +In addition to performing one of these actions, zero, one, or both of two +auxiliary actions can be triggered by clicking: + +* Play a sound +* Highlight the shape with a dashed line for a short time + +Hyperlinkable shapes +~~~~~~~~~~~~~~~~~~~~ + +These shape types can have hyperlinks: + + + `Autoshapes` + + `Textbox` + + `Picture` + + `Connector` + + `Chart` + +These shape types cannot: + + + `Table` + + `Group Shape` + + +UI procedures +------------- + +Hyperlink autoshape to other slide by title +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* Right-click > Hyperlink... (Cmd-K) +* Select Document panel +* Anchor: > Locate... > Slide Titles +* select slide by number and title, e.g. "2 + +Add Anchor point in a document (or perhaps a slide) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* A hyperlink can link to a bookmark in a Word document +* It appears that maximum granularity in PowerPoint is to an entire slide + (not to a range of text in a shape, for example) + + +MS API +------ + +Shape.ActionSettings(ppMouseClick | ppMouseOver) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Shape object has an ActionSettings property, which is a collection of two +ActionSetting objects, one for click and the other for hover. +https://msdn.microsoft.com/EN-US/library/office/ff745656.aspx + +ActionSetting +~~~~~~~~~~~~~ + +* Shape.ActionSettings(ppMouseClick | ppMouseOver) => ActionSetting + +* ActionSetting.Action + + + one of: ppActionHyperlink, ppActionFirstSlide, ppActionPlay, or several + others: https://msdn.microsoft.com/EN-US/library/office/ff744511.aspx + +* ActionSetting.Hyperlink => Hyperlink + +* Hyperlink members: + + + Address + + SubAddress + + TextToDisplay + + ScreenTip + + EmailSubject + + Type (read-only, one of msoHyperlinkRange (run) or msoHyperlinkShape) + + +XML specimens +------------- + +.. highlight:: xml + +These are representative samples of shape XML showing the hyperlinks +associated the shape (as opposed to text contained by the shape). + +* The `a:hlinkClick` element can be present or absent. + +* Its parent, `p:cNvPr` is always present (is a required element). + +* All of its attributes are optional, but an `a:hlinkClick` having no + attributes has no meaning (or may trigger an error). + +* Its `r:id` element is always present on click actions created by PowerPoint. + Its value is an empty string when the action is first, last, next, previous, + macro, and perhaps others. + +* Adding a `highlightClick` attribute set True causes the shape to get + a dashed line border for a short time when it is clicked. + +* There are some more obscure attributes like "stop playing sound before + navigating" that are available on `CT_Hyperlink`, perhaps meant for + kiosk-style applications. + +Summary +~~~~~~~ + +The action to perform on a mouse click is specified by the `action` attribute +of the `a:hlinkClick` element. Its value is a URL having the `ppaction://` +protocol, a verb, and an optional query string. + +Some actions reference a relationship that specifies the target of the +action. + +============= ======== ======================================================= +verb rId behavior +============= ======== ======================================================= +none external Open a browser and navigate to URL in relationship +hlinkshowjump none Jump to a relative slide in the same presentation +hlinksldjump internal Jump to a specified slide in the same presentation +hlinkpres external Jump to a specified slide in another presentation +hlinkfile external Open an arbitrary file on the same computer +customshow none Start a custom slide show, option to return after +ole none Execute an OLE action (open, edit) +macro none Run an embedded VBA macro +program external Execute an arbitrary program on same computer +============= ======== ======================================================= + +Jump to relative slide within presentation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**hlinkshowjump** action + +:: + + + + + + + + + + + + + + + + + + + + + + + + + Click to go to Foobar Slide + + + + + + +* `jump` key can have value `firstslide`, `lastslide`, `previousslide`, + `nextslide`, `lastslideviewed`, `endshow`. +* Note that `r:id` attribute is empty string; no relationship is required to + determine target slide. + +Jump to specific slide within presentation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**hlinksldjump** action + +:: + + + + + + + ... + + +The corresponding `Relationship` element must be of type `slide`, be +internal, and point to the target slide in the package:: + + + +Jump to slide in another presentation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**hlinkpres** action + +:: + + + + + + + ... + + +The corresponding `Relationship` element must be of type `hyperlink`, be +*external*, and point to the target presentation with a URL (using the +`file://` protocol for a local file). The slide number and slide title are +provided in the `ppaction://` URL in the `a:hlinkClick` element:: + + + +Web link (hyperlink) +~~~~~~~~~~~~~~~~~~~~ + +Note: The `action` attribute of `a:hlinkClick` has no value in this case. + +:: + + + + + + ... + + +The corresponding `Relationship` element must be of type `hyperlink`, be +*external*, and point to the target URL (using a web protocol). + +The target is often a web URL, such as https://github/scanny/python-pptx, +including an optional anchor (e.g. #sub-heading suffix to jump mid-page). The +target can also be an email address, launching the local email client. +A mailto: URI is used in this case, with subject specifiable using +a '?subject=xyz' suffix. + +An optional ScreenTip, a roll-over tool-tip sort of message, can also be +specified for a hyperlink. The XML schema does not limit its use to +hyperlinks, although the PowerPoint UI may not provide access to this field +in non-hyperlink cases.:: + + + +Open an arbitrary file on the same computer +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**hlinkfile** action + +:: + + + + + + ... + + +* PowerPoint opens the file (after a warning dialog) using the default + application for the file. + +The corresponding `Relationship` element must be of type `hyperlink`, be +*external*, and point to the target file with a `file://` protocol URL:: + + + +Run Custom SlideShow +~~~~~~~~~~~~~~~~~~~~ + +**customshow** action + +:: + + + + + + ... + + +* The `return` query field determines whether focus returns to the current show + after running the linked show. This field can be omitted, and defaults to + `false`. + +Execute an OLE action +~~~~~~~~~~~~~~~~~~~~~ + +**ole** action + +:: + + + + + + + ... + + +This option is only available on an embedded (OLE) object. The verb field is +'0' for Edit and '1' for Open. + +Run macro +~~~~~~~~~ + +**macro** action + +:: + + + + + + + ... + + +Run a program +~~~~~~~~~~~~~ + +**program** action + +:: + + + + + + ... + + +The corresponding `Relationship` element must be of type `hyperlink`, be +*external*, and point to the target application with a `file://` protocol +URL. :: + + + +Play a sound +~~~~~~~~~~~~ + +Playing a sound is not a distinct action; rather, like highlighting, it is an +optional additional action to be performed on a click or hover event. + +:: + + + + + + + + ... + + +The corresponding `Relationship` element must be of type `audio`, be +internal, and point to a sound file embedded in the presentation:: + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-movie.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-movie.rst new file mode 100644 index 0000000000000000000000000000000000000000..e6632b8491405fe1f037f2bea7da33456e10367a --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-movie.rst @@ -0,0 +1,788 @@ + +Movie +===== + +PowerPoint allows a video to be inserted into a slide and run in slide show +mode. In the PowerPoint UI, a shape of this type is called a *movie*. + +A movie is implemented as a variant form of a `p:pic` element, which makes it +closely related to a `Picture` object. This close relationship makes sense, +because a movie acts very much like an image when it is not playing and the +two shapes therefore share much of their behavior. When not playing, a movie +shape displays a static image, called a *poster frame*. + + +Candidate Protocol +------------------ + +A video can be added to a slide by specifying a video file, position, size, +and optional poster frame:: + + >>> movie = shapes.add_movie( + ... movie_file, left, top, width, height, poster_frame_image, + ... mime_type + ... ) + + >>> movie + + + >>> movie.shape_type + MSO.MEDIA + + >>> movie.media_type + PP_MEDIA_TYPE.MOVIE + + >>> movie.media_format + + + +Animation/timing resources +-------------------------- + +* Working with animation (Open XML SDK) + https://msdn.microsoft.com/en-us/library/office/gg278329.aspx + +* AnimationBehaviors (Collection) Members (PowerPoint) + https://msdn.microsoft.com/en-us/library/office/ff746028.aspx + +* AnimationBehavior Members (PowerPoint) + https://msdn.microsoft.com/en-us/library/office/ff746141.aspx + +* stands for *parallel*, and is one of the available time containers + (like "parallel" timing, or executing at the same time). + https://folk.uio.no/annembek/inf3210/how_2_SMIL.html + +* https://technet.microsoft.com/en-au/library/gg278329.aspx + +* http://openxmldeveloper.org/discussions/formats/f/15/t/6838.aspx + + +Possibly interesting resources +------------------------------ + +.. both of these formats work + +* `Apache POI discussion `_ + +* `Apache POI discussion on inserting video`_ + +.. _`Apache POI discussion on inserting video`: + http://apache-poi.1045710.n5.nabble.com/Question-about-embedded-video-in-P + PTX-files-td5718461.html + + +MS API +------ + +* Slide.Timeline + https://msdn.microsoft.com/en-us/library/office/ff745382.aspx + +* TimeLine Object + https://msdn.microsoft.com/en-us/library/office/ff743965.aspx + +* Shapes.AddMediaObject() (deprecated in PowerPoint 2013, see AddMediaObject2) + https://msdn.microsoft.com/EN-US/library/office/ff745385.aspx + +* Shapes.AddMediaObject2() + https://msdn.microsoft.com/en-us/library/office/ff744080.aspx + +* MediaFormat + https://msdn.microsoft.com/en-us/library/office/ff745983.aspx + + +Enumerations +------------ + +PP_MEDIA_TYPE - https://msdn.microsoft.com/en-us/library/office/ff746008.aspx + ++---------------------+----+--------+ +| PP_MEDIA_TYPE.MOVIE | 3 | Movie | ++---------------------+----+--------+ +| PP_MEDIA_TYPE.SOUND | 2 | Sound | ++---------------------+----+--------+ +| PP_MEDIA_TYPE.OTHER | 1 | Others | ++---------------------+----+--------+ +| PP_MEDIA_TYPE.MIXED | -2 | Mixed | ++---------------------+----+--------+ + + +Click Behavior +-------------- + +The video's "play on click" behavior in slideshow mode is implemented by the +use of a `` element in the `` element. No "play" button or +slider control appears when this element is not present. + + +Poster Frame +------------ + +A *poster frame* is the static image displayed in the video location when the +video is not playing. Each image that appears on the YouTube home page +representing a video is an example of a poster frame. + +The poster frame is perhaps most frequently a frame from the video itself. In +some contexts, the first frame is used by default. The poster frame can be +undefined, or empty, and it can also be an unrelated image. + +Some of the example videos for this feature get a poster frame upon +insertion; however at least one does not. In that case, a media "speaker" +icon (stretched to fit) is shown instead. + + +XML Semantics +------------- + +* `id=` of p:cTn element just needs to be unique among `p:cTn` elements, + apparently. + + +Example XML +----------- + +.. highlight:: xml + +Inserted MPEG-4 H.264 video:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Regular picture shape, for comparison:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +p:video element +--------------- + +Provides playback controls. + +http://openxmldeveloper.org/discussions/formats/f/15/p/1124/2842.aspx#2842 + + +XML Semantics +------------- + +* Extension DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230 is described as a + `media extension`_. It appears to allow: + + + "cropping" the video period (set start and stop time markers) + + provide for "fade-in" + + allow for setting bookmarks in the video for fast jumps to a particular + location + +.. _media extension: + https://msdn.microsoft.com/en-us/library/dd947021(v=office.12).aspx + +* This and other extensions are documented in `this PDF `_. + +.. _media_pdf: + http://interoperability.blob.core.windows.net/files/MS-PPTX/[MS-PPTX].pdf + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +The root element of a picture shape is a `p:pic (CT_Picture)` element:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +`p:timing` related Schema Definitions +------------------------------------- + +.. highlight:: xml + +The `p:timing` element is a child of the `p:sld (CT_Slide)` element:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-ole-object.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-ole-object.rst new file mode 100644 index 0000000000000000000000000000000000000000..547c7fc60016bd011bdeff68dbcb31c7eb6af8cd --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-ole-object.rst @@ -0,0 +1,410 @@ + +Shape - OLE Object +================== + +An embedded Excel worksheet can appear as a shape on a slide. The shape itself is a +graphics-frame, in which the worksheet "file" is embedded. The Excel binary appears as +an additional part in the package. Other file types such as DOCX and PDF can also be +embedded in a similar way. + +Support for different file (object) types is OS dependent. For example, there is no +support for embedded PPTX objects on MacOS although there is for Windows. Excel (XLSX) +and Word (DOCX) are the two common denominators. + + +Proposed protocol +----------------- + +:: + + >>> from pptx.enum.shapes import PROG_ID + >>> shapes = prs.slides[0].shapes + >>> shape = shapes.add_ole_object( + "worksheet.xlsx", PROG_ID.EXCEL, left, top, width, height + ) + >>> shape + + >>> shape.shape_type + MSO_SHAPE_TYPE.EMBEDDED_OLE_OBJECT + >>> ole_format = shape.ole_format + >>> ole_format + + >>> ole_format.blob + + >>> ole_format.prog_id + 'Excel.Sheet.12' + >>> ole_format.show_as_icon + True + + +PowerPoint UI behaviors +----------------------- + +* **Insert a blank object.** PowerPoint allows a "new", blank OLE object to be inserted by + selecting the type. The available types appear to be determined by a set of + "registered" OLE server applications. + + This behavior seems quite bound to some user interaction to fill out the object and in + any case is outside the abilities of `python-pptx` running on an arbitrary OS. This + behavior will have no counterpart in `python-pptx`. Only the "insert-from-file" mode + will be available in `python-pptx`. + +* **Auto-detect `progId` from file.** When the "insert-from-file" option is chosen, + PowerPoint automatically detects the `progId` (str OLE server identifier, intuitively + "file-type") for the inserted file. + + This would be a lot of work for `python-pptx` to accomplish and in the end would be + partial at best. The base case would be that `python-pptx` requires `progId` to be + specified by the caller. `python-pptx` will provide an Enum that provides ready access + to common str `progId` cases like Excel Worksheet, Word Document, and PowerPoint + Presentation. Other cases could be resolved by experimentation and inspecting the XML + to determine the appropriate str `progId` value. + +* **Show as preview.** PowerPoint allows the option to show the embedded object as + either a "preview" of the content or as an icon. The preview is an image (EMF for XLSX + and perhaps other MS Office applications) and I expect it is provided by the OLE + server application (Excel in the XLSX case) which renders to an image instead of + rendering to the screen. + + `python-pptx` has no access to an OLE server and therefore cannot request this image. + Only the "display as icon" mode will be supported in `python-pptx`. For this reason, + the `python-pptx` call will have no `display_as_icon` parameter and that "value" will + always be True. + +* **User-selectable and partially-generated icon.** When "display-as-icon" is selected, + PowerPoint generates a composite icon that combines a graphical icon and a caption. + Together, these typically look like a file icon that appears on the user's desktop, + except the file-name portion is a generic file-type name like "Microsoft Excel + Workbook". + + The icon portion can be replaced with an arbitrary icon selected by the user (Windows + only). The icon can be selected from a `.ico` file or an icon library or from the + resource area of an `.exe` file. + + The resulting image in the PPTX package is a Windows Meta File (WMF/EMF), a vector + format, perhaps to allow smooth scaling. + + In the general case (i.e. non-Windows OS), `python-pptx` has neither the option of + extracting icons from an arbitrary icon or resource library or + +* **Link to file rather than embed.** When inserting an object from a file, a user can + choose to link the selected file rather than embed it. This option appears in the + Windows version only. + + The only difference in the slide XML is the appearance of a `` element under + `` rather than a `` element. In this case, the relationship + referred to by `r:id` attribute of `p:oleObj` is an external link to the target file + and no OLE object part is added to the PPTX package. + +* **Auto-position and size.** In the PowerPoint UI, the OLE object is inserted at a + fixed size and in a default location. Afterward the shape can be repositioned and + resized to suit. In the API, the position and size are specified in the call. + + +MS API Protocol +--------------- + +:: + + Shapes.AddOLEObject( + Left, Top, Width, Height, + ClassName, + FileName, + DisplayAsIcon, + IconFileName, + IconIndex, + IconLabel, + Link, + ) + +* `Left, Top, Width` and `Height` specify the position and size of the graphic-frame + object. They also specify the size of the icon image when `display_as_icon` is True + and the size of the preview image when `display_as_icon` is False or omitted. These + are all optional, and are determined by PowerPoint if not specified. I believe the + shape is placed centered in the slide if the position is not specified and the size is + determined by the icon or preview graphic if not specified. + + PowerPoint updates these values in the icon-image element to track those of the + graphic-frame shape when the user changes the size of the graphic-frame shape, but it + seems to ignore these values when they don't agree. + +* `ClassName` identifies the "file-type" or more precisely, the OLE server (program) + used to "open" the embedded or linked file. This is used only when a new, empty object + is being added because otherwise PowerPoint derives this from the file specified with + `FileName` + + This can be either the OLE long class name or the ProgID for the object that's to be + created, but a class-name ends up being converted to a ProgID. Either the ClassName or + FileName argument for the object must be specified, but not both. ClassName triggers + the "insert-newly-created-object" mode and FileName triggers "insert-existing-object" + mode. + +* `DisplayAsIcon` (optional boolean) determines whether the OLE object will be displayed + as an icon or as a "preview". The default is `False`. + +* `IconFileName` allows the user to specify an *icon file* containing the icon to + display when `DisplayAsIcon` is `True`. If not specified, a default icon for the OLE + class is used. Note that this file can contain a collection of images, which is why + the `IconIndex` parameter is available. These icon files are Windows specific and + would not typically be found in other operating systems. + +* `IconIndex` specifies the index of the desired icon within `IconFileName`. The first + icon in the file has the index number 0 (zero). If an icon with the given index number + doesn't exist in IconFileName, the icon with the index number 1 (the second icon in + the file) is used. The default value is 0 (zero). + +* `IconLabel` is a str label (caption) to be displayed beneath the icon. By default, + this is like "Microsoft Excel Worksheet". This caption is integrated into the + specified "display-as-icon" image. + +* `Link` is a boolean flag that determines whether the OLE object will be linked to the + file from which it was created (rather than embedded). If you specified a value for + ClassName, this argument must be msoFalse (linking is not an option in + "insert-newly-created-object" mode). + + +Candiate protocol +----------------- + +:: + + SlideShapes.add_ole_object( + object_file, + prog_id, + left, + top, + width=None, + height=None, + icon=None, + link=False, + ) + +`python-pptx` only supports adding an OLE object in "display-as-icon" mode. It has no +way of soliciting a preview image from an OLE server application, so that option is not +practical for us. + +* `object_file` is the file containing the object to be inserted. It may be either a str + path to the file or a (binary) file-like object (typically `io.Bytes`) containing the + bytes of the file and implementing file-object semantics like `.read()` and `.seek()`. + +* `prog_id` is a PROG_ID Enum member or str identifier like `"Excel.Sheet.12"` + specifying the "type" of the object in terms of what application is used to "open" it. + In Microsoft parlance, this identifies the OLE server called upon to operate on this + object. + + The `pptx.enum.shapes.PROG_ID` enumeration defines these values for common cases like + an Excel workbook, an Word document, or another PowerPoint presentation. Probably we + should also include PDFs and any other common cases we can think of. + + A regular `str` value can be discovered by inspecting the XML of an example + presentation and these will work just the same as a `PROG_ID` Enum value, allowing + ready expansion to other OLE object types. + + I expect that a file of any type could be included, even if it doesn't have an OLE + server application and it could then at least be accessed via `python-pptx`, although + I don't suppose it would do anything useful from the PowerPoint UI. In any case, I + don't believe it would raise an error and there wouldn't be anything we could (or + would probably want) to do to stop someone from doing that. + +* `left` and `top` are each an Emu object (or an int interpreted as Emu) and specify the + position of the inserted-object shape. + +* `width` and `height` are optional Emu/int objects and together specify the size of the + graphic-frame object. Their use is not required and perhaps even discouraged unless + the defaults of 1.00" (914400 EMU) wide and .84" (771480 EMU) tall do not suit for + some reason, perhaps because the provided icon image is a non-standard size. The + default size is that when a user inserts an object displayed as an icon in the + PowerPoint UI and I at least have been unable to make it look better by resizing it. + +* `icon` is an arbitrary image that appears in the graphic-frame object in lieu of the + inserted object. It is optional, because a default icon is provided for each of the + members of `PROG_ID` and this image need not be specified when `prog_id` is an + instance of `PROG_ID`. Like an image object used in `SlideShapes.add_picture()`, this + object can be either a `str` path or a file-like object (typically `io.BytesIO`) + containing the image. + + This parameter is technically optional, but is required when `prog_id` is not an + member of `PROG_ID` (because in that case we have no default icon available). The + caller can always specify a custom icon image, even when inserting an object type + available in `PROG_ID`. In that case, the image provided is used instead of the + default icon. + +* `link` is a boolean indicating the object should be linked rather than embedded. + Linking probably only works in a Windows environment. This option may not be + implemented in the initial release and this parameter will not appear in that case. + +:: + + >>> shapes = slide.shapes + >>> embedded_xlsx_shape = shapes.AddOLEObject(left, top, width, height, file_name) + + +XML specimens +------------- + +.. highlight:: xml + + +relationships:: + + + + + + + + + + +simple column chart:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-picture.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-picture.rst new file mode 100644 index 0000000000000000000000000000000000000000..109eb338cddd379c4d508403d9c04e8b4c309af1 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-picture.rst @@ -0,0 +1,270 @@ + +Picture +======= + +PowerPoint allows an image to be added to a slide as a |Picture| shape. + + +Protocol +-------- + +Add a picture:: + + >>> shapes = Presentation(...).slides[0].shapes + >>> picture = shapes.add_picture('python.jpg', Inches(1), Inches(1)) + +Interrogate and set cropping:: + + >>> picture.crop_right + None + >>> picture.crop_right = 25000 # ---in 1000ths of a percent + >>> picture.crop_right + 25000.0 + + +XML Specimens +------------- + +.. highlight:: xml + +Picture shape as added by PowerPoint Mac 2011:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Cropped `pic` (`p:blipFill` child only):: + + + + + + + + +Schema excerpt +-------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-pos-and-size.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-pos-and-size.rst new file mode 100644 index 0000000000000000000000000000000000000000..155a059e937a6403f697b747da51f9b95eb34b0c --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-pos-and-size.rst @@ -0,0 +1,181 @@ + +Shape position and size +======================= + +Shapes of the following types can appear in the shape tree of a slide +(````) and each will require support for querying size and position. + +* **sp** -- Auto Shape *(completed)* +* **pic** -- Picture *(completed)* +* **graphicFrame** -- container for table and chart shapes +* **grpSp** -- Group Shape +* **cxnSp** -- Connector (line) +* **contentPart** -- has no position, but should return None instead of raising + an exception + + +Protocol +-------- + +:: + + >>> assert isinstance(shape, pptx.shapes.autoshape.Shape) + >>> shape.left + 914400 + >>> shape.left = Inches(0.5) + >>> shape.left + 457200 + + +XML specimens +------------- + +.. highlight:: xml + +Here is a representative sample of shape XML showing the placement of the +position and size elements (in the element). + +*Auto shape (rounded rectangle in this case)*:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is text inside a rounded rectangle + + + + + + +*Example picture shape*:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + ... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-preset-geom.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-preset-geom.rst new file mode 100644 index 0000000000000000000000000000000000000000..4a9c3612f206f840ac2f318cc1288f37a4836fc2 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-preset-geom.rst @@ -0,0 +1,246 @@ + +``CT_PresetGeometry2D`` +======================= + +.. highlight:: xml + +.. csv-table:: + :header-rows: 0 + :stub-columns: 1 + :widths: 15, 50 + + Spec Name , Preset Geometry + Tag(s) , a:prstGeom + Namespace , drawingml (dml-main.xsd) + Spec Section , 20.1.9.18 + + +Spec text +--------- + + This element specifies when a preset geometric shape should be used instead + of a custom geometric shape. The generating application should be able to + render all preset geometries enumerated in the ST_ShapeType list. + + +Schema excerpt +-------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-shadow.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-shadow.rst new file mode 100644 index 0000000000000000000000000000000000000000..b7c483f458668904153ffd271c46d0efc8e5b9ef --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-shadow.rst @@ -0,0 +1,342 @@ +.. _ShapeShadow: + +Shadow +====== + +Shadow is inherited, and a shape often appears with a shadow without +explicitly applying a shadow format. + +The only difference in a shape with shadow turned off is the presence of an +empty `` child in its `` element. Inherited shadow is +turned off when `p:spPr/a:effectLst` is present with no `a:outerShdw` child +element. Other effect child elements may be present. + +A shadow is one type of "effect". The others are glow/soft-edges and +reflection. + +Shadow may be of type *outer* (perhaps most common), *inner*, or +*perspective*. + +.. highlight:: xml + + +Scope +----- + +* `Shape.shadow` is a `ShadowFormat` object (all shape types) + +* `shape.shadow.inherit = True` removes any explicitly applied effects + (including glow/soft-edge and reflection, not just shadow). This restores + the "inherit" state for effects and makes the shape sensitive to changes in + theme. + +* `shape.shadow.inherit = False` overrides any default (theme) effects. Any + inherited shadow, glow, and/or reflection will no longer appear. This + operation adds an empty effects element, which causes no effects to be + applied, regardless of theme settings. + + +**Out-of-scope** + +Minimum for specifying a basic shadow + +* `ShadowFormat.visible` - applies a reasonable standard shadow override. +* `ShadowFormat.shadow_type` (inner, outer, perspective) +* `ShadowFormat.alignment` (shadow anchor, automatic based on angle) +* `ShadowFormat.angle` (0-degrees is to the right, increasing CCW) +* `ShadowFormat.blur_radius` (generally a few points, maybe 3-5) +* `ShadowFormat.color` (theme or RGB color) +* `ColorFormat.transparency` (needed for proper shadow rendering) +* `ShadowFormat.distance` (generally a couple points, maybe 1-3) +* `shape.shadow.style` (MSO_SHADOW_STYLE) indicates whether shadow is inner, + outer, or perspective (or None). + +Nice to have for finer tuning + +* `ShadowFormat.rotate_with_shape` (boolean) +* `ShadowFormat.scale` (shadow bigger/smaller than shape, default 100%) + +* Retaining non-shadow effects when turning off shadow. This requires the + ability to "clone" the currently enabled defaults. Effects are not + inherited separately; making explicit the currently active default is how + PowerPoint works around the "all-or-nothing" inheritance behavior. + +* Clone effective shadow, glow, and/or reflection. + + +Protocol +-------- + +.. highlight:: python + +The `.shadow` property on a shape *always* returns *the* `ShadowFormat` +object for that shape, regardless of whether its shadow is explicit or +inherited:: + + >>> shape = prs.slides[0].shapes[0] + >>> shadow = shape.shadow + >>> shadow + + +The `.shadow` property is idempotent, meaning the same `ShadowFormat` object +(verified by comparing ID) is returned on every call, for the lifetime of the +shape object:: + + >>> shape.shadow + + >>> shape.shadow + + +The `ShadowFormat.inherit` property indicates whether the shape inherits its +shadow effect or overrides it with an explicitly defined setting. The default +setting for a new shape is `True`:: + + >>> shadow.inherit + True + +Assigning `False` breaks the inheritance link by explicitly defining +a "no-shadow" setting for the shape. This causes the shape to appear without +a shadow, regardless of the applied theme:: + + >>> shadow.inherit = False + >>> shadow.inherit + False + +Note that this has the side-effect of disabling inheritance of **all** +effects for that shape. + + +PowerPoint behaviors +-------------------- + +* All 5 shape-types can display a shadow, but graphics-frame objects like + chart and table use a different mechanism than the other shapes. Those + won't be supported initially. + + + AutoShape + + Connector + + Picture + + Group Shape (parent is `p:grpSpPr` rather than `p:spPr`) + + Graphics Frame (UI allows, but uses a different mechanism) + +* Adding shadow to a group shape adds that shadow to each component shape in + the group. + +* There is a "new-shape format" concept. This format determines what a new + shape looks like, but does not change the appearance of shapes already in + place. It's basically a template imprinted on new shapes when they are + added. + +*Theme Effects* are a thing here. They are Subtle, Moderate, and Intense. + +There are 40 built-in theme effects. Each of these have ... + +* Setting visible off (Format Shape > Shadow > Clear Shadow checkbox) for + a customized shadow removes all customized settings and they are not + recoverable by setting the shadow visible again (clicking the shadow + checkbox). + + +MS API +------ + +ShadowFormat object +~~~~~~~~~~~~~~~~~~~ + +* `ShadowFormat.Visible` + + +Specimen XML +------------ + +.. highlight:: xml + +Shape inheriting shadow. Note the absence of `p:spPr/a:effectLst`, causing +all effects to be inherited:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Shape with inherited shadow turned off:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +XML Semantics +------------- + +**Effect inheritance is "all-or-nothing"** + +* If `p:spPr/a:effectLst` is present, all desired effects must be specified + explicitly as its children; a missing child, such as `a:outerShdw`, will + cause that effect to be turned off. PowerPoint automatically adds those + populated with inherited values when one of the effects is customized, + necessitating that addition of an `a:effectLst` element. + +* Theme sub-tree `a:theme/a:objectDefaults/a:spDef/a:style/a:effectRef/idx=2` + specifies that new objects will get the second effect in + `a:theme/a:themeElements/a:fmtScheme/a:effectStyleLst`. That effect looks + like this:: + + + + + + + + + + + + +Schema excerpt +-------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-shapes.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-shapes.rst new file mode 100644 index 0000000000000000000000000000000000000000..69d8993c9235fa54ca86f19eab9bc51ec7f7b86a --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/shp-shapes.rst @@ -0,0 +1,521 @@ + +Shapes - In General +=================== + +Each visual element in a PowerPoint presentation is a *shape*. A shape +appears on the "canvas" of a slide, which includes the various types of +*master*. Within a slide, shapes appear in a *shape tree*, corresponding to +an ```` element. + +The following table summarizes the six shape types: + +============ ==================== +shape type element +============ ==================== +auto shape ```` +group shape ```` +graphicFrame ```` +connector ```` +picture ```` +content part ```` +============ ==================== + +Some of these shape types have important sub-types. For example, +a placeholder, a text box, and a preset geometry shape such as a circle, are +all defined with an ```` element. + + +```` shape elements +------------------------- + +The ```` element is used for three types of shape: placeholder, text +box, and geometric shapes. A geometric shape with preset geometry is referred +to as an *auto shape*. Placeholder shapes are documented on the +:ref:`placeholder` page. Auto shapes are documented on the :ref:`autoshape` +page. + +Geometric shapes are the familiar shapes that may be placed on a slide such +as a rectangle or an ellipse. In the PowerPoint UI they are simply called +shapes. There are two types of geometric shapes, preset geometry shapes and +custom geometry shapes. + + +``Shape.shape_id`` and ``Shape.name`` +------------------------------------- + +``Shape.shape_id`` is read-only and is assigned by python-pptx when +necessary. + +Proposed protocol:: + + >>> shape.shape_id + 42 + >>> shape.name + u'Picture 5' + >>> shape.name = 'T501 - Foo; B. Baz; 2014' + >>> shape.name + u'T501 - Foo; B. Baz; 2014' + + +:attr:`Shape.rotation` +---------------------- + +Read/write float degrees of clockwise rotation. Negative values can be used +for counter-clockwise rotation. + +*XML Semantics* + ST_Angle is an integer value, 60,000 to each degree. PowerPoint appears + to only ever use positive values. Oddly, the UI uses positive values for + counter-clockwise rotation while the XML uses positive increase for + clockwise rotation. + +*PowerPoint behavior* + It appears graphic frame shapes can't be rotated. AutoShape, group, + connector, and picture all rotate fine. + + +Proposed protocol:: + + >>> shape.rotation + 0.0 + >>> shape.rotation = 45.2 + >>> shape.rotation + 45.2 + + +Math:: + + def rot_from_angle(value): + """ + Return positive integer rotation in 60,000ths of a degree + corresponding to *value* expressed as a float number of degrees. + """ + DEGREE_INCREMENTS = 60000 + THREE_SIXTY = 360 * DEGREE_INCREMENTS + # modulo normalizes negative and >360 degree values + return int(round(value * DEGREE_INCREMENTS)) % THREE_SIXTY + + +Specimen XML +------------ + +.. highlight:: xml + +Geometric shape (rounded rectangle):: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is text inside a rounded rectangle + + + + + + + +Default textbox shape as inserted by PowerPoint:: + + + + + + + + + + + + + + + + + + + + + + + + + + This is text in a text box + + + + + + + +Group shape (some contents elided for size):: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Graphical object (e.g. table, chart) in a graphic frame:: + + + + + + + + + + + + + + + + + + + + + +Connector shape:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Picture shape:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Resources +--------- + +* `DrawingML Shapes`_ on officeopenxml.com + +.. _DrawingML Shapes: + http://officeopenxml.com/drwShape.php + +* `Shape Object MSDN page`_ + +.. _Shape Object MSDN page: + http://msdn.microsoft.com/en-us/library/office/ff744177(v=office.14).aspx + +* `MsoShapeType Enumeration`_ + +.. _MsoShapeType Enumeration: + http://msdn.microsoft.com/en-us/library/office/aa432678(v=office.14).aspx + + +Schema excerpt +-------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-background.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-background.rst new file mode 100644 index 0000000000000000000000000000000000000000..9f7f2e606aebd39f9af84ebb0eba51a90863756e --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-background.rst @@ -0,0 +1,158 @@ +.. _SlideBackground: + +Slide Background +================ + +A slide inherits its background from its layout or master (and possibly +theme), in that order. Each slide can also override its inherited background +settings. + +A background is essentially a container for a fill. + + +Protocol +-------- + +**Access slide background.** `Slide.background` is the `Background` object +for the slide. Its presence is unconditional and the same `Background` object +is provided on each access for a particular `Slide` instance. Its presence +does not imply an explicitly applied slide background:: + + >>> background = slide.background + >>> background + + +**Detect explicitly-applied slide background.** A slide inherits its +background unless an explicitly-defined background has been applied to the +slide. The presence of an "override" background is determined by +interrogating the `.follow_master_background` property on each slide:: + + >>> slide.follow_master_background + True + +**Override inheritance of background.** Assigning `False` to +`.follow_master_background` adds a "blank" background to the slide, which +then no longer inherits any layout or master background:: + + >>> slide.follow_master_background = False + >>> slide.follow_master_background + False + +Note that this step is not necessary to override inheritance. Merely +specifying a background fill will also interrupt inheritance. This approach +might be the easiest way though, if all you want is to interrupt inheritance +and don't want to apply a particular fill. + +**Restore inheritance of slide background.** Any explicitly-applied slide +background can be removed by assigning `True` to +`.follow_master_background`:: + + >>> slide.follow_master_background = True + >>> slide.follow_master_background + True + +**Access background fill.** The `FillFormat` object for a slide background is +accessed using the background's `.fill` property. Note that merely accessing +this property will suppress inheritance of background for this slide. This +shouldn't normally be a problem as there would be little reason to access the +property without intention to change it:: + + >>> background.fill + + +**Apply solid color background.** A background color is specified in the same +way as fill is specified for a shape. Note that the `FillFormat` object also +supports applying theme colors and patterns:: + + >>> fill = background.fill + >>> fill.solid() + >>> fill.fore_color.rgb = RGBColor(255, 0, 0) + +Minimal `p:bg`?:: + + + + + + + + + ... + + + +Schema excerpt +-------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-base.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-base.rst new file mode 100644 index 0000000000000000000000000000000000000000..9f79f32119634202fb90d504beaa82e0e8ba4507 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-base.rst @@ -0,0 +1,148 @@ +.. _BaseSlide: + +Base Slide +========== + +A slide is the fundamental visual content container in a presentation, that +content taking the form of shape objects. The SlideMaster and SlideLayout +objects are also slides and the three share common behaviors. They each also +have distinctive behaviors. The focus of this page is the common slide +characteristics. + + +Name +---- + +For the moment, the only shared attribute is name, stored in the +`p:sld/p:cSld/@name` attribute. + +While this attribute is populated by PowerPoint in slide layouts, it is +commonly unpopulated in slides and slide masters. When a slide has no +explicit name, PowerPoint uses the default name 'Slide {n}', where *n* is the +sequence number of the slide in the current presentation. This name is not +written to the `p:cSlide/@name` attribute. In the outline pane, PowerPoint +uses the slide title if there is one. + +Slide names may come into things when doing animations. Otherwise they don't +show up in the commonly-used parts of the UI. + + +XML specimens +------------- + +.. highlight:: xml + + +Example slide contents:: + + + + + + ... + + + + + + + + +Schema excerpt +-------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-layout.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-layout.rst new file mode 100644 index 0000000000000000000000000000000000000000..6616683bdc9eb072db07a552fefe3b81bfd7e785 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-layout.rst @@ -0,0 +1,118 @@ + +Slide Layout +============ + +A slide layout acts as an property inheritance base for zero or more slides. +This provides a certain amount of separation between formatting and content +and contributes to visual consistency across the slides of a presentation. + +Remove Layout +------------- + +Preliminary notes +~~~~~~~~~~~~~~~~~ + +* Images on a removed slide layout appear to disappear automatically (without explicitly + dropping their relationship from the slide layout before removing it). + +* A "used" layout cannot be removed. Being "used" in this context means the presentation + contains one or more slides *based* on that layout. The layout provides inherited + placeholders, styling, and perhaps other background objects and will cause a repair + error if missing. + + +Protocol +~~~~~~~~ + +The default slide layout collection (the one belonging to the first slide master) is +accessible directly from the presentation object:: + + >>> from pptx import Presentation + >>> prs = Presentation() + >>> slide_layouts = prs.slide_layouts + +Remove an (unused) slide layout:: + + >>> slide_layouts.remove(slide_layouts[3]) + +Identify unused slide layouts:: + + >>> [layout for layout in slide_layouts if not layout.used_by_slides]) + [ + + + ... + ] + + +Specimen XML +------------ + +Each slide master contains a list of its slide layouts. Each layout is uniquely +identified by a slide-layout id (although this is the only place it appears) and is +accessed by traversing the relationship-id (rId) in the `r:id` attribute:: + + + + + + + + + + + + + + + + + + + +The layout used by a slide is specified (only) in the `.rels` file for that slide:: + + + + + + +Schema excerpt +-------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-master.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-master.rst new file mode 100644 index 0000000000000000000000000000000000000000..b9a53639e7bb2016fa5fc6c9096d43344bf63572 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-master.rst @@ -0,0 +1,67 @@ +.. _SlideMaster: + +Slide Master +============ + +A slide master acts as a "parent" for zero or more slide layouts, providing +an inheritance base for placeholders and other slide and shape properties. + + +Schema excerpt +-------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-notes-master.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-notes-master.rst new file mode 100644 index 0000000000000000000000000000000000000000..f8d3c2e85c18a76f494dfe73d27ad64355fee247 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-notes-master.rst @@ -0,0 +1,140 @@ + +Notes Master +============ + +A presentation may have a notes master part (zero or one). The notes master +determines the background elements and default layout of a notes page. + +In the PowerPoint UI, a notes item is called a "notes page"; internally +however, it is referred to as a "notes slide", is based on the Slide object, +and shares many behaviors with it such as containing shapes and inheriting +from a master. + +A notes slide is created on-first use, perhaps most frequently by typing text +into the notes pane. When a new notes slide is created, it is based on the +notes master. If no notes master is yet present, a new one is created from +an internal PowerPoint-preset default and added to the package. + +When a notes slide is created from the notes master, certain placeholders are +partially "cloned" from the master. All other placeholders and shapes remain +only on the master. The cloning process only creates placeholder shapes on +the notes slide, but does not copy position or size information or other +formatting. By default, position, size, and other formatting is inherited +from the corresponding master placeholder. This achieves consistency through +a presentation. + +If position, size, etc. is changed on a NotesSlide, the new position +overrides that on the master. This override is property-by-property. + +A notes slide maintains a relationship with the master it was created from. +This relationship is traversed to access the master placeholder properties +for inheritance purposes. + +A master can contain at most one each of six different placeholders: slide +image, notes (textbox), header, footer, date, and slide number. The header, +footer, and date placeholders are not copied to the notes slide by default. +These three placeholders can be individually shown or hidden (copied to or +deleted from the notes slide actually) using the Insert > Header and +Footer... menu option/dialog. This dialog is also available from the Page +Setup dialog. + +All other items on the notes master, such as background color/texture/image +and any additional text boxes or other shapes such as a logo, constitute +"background graphics" and are shown by default. The may be hidden or re-shown +on a notes slide-by-slide basis using the Format Background... (context or +menu bar) menu item. + + +Candidate Protocol +------------------ + +A NotesMaster part is created on first access when not yet present:: + + >>> notes_master = presentation.notes_master + >>> notes_master + + +It provides access to its placeholders and its shapes (which include +placeholders):: + + >>> notes_master.shapes + + >>> notes_master.placeholders + + +These placeholders and other shapes can be manipulated as usual. + + +Understanding Placeholders implementation +----------------------------------------- + +* SlidePlaceholders is a direct implementation, not subclassing Shapes + +Call stacks: +------------ + +* _BaseSlide.placeholders + => BasePlaceholders() + => _BaseShapes + _is_member_elm() override + +* NotesMaster.placeholders + => _BaseMaster.placeholders + => MasterPlaceholders() + => BasePlaceholders() + get() + _shape_factory() override + => _BaseShapes + _is_member_elm() override + + +PowerPoint behavior +------------------- + +* A NotesSlide placeholder inherits properties from the NotesMaster + placeholder *of the same type* (there can be at most one). + +* For some reason PowerPoint adds a second theme for the NotesMaster, not + sure what that's all about. I'll just add the default theme2.xml, then + folks can avoid that if there are problems just by pre-loading + a notesMaster of their own in their template. + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +The root element of a notesSlide part is a `p:notes` element:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-notes-slide.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-notes-slide.rst new file mode 100644 index 0000000000000000000000000000000000000000..43d88cbf00ba3febded57b30b4173d6258b4e488 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-notes-slide.rst @@ -0,0 +1,260 @@ + +Notes Slide +=========== + +A slide may have an associated notes page. The notes it contains are +displayed under the slide in the PowerPoint UI when in edit mode. The slide +notes are also shown in presenter mode, are displayed in Notes Pages view, +and are printed on those notes pages. + +Internally, a notes page is referred to as a *notes slide*. This is sensible +because it is actually a specialized instance of a slide. It contains shapes, +many of which are placeholders, and allows inserting of new shapes such as +auto shapes, tables, and charts (although it is probably not common). Much of +the functionality for a notes slide is inherited from existing base classes. + +A notes slide is created using the notes master as a template. A presentation +has no notes master when created from a template in PowerPoint. One is +created according to a PowerPoint-internal preset default the first time +it is needed, which is generally when a notes slide is created. It's possible +one can also be created by entering the Notes Master view and almost +certainly is created by editing the master found there (haven't tried it +though). A presentation can have at most one notes master. + +On creation, certain placeholders (slide image, notes, slide number) are +copied from the notes master onto the new notes slide (if they have not been +removed from the master). These "cloned" placeholders inherit position, size, +and formatting from their corresponding notes master placeholder. If the +position, size, or formatting of a notes slide placeholder is changed, the +changed property is no long inherited (unchanged properties, however, +continue to be inherited). + +The remaining three placeholders that can appear on the notes master (date, +header text, footer text) can optionally be made to appear on an individual +notes slide using the Header and Footer... dialog. This dialog also has +a button allowing all notes slides to be updated with the selected options. +There appears to be some heuristic logic that automatically propagates these +settings to notes for new slides as they are created. + +A notes slide is not automatically created for each slide. Rather it is +created the first time it is needed, perhaps most commonly when notes text is +typed into the notes area under the slide in the UI. + + +Candidate Protocol +------------------ + +A notes slide is created on first access if one doesn't exist. Consequently, +Slide.has_notes_slide is provided to detect the presence of an existing notes +slide, avoiding creation of unwanted notes slide objects:: + + >>> slide.has_notes_slide + False + +Because a notes slide is created on first access, Slide.notes_slide +unconditionally returns a |NotesSlide| object. Once created, the same +instance is returned on each call:: + + >>> notes_slide = slide.notes_slide + >>> notes_slide + + >>> slide.has_notes_slide + True + +Like any slide (slide, slide layout, slide master, etc.), a notes slide has +shapes and placeholders, as well as other standard properties:: + + >>> notes_slide.shapes + + >>> notes_slide.placeholders + + +The distinctive characteristic of a notes slide is the notes it contains. +These notes are contained in the text frame of the notes placeholder and are +manipulated using the same properties and methods as any shape textframe:: + + >>> text_frame = notes_slide.notes_text_frame + >>> text_frame.text = 'foobar' + >>> text_frame.text + 'foobar' + >>> text_frame.add_paragraph('barfoo') + >>> text_frame.text + 'foobar\nbarfoo' + + +PowerPoint behavior +------------------- + +* Notes page has its own view (View > Notes Page) + + + Notes can be edited from there too + + It has a hide background graphics option and the other background settings + + Notes have richer edit capabilities (such as ruler for tabs and indents) + in the Notes view. + +* A notes slide, once created, doesn't disappear when its notes content is + deleted. + +* NotesSlide placeholders inherit properties from the NotesMaster placeholder + *of the same type*. + +* For some reason PowerPoint adds a second theme for the NotesMaster, not + sure what that's all about. I'll just add the default theme2.xml, then + folks can avoid that if they encounter problems just by pre-loading + a notesMaster of their own in their template. + + +Example XML +----------- + +.. highlight:: xml + +Empty notes page element:: + + + + + + + + + + + + + + + + + + + + + + + + +Default notes page populated with three base placeholders:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Notes + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +The root element of a notesSlide part is a `p:notes` element:: + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-slide-shapes.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-slide-shapes.rst new file mode 100644 index 0000000000000000000000000000000000000000..c70602f209b1e8cd25bcfb1c459b995789b5714f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-slide-shapes.rst @@ -0,0 +1,56 @@ + +SlideShapes +=========== + +Shapes on a slide are specified in the shape tree, a hierarchical data +structure rooted in a ```` element. + + +Schema excerpt +-------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-slide.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-slide.rst new file mode 100644 index 0000000000000000000000000000000000000000..95fd406365c0e1ec206d1bb221826121a6c25d70 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/sld-slide.rst @@ -0,0 +1,173 @@ +.. _Slide: + +Slide +===== + +A slide is the fundamental visual content container in a presentation, that +content taking the form of shape objects. + +The slides in a presentation are owned by the presentation object. In +particular, the unique identifier of a slide, the slide id, is assigned and +managed by the presentation part, and is not recorded in the slide XML. + +A slide master and slide layout are both closely related to slide and the three +share the majority of their properties and behaviors. + + +Slide ID +-------- + +PowerPoint assigns a unique integer identifier to a slide when it is created. +Note that this identifier is only present in the presentation part, and maps +to a relationship ID; it is not recorded in the XML of the slide itself. +Therefore the identifier is only unique within a presentation. The ID takes +the form of an integer starting at 256 and incrementing by one for each new +slide. Changing the ordering of the slides does not change the id. The id of +a deleted slide is not reused, although I'm not sure whether it's clever +enough not to reuse the id of the last added slide when it's been deleted as +there doesn't seem to be any record in the XML of the max value assigned. + + +XML specimens +------------- + +.. highlight:: xml + + +Example presentation XML showing sldIdLst:: + + + + + + + + + + + + + + +Example slide contents:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Schema excerpt +-------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/tbl-merge.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/tbl-merge.rst new file mode 100644 index 0000000000000000000000000000000000000000..60793aac68a086bca6c7c5617c663da6e3b04140 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/tbl-merge.rst @@ -0,0 +1,304 @@ +.. _table_merge: + +Cell Merge +========== + +PowerPoint allows a user to *merge* table cells, causing multiple *grid +cells* to appear and behave as a single cell. + + +Terminology +----------- + +The following distinctions are important to the implementation and also to +using the API. + +table grid + A PowerPoint (DrawingML) table has an underlying grid which is a strict + two-dimensional (n X m) array; each row in the table grid has m cells and + each column has n cells. Grid cell boundaries are aligned both vertically + and horizontally. + +grid cell + Each of the n x m cells in a table is a grid cell. Every grid cell is + addressable, even those "shadowed" by a merge-origin cell. + + *Apparent* cell boundaries can be modified by *merging* two or more grid + cells. + +merge-origin cell + The top-left grid cell in a merged cell. This cell will be visible, have + the combined extent of all spanned cells, and contain any visible content. + +spanned cell + All grid cells in a merged cell are spanned cells, excepting the one at + the top-left (the merge-origin cell). Intuitively, the merge-origin cell + "spans" all the other grid cells in the merge range. + + Content in a spanned cell is not visible, and is typically moved to the + merge-origin cell as part of the merge operation, leaving each spanned + cell with exactly one empty paragraph. This content becomes visible again + if the merged cell is split. + +unmerged cell + While not a distinction directly embodied in the code, any cell which is + not a merge-origin cell and is also not a spanned cell is a "regular" cell + and not part of a merged cell. + + +Protocol +-------- + +A cell is accessed by grid location (regardless of any merged regions). All +grid cells are addressable, even those "shadowed" by a merge (such a shadowed +cell is a *spanned* cell):: + + >>> table = shapes.add_table(rows=3, cols=3, x, y, cx, cy).table + >>> len(table.rows) + 3 + >>> len(table.columns) + 3 + >>> len(table.rows[0].cells) + 3 + +Merge 2 x 2 cells at top left:: + + >>> cell = table.cells(0, 0) + >>> other_cell = table.cells(1, 1) + >>> cell.merge(other_cell) + +The top-left cell of a merged cell is the merge-origin cell:: + + >>> origin_cell = table.cells(0, 0) + >>> origin_cell + + >>> origin_cell.is_merge_origin + True + >>> origin_cell.is_spanned + False + >>> origin_cell.span_height + 1 + >>> origin_cell.span_width + 2 + +A spanned cell has |True| on its `.is_spanned` property:: + + >>> spanned_cell = table.cell(0, 1) + >>> spanned_cell + + >>> spanned_cell.is_merge_origin + False + >>> spanned_cell.is_spanned + True + +A "regular" cell not participating in a merge is neither the merge origin nor +spanned:: + + >>> cell = table.cell(0, 2) + >>> cell + + >>> cell.is_merge_origin + False + >>> cell.is_spanned + False + +Cell instances proxying the same `a:tc` element compare equal:: + + >>> origin_cell == table.cell(0, 0) + True + >>> spanned_cell == table.cell(0, 1) + True + >>> cell == table.cell(0, 2) + True + >>> origin_cell == spanned_cell + False + + +Use Cases +--------- + +Use Case: Interrogate table for merged cells:: + + def iter_merge_origins(table): + """Generate each merge-origin cell in *table*. + + Cell objects are ordered by their position in the table, + left-to-right, top-to-bottom. + """ + return (cell for cell in table.iter_cells() if cell.is_merge_origin) + + def merged_cell_report(cell): + """Return str summarizing position and size of merged *cell*.""" + return ( + 'merged cell at row %d, col %d, %d cells high and %d cells wide' + % (cell.row_idx, cell.col_idx, cell.span_height, cell.span_width) + ) + + # ---Print a summary line for each merged cell in *table*.--- + for merge_origin_cell in iter_merge_origins(table): + print(merged_cell_report(merge_origin_cell)) + +Use Case: Access only cells that display text (are not spanned):: + + def iter_visible_cells(table): + return (cell for cell in table.iter_cells() if not cell.is_spanned) + +Use Case: Determine whether table contains merged cells:: + + def has_merged_cells(table): + for cell in table.iter_cells(): + if cell.is_merge_origin: + return True + + +PowerPoint behaviors +-------------------- + +* Two or more cells are merged by selecting them using the mouse, then + selecting "Merge cells" from the context menu. + +* Content from spanned cells is moved to the merge origin cell. + +* A merged cell can be split ("unmerged" roughly). The UI allows the merge to + be split into an arbitrary number of rows and columns and adjusts the table + grid and row heights etc. to accommodate, adding (potentially very many) + new merged cells as required. + + `python-pptx` just removes the merge, restoring the underlying table grid + cells to regular (unmerged) cells. + + +Specimen XML +------------ + +.. highlight:: xml + +Super-simplified 3-cell horizontal merge:: + + + + + + + +Super-simplified 3-cell vertical merge:: + + + + + + + + + + + +Super-simplified 2D merge:: + + + + + + + + + + + + + + + + + +Simplified 2 x 3 table with first two horizontal cells merged:: + + + + + + + + + + ... + + + + ... + + + + ... + + + + + ... + ... + ... + + + +Simplified 2 x 3 table with first two vertical cells merged:: + + + + + + + + + + + Vertical + + + + + + + Span + + + + + + + ... + ... + + + + + + + + + + + + + ... + ... + + + + +Schema excerpt +-------------- + +:: + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/tbl-table-style.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/tbl-table-style.rst new file mode 100644 index 0000000000000000000000000000000000000000..21b62dca73fd00146ebc156cb33efa19e22ed74b --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/tbl-table-style.rst @@ -0,0 +1,21 @@ + +How table styles work +--------------------- + +* PowerPoint allows many formatting characteristics of a table to be set at + once by assigning a *table style* to a table. + +* PowerPoint includes an array of built-in table styles that a user can + browse in the *table style gallery*. These styles are built into the + PowerPoint *application*, and are only added to a `.pptx` file on first + use. + +* Zero or more table-styles can appear in the `ppt/tableStyles.xml` part. + Each is keyed with a UUID, by which it is referred to by a particular table + that uses that style. + +* A table may be assigned a table style by placing the matching UUID in the + `a:tbl/a:tblPr/a:tableStyleId` element text. + +* A default table style may be specified by placing its id in + `a:tblStyleLst/@def` in the `tableStyles.xml` part. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/tbl-table.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/tbl-table.rst new file mode 100644 index 0000000000000000000000000000000000000000..09e74227d79142b9a7c0b5ffb9f2955ad8410bfe --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/tbl-table.rst @@ -0,0 +1,431 @@ +.. _table: + +Table +===== + +One of the shapes available for placing on a PowerPoint slide is the *table*. +As shapes go, it is one of the more complex. In addition to having standard +shape properties such as position and size, it contains what amount to +sub-shapes that each have properties of their own. Prominent among these +sub-element types are row, column, and cell. + + +Table Properties +---------------- + +``first_row`` + read/write boolean property which, when true, indicates the first row should + be formatted differently, as for a heading row at the top of the table. + +``first_col`` + read/write boolean property which, when true, indicates the first column + should be formatted differently, as for a side-heading column at the far + left of the table. + +``last_row`` + read/write boolean property which, when true, indicates the last row should + be formatted differently, as for a totals row at the bottom of the table. + +``last_col`` + read/write boolean property which, when true, indicates the last column + should be formatted differently, as for a side totals column at the far + right of the table. + +``horz_banding`` + read/write boolean property indicating whether alternate color "banding" + should be applied to the body rows. + +``vert_banding`` + read/write boolean property indicating whether alternate color "banding" + should be applied to the table columns. + + +PowerPoint UI behavior +---------------------- + +The MS PowerPoint® client exhibits the following behavior related to table +properties: + +Upon insertion of a default, empty table + `` A `tblPr` element is present with a + `firstRow` and `bandRow` attribute, each set to True. + +After setting `firstRow` property off + `` The `firstRow` attribute is removed, not set to + `0` or `false`. + +The `` element is always present, even when it contains no +attributes, because it contains an `` element, even when the +table style is set to none using the UI. + + +API requirements +---------------- + +|Table| class +~~~~~~~~~~~~~ + +Properties and methods required for a |Table| shape. + +* ``apply_style(style_id)`` -- change the style of the table. Not sure what the + domain of ``style_id`` is. + +* ``cell(row, col)`` -- method to access an individual |_Cell| object. + +* ``columns`` -- collection of |_Column| objects, each corresponding to + a column in the table, in left-to-right order. + +* ``first_col`` -- read/write boolean property which, when true, indicates the + first column should be formatted differently, as for a side-heading column at + the far left of the table. + +* ``first_row`` -- read/write boolean property which, when true, indicates the + first row should be formatted differently, as for a heading row at the top of + the table. + +* ``horz_banding`` -- read/write boolean property indicating whether alternate + color "banding" should be applied to the body rows. + +* ``last_col`` -- read/write boolean property which, when true, indicates the + last column should be formatted differently, as for a side totals column at + the far right of the table. + +* ``last_row`` -- read/write boolean property which, when true, indicates the + last row should be formatted differently, as for a totals row at the bottom + of the table. + +* ``rows`` -- collection of |_Row| objects, each corresponding to a row in the + table, in top-to-bottom order. + +* ``vert_banding`` -- read/write boolean property indicating whether alternate + color "banding" should be applied to the table columns. + + +|_Cell| class +~~~~~~~~~~~~~ + +* ``text_frame`` -- container for text in the cell. +* borders, something like LineProperties on each side +* inset (margins) +* anchor and anchor_center +* horzOverflow, not sure what this is exactly, maybe wrap or auto-resize to + fit. + + +|_Column| class +~~~~~~~~~~~~~~~ + +Provide the properties and methods appropriate to a table column. + +* ``width`` -- read/write integer width of the column in English Metric Units +* perhaps ``delete()`` method + + +|_ColumnCollection| class +~~~~~~~~~~~~~~~~~~~~~~~~~ + +* ``add(before)`` -- add a new column to the left of the column having index + *before*, returning a reference to the new column. *before* defaults to + ``-1``, which adds the column as the last column in the table. + + +|_Row| class +~~~~~~~~~~~~ + +* ``height`` -- read/write integer height of the row in English Metric Units + (EMU). + + +|_RowCollection| class +~~~~~~~~~~~~~~~~~~~~~~ + +* ``add(before)`` -- add a new row before the row having index *before*, + returning a reference to the new row. *before* defaults to ``-1``, which adds + the row as the last row in the table. + + +Behavior +-------- + +Table width and column widths +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A table is created by specifying a row and column count, a position, and an +overall size. Initial column widths are set by dividing the overall width by +the number of columns, resolving any rounding errors in the last column. +Conversely, when a column's width is specified, the table width is adjusted to +the sum of the widths of all columns. Initial row heights are set similarly and +overall table height adjusted to the sum of row heights when a row's height is +specified. + + +MS API Analysis +--------------- + +MS API method to add a table is:: + + Shapes.AddTable(NumRows, NumColumns, Left, Top, Width, Height) + +There is a `Shape.HasTable` property which is true when a (`GraphicFrame`) +shape contains a table. + +Most interesting `Table` members: + +* `Cell(row, col)` method to access individual cells. +* `Columns` collection reference, with `Add` method (`Delete` method is + on `Column` object) +* `Rows` collection reference +* `FirstCol` and `FirstRow` boolean properties that indicate whether to apply + special formatting from theme or whatever to first column/row. +* `LastCol`, `LastRow`, and `HorizBanding`, all also boolean with similar + behaviors. +* `TableStyle` read-only to table style in theme. `Table.ApplyStyle()` method + is used to set table style. + +* `Columns.Add()` +* `Rows.Add()` + +`Column Members`_ page on MSDN. + +* Delete() +* Width property + +`Cell Members`_ page on MSDN. + +* Merge() and Split() methods +* Borders reference to Borders collection of LineFormat objects +* Shape reference to shape object that cell is or has. + +`LineFormat Members`_ page on MSDN. + +* ForeColor +* Weight + + +XML Semantics +------------- + +A `tableStyles.xml` part is present in default document, containing the +single (default) style "Medium Style 2 - Accent 1". Colors are specified +indirectly by reference to theme-specified values. + + +Specimen XML +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. highlight:: xml + +Default table produced by PowerPoint:: + + + + + + + + + + + + + + + + + + {5C22544A-7EE6-4342-B048-85BDC9FD1C3A} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Schema excerpt +-------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Resources +--------- + +`Table.FirstCol Property page on MSDN`_ + +.. _Table.FirstCol Property page on MSDN: + http://msdn.microsoft.com/en-us/library/office/ff744530.aspx + +* ISO-IEC-29500-1, Section 21.1.3 (DrawingML) Tables, pp3331 +* ISO-IEC-29500-1, Section 21.1.3.13 tbl (Table), pp3344 + + +.. _Table Members: + http://msdn.microsoft.com/en-us/library/office/ff745711(v=office.14).aspx + +.. _Column Members: + http://msdn.microsoft.com/en-us/library/office/ff746286(v=office.14).aspx + +.. _Cell Members: + http://msdn.microsoft.com/en-us/library/office/ff744136(v=office.14).aspx + +.. _LineFormat Members: + http://msdn.microsoft.com/en-us/library/office/ff745240(v=office.14).aspx diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-autofit-text.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-autofit-text.rst new file mode 100644 index 0000000000000000000000000000000000000000..c1cacd546a3977195950dc76e9aebef09e6043b8 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-autofit-text.rst @@ -0,0 +1,264 @@ + +Text - Auto-fit text to shape +============================= + +An AutoShape has a text frame, referred to in the PowerPoint UI as the +shape's *Text Box*. One of the settings provided is *Autofit*, which can be +one of "Do not autofit", "Resize text to fit shape", or "Resize shape to fit +text". The scope of this analysis is how best to implement the "Resize text +to fit shape" behavior. + +A robust implementation would be complex and would lead the project outside +the currently intended scope. In particular, because the shape size, text +content, the "full" point size of the text, and the autofit and wrap settings +of the text frame all interact to determine the proper "fit" of adjusted +text, all events that could change the state of any of these five factors +would need to be coupled to an "update" method. There would also need to be +at least two "fitting" algorithms, one for when wrap was turned on and +another for when it was off. + +The initial solution we'll pursue is a special-purpose method on TextFrame +that reduces the permutations of these variables to one and places +responsibility on the developer to call it at the appropriate time. The +method will calculate based on the current text and shape size, set wrap on, +and set auto_size to fit text to the shape. If any of the variables change, +the developer will be responsible for re-calling the method. + + +Current constraints +------------------- + +:meth:`.TextFrame.autofit_text` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* User must manually set all shape text to a uniform 12pt default full-size + font point size. + + + This is intended to be done before the call, but might work okay if done + after too, as long as it matches the default 12pt. + +* Only 12pt "full-size" is supported. There is no mechanism to specify other + sizes. +* Unconditionally sets autofit and wrap. +* Path to font file must be provided manually. +* User must manually set the font typeface of all shape text to match the + provided font file. + + +Incremental enhancements +------------------------ + +* **.fit_text() or .autofit_text().** Two related methods are used to fit + text in a shape using different approaches. ``TextFrame.autofit_text()`` + uses the `TEXT_TO_FIT_SHAPE` autofit setting to shrink a full-size + paragraph of text. Later edits to that text using PowerPoint will re-fit + the text automatically, up to the original (full-size) font size. + + ``TextFrame.fit_text()`` takes the approach of simply setting the font size + for all text in the shape to the best-fit size. No automatic resizing + occurs on later edits in PowerPoint, although the user can switch on + auto-fit for that text box, perhaps after setting the full-size point size + to their preferred size. + +* **Specified full point size.** Allow the point size maximum to be + specified; defaults to 18pt. All text in the shape is set to this size + before calculating the best-fit based on that size. + +* **Specified font.** In the process, this specifies the font to use, + although it may require a tuple specifying the type family name as well as + the bold and italic states, plus a file path. + +* **Auto-locate installed font file.** Search for and use the appropriate + locally-installed font file corresponding to the selected typeface. On + Windows, the font directory can be located using a registry key, and is + perhaps often `C:\Windows\Fonts`. However the font filename is not the same + as the UI typeface name, so some mapping would be required, including + detecting whether bold and/or italic were specified. + +* **Accommodate line breaks.** Either from `` elements or multiple + paragraphs. Would involve ending lines at a break, other than the last + paragraph. + +* **Add line space reduction.** PowerPoint always reduces line spacing by as + much as 20% to maximize the font size used. Add this factor into the + calculation to improve the exact match likelihood for font scale and + lnSpcReduction and thereby reduce occurence of "jumping" of text to a new + size on edit. + + +Candidate Protocol +------------------ + +Shape size and text are set before calling +:meth:`.TextFrame.autofit_text` or :meth:`.TextFrame.fit_text`:: + + >>> shape.width, shape.height = cx, cy + >>> shape.text = 'Lorem ipsum .. post facto.' + >>> text_frame = shape.text_frame + >>> text_frame.auto_size, text_frame.word_wrap, text_frame._font_scale + (None, False, None) + +Calling :meth:`TextFrame.autofit_text` turns on auto fit (text to shape), +switches on word wrap, and calculates the best-fit font scaling factor:: + + >>> text_frame.autofit_text() + >>> text_frame.auto_size, text_frame.word_wrap, text_frame._font_scale + (TEXT_TO_FIT_SHAPE (2), True, 55.0) + +Calling :meth:`TextFrame.fit_text` produces the same sized text, but autofit +is not turned on. Rather the actual font size for text in the shape is set to +the calculated "best fit" point size:: + + >>> text_frame.fit_text() + >>> text_frame.auto_size, text_frame.word_wrap, text_frame._font_scale + (None, True, None) + >>> text_frame.paragraphs[0].font.size.pt + 10 + + +Proposed |pp| behavior +---------------------- + +The :meth:`TextFrame.fit_text` method produces the following side effects: + +* :attr:`TextFrame.auto_size` is set to + :attr:`MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE` +* :attr:`TextFrame.word_wrap` is set to |True|. +* A suitable value is calculated for ``. The + `fontScale` attribute is set to this value and the `lnSpcReduction` + attribute is removed, if present. + +The operation can be undone by assigning |None|, :attr:`MSO_AUTO_SIZE.NONE`, +or :attr:`MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT` to `TextFrame.auto_size`. + + +PowerPoint behavior +------------------- + +* PowerPoint shrinks text in whole-number font sizes. + +* The behavior interacts with *Wrap text in shape*. The behavior we want here + is only when wrap is turned on. When wrap is off, only height and manual + line breaks are taken into account. Long lines simply extend outside the + box. + +* When assigning a font size to a shape, PowerPoint applies that font size at + the run level, adding a `sz` attribute to the `` element for every + content child of every `` element in the shape. The sentinel + `` element also gets a `sz` attribute set to that size, but + only in the last paragraph, it appears. + + +XML specimens +------------- + +.. highlight:: xml + +```` for default new textbox:: + + + + + + + + + +8" x 0.5" text box, default margins, defaulting to 18pt "full-size" text, +auto-reduced to 10pt. ```` element text wrapped for compact display:: + + + + + + + + + + The art and craft of designing typefaces is called type design. + Designers of typefaces are called type designers and are often + employed by type foundries. In digital typography, type + designers are sometimes also called font developers or font + designers. + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-fit-text.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-fit-text.rst new file mode 100644 index 0000000000000000000000000000000000000000..8c31aa27a6c7b7dbda35a324c50d5017c066f677 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-fit-text.rst @@ -0,0 +1,289 @@ + +Text - Fit text to shape +======================== + +An AutoShape has a text frame, referred to in the PowerPoint UI as the +shape's *Text Box*. One of the settings provided is *Autofit*, which can be +one of "Do not autofit", "Resize text to fit shape", or "Resize shape to fit +text". The scope of this analysis is how best to provide an alternative to +the "Resize text to fit shape" behavior that simply resizes the text to the +largest point size that will fit entirely within the shape extents. + +This produces a similar visual effect, but the "auto-size" behavior does not +persist to later changes to the text or shape. It is just as though the user +had reduced the font size just until all the text fit within the shape. + + +Candidate Protocol +------------------ + +Shape size and text are set before calling :meth:`.TextFrame.fit_text`:: + + >>> shape.width, shape.height = cx, cy + >>> shape.text = 'Lorem ipsum .. post facto.' + >>> text_frame = shape.text_frame + >>> text_frame.auto_size, text_frame.word_wrap + (None, False) + +Calling :meth:`TextFrame.fit_text` sets auto-size to MSO_AUTO_SIZE.NONE, +turns word-wrap on, and sets the font size of all text in the shape to the +maximum size that will fit entirely within the shape, not to exceed the +optional *max_size*. The default *max_size* is 18pt. The font size is applied +directly on each run-level element in the shape. The path to the matching +font file must be specified:: + + >>> text_frame.fit_text('calibriz.ttf', max_size=18) + >>> text_frame.auto_size, text_frame.word_wrap + (MSO_AUTO_SIZE.NONE (0), True) + >>> text_frame.paragraphs[0].runs[0].font.size.pt + 10 + + +Current constraints +------------------- + +:meth:`.TextFrame.fit_text` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* Path to font file must be provided manually. +* Bold and italic variant is selected unconditionally. +* Calibri typeface name is selected unconditionally. +* User must manually set the font typeface of all shape text to match the + provided font file. +* Font typeface and variant is assumed to be uniform. +* Font size is made uniform, without regard to existing differences in font + size in the shape text. +* Line breaks are replaced with a single space. + + +Incremental enhancements +------------------------ + +* **Allow font file to be specified.** This allows + :meth:`.TextFrame.fit_text` to be run from `pip` installed version. + OS-specific file locations and names can be determined by client. + +* **Allow bold and italic to be specified.** This allows the client to + determine whether to apply the bold and/or italic typeface variant to the + text. + +* **Allow typeface name to be specified.** This allows the client to + determine which base typeface is applied to the text. + +* **Auto-locate font file based on typeface and variants.** Relax requirement + for client to specify font file, looking it up in current system based on + system type, typeface name, and variants. + + +PowerPoint behavior +------------------- + +* PowerPoint shrinks text in whole-number font sizes. + +* When assigning a font size to a shape, PowerPoint applies that font size at + the run level, adding a `sz` attribute to the `` element for every + content child of every `` element in the shape. The `` + element in each paragraph also gets a `sz` attribute set to that size. + + +XML specimens +------------- + +.. highlight:: xml + +```` for default new textbox:: + + + + + + + + + +8" x 0.5" text box, default margins, defaulting to 18pt "full-size" text, +auto-reduced to 12pt. ```` element text wrapped for compact display:: + + + + + + + + + + The art and craft of designing typefaces is called type design. + Designers of typefaces are called type designers and are often + employed by type foundries. In digital typography, type + designers are sometimes also called font developers or font + designers. + + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-font-color.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-font-color.rst new file mode 100644 index 0000000000000000000000000000000000000000..5f53cfea7a408068ba74b91d6987117b203c8746 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-font-color.rst @@ -0,0 +1,496 @@ + +Font Color +========== + +Overview +-------- + +Font color is a particular case of the broader topic of *fill*, the case of +*solid fill*, in which a drawing element is filled with a single color. Other +possible fill types are *gradient*, *picture*, *pattern*, and *background* +(transparent). + +Any drawing element that can have a fill can have a solid fill, or color. +Elements that can have a fill include shape, line, text, table, table cell, and +slide background. + + +Scope +----- + +This analysis focuses on *font color*, although much of it is general to solid +fills. The focus is simply to enable getting to feature implementation as +quickly as possible, just not before its clear I understand how it works in +general. + + +Candidate API +------------- + +New members: + +* ``Font.color`` +* ``ColorFormat(fillable_elm)`` +* ``ColorFormat.type`` +* ``ColorFormat.rgb`` +* ``ColorFormat.theme_color`` +* ``ColorFormat.brightness`` +* ``RGBColor(r, g, b)`` +* ``RGBColor.__str__`` +* ``RGBColor.from_str(rgb_str)`` + +Enumerations: + +* MSO_COLOR_TYPE_INDEX +* MSO_THEME_COLOR_INDEX + + +Protocol:: + + >>> assert isinstance(font.color, ColorFormat) + + >>> font.color = 'anything' + AttributeError: can't set attribute + + >>> assert font.color.type in MSO_COLOR_TYPE_INDEX + wouldn't actually work, but conceptually true + + >>> font.color.rgb = RGB(0x3F, 0x2c, 0x36) + + >>> font.color.theme_color = MSO_THEME_COLOR.ACCENT_1 + + >>> font.color.brightness = -0.25 + + +XML specimens +------------- + +Here is a representative sample of the various font color cases as they appear +in the XML, as produced by PowerPoint. Some inoperative attributes have been +removed for clarity. + +Baseline run:: + + + + test text + + +set to a specific RGB color, using color wheel; HSB sliders yield the same:: + + + + + + + +set to theme color, Text 2:: + + + + + + + +set to theme color, Accent 2, 80% Lighter:: + + + + + + + + + + + +PowerPoint API +-------------- + +Changing the color of text in the PowerPoint API is accomplished with something +like this:: + + Set font = textbox.TextFrame.TextRange.Font + + 'set font to a specific RGB color + font.Color.RGB = RGB(12, 34, 56) + + Debug.Print font.Color.RGB + > 3678732 + + 'set font to a theme color; Accent 1, 25% Darker in this example + font.Color.ObjectThemeColor = msoThemeColorAccent1 + font.Color.Brightness = -0.25 + +The ColorFormat object is the first interesting object here, the type of object +returned by ``TextRange.Font.Color``. It includes the following properties that +will likely have counterparts in python-pptx: + +Brightness + Returns or sets the brightness of the specified object. The value for + this property must be a number from -1.0 (darker) to 1.0 (lighter), with + 0 corresponding to no brightness adjustment. Read/write Single. Note: this + corresponds to selecting an adjusted theme color from the PowerPoint ribbon + color picker, like 'Accent 1, 40% Lighter'. + +ObjectThemeColor + Returns or sets the theme color of the specified ColorFormat object. + Read/Write. Accepts and returns values from the enumeration + MsoThemeColorIndex. + +RGB + Returns or sets the red-green-blue (RGB) value of the specified color. + Read/write. + +Type + Represents the type of color. Read-only. + + +Legacy properties +~~~~~~~~~~~~~~~~~ + +These two properties will probably not need to be implemented in python-pptx. + +SchemeColor + Returns or sets the color in the applied color scheme that's associated + with the specified object. Accepts and returns values from + PpColorSchemeIndex. Read/write. Appears to be a legacy method to accomodate + code prior to PowerPoint 2007. + +TintAndShade + Sets or returns the lightening or darkening of the the color of a specified + shape. Read/write. + + +Resources +~~~~~~~~~ + +* `MSDN TextFrame2 Members`_ +* `MSDN TextRange Members`_ +* `MSDN Font Members`_ +* `MSDN ColorFormat Members`_ +* `MSDN MsoThemeColorIndex Enumeration`_ + + +.. _`MSDN TextFrame2 Members`: + http://msdn.microsoft.com/en-us/library/office/ff746114.aspx + +.. _`MSDN TextRange Members`: + http://msdn.microsoft.com/en-us/library/office/ff746274.aspx + +.. _`MSDN Font Members`: + http://msdn.microsoft.com/en-us/library/office/ff745818.aspx + +.. _`MSDN ColorFormat Members`: + http://msdn.microsoft.com/en-us/library/office/ff745051.aspx + +.. _`MSDN MsoThemeColorIndex Enumeration`: + http://msdn.microsoft.com/en-us/library/office/ff860782.aspx + + +Behaviors +--------- + +The API method ``Brightness`` corresponds to the UI action of selecting an +auto-generated tint or shade of a theme color from the PowerPoint ribbon color +picker: + +Setting font color to Accent 1 from the UI produces:: + + + + + + + +The following code does the same from the API:: + + fnt.Color.ObjectThemeColor = msoThemeColorAccent1 + +Setting font color to Accent 1, Lighter 40% (40% tint) from the PowerPoint UI +produces this XML:: + + + + + + + + + + +Setting ``Brightness`` to +0.4 has the same effect:: + + fnt.Color.Brightness = 0.4 + +Setting font color to Accent 1, Darker 25% (25% shade) from the UI results in +the following XML. Note that no ```` element is used.:: + + + + + + + + + +Setting ``Brightness`` to -0.25 has the same effect:: + + fnt.Color.Brightness = -0.25 + +Calling ``TintAndShade`` with a positive value (between 0 and 1) causes a tint +element to be inserted, but I'm not at all sure why and when one would want to +use it rather than the ``Brightness`` property.:: + + fnt.Color.TintAndShade = 0.75 + + + + + + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Enumerations +------------ + +**MsoColorType** + +http://msdn.microsoft.com/en-us/library/office/aa432491(v=office.12).aspx + +msoColorTypeRGB + 1 - Color is determined by values of red, green, and blue. + +msoColorTypeScheme + 2 - Color is defined by an application-specific scheme. + +msoColorTypeCMYK + 3 - Color is determined by values of cyan, magenta, yellow, and black. + +msoColorTypeCMS + 4 - Color Management System color type. + +msoColorTypeInk + 5 - Not supported. + +msoColorTypeMixed + -2 - Not supported. + +**MsoThemeColorIndex** + +http://msdn.microsoft.com/en-us/library/office/aa432702(v=office.12).aspx + +msoNotThemeColor + 0 - Specifies no theme color. +msoThemeColorDark1 + 1 - Specifies the Dark 1 theme color. +msoThemeColorLight1 + 2 - Specifies the Light 1 theme color. +msoThemeColorDark2 + 3 - Specifies the Dark 2 theme color. +msoThemeColorLight2 + 4 - Specifies the Light 2 theme color. +msoThemeColorAccent1 + 5 - Specifies the Accent 1 theme color. +msoThemeColorAccent2 + 6 - Specifies the Accent 2 theme color. +msoThemeColorAccent3 + 7 - Specifies the Accent 3 theme color. +msoThemeColorAccent4 + 8 - Specifies the Accent 4 theme color. +msoThemeColorAccent5 + 9 - Specifies the Accent 5 theme color. +msoThemeColorAccent6 + 10 - Specifies the Accent 6 theme color. +msoThemeColorHyperlink + 11 - Specifies the theme color for a hyperlink. +msoThemeColorFollowedHyperlink + 12 - Specifies the theme color for a clicked hyperlink. +msoThemeColorText1 + 13 - Specifies the Text 1 theme color. +msoThemeColorBackground1 + 14 - Specifies the Background 1 theme color. +msoThemeColorText2 + 15 - Specifies the Text 2 theme color. +msoThemeColorBackground2 + 16 - Specifies the Background 2 theme color. +msoThemeColorMixed + -2 - Specifies a mixed color theme. + + +Value Objects +------------- + +RGB + RGBColor would be an immutable value object that could be reused as often + as needed and not tied to any part of the underlying XML tree. + + +Other possible bits +------------------- + +* acceptance test sketch +* test data requirements; files, builder(s) +* enumerations and mappings +* value types required +* test criteria + +Example test criteria:: + + # XML + + + + + + + assert font.color.type == MSO_COLOR_TYPE.RGB + assert font.color.rgb == RGB(0x12, 0x34, 0x56) + assert font.color.schemeClr == MSO_THEME_COLOR.NONE + assert font.color.brightness == 0.0 diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-font-typeface.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-font-typeface.rst new file mode 100644 index 0000000000000000000000000000000000000000..556a3c71a6ab2cf97cdb8e808e668089a42d4ad9 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-font-typeface.rst @@ -0,0 +1,246 @@ + +Font typeface +============= + +Overview +-------- + +PowerPoint allows the font of text elements to be changed from, for example, +Verdana to Arial. This aspect of a font is its *typeface*, as opposed to its +size (e.g. 18 points) or style (e.g. bold, italic). + + +Minimum viable feature +---------------------- + +:: + + >>> assert isinstance(font, pptx.text.Font) + >>> font.name + None + >>> font.name = 'Verdana' + >>> font.name + 'Verdana' + + +Related MS API +-------------- + +* Font.Name +* Font.NameAscii +* Font.NameComplexScript +* Font.NameFarEast +* Font.NameOther + + +Protocol +-------- + +:: + + >>> assert isinstance(font, pptx.text.Font) + >>> font.name + None + >>> font.name = 'Verdana' + >>> font.name + 'Verdana' + + +XML specimens +------------- + +.. highlight:: xml + +Here is a representative sample of textbox XML showing the effect of applying +a non-default typeface. + +*Baseline default textbox*:: + + + + + + + + + + Baseline default textbox, no adjustments of any kind + + + + + +*textbox with typeface applied at shape level*:: + + + + + + + + + + + + + A textbox with Verdana typeface applied to shape, not text selection + + + + + + + + +*textbox with multiple runs, typeface applied at shape level*:: + + + + + + + + + + + + + + textbox with multiple runs having typeface + + + + + + + + + + + + + customized at shape level + + + + + + + + +*Asian characters, or possibly Asian font being applied*:: + + + + + + + + + + + + + + + 暒龢加咊晴弗 + + + + + + + + + +*then applying Arial from font pull-down*:: + + + + + + + + + + + + + + + 暒龢加咊晴弗 + + + + + + + + + + +Observations +~~~~~~~~~~~~ + +* PowerPoint UI always applies typeface customization at run level rather + than paragraph (defRPr) level, even when applied to shape rather than + a specific selection of text. +* PowerPoint applies the same typeface to the ```` and ```` + tag when a typeface is selected from the font pull-down in the UI. + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-font-underline.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-font-underline.rst new file mode 100644 index 0000000000000000000000000000000000000000..b03d6af6c6b39926bb19c8baa59a71c0746f1a05 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-font-underline.rst @@ -0,0 +1,132 @@ + +Font - Underline +================ + +Text in PowerPoint shapes can be formatted with a rich choice of underlining +styles. Two choices control the underline appearance of a font: the underline +style and the underline color. There are 18 available underline styles, +including such choices as single line, wavy, and dot-dash. + + +Candidate Protocol +------------------ + +:: + + >>> font.underline + False + >>> font.underline = True + >>> font.underline + SINGLE_LINE (2) + >>> font.underline = MSO_UNDERLINE.WAVY_DOUBLE_LINE + >>> font.underline + WAVY_DOUBLE_LINE (17) + >>> font.underline = False + >>> font.underline + False + + +XML specimens +------------- + +.. highlight:: xml + +Run with MSO_UNDERLINE.DOTTED_HEAVY_LINE:: + + + + + foobar + + + + + +Related Schema Definitions +-------------------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-hyperlink.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-hyperlink.rst new file mode 100644 index 0000000000000000000000000000000000000000..a08bbd274f7715fbc3b6a0e1ee4cb2fc4958ba32 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-hyperlink.rst @@ -0,0 +1,211 @@ + +Hyperlinks +========== + +Overview +-------- + +PowerPoint supports hyperlinks at two distinct levels: + +* a run of text can be a hyperlink +* an entire shape can be a hyperlink + +Hyperlinks in PowerPoint can have four types of targets: + +* a Internet address, such as https://github/scanny/python-pptx, including an + optional anchor (e.g. #sub-heading suffix to jump mid-page). This can also + be an email address, launching the local email client. A mailto: URI is used, + with subject specifiable using a '?subject=xyz' suffix. + +* another file, e.g. another PowerPoint file, including an optional anchor to, + for example, a specific slide. A `file://` URI is used to specify the file + path. + +* another part in the same presentation. This uses an internal relationship + (in the .rels item) to the target part. + +An optional ScreenTip, a roll-over tool-tip sort of message, can also be +specified for any of these link types. + +There are some more obscure attributes like "stop playing sound before +navigating" that are available, perhaps meant for kiosk-style applications. + +A run or shape can actually have two distinct link behaviors, one for clicking +and another for rolling over with the mouse. These are independent; a run or +shape can have one, the other, both, or neither. These are the two hyperlink +types reported by the Hyperlink.type attribute and using enumeration values +from MsoHyperlinkType. + + +Minimum viable feature +---------------------- + +Start with Run since that's the current use case and doesn't require working +out exactly which shapes can be hyperlinked. + + +.. highlight:: python + +:: + + r = p.add_run() + r.text = 'link to python-pptx @ GitHub' + hlink = r.hyperlink + hlink.address = 'https://github.com/scanny/python-pptx' + + +Roadmap items +------------- + +* add .hyperlink attribute to Shape and Picture + + +Resources +--------- + +* `Hyperlink Object (PowerPoint) on MSDN`_ + +.. _`Hyperlink Object (PowerPoint) on MSDN`: + http://msdn.microsoft.com/en-us/library/office/ff746252.aspx + + +Candidate Protocol +------------------ + +Add a hyperlink:: + + p = shape.text_frame.paragraphs[0] + r = p.add_run() + r.text = 'link to python-pptx @ GitHub' + hlink = r.hyperlink + hlink.address = 'https://github.com/scanny/python-pptx' + +Delete a hyperlink:: + + r.hyperlink = None + + # or ----------- + + r.hyperlink.address = None # empty string '' will do it too + +A Hyperlink instance is lazy-created on first reference. The object persists +until garbage collected once created. The link XML is not written until +.address is specified. Setting ``hlink.address`` to None or '' causes the +hlink entry to be removed if present. + + +Candidate API +------------- + +_Run.hyperlink + +Shape.hyperlink + +Hyperlink + + .address - target URL + + .screen_tip - tool-tip text displayed on mouse rollover is slideshow mode + + .type - MsoHyperlinkType (shape or run) + + .show_and_return ... + +_Run.rolloverlink would be an analogous property corresponding to the + element + + +Enumerations +------------ + +* MsoHyperlinkType: msoHyperlinkRange, msoHyperlinkShape + + +Open questions +-------------- + +* What is the precise scope of shape types that may have a hyperlink applied? +* does leading and trailing space around a hyperlink work as expected? +* not sure what PowerPoint does if you select multiple runs and then insert + a hyperlink, like including a stretch of bold text surrounded by plain text + in the selection. + + +XML specimens +------------- + +.. highlight:: xml + +Link on overall shape:: + + + + + + + + + + ... + + +Link on a run within a paragraph:: + + + + + Code is available at + + + + + + the python-pptx repository on GitHub + + + + + +Related Schema Definitions +-------------------------- + +:: + + + + + + + + + + + + + + + + + + + ... 19 attributes ... + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-para-spacing.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-para-spacing.rst new file mode 100644 index 0000000000000000000000000000000000000000..4386248b9de2dbf4373b0574e301002f32c0dd28 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-para-spacing.rst @@ -0,0 +1,262 @@ + +Paragraph Spacing +================= + +A paragraph has three spacing properties. It can have spacing that separates +it from the prior paragraph, spacing that separates it from the following +paragraph, and line spacing less than or greater than the default single line +spacing. + + +Candidate protocol +------------------ + +Get and set space before/after:: + + >>> paragraph = TextFrame.add_paragraph() + >>> paragraph.space_before + 0 + >>> paragraph.space_before = Pt(6) + >>> paragraph.space_before + 76200 + >>> paragraph.space_before.pt + 6.0 + +An existing paragraph that somehow has space before or after set in terms of +lines (````) will return a value of Length(0) for that property. + +Get and set line spacing:: + + >>> paragraph = TextFrame.add_paragraph() + >>> paragraph.line_spacing + 1.0 + >>> isinstance(paragraph.line_spacing, float) + True + >>> paragraph.line_spacing = Pt(18) + >>> paragraph.line_spacing + 228600 + >>> isinstance(paragraph.line_spacing, Length) + True + >>> isinstance(paragraph.line_spacing, int) + True + >>> paragraph.line_spacing.pt + 18.0 + +* The default value for ``Paragraph.line_spacing`` is 1.0 (lines). +* The units of the return value can be distinguished by its type. In + practice, units can also be distinguished by magnitude. Lines are returned + as a small-ish float. Point values are returned as a `Length` value. + + If type is the most convenient discriminator, the expression + `isinstance(line_spacing, float)` will serve as an effective `is_lines` + predicate. + + In practice, line values will rarely be greater than 3.0 and it would be + hard to imagine a useful line spacing less than 1 pt (12700). If magnitude + is the most convenient discriminator, 256 can be assumed to be a safe + threshold value. + + +MS API +------ + +LineRuleAfter + Determines whether line spacing after the last line in each paragraph is + set to a specific number of points or lines. Read/write. + +LineRuleBefore + Determines whether line spacing before the first line in each paragraph + is set to a specific number of points or lines. Read/write. + +LineRuleWithin + Determines whether line spacing between base lines is set to a specific + number of points or lines. Read/write. + +SpaceAfter + Returns or sets the amount of space after the last line in each paragraph + of the specified text, in points or lines. Read/write. + +SpaceBefore + Returns or sets the amount of space before the first line in each + paragraph of the specified text, in points or lines. Read/write. + +SpaceWithin + Returns or sets the amount of space between base lines in the specified + text, in points or lines. Read/write. + + +PowerPoint behavior +------------------- + +* The UI doesn't appear to allow line spacing to be set in units of lines, + although the XML and MS API allow it to be specified so. + + +XML specimens +------------- + +.. highlight:: xml + +Default paragraph spacing:: + + + + Paragraph with default spacing + + + +Spacing before = 6 pt:: + + + + + + + + + Paragraph spacing before = 6pt + + + +Spacing after = 12 pt:: + + + + + + + + + Paragraph spacing after = 12pt + + + +Line spacing = 24 pt:: + + + + + + + + + Paragraph line spacing = 24pt + + + + second line + + + +Line spacing = 2 lines:: + + + + + + + + + Paragraph line spacing = 2 line + + + + second line + + + + +Schema excerpt +-------------- + +.. highlight:: xml + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-text.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-text.rst new file mode 100644 index 0000000000000000000000000000000000000000..5ec4ce9ecbeb2998c9c2e72546ce8bda5165c30f --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/analysis/txt-text.rst @@ -0,0 +1,150 @@ + +Text +==== + +All text in PowerPoint appears in a shape. Of the six shape types, only +an AutoShape can directly contain text. This includes text placeholders, text +boxes, and geometric auto shapes. These correspond to shapes based on the +```` XML element. + +Each auto shape has a text frame, represented by a |TextFrame| object. A text +frame contains one or more paragraphs, and each paragraph contains a sequence +of zero or more run, line break, or field elements (````, ````, +and ````, respectively). + + +Notes +----- + +* include a:fld/a:t contents in Paragraph.text + + +XML specimens +------------- + +.. highlight:: xml + +Default text box with text, a line break, and a field:: + + + + + + + + + + This text box has a break here -> + + + + + + + and a Field here -> + + + + Monday, September 15, 14 + + + + + + +Schema excerpt +-------------- + +:: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/development_practices.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/development_practices.rst new file mode 100644 index 0000000000000000000000000000000000000000..be448bd9d3ba438b50dbe4ea8b7785ce62ed660a --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/development_practices.rst @@ -0,0 +1,161 @@ +##################### +Development Practices +##################### + +Release procedure +================= + +* merge outstanding feature branch(es) into develop + + + ``$ git checkout develop`` + + ``$ git merge --no-ff {feature-branch}`` + +* complete release updates + + + update version number in `pptx/__init__.py` + + update setup.py (shouldn't usually be any changes) + + update README.py, in particular, the release history + + update doc/index.rst + + confirm docs compile without errors + + run all tests (behave, nosetests, tox) + + create trial distribution (make clean sdist) + + ``git commit -m 'Release v0.2.2'`` + + merge develop into master + + - ``$ git checkout master`` + - ``$ git merge --no-ff develop`` + + + create tag for new version + + - $ ``git tag -a v0.2.5 -m 'Release version 0.2.5'`` + +* release uploaded to PyPI + + + upload: ``make upload`` + +* synchronize local repo with github + + + ``$ git push scanny develop`` + + ``$ git push scanny master`` + + ``$ git push --tags`` + +* docs regenerated + + + trigger regeneration of docs on RTD.org + + +Creating a hand-modified package +================================ + +* remove file, e.g. /docProps/core.xml +* remove reference from [Content_Types].xml +* remove relationship(s) from _rels/.rels or wherever they are + +Repackage:: + + rm -f ../no-core-props.pptx && zip -Dqr ../no-core-props.pptx . + + +Procedure -- Adding a new feature +================================= + +* issue added to github issue tracker +* git feature branch created +* working analysis documented +* acceptance test failing (not just raising exceptions) +* recursively, outside in: + + + unit test failing + + next level method(s) written + + unit test passing + +* all tests passing + + + unit + + acceptance + + tox + + visual confirmation of behavior in PowerPoint + +* documentation updated as required + + + API additions + + example code + +* feature branch committed, rebased if required +* feature branch merged into develop + + + ``git flow feature finish paragraph-level`` + +* changes pushed to github +* issue closed + + +Outside-in layers +----------------- + +* API wrapper method (if applicable) +* Internal API method +* objectify manipulation layer +* perhaps others + + +Creating slide images for documentation +======================================= + +* Desired slide created using a test script +* Zoom slide to 100% with: click on slide, View > Zoom > Zoom... > 100% > OK +* Screenshot file on desktop using Cmd-Shift-4, Space, click +* Load into PhotoShop and crop, keeping dark gray border +* Save as PNG, scaled to 280 x 210px +* Completed image saved in ``doc/_static/img/`` + + +Acceptance testing with ``behave`` +================================== + +... using *behave* for now for acceptance testing ... + + +Installation +------------ + +:: + + pip install behave + + +Tutorial +-------- + +The `behave tutorial`_ is well worth working through. + +.. _behave tutorial: + http://packages.python.org/behave/tutorial.html + +And this more detailed set of `examples and tutorials`_ is great for getting +the practicalities down. + +.. _examples and tutorials: + http://jenisys.github.com/behave.example/index.html + + +``behave`` Resources +-------------------- + +* `INVEST in Good Stories, and SMART Tasks`_ +* `The Secret Ninja Cucumber Scrolls`_ +* `Behavior Driven Outside In Development Explained, Part 1`_ +* The `behave website`_ contains excellent documentation on installing and + using behave. + +.. _`INVEST in Good Stories, and SMART Tasks`: + http://xp123.com/articles/invest-in-good-stories-and-smart-tasks/ + +.. _`The Secret Ninja Cucumber Scrolls`: + http://cuke4ninja.com/sec_cucumber_jargon.html + +.. _`Behavior Driven Outside In Development Explained, Part 1`: + http://www.knwang.com/behavior-driven-outside-in-development-explai + +.. _behave website: + http://packages.python.org/behave/index.html diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/philosophy.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/philosophy.rst new file mode 100644 index 0000000000000000000000000000000000000000..635ce009c76e255e07d58ce4916b7112ddd8109d --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/philosophy.rst @@ -0,0 +1,30 @@ +Vision +====== + +A robust, full-featured, and well-documented general-purpose library for +manipulating Open XML PowerPoint files. + +* **robust** - High reliability driven by a comprehensive test suite. + +* **full-featured** - Anything that the file format will allow can be + accomplished via the API. (Note that visions often take some time to fulfill + completely :). + +* **well-documented** - I don't know about you, but I find it hard to remember + what I was thinking yesterday if I don't write it down. That's not a problem + for most of my thinking, but when it comes to how I set up an object + hierarchy to interact, it can be a big time-waster. So I like it when things + are nicely laid out in black-and-white. Other folks seem to like that too + :). + +* **general-purpose** - Applicability to all conceivable purposes is valued + over being especially well-suited to any particular purpose. Particular + purposes can always be accomplished by building a wrapper library of your + own. Serving general purposes from a particularized library is not so easy. + +* **create AND manipulate** - While this library will perhaps most commonly be + used for *writing* .pptx files, it will also be suitable for *reading* .pptx + files and inspecting and manipulating their contents. I could see that coming + in handy for full-text indexing, removing speaker notes, changing out + templates, adding dynamically generated slides to static boilerplate, that + sort of thing. diff --git a/tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/about_packaging.rst b/tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/about_packaging.rst new file mode 100644 index 0000000000000000000000000000000000000000..a346b23254c7546f03fa68585b750103159fd961 --- /dev/null +++ b/tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/about_packaging.rst @@ -0,0 +1,144 @@ +======================== +About Open XML Packaging +======================== + +Recent Notes +============ + +* The content type for **XML** parts (only) is strictly determined by the + relationship type. Binary media parts may have multiple allowable content + types. + +* Each part type has one and only one relationship type. + + +About Packages +============== + +Open XML PowerPoint files are stored in files with the extension ``.pptx``. +These ``.pptx`` files are zip archives containing a separate file for each +main component of the presentation along with other files which contain +metadata about the overall presentation and relationships between its +components. + +The overall collection of files is known as a **package**. Each file within +the package represents a **package item**, commonly although sometimes +ambiguously referred to simply as an **item**. Package items that represent +high-level presentation components, such as slides, slide masters, and themes, +are referred to as **parts**. All parts are package items, but not all +package items are parts. + +Package items that are not parts are primarily **relationship items** that +express relationships between one part and another. Examples of relationships +include a slide having a relationship to the slide layout it is based on and a +slide master's relationship to an image such as a logo it displays. There is +one special relationship item, the **package relationship item** +(``/_rels/.rels``) which contains relationships between the package and +certain parts rather than relationships between parts. + +The only other package item is the **content types item** +(``/[Content_Types].xml``) which contains mappings of the parts to their +content types (roughly MIME types). + + +Package Loading Strategies +========================== + +Strategy 1 +---------- + +The content type item ([Content_Types].xml actually contains references to all +the main parts of the package. So one approach might be: + +1. Have passed in a mapping of content types to target classes that each + know how to load themselves from the xml and a list of relationships. + These classes are what OpenXML4J calls an *unmarshaller*. These would + each look something like:: + + { 'application/vnd...slide+xml' : Slide + , 'application/vnd...slideLayout+xml' : SlideLayout + , ... + } + +2. Have a ContentType class that can load from a content type item and allow + lookups by partname. Have it load the content type item from the package. + Lookups on it first look for an explicit override, but then fall back to + defaults. Not sure yet whether it should try to be smart about whether a + package part that looks like one that should have an override will get + fed to the xml default or not. + +3. Walk the package directory tree, and as each file is encountered: + +OR + +3. Walk the relationships tree, starting from /_rels/.rels + + * look up its content type in the content type manager + * look up the unmarshaller for that content type + * dispatch the part to the specified unmarshaller for loading + * add the resulting part to the package parts collection + * if it's a rels file, parse it and associate the relationships with the + appropriate source part. + + If a content type or unmarshaller is not found, throw an exception and + exit. Skip the content type item (already processed), and for now skip + the package relationship item. Infer the corresponding part name from + part rels item names. I think the walk can be configured so rels items + are encountered only after their part has been processed. + +4. Resolve all part relationship targets to in-memory references. + + +Principles upheld: +^^^^^^^^^^^^^^^^^^ + +* If there are any stray items in the package (items not referenced in the + content type part), they are identified and can be dealt with appropriately + by throwing an exception if it looks like a package part or just writing it + to the log if it's an extra file. Can set debug during development to throw + an exception either way just to give a sense of what might typically be + found in a package or to give notice that a hand-crafted package has an + internal inconsistency. + +* Conversely, if there are any parts referenced in the content type part that + are not found in the zip archive, that throws an exception too. + + +Random thoughts +=============== + +I'm starting to think that the packaging module could be a useful +general-purpose capability that could be applied to .docx and .xlsx files in +addition to .pptx ones. + +Also I'm thinking that a generalized loading strategy that walks the zip +archive directory tree and loads files based on combining what it discovers +there with what it can look up in it's spec tables might be an interesting +approach. + +I can think of the following possible ways to identify the type of package, +not sure which one is most reliable or definitive: + +* Check the file extension. Kind of thinking this should do the trick 99.99% + of the time. + +* Might not hurt to confirm that by finding an expected directory of /ppt, /word, or /xl. + +* A little further on that would be to find /ppt/presentation.xml, /word/document.xml, or /xl/workbook.xml. + +* Even further would be to find a relationship in the package relationship item to one of those three and not to any of the others. + +* Another confirmation might be finding a content type in [Content_Types].xml of: + + * .../presentationml.presentation.main+xml for /ppt/presentation.xml + + * .../spreadsheetml.sheet.main+xml for /xl/workbook.xml (Note that + macro-enabled workbooks use a different content type + 'application/vnd.ms-excel.sheet.macroEnabled.main+xml', I believe there + are variants for PresentationML as well, used for templates and slide + shows. + + * .../wordprocessingml.document.main+xml for /word/document.xml + +It's probably worth consulting ECMA-376 Part 2 to see if there are any hard +rules that might help determine what a definitive test would be.