python-hwpx 6.8.0__py3-none-any.whl → 6.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. hwpx/_document/fields.py +218 -85
  2. hwpx/_document/layout.py +46 -25
  3. hwpx/_document/media.py +45 -8
  4. hwpx/_document/memos.py +3 -1
  5. hwpx/_document/ns/fields.py +17 -1
  6. hwpx/_document/ns/refs.py +14 -0
  7. hwpx/_document/ns/shapes.py +2 -2
  8. hwpx/_document/ns/styles.py +135 -0
  9. hwpx/_document/ns/tables.py +49 -3
  10. hwpx/_document/shapes.py +15 -7
  11. hwpx/body_patch.py +27 -12
  12. hwpx/capabilities.py +1 -1
  13. hwpx/data/contract_docs/support-matrix.md +5 -5
  14. hwpx/document.py +35 -1
  15. hwpx/equation/authoring.py +3 -0
  16. hwpx/equation/eqedit.py +88 -5
  17. hwpx/errors.py +22 -1
  18. hwpx/form_fit/_glyph_table.py +5511 -297
  19. hwpx/form_fit/measure.py +1074 -105
  20. hwpx/hwp5/docinfo_writer.py +4 -3
  21. hwpx/hwp5/header_xml.py +4 -3
  22. hwpx/hwp5/package.py +70 -3
  23. hwpx/hwp5/records.py +2 -0
  24. hwpx/hwp5/section_writer.py +6 -5
  25. hwpx/hwp5/section_xml.py +69 -6
  26. hwpx/hwp5/shape_xml.py +6 -4
  27. hwpx/hwp5/shapes.py +22 -16
  28. hwpx/layout/line_cache.py +770 -0
  29. hwpx/layout/lint.py +4 -3
  30. hwpx/layout/pages.py +1608 -259
  31. hwpx/objects/__init__.py +3 -1
  32. hwpx/objects/form_field.py +73 -3
  33. hwpx/oxml/__init__.py +4 -0
  34. hwpx/oxml/_document_primitives.py +52 -64
  35. hwpx/oxml/_paragraph_text_edit.py +5 -11
  36. hwpx/oxml/body.py +3 -3
  37. hwpx/oxml/container.py +377 -0
  38. hwpx/oxml/curves.py +10 -3
  39. hwpx/oxml/document_parts.py +47 -10
  40. hwpx/oxml/dutmal_compose.py +1 -1
  41. hwpx/oxml/header.py +4 -0
  42. hwpx/oxml/header_compat.py +6 -0
  43. hwpx/oxml/header_fonts.py +140 -5
  44. hwpx/oxml/memo.py +4 -1
  45. hwpx/oxml/note_authoring.py +2 -0
  46. hwpx/oxml/objects.py +145 -215
  47. hwpx/oxml/paragraph.py +70 -84
  48. hwpx/oxml/run.py +1 -0
  49. hwpx/oxml/section.py +69 -15
  50. hwpx/oxml/section_format.py +185 -54
  51. hwpx/oxml/shape_position.py +320 -2
  52. hwpx/oxml/table.py +6 -4
  53. hwpx/oxml/table_sizes.py +53 -1
  54. hwpx/oxml/table_structure.py +166 -0
  55. hwpx/oxml/utils.py +28 -0
  56. hwpx/patch.py +259 -8
  57. hwpx/table_patch.py +428 -56
  58. hwpx/tools/package_validator.py +27 -4
  59. hwpx/tools/repair.py +123 -3
  60. hwpx/tools/toc_author.py +1 -1
  61. python_hwpx-6.10.0.dist-info/METADATA +256 -0
  62. {python_hwpx-6.8.0.dist-info → python_hwpx-6.10.0.dist-info}/RECORD +67 -64
  63. {python_hwpx-6.8.0.dist-info → python_hwpx-6.10.0.dist-info}/WHEEL +1 -1
  64. python_hwpx-6.8.0.dist-info/METADATA +0 -247
  65. {python_hwpx-6.8.0.dist-info → python_hwpx-6.10.0.dist-info}/entry_points.txt +0 -0
  66. {python_hwpx-6.8.0.dist-info → python_hwpx-6.10.0.dist-info}/licenses/LICENSE +0 -0
  67. {python_hwpx-6.8.0.dist-info → python_hwpx-6.10.0.dist-info}/licenses/NOTICE +0 -0
  68. {python_hwpx-6.8.0.dist-info → python_hwpx-6.10.0.dist-info}/top_level.txt +0 -0
hwpx/_document/fields.py CHANGED
@@ -8,7 +8,15 @@ from typing import TYPE_CHECKING, Any, Iterator, Mapping, Sequence, cast
8
8
 
9
9
  from ..errors import HwpxStateError, HwpxValueError
10
10
  from ..objects.checkbox import CheckBox
11
- from ..objects.form_field import CellField, FieldLocation, FieldParameter, FormField, TextBoxField
11
+ from ..objects.form_field import (
12
+ Bookmark,
13
+ CellField,
14
+ FieldLocation,
15
+ FieldParameter,
16
+ FormField,
17
+ FormulaField,
18
+ TextBoxField,
19
+ )
12
20
  from ..objects.results import FieldFillResult
13
21
  from ..oxml import HwpxOxmlParagraph
14
22
  from ..oxml.namespaces import HP
@@ -386,8 +394,15 @@ def _form_field_payload(
386
394
  }
387
395
 
388
396
 
389
- def _iter_form_field_matches(doc: "HwpxDocument") -> list[dict[str, Any]]:
390
- matches: list[dict[str, Any]] = []
397
+ def _iter_content_paragraphs(
398
+ doc: "HwpxDocument",
399
+ ) -> Iterator[tuple[int, int, int, Any, HwpxOxmlParagraph, list[Any]]]:
400
+ """Every paragraph of the document in order, those in table cells and objects
401
+ included: section index, paragraph index (over all of them), index among the
402
+ section's own paragraphs (-1 for a nested one), the ``<hp:p>``, its view and
403
+ its runs. Memo bodies are not content, and a header/footer python-hwpx keeps
404
+ twice is walked once."""
405
+
391
406
  paragraph_index = 0
392
407
  for section_index, section in enumerate(doc.sections):
393
408
  direct_indexes = {
@@ -408,80 +423,106 @@ def _iter_form_field_matches(doc: "HwpxDocument") -> list[dict[str, Any]]:
408
423
 
409
424
  for paragraph_element in iter_content_paragraphs(section.element):
410
425
  paragraph = HwpxOxmlParagraph(paragraph_element, section)
411
- paragraph_index_in_section = direct_indexes.get(paragraph_element, -1)
412
- runs = [child for child in paragraph.element if _local_name(child) == "run"]
413
- for run_index, run in enumerate(runs):
414
- children = list(run)
415
- for child_index, child in enumerate(children):
416
- if _local_name(child) != "ctrl":
426
+ runs = [child for child in paragraph_element if _local_name(child) == "run"]
427
+ yield (
428
+ section_index,
429
+ paragraph_index,
430
+ direct_indexes.get(paragraph_element, -1),
431
+ paragraph_element,
432
+ paragraph,
433
+ runs,
434
+ )
435
+ paragraph_index += 1
436
+
437
+
438
+ def _iter_form_field_matches(doc: "HwpxDocument") -> list[dict[str, Any]]:
439
+ return _iter_field_matches(doc, _is_form_field_begin)
440
+
441
+
442
+ def _iter_field_matches(doc: "HwpxDocument", accept: Any) -> list[dict[str, Any]]:
443
+ """The fields whose ``<hp:fieldBegin>`` *accept(ctrl, field_begin)* takes, in
444
+ document order, with their text up to the matching ``<hp:fieldEnd>``."""
445
+
446
+ matches: list[dict[str, Any]] = []
447
+ for (
448
+ section_index,
449
+ paragraph_index,
450
+ paragraph_index_in_section,
451
+ paragraph_element,
452
+ paragraph,
453
+ runs,
454
+ ) in _iter_content_paragraphs(doc):
455
+ for run_index, run in enumerate(runs):
456
+ children = list(run)
457
+ for child_index, child in enumerate(children):
458
+ if _local_name(child) != "ctrl":
459
+ continue
460
+ for field_begin in child.findall(f"{_HP}fieldBegin"):
461
+ if not accept(child, field_begin):
417
462
  continue
418
- for field_begin in child.findall(f"{_HP}fieldBegin"):
419
- if not _is_form_field_begin(child, field_begin):
420
- continue
421
- end_position = _find_field_end_position(
422
- doc,
423
- runs,
424
- begin_run_index=run_index,
425
- begin_child_index=child_index,
426
- field_begin=field_begin,
427
- )
428
- end_run_index: int | None = None
429
- end_child_index: int | None = None
430
- span = None
431
- if end_position is not None:
432
- end_run_index, end_child_index, _field_end = end_position
433
- else:
434
- span = _find_field_end_in_following_paragraphs(paragraph_element, field_begin)
435
- text_nodes = _field_text_nodes(
463
+ end_position = _find_field_end_position(
464
+ doc,
465
+ runs,
466
+ begin_run_index=run_index,
467
+ begin_child_index=child_index,
468
+ field_begin=field_begin,
469
+ )
470
+ end_run_index: int | None = None
471
+ end_child_index: int | None = None
472
+ span = None
473
+ if end_position is not None:
474
+ end_run_index, end_child_index, _field_end = end_position
475
+ else:
476
+ span = _find_field_end_in_following_paragraphs(paragraph_element, field_begin)
477
+ text_nodes = _field_text_nodes(
478
+ doc,
479
+ runs,
480
+ begin_run_index=run_index,
481
+ begin_child_index=child_index,
482
+ end_run_index=end_run_index if span is None else len(runs) - 1,
483
+ end_child_index=end_child_index,
484
+ )
485
+ current_value = "".join(_text_node_value(node) for node in text_nodes)
486
+ if span is not None:
487
+ # the content goes on over paragraphs: their texts, one per line
488
+ end_paragraph, end_runs, span_run, span_child, middle = span
489
+ tail = _field_text_nodes(
436
490
  doc,
437
- runs,
438
- begin_run_index=run_index,
439
- begin_child_index=child_index,
440
- end_run_index=end_run_index if span is None else len(runs) - 1,
441
- end_child_index=end_child_index,
491
+ end_runs,
492
+ begin_run_index=0,
493
+ begin_child_index=-1,
494
+ end_run_index=span_run,
495
+ end_child_index=span_child,
442
496
  )
443
- current_value = "".join(_text_node_value(node) for node in text_nodes)
444
- if span is not None:
445
- # the content goes on over paragraphs: their texts, one per line
446
- end_paragraph, end_runs, span_run, span_child, middle = span
447
- tail = _field_text_nodes(
448
- doc,
449
- end_runs,
450
- begin_run_index=0,
451
- begin_child_index=-1,
452
- end_run_index=span_run,
453
- end_child_index=span_child,
454
- )
455
- current_value = "\n".join(
456
- [
457
- current_value,
458
- *(_run_texts([c for c in p if _local_name(c) == "run"]) for p in middle),
459
- "".join(_text_node_value(node) for node in tail),
460
- ]
461
- )
462
- payload = _form_field_payload(
463
- doc,
464
- index=len(matches),
465
- section_index=section_index,
466
- paragraph_index=paragraph_index,
467
- paragraph_index_in_section=paragraph_index_in_section,
468
- run_index=run_index,
469
- child_index=child_index,
470
- ctrl=child,
471
- field_begin=field_begin,
472
- current_value=current_value,
473
- has_end=end_position is not None or span is not None,
497
+ current_value = "\n".join(
498
+ [
499
+ current_value,
500
+ *(_run_texts([c for c in p if _local_name(c) == "run"]) for p in middle),
501
+ "".join(_text_node_value(node) for node in tail),
502
+ ]
474
503
  )
475
- payload["_paragraph"] = paragraph
476
- payload["_runs"] = runs
477
- payload["_begin_run_index"] = run_index
478
- payload["_begin_child_index"] = child_index
479
- payload["_end_run_index"] = end_run_index
480
- payload["_end_child_index"] = end_child_index
481
- payload["_text_nodes"] = text_nodes
482
- payload["_span"] = span
483
- matches.append(payload)
484
- paragraph_index += 1
504
+ payload = _form_field_payload(
505
+ doc,
506
+ index=len(matches),
507
+ section_index=section_index,
508
+ paragraph_index=paragraph_index,
509
+ paragraph_index_in_section=paragraph_index_in_section,
510
+ run_index=run_index,
511
+ child_index=child_index,
512
+ ctrl=child,
513
+ field_begin=field_begin,
514
+ current_value=current_value,
515
+ has_end=end_position is not None or span is not None,
516
+ )
517
+ payload["_paragraph"] = paragraph
518
+ payload["_runs"] = runs
519
+ payload["_begin_run_index"] = run_index
520
+ payload["_begin_child_index"] = child_index
521
+ payload["_end_run_index"] = end_run_index
522
+ payload["_end_child_index"] = end_child_index
523
+ payload["_text_nodes"] = text_nodes
524
+ payload["_span"] = span
525
+ matches.append(payload)
485
526
  return matches
486
527
 
487
528
 
@@ -494,17 +535,8 @@ def _form_field_from_match(doc: "HwpxDocument", match: Mapping[str, Any]) -> For
494
535
  ``field_type``) that 5.x exposed as separate dict keys (design §2.3).
495
536
  """
496
537
 
497
- location = FieldLocation(
498
- section_index=match["section_index"],
499
- paragraph_index=match["paragraph_index"],
500
- paragraph_index_in_section=match["paragraph_index_in_section"],
501
- run_index=match["run_index"],
502
- child_index=match["child_index"],
503
- )
504
- parameters = tuple(
505
- FieldParameter(name=parameter.get("name", ""), value=parameter.get("value", ""))
506
- for parameter in match.get("parameters", [])
507
- )
538
+ location = _match_location(match)
539
+ parameters = _match_parameters(match)
508
540
  field_begin = match["_field_begin"]
509
541
  editable = (field_begin.get("editable") or "").strip().lower() in {"1", "true"}
510
542
  return FormField(
@@ -536,6 +568,107 @@ def list_form_fields(doc: "HwpxDocument") -> tuple[FormField, ...]:
536
568
  return tuple(_form_field_from_match(doc, match) for match in _iter_form_field_matches(doc))
537
569
 
538
570
 
571
+ def _match_location(match: Mapping[str, Any]) -> FieldLocation:
572
+ return FieldLocation(
573
+ section_index=match["section_index"],
574
+ paragraph_index=match["paragraph_index"],
575
+ paragraph_index_in_section=match["paragraph_index_in_section"],
576
+ run_index=match["run_index"],
577
+ child_index=match["child_index"],
578
+ )
579
+
580
+
581
+ def _match_parameters(match: Mapping[str, Any]) -> tuple[FieldParameter, ...]:
582
+ return tuple(
583
+ FieldParameter(name=parameter.get("name", ""), value=parameter.get("value", ""))
584
+ for parameter in match.get("parameters", [])
585
+ )
586
+
587
+
588
+ def _field_type_is(field_type: str) -> Any:
589
+ def accept(_ctrl: Any, field_begin: Any) -> bool:
590
+ return (field_begin.get("type") or "").strip().upper() == field_type
591
+
592
+ return accept
593
+
594
+
595
+ def _cell_address(element: Any) -> tuple[int, int] | None:
596
+ """``(row, column)`` of the innermost table cell holding *element*, else ``None``."""
597
+
598
+ node = element.getparent()
599
+ while node is not None:
600
+ if _local_name(node) == "tc":
601
+ address = node.find(f"{_HP}cellAddr")
602
+ if address is None:
603
+ return None
604
+ try:
605
+ return int(address.get("rowAddr", "")), int(address.get("colAddr", ""))
606
+ except ValueError:
607
+ return None
608
+ node = node.getparent()
609
+ return None
610
+
611
+
612
+ def list_formula_fields(doc: "HwpxDocument") -> tuple[FormulaField, ...]:
613
+ """Return the table formulas Hancom saved (``fieldBegin type="FORMULA"``), in
614
+ document order, with the values Hancom wrote. Nothing is recomputed."""
615
+
616
+ formulas: list[FormulaField] = []
617
+ for match in _iter_field_matches(doc, _field_type_is("FORMULA")):
618
+ parameters = match["parameters"]
619
+ command = _field_parameter_value(parameters, "Command")
620
+ formulas.append(
621
+ FormulaField(
622
+ field_id=match["field_id"],
623
+ # Hancom also writes the formula as the head of its Command
624
+ # ("=SUM(A1:A3)??%g,;;6"); read it there when Formula is absent.
625
+ formula=_field_parameter_value(parameters, "Formula") or command.split("??", 1)[0],
626
+ result_format=_field_parameter_value(parameters, "ResultFormat"),
627
+ last_result=_field_parameter_value(parameters, "LastResult"),
628
+ command=command,
629
+ value=match["current_value"],
630
+ location=_match_location(match),
631
+ cell_address=_cell_address(match["_paragraph"].element),
632
+ parameters=_match_parameters(match),
633
+ element=match["_field_begin"],
634
+ )
635
+ )
636
+ return tuple(formulas)
637
+
638
+
639
+ def list_bookmarks(doc: "HwpxDocument") -> tuple[Bookmark, ...]:
640
+ """Return every bookmark in document order, in either form Hancom saves it
641
+ (see :class:`~hwpx.objects.Bookmark`), those in table cells and objects included."""
642
+
643
+ fields = {
644
+ match["_field_begin"]: match
645
+ for match in _iter_field_matches(doc, _field_type_is("BOOKMARK"))
646
+ }
647
+ bookmarks: list[Bookmark] = []
648
+ for section_index, paragraph_index, paragraph_index_in_section, _p, _view, runs in _iter_content_paragraphs(doc):
649
+ for run_index, run in enumerate(runs):
650
+ for child_index, child in enumerate(run):
651
+ if _local_name(child) != "ctrl":
652
+ continue
653
+ location = FieldLocation(
654
+ section_index=section_index,
655
+ paragraph_index=paragraph_index,
656
+ paragraph_index_in_section=paragraph_index_in_section,
657
+ run_index=run_index,
658
+ child_index=child_index,
659
+ )
660
+ for mark in child:
661
+ if mark.tag == f"{_HP}bookmark":
662
+ name = mark.get("name", "")
663
+ if name:
664
+ bookmarks.append(Bookmark(name, "point", "", location, mark))
665
+ elif mark in fields:
666
+ name = (mark.get("name") or "").strip()
667
+ if name:
668
+ bookmarks.append(Bookmark(name, "field", fields[mark]["current_value"], location, mark))
669
+ return tuple(bookmarks)
670
+
671
+
539
672
  def _named_cells(paragraphs: Any) -> Iterator[Any]:
540
673
  for paragraph in paragraphs:
541
674
  for table in paragraph.tables:
@@ -663,7 +796,7 @@ def add_form_field(
663
796
  """Create a click-here (누름틀) form field and return it as a :class:`FormField`.
664
797
 
665
798
  The emitted XML follows the real-Hancom CLICKHERE contract
666
- (reverse-engineered from Hancom Office 12.0.0.3288 gold documents). The
799
+ (inferred from Hancom Office 12.0.0.3288 gold documents). The
667
800
  prompt (안내문) is materialized as a screen-only red-italic run, exactly as
668
801
  Hancom authors it. The created field is immediately re-read through the
669
802
  standard ``list_form_fields`` matcher — creation fails loudly if the
hwpx/_document/layout.py CHANGED
@@ -19,7 +19,9 @@ from ..oxml._document_primitives import NEW_NUM_KINDS
19
19
  from ..oxml.namespaces import HH, HP
20
20
  from ..oxml.numbering_kinds import ensure_numbering_levels
21
21
  from ..oxml.objects import HwpxOxmlInlineObject
22
- from ..oxml.section_format import _PAGE_LANDSCAPE, _PAGE_PORTRAIT, _page_orientation_value
22
+ from ..oxml.section_format import (
23
+ _PAGE_LANDSCAPE, _PAGE_PORTRAIT, _checked, _page_orientation_value, column_shares, validate_column_gap,
24
+ )
23
25
  from ..oxml.table_sizes import cell_margins_of
24
26
  from ._units import _mm_to_hwp_units, _pt_to_hwp_units
25
27
 
@@ -512,12 +514,12 @@ def set_list_format(
512
514
  suggestion="A continued list numbers on in the format of the list before it: "
513
515
  "leave out number_format and start, or continue_list to start a new list.",
514
516
  )
515
- if level < 1:
517
+ if isinstance(level, bool) or not isinstance(level, int) or not 1 <= level <= 10:
516
518
  raise HwpxValueError(
517
- "level must be 1 or greater",
519
+ f"level must be an int from 1 to 10; got {level!r}",
518
520
  code="style-list-level-invalid",
519
- context={"requested": level},
520
- suggestion="Levels start at 1.",
521
+ context={"requested": repr(level)},
522
+ suggestion="Hancom lists have ten levels, 1 to 10; it cannot save a document using a deeper one.",
521
523
  )
522
524
  if not doc._root.headers:
523
525
  raise HwpxValueError(
@@ -525,6 +527,13 @@ def set_list_format(
525
527
  code="document-header-missing",
526
528
  suggestion="Check that this is an intact HWPX package.",
527
529
  )
530
+ if start is not None and (isinstance(start, bool) or not isinstance(start, int) or not 0 <= start <= 0xFFFF):
531
+ raise HwpxValueError( # Hancom keeps a list's start as 16 bits unsigned (0 drawn as 1)
532
+ f"start must be an int from 0 to 65535; got {start!r}",
533
+ code="style-list-start-value",
534
+ context={"requested": repr(start)},
535
+ suggestion="Pass the number the list starts at, from 0 to 65535.",
536
+ )
528
537
 
529
538
  level_specs: list[dict[str, str]] = [{} for _ in range(level)]
530
539
  if bullet_char:
@@ -532,7 +541,7 @@ def set_list_format(
532
541
  if number_format:
533
542
  level_specs[level - 1]["format"] = str(number_format).upper()
534
543
  if start is not None:
535
- level_specs[level - 1]["start"] = str(max(1, int(start)))
544
+ level_specs[level - 1]["start"] = str(start)
536
545
 
537
546
  targets = _resolve_paragraph_targets(doc,
538
547
  paragraph_index=paragraph_index,
@@ -609,6 +618,8 @@ def set_page_setup(
609
618
  """
610
619
 
611
620
  normalized_orientation = _normalize_page_orientation(orientation)
621
+ if columns is not None: # the gap checked before the page or its margins change
622
+ validate_column_gap(_mm_to_hwp_units(float(column_gap_mm or 0)))
612
623
  target_width_mm = width_mm
613
624
  target_height_mm = height_mm
614
625
  if paper_size:
@@ -633,6 +644,24 @@ def set_page_setup(
633
644
 
634
645
  width = _mm_to_hwp_units(float(target_width_mm)) if target_width_mm is not None else None
635
646
  height = _mm_to_hwp_units(float(target_height_mm)) if target_height_mm is not None else None
647
+ margin_source = dict(margins_mm or {})
648
+ margin_values = {
649
+ "left": margin_left_mm if margin_left_mm is not None else margin_source.get("left"),
650
+ "right": margin_right_mm if margin_right_mm is not None else margin_source.get("right"),
651
+ "top": margin_top_mm if margin_top_mm is not None else margin_source.get("top"),
652
+ "bottom": margin_bottom_mm if margin_bottom_mm is not None else margin_source.get("bottom"),
653
+ "header": header_margin_mm if header_margin_mm is not None else margin_source.get("header"),
654
+ "footer": footer_margin_mm if footer_margin_mm is not None else margin_source.get("footer"),
655
+ "gutter": gutter_mm if gutter_mm is not None else margin_source.get("gutter"),
656
+ }
657
+ hwp_margins = {
658
+ name: _mm_to_hwp_units(float(value))
659
+ for name, value in margin_values.items()
660
+ if value is not None
661
+ }
662
+ for name, value in (("width", width), ("height", height), *hwp_margins.items()):
663
+ if value is not None: # checked before the page or its margins change
664
+ _checked(name, value, 2**31 - 1, "page-size-value")
636
665
  if width is not None or height is not None or normalized_orientation is not None:
637
666
  # Call the local primitives directly rather than `doc.set_page_size`/
638
667
  # `doc.set_page_margins`/`doc.set_columns` below — all three names
@@ -649,21 +678,6 @@ def set_page_setup(
649
678
  section_index=section_index,
650
679
  )
651
680
 
652
- margin_source = dict(margins_mm or {})
653
- margin_values = {
654
- "left": margin_left_mm if margin_left_mm is not None else margin_source.get("left"),
655
- "right": margin_right_mm if margin_right_mm is not None else margin_source.get("right"),
656
- "top": margin_top_mm if margin_top_mm is not None else margin_source.get("top"),
657
- "bottom": margin_bottom_mm if margin_bottom_mm is not None else margin_source.get("bottom"),
658
- "header": header_margin_mm if header_margin_mm is not None else margin_source.get("header"),
659
- "footer": footer_margin_mm if footer_margin_mm is not None else margin_source.get("footer"),
660
- "gutter": gutter_mm if gutter_mm is not None else margin_source.get("gutter"),
661
- }
662
- hwp_margins = {
663
- name: _mm_to_hwp_units(float(value))
664
- for name, value in margin_values.items()
665
- if value is not None
666
- }
667
681
  if hwp_margins:
668
682
  set_page_margins(
669
683
  doc,
@@ -723,15 +737,18 @@ def set_columns(
723
737
  ) -> HwpxOxmlInlineObject:
724
738
  """Set the columns of a section, or start new columns at a paragraph.
725
739
 
726
- Without ``paragraph`` this rewrites the section's own column layout (the
727
- ``hp:colPr`` next to ``hp:secPr``) in place, so the whole section is laid
728
- out in ``col_count`` columns. With ``paragraph`` it adds a column
729
- definition control there, and the text from that paragraph on uses it.
740
+ Without ``paragraph``, or with a section's first one, this rewrites the
741
+ section's own column layout (the ``hp:colPr`` next to ``hp:secPr``) in
742
+ place, so the whole section is laid out in ``col_count`` columns. With a
743
+ later ``paragraph`` it adds a column definition there, used from it on.
730
744
 
731
745
  Args:
732
746
  col_count: Number of columns (1–255).
733
747
  col_type: ``NEWSPAPER``, ``BALANCED_NEWSPAPER``, or ``PARALLEL``.
734
748
  same_gap: Gap in HWPUNIT (7200 = 1 inch).
749
+ column_widths: With ``same_size=False``, a ``(width, gap)`` pair per
750
+ column, in HWPUNIT adding up to the text width or in plain
751
+ proportions; Hancom keeps them as shares of 32768 of the text width.
735
752
  separator_type: Optional column separator line type (e.g. ``SOLID``).
736
753
  """
737
754
  if not 1 <= col_count <= 255:
@@ -741,6 +758,10 @@ def set_columns(
741
758
  context={"requested": col_count},
742
759
  suggestion="Use columns=1 to remove columns.",
743
760
  )
761
+ if same_size:
762
+ validate_column_gap(same_gap) # before a paragraph is added
763
+ elif column_widths:
764
+ column_shares(column_widths) # checked before a paragraph is added too
744
765
  if paragraph is None:
745
766
  target_section = _resolve_section(doc, section=section, section_index=section_index)
746
767
  ctrl = target_section.properties.set_columns(
hwpx/_document/media.py CHANGED
@@ -19,6 +19,11 @@ from ..opc.relationships import (
19
19
  )
20
20
  from ..oxml import HwpxOxmlInlineObject, HwpxOxmlParagraph
21
21
  from ..oxml.namespaces import HC, HP
22
+ from ..oxml.color import normalize_color
23
+ from ..oxml.shape_position import PictureGlow, PictureReflection, PictureShadow, validate_picture_effects
24
+ from ..oxml.shape_position import (
25
+ validate_picture_align, validate_picture_border, validate_picture_crop, validate_picture_image, validate_shape_size,
26
+ )
22
27
  from ._units import _mm_to_hwp_units
23
28
 
24
29
  if TYPE_CHECKING:
@@ -106,23 +111,35 @@ def add_picture(
106
111
  width_mm: float | None = None,
107
112
  height_mm: float | None = None,
108
113
  align: str | None = None,
114
+ brightness: int = 0,
115
+ contrast: int = 0,
116
+ effect: str = "REAL_PIC",
117
+ alpha: int = 0,
118
+ line_color: str | None = None,
119
+ line_width: int = 33,
120
+ crop: tuple[int, int, int, int] | None = None,
121
+ shadow: PictureShadow | None = None,
122
+ glow: PictureGlow | None = None,
123
+ soft_edge: int | None = None,
124
+ reflection: PictureReflection | None = None,
109
125
  para_pr_id_ref: str | int | None = None,
110
126
  style_id_ref: str | int | None = None,
111
127
  char_pr_id_ref: str | int | None = None,
112
128
  run_attributes: dict[str, str] | None = None,
113
129
  **extra_attrs: str,
114
130
  ) -> HwpxOxmlInlineObject:
115
- """Embed image data and place a picture object in a new paragraph."""
116
-
117
- # Call the local primitive directly rather than `doc.add_image` — that
118
- # facade name moved in 6.0 (design table row 33), and going through it
119
- # would fire a DeprecationWarning on every `add_picture` call even though
120
- # `add_picture` itself is a kept (unmoved) root method.
121
- binary_item_id_ref = str(add_image(doc, image_data, image_format))
122
-
131
+ """Embed image data and place a picture object in a new paragraph, the image adjusted and bordered as
132
+ :meth:`HwpxOxmlParagraph.add_picture` takes it."""
133
+
134
+ validate_picture_align(align) # before anything is stored: Hancom reads an unknown one as LEFT
135
+ validate_picture_image(brightness, contrast, effect, alpha) # ... and draws no other adjustment
136
+ validate_picture_border(line_width)
137
+ if line_color is not None:
138
+ normalize_color(line_color)
123
139
  resolved_width = width
124
140
  if resolved_width is None:
125
141
  resolved_width = _mm_to_hwp_units(width_mm) if width_mm is not None else 14400
142
+ validate_shape_size(resolved_width, 0) # validate before aspect-ratio arithmetic too
126
143
 
127
144
  resolved_height = height
128
145
  if resolved_height is None:
@@ -135,6 +152,15 @@ def add_picture(
135
152
  resolved_height = round(resolved_width * source_height / source_width)
136
153
  else:
137
154
  resolved_height = resolved_width
155
+ validate_shape_size(resolved_width, resolved_height) # before anything is stored too
156
+ validate_picture_crop(crop, resolved_width, resolved_height)
157
+ validate_picture_effects(shadow, glow, soft_edge, reflection)
158
+
159
+ # Call the local primitive directly rather than `doc.add_image` — that
160
+ # facade name moved in 6.0 (design table row 33), and going through it
161
+ # would fire a DeprecationWarning on every `add_picture` call even though
162
+ # `add_picture` itself is a kept (unmoved) root method.
163
+ binary_item_id_ref = str(add_image(doc, image_data, image_format))
138
164
 
139
165
  paragraph = doc.add_paragraph(
140
166
  "",
@@ -158,6 +184,17 @@ def add_picture(
158
184
  width=resolved_width,
159
185
  height=resolved_height,
160
186
  align=align,
187
+ brightness=brightness,
188
+ contrast=contrast,
189
+ effect=effect,
190
+ alpha=alpha,
191
+ line_color=line_color,
192
+ line_width=line_width,
193
+ crop=crop,
194
+ shadow=shadow,
195
+ glow=glow,
196
+ soft_edge=soft_edge,
197
+ reflection=reflection,
161
198
  run_attributes=run_attributes,
162
199
  char_pr_id_ref=char_pr_id_ref,
163
200
  )
hwpx/_document/memos.py CHANGED
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Any
8
8
 
9
9
  from ..errors import HwpxValueError
10
10
 
11
- from ..oxml._document_primitives import _object_id
11
+ from ..oxml._document_primitives import _clear_paragraph_layout_cache, _object_id
12
12
  from ..oxml.namespaces import HP
13
13
 
14
14
  if TYPE_CHECKING:
@@ -189,6 +189,7 @@ def attach_memo_field(
189
189
  "dirty": "0",
190
190
  "zorder": order,
191
191
  "fieldid": MEMO_FIELD_ID,
192
+ "metaTag": "",
192
193
  },
193
194
  )
194
195
 
@@ -247,6 +248,7 @@ def attach_memo_field(
247
248
 
248
249
  paragraph.element.insert(0, run_begin)
249
250
  paragraph.element.append(run_end)
251
+ _clear_paragraph_layout_cache(paragraph.element) # the field's controls move its text: laid out again
250
252
  paragraph.section.mark_dirty()
251
253
 
252
254
  return memo
@@ -28,7 +28,7 @@ from ._base import _Namespace
28
28
 
29
29
  if TYPE_CHECKING:
30
30
  from ...form_fit.policy import FitPolicy
31
- from ...objects import CellField, CheckBox, FieldFillResult, FormField, TextBoxField
31
+ from ...objects import CellField, CheckBox, FieldFillResult, FormField, FormulaField, TextBoxField
32
32
  from ...oxml import HwpxOxmlParagraph, HwpxOxmlSection
33
33
 
34
34
  __all__ = ["FieldsNamespace"]
@@ -142,6 +142,22 @@ class FieldsNamespace(_Namespace):
142
142
 
143
143
  return _fields.fill_cell_fields(self._doc, value, name=name, index=index)
144
144
 
145
+ # -- 계산식 필드 -------------------------------------------------------
146
+
147
+ @property
148
+ def formulas(self) -> "tuple[FormulaField, ...]":
149
+ """한/글이 저장한 표 계산식(``fieldBegin type="FORMULA"``)을 문서 순서로. 본문 표와 그 칸
150
+ 안의 표를 본다.
151
+
152
+ 값은 한/글이 적은 그대로다. 다시 계산하지 않는다: ``formula``는 한/글 표기(``=SUM(?1:?3)``의
153
+ ``?`` 같은)를 그대로 두고, ``last_result``는 한/글이 마지막으로 계산한 값, ``value``는
154
+ 문서에 보이는 글이다. ``cell_address``는 계산식이 든 칸의 ``(행, 열)``이다.
155
+ """
156
+
157
+ from .. import fields as _fields
158
+
159
+ return _fields.list_formula_fields(self._doc)
160
+
145
161
  # -- 글상자 필드 -------------------------------------------------------
146
162
 
147
163
  @property
hwpx/_document/ns/refs.py CHANGED
@@ -15,6 +15,7 @@ from ._base import _Namespace
15
15
 
16
16
  if TYPE_CHECKING:
17
17
  from ...model import InlineObject, Paragraph, Section
18
+ from ...objects import Bookmark
18
19
 
19
20
  __all__ = ["RefsNamespace"]
20
21
 
@@ -25,6 +26,19 @@ class RefsNamespace(_Namespace):
25
26
  __slots__ = ()
26
27
  _path = "doc.refs"
27
28
 
29
+ @property
30
+ def bookmarks(self) -> "tuple[Bookmark, ...]":
31
+ """문서의 모든 책갈피를 문서 순서로. 표 칸과 개체 안의 것도 본다.
32
+
33
+ 한/글이 책갈피를 저장하는 두 형태를 함께 낸다: ``hp:bookmark``(``kind="point"``)와
34
+ ``fieldBegin type="BOOKMARK"``…``fieldEnd`` 짝(``kind="field"``). 필드 형태의 ``text``는
35
+ 시작과 끝 사이의 글이다(한/글은 흔히 사이를 비워 둔다).
36
+ """
37
+
38
+ from .. import fields as _fields
39
+
40
+ return _fields.list_bookmarks(self._doc)
41
+
28
42
  def add_bookmark(
29
43
  self,
30
44
  name: str,