;;; AutoCATS 리습 자료실
;; 명령: TOBLIQUE
;; 기능: TEXT 문자의 기울기를 -85도에서 85도 사이의 값으로 맞춥니다.
;; 출처: https://www.autocats.co.kr/lisp/text-oblique
;; 버전: 1.0 (2026-10-23)
;; 라이선스: 자유 사용·수정, 재배포 시 출처(autocats.co.kr) 표기
;; 안전: 잠긴 레이어·외부참조 보호, 변경은 UNDO 그룹, 명령별 범위는 상세 가이드 참고

(vl-load-com)

(defun autocats-toblique-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-toblique-replace-pair (code value data)
  (if (assoc code data) (subst (cons code value) (assoc code data) data)
    (append data (list (cons code value)))))

(defun autocats-toblique-put (ent property value / data)
  (if (autocats-toblique-safe-p ent)
    (progn
      (setq data (autocats-toblique-replace-pair 51 value (entget ent)))
      (if (entmod data) (progn (entupd ent) T)))))

(defun autocats-toblique-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-toblique-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[TOBLIQUE] 완료: " (itoa changed) " / 건너뜀: " (itoa skipped)))
  (list changed skipped))

(defun autocats-toblique-apply (ent value)
  (and (and (numberp value) (<= (abs value) (* pi (/ 85.0 180.0)))) (member (cdr (assoc 0 (entget ent))) '("TEXT"))
    (autocats-toblique-put ent 'ObliqueAngle value)))

(defun c:TOBLIQUE (/ *error* undo-open value degrees 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[TOBLIQUE] 중단: " msg)))
    (princ))
  (setq degrees (getreal "\n기울기 각도 -85~85 (정체=0): ")) (if (and degrees (<= (abs degrees) 85.0)) (setq value (* pi (/ degrees 180.0))))
  (if value (progn
      (princ "\n대상 객체를 선택하세요: ")
      (setq selection (ssget '((0 . "TEXT"))))
      (if selection
        (progn
          (command "_.UNDO" "_Begin")

          (setq undo-open T)
          (autocats-toblique-batch selection '(lambda (ent) (autocats-toblique-apply ent value)))
          (command "_.UNDO" "_End")
          (setq undo-open nil)))))
  (princ))

(princ "\n[AutoCATS] TOBLIQUE 로드 완료")
(princ)
