;;; AutoCATS 리습 자료실
;; 명령: DHEIGHT
;; 기능: 선택한 치수에 문자 높이 재지정을 적용합니다.
;; 출처: https://www.autocats.co.kr/lisp/dimension-height
;; 버전: 1.0 (2026-10-23)
;; 라이선스: 자유 사용·수정, 재배포 시 출처(autocats.co.kr) 표기
;; 안전: 잠긴 레이어·외부참조 보호, 변경은 UNDO 그룹, 명령별 범위는 상세 가이드 참고

(vl-load-com)

(defun autocats-dheight-safe-p (ent / data row block)
  (setq data (entget ent)
    row (tblsearch "LAYER" (cdr (assoc 8 data))))
  (and data row (= 0 (logand 4 (cdr (assoc 70 row))))
    (or (/= "INSERT" (cdr (assoc 0 data)))
      (and (setq block (tblsearch "BLOCK" (cdr (assoc 2 data))))
        (= 0 (logand 12 (cdr (assoc 70 block))))))))

(defun autocats-dheight-put (ent property value / old result)
  (if (autocats-dheight-safe-p ent)
    (progn
      (setq old (getvar "DIMTXT")
        result (vl-catch-all-apply
          '(lambda () (command "_.DIMOVERRIDE" "DIMTXT" value "" ent "") T)))
      (setvar "DIMTXT" old)
      (not (vl-catch-all-error-p result)))))

(defun autocats-dheight-batch (selection action / index changed skipped ent result)
  (setq index 0 changed 0 skipped 0)
  (if selection
    (repeat (sslength selection)
      (setq ent (ssname selection index)
        result (if (autocats-dheight-safe-p ent) (vl-catch-all-apply action (list ent))))
      (if (and result (not (vl-catch-all-error-p result)))
        (setq changed (1+ changed))
        (setq skipped (1+ skipped)))
      (setq index (1+ index))))
  (princ (strcat "\n[DHEIGHT] 완료: " (itoa changed) " / 건너뜀: " (itoa skipped)))
  (list changed skipped))

(defun autocats-dheight-apply (ent value)
  (and (and (numberp value) (> value 0.0)) (member (cdr (assoc 0 (entget ent))) '("DIMENSION"))
    (autocats-dheight-put ent 'TextHeight value)))

(defun c:DHEIGHT (/ *error* undo-open value selection)
  (defun *error* (msg)
    (if undo-open (progn (command-s "_.UNDO" "_End") (setq undo-open nil)))
    (if (and msg (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*EXIT*,*취소*")))
      (princ (strcat "\n[DHEIGHT] 중단: " msg)))
    (princ))
  (initget 7) (setq value (getdist "\n치수 문자 높이: "))
  (if value (progn
      (princ "\n대상 객체를 선택하세요: ")
      (setq selection (ssget '((0 . "DIMENSION"))))
      (if selection
        (progn
          (command "_.UNDO" "_Begin")

          (setq undo-open T)
          (autocats-dheight-batch selection '(lambda (ent) (autocats-dheight-apply ent value)))
          (command "_.UNDO" "_End")
          (setq undo-open nil)))))
  (princ))

(princ "\n[AutoCATS] DHEIGHT 로드 완료")
(princ)
