;;; ==========================================================================
;;;  PodgladUW.lsp  -  UTNIJ / WYDLUZ z podgladem na zywo   (ZWCAD 2026)
;;;
;;;  Polecenia:
;;;    PTRIM   (alias UP)  - utnij z podgladem
;;;    PEXTEND (alias WP)  - wydluz z podgladem
;;;
;;;  Dzialanie:
;;;    1. Wybierz krawedzie tnace / graniczne  (Enter = wszystkie obiekty).
;;;    2. Przesuwaj kursor nad obiektami:
;;;         - czerwona linia  = fragment, ktory zostanie uciety,
;;;         - zielona linia   = przedluzenie do krawedzi granicznej.
;;;    3. Kliknij, aby wykonac operacje. Mozna klikac wielokrotnie.
;;;       Klawisze w trakcie:  U / T = tryb utnij,  W / E = tryb wydluz,
;;;                            Enter / Spacja / prawy przycisk = koniec.
;;;    Cala sesja polecenia to jeden krok COFNIJ.
;;;
;;;  Obslugiwane obiekty:
;;;    Utnij  : LINE, ARC, CIRCLE, LWPOLYLINE (geometria liczona w skrypcie),
;;;             ELLIPSE, SPLINE, POLYLINE (podglad + natywne _TRIM).
;;;    Wydluz : LINE, ARC, otwarta LWPOLYLINE (podglad + wykonanie w skrypcie),
;;;             pozostale otwarte krzywe - natywne _EXTEND bez podgladu.
;;;    Uwzglednia zmienna EDGEMODE (0 = krawedzie bez przedluzania,
;;;    1 = krawedzie przedluzone).
;;;
;;;  Uwaga: przy ucinaniu LWPOLYLINE zmienne szerokosci segmentow sa
;;;  zastepowane szerokoscia stala (grupa 43).
;;; ==========================================================================

(vl-load-com)

(setq *pte-types*    "LINE,ARC,CIRCLE,ELLIPSE,LWPOLYLINE,POLYLINE,SPLINE")
(setq *pte-btypes*   "LINE,ARC,CIRCLE,ELLIPSE,LWPOLYLINE,POLYLINE,SPLINE,XLINE,RAY")
(setq *pte-col-trim* 1)   ; kolor podgladu ucinania  (-1 = podswietlenie przerywane)
(setq *pte-col-ext*  3)   ; kolor podgladu wydluzania

;;; ------------------------------------------------------------ matematyka --
(defun pte:norm (a)
  (while (< a 0.0) (setq a (+ a pi pi)))
  (while (>= a (+ pi pi)) (setq a (- a pi pi)))
  a
)
(defun pte:tan (x) (/ (sin x) (cos x)))
(defun pte:dot (a b) (apply '+ (mapcar '* a b)))
(defun pte:unit (v / n)
  (setq n (sqrt (pte:dot v v)))
  (if (> n 1e-12) (mapcar '(lambda (x) (/ x n)) v))
)
(defun pte:sign (x) (if (minusp x) -1.0 1.0))
;; srodek luku segmentu polilinii (p1 -> p2, bulge b)
(defun pte:bcen (p1 p2 b)
  (polar p1
         (+ (angle p1 p2) (- (/ pi 2.0) (* 2.0 (atan b))))
         (/ (* (distance p1 p2) (+ 1.0 (* b b))) 4.0 b)
  )
)
(defun pte:put (ed code val / old)
  (if (setq old (assoc code ed))
    (subst (cons code val) old ed)
    (append ed (list (cons code val)))
  )
)
(defun pte:uniq (lst / r)
  (foreach x lst
    (if (not (and r (equal x (car r) 1e-6))) (setq r (cons x r)))
  )
  (reverse r)
)

;;; ---------------------------------------------------------------- krzywe --
(defun pte:len (o) (vlax-curve-getDistAtParam o (vlax-curve-getEndParam o)))

(defun pte:dat (o p / cp)
  (if (setq cp (vlax-curve-getClosestPointTo o p))
    (vlax-curve-getDistAtPoint o cp)
  )
)

;; punkt na krzywej w odleglosci x (cl = krzywa zamknieta -> zawijanie)
(defun pte:pad (o x l cl)
  (setq x (cond ((and cl (> x l)) (- x l)) ((> x l) l) ((< x 0.0) 0.0) (x)))
  (cond ((vlax-curve-getPointAtDist o x))
        ((> x (/ l 2.0)) (vlax-curve-getEndPoint o))
        ((vlax-curve-getStartPoint o))
  )
)

;; parametr krzywej w odleglosci x
(defun pte:par (o x l)
  (cond ((vlax-curve-getParamAtDist o (max 0.0 (min x l))))
        ((> x (/ l 2.0)) (vlax-curve-getEndParam o))
        (0.0)
  )
)

(defun pte:locked (e / lay)
  (and (setq lay (tblsearch "LAYER" (cdr (assoc 8 (entget e)))))
       (= 4 (logand 4 (cdr (assoc 70 lay))))
  )
)

;; tryby IntersectWith: 0 brak, 1 ten obiekt, 2 drugi obiekt, 3 oba
(defun pte:mtrim () (if (= 1 (getvar "EDGEMODE")) 2 0))
(defun pte:mext  () (if (= 1 (getvar "EDGEMODE")) 3 1))

;; punkty przeciecia dwoch obiektow VLA (WCS)
(defun pte:inters (o1 o2 m / v r lst)
  (setq v (vl-catch-all-apply 'vla-IntersectWith (list o1 o2 m)))
  (if (and (not (vl-catch-all-error-p v))
           (= (type v) 'VARIANT)
           (not (vl-catch-all-error-p
                  (setq r (vl-catch-all-apply 'vlax-safearray->list
                                              (list (vlax-variant-value v))))
                ))
      )
    (while (>= (length r) 3)
      (setq lst (cons (list (car r) (cadr r) (caddr r)) lst)
            r   (cdddr r)
      )
    )
  )
  lst
)

;;; ------------------------------------------------------------- krawedzie --
(defun pte:bnd-get (ss / i e lst)
  (if ss
    (repeat (setq i (sslength ss))
      (setq e   (ssname ss (setq i (1- i)))
            lst (cons (cons e (vlax-ename->vla-object e)) lst)
      )
    )
  )
  lst
)

(defun pte:bnd-all ()
  (pte:bnd-get
    (ssget "_X"
           (list (cons 0 *pte-btypes*)
                 (cons 410 (if (and (= 0 (getvar "TILEMODE")) (= 1 (getvar "CVPORT")))
                             (getvar "CTAB")
                             "Model"
                           )
                 )
           )
    )
  )
)

(defun pte:hl (m)
  (foreach b *pte-bnd* (if (entget (car b)) (redraw (car b) m)))
)

;;; ------------------------------------------------------- polilinie LW ---
(defun pte:pl-verts (ed / r)
  (foreach g ed
    (cond ((= (car g) 10)
           (setq r (cons (list (list (cadr g) (caddr g)) 0.0) r)))
          ((and (= (car g) 42) r)
           (setq r (cons (list (car (car r)) (cdr g)) (cdr r))))
    )
  )
  (reverse r)
)

;; zmiana punktu i/lub bulge wierzcholka nr i
(defun pte:vset (vs i p b / j)
  (setq j -1)
  (mapcar '(lambda (v)
             (if (= (setq j (1+ j)) i)
               (list (if p p (car v)) (if b b (cadr v)))
               v
             )
           )
          vs
  )
)

;; przebudowa LWPOLYLINE z nowa lista wierzcholkow
(defun pte:pl-rebuild (e vs cl / ed hdr tl w f)
  (setq ed (entget e)
        w  (cond ((cdr (assoc 43 ed))) (0.0))
  )
  (while (and ed (/= (caar ed) 10))
    (setq hdr (cons (car ed) hdr) ed (cdr ed))
  )
  (setq hdr (reverse hdr)
        tl  (vl-remove-if '(lambda (g) (member (car g) '(10 40 41 42 91))) ed)
        f   (cdr (assoc 70 hdr))
        hdr (subst (cons 70 (if cl (logior f 1) (logand f -2))) (assoc 70 hdr) hdr)
        hdr (subst (cons 90 (length vs)) (assoc 90 hdr) hdr)
  )
  (entmod
    (append hdr
            (apply 'append
                   (mapcar '(lambda (v)
                              (list (cons 10 (car v)) (cons 40 w) (cons 41 w) (cons 42 (cadr v)))
                            )
                           vs
                   )
            )
            tl
    )
  )
)

;; punkt OCS 2D polilinii dla parametru p (z zawijaniem)
(defun pte:ppar (o p nrm / ep w)
  (setq ep (vlax-curve-getEndParam o))
  (if (> p ep) (setq p (- p ep)))
  (setq w (trans (vlax-curve-getPointAtParam o (min p ep)) 0 nrm))
  (list (car w) (cadr w))
)

;; fragment polilinii od parametru ps do pf (pf moze byc > EndParam dla zamknietej)
(defun pte:pl-sub (o vs nrm ps pf / nn nseg out tp k t1 p0 p1 bg b0 sg c s th)
  (setq nn   (length vs)
        nseg (fix (+ (vlax-curve-getEndParam o) 1e-9))
        tp   ps
  )
  (while (< tp (- pf 1e-9))
    (setq k  (fix (+ tp 1e-9))
          t1 (min (+ k 1.0) pf)
    )
    (if (> (- t1 tp) 1e-9)
      (progn
        (setq sg (rem k nseg)
              p0 (pte:ppar o tp nrm)
              p1 (pte:ppar o t1 nrm)
              b0 (cadr (nth sg vs))
        )
        (if (< (abs b0) 1e-12)
          (setq bg 0.0)
          (progn
            (setq c  (pte:bcen (car (nth sg vs)) (car (nth (rem (1+ sg) nn) vs)) b0)
                  s  (pte:sign b0)
                  th (pte:norm (* s (- (angle c p1) (angle c p0))))
            )
            (if (> th (+ (abs (* 4.0 (atan b0))) 1e-6)) (setq th 0.0))
            (setq bg (* s (pte:tan (/ th 4.0))))
          )
        )
        (setq out (cons (list p0 bg) out))
      )
    )
    (setq tp t1)
  )
  (reverse (cons (list (pte:ppar o pf nrm) 0.0) out))
)

;;; --------------------------------------------------------------- UTNIJ ---
;; posortowane odleglosci punktow ciecia na obiekcie
(defun pte:trim-ds (e o / m lst dd)
  (setq m (pte:mtrim))
  (foreach b *pte-bnd*
    (if (not (equal (car b) e))
      (foreach p (pte:inters o (cdr b) m)
        (if (setq dd (pte:dat o p)) (setq lst (cons dd lst)))
      )
    )
  )
  (pte:uniq (vl-sort lst '<))
)

;; przedzial [a b] do uciecia wokol odleglosci dc
(defun pte:iv (ds dc l cl / a b)
  (if cl
    (if (>= (length ds) 2)
      (progn
        (foreach x ds (if (<= x dc) (setq a x)))
        (foreach x (reverse ds) (if (>= x dc) (setq b x)))
        (if (not (and a b)) (setq a (last ds) b (+ (car ds) l)))
      )
    )
    (progn
      (setq a 0.0 b l)
      (foreach x ds
        (if (and (<= x dc) (> x a)) (setq a x))
        (if (and (>= x dc) (< x b)) (setq b x))
      )
      (if (and (equal a 0.0 1e-6) (equal b l 1e-6)) (setq a nil))
    )
  )
  (if (and a b (> (- b a) 1e-6)) (list a b))
)

;; punkty podgladu odcinka krzywej [a b]
(defun pte:trim-pts (e o a b l cl / typ n i xs v ep)
  (setq typ (cdr (assoc 0 (entget e)))
        n   (if (= typ "LINE") 1 64)
        i   -1
  )
  (repeat (1+ n)
    (setq xs (cons (+ a (* (- b a) (/ (setq i (1+ i)) (float n)))) xs))
  )
  (if (wcmatch typ "*POLYLINE")
    (progn
      (setq i -1 ep (fix (+ 1e-9 (vlax-curve-getEndParam o))))
      (repeat (1+ ep)
        (if (setq v (vlax-curve-getDistAtParam o (setq i (1+ i))))
          (foreach x (list v (+ v l)) (if (< a x b) (setq xs (cons x xs))))
        )
      )
    )
  )
  (mapcar '(lambda (x) (pte:pad o x l cl)) (vl-sort xs '<))
)

(defun pte:entmod-chg (e chg / ed)
  (setq ed (entget e))
  (foreach g chg (setq ed (pte:put ed (car g) (cdr g))))
  (entmod ed)
)

;; pierwszy kawalek modyfikuje oryginal, kolejne - kopie oryginalu
(defun pte:pieces (e chgs pl / first new res)
  (setq first T)
  (foreach ch chgs
    (setq new (if first e (vlax-vla-object->ename (vla-copy (vlax-ename->vla-object e)))))
    (if pl (pte:pl-rebuild new ch nil) (pte:entmod-chg new ch))
    (if (not first) (setq res (cons new res)))
    (setq first nil)
  )
  res
)

;; natywne polecenie TRIM / EXTEND (dla typow bez wlasnej geometrii)
(defun pte:native (cmd e cp / ss tem)
  (setq ss (ssadd))
  (foreach b *pte-bnd* (if (entget (car b)) (ssadd (car b) ss)))
  (setq tem (getvar "TRIMEXTENDMODE"))
  (if tem (vl-catch-all-apply 'setvar (list "TRIMEXTENDMODE" 0)))
  (command cmd ss "" (list e (trans cp 0 1)) "")
  (if tem (vl-catch-all-apply 'setvar (list "TRIMEXTENDMODE" tem)))
  nil
)

;; wykonanie uciecia; zwraca liste nowych obiektow
(defun pte:trim-apply (e o iv cp / ed typ l cl a b keep cc nv vs ep new k a1 a2)
  (setq ed   (entget e)
        typ  (cdr (assoc 0 ed))
        l    (pte:len o)
        cl   (vlax-curve-isClosed o)
        a    (car iv)
        b    (cadr iv)
        keep (if cl
               (if (> b l) (list (list (- b l) a)) (list (list b (+ a l))))
               (vl-remove nil
                 (list (if (> a 1e-6) (list 0.0 a))
                       (if (< b (- l 1e-6)) (list b l))
                 )
               )
             )
  )
  (cond
    ((= typ "LINE")
     (pte:pieces e
       (mapcar '(lambda (k)
                  (list (cons 10 (pte:pad o (car k) l nil))
                        (cons 11 (pte:pad o (cadr k) l nil))))
               keep)
       nil)
    )
    ((= typ "ARC")
     (setq cc (cdr (assoc 10 ed)) nv (cdr (assoc 210 ed)))
     (pte:pieces e
       (mapcar '(lambda (k)
                  (list (cons 50 (angle cc (trans (pte:pad o (car k) l nil) 0 nv)))
                        (cons 51 (angle cc (trans (pte:pad o (cadr k) l nil) 0 nv)))))
               keep)
       nil)
    )
    ((= typ "CIRCLE")
     (setq k  (car keep)
           cc (cdr (assoc 10 ed))
           nv (cdr (assoc 210 ed))
           a1 (angle cc (trans (pte:pad o (car k) l T) 0 nv))
           a2 (angle cc (trans (pte:pad o (cadr k) l T) 0 nv))
     )
     (if (setq new
           (entmakex
             (append (list '(0 . "ARC"))
                     (vl-remove-if-not
                       '(lambda (g) (member (car g) '(8 6 62 48 370 420 430 39 60)))
                       ed)
                     (list (assoc 10 ed) (assoc 40 ed) (cons 50 a1) (cons 51 a2) (assoc 210 ed))
             )
           )
         )
       (progn (entdel e) (list new))
     )
    )
    ((= typ "LWPOLYLINE")
     (setq nv (cdr (assoc 210 ed))
           vs (pte:pl-verts ed)
           ep (vlax-curve-getEndParam o)
     )
     (pte:pieces e
       (mapcar '(lambda (k / ps pf)
                  (setq ps (pte:par o (car k) l)
                        pf (if (> (cadr k) l)
                             (+ ep (pte:par o (- (cadr k) l) l))
                             (pte:par o (cadr k) l)))
                  (pte:pl-sub o vs nv ps pf))
               keep)
       T)
    )
    (T (pte:native "_.TRIM" e cp))
  )
)

;;; -------------------------------------------------------------- WYDLUZ ---
;; prosty koniec: P - koniec, Q - drugi punkt (WCS); zwraca nowy punkt konca
(defun pte:ext-line (p q io ex / dir best tt)
  (if (setq dir (pte:unit (mapcar '- p q)))
    (foreach b *pte-bnd*
      (if (not (equal (car b) ex))
        (foreach x (pte:inters io (cdr b) (pte:mext))
          (setq tt (pte:dot (mapcar '- x p) dir))
          (if (and (> tt 1e-6) (or (not best) (< tt best))) (setq best tt))
        )
      )
    )
  )
  (if best (mapcar '(lambda (u v) (+ u (* v best))) p dir))
)

;; koniec lukowy: c srodek (OCS), ae kat konca, s kierunek (+1 CCW / -1 CW)
;; zwraca kat przedluzenia
(defun pte:ext-arc (c r ae s span nrm io ex / best a dl)
  (foreach b *pte-bnd*
    (if (not (equal (car b) ex))
      (foreach x (pte:inters io (cdr b) (pte:mext))
        (setq a  (angle c (trans x 0 nrm))
              dl (pte:norm (* s (- a ae)))
        )
        (if (and (> dl 1e-9)
                 (< dl (- (+ pi pi) span 1e-9))
                 (or (not best) (< dl best)))
          (setq best dl)
        )
      )
    )
  )
  best
)

(defun pte:arc-pts (c r a0 s dl nrm / n i lst)
  (setq n (max 4 (fix (/ dl 0.04))) i -1)
  (repeat (1+ n)
    (setq lst (cons (trans (polar c (+ a0 (* s dl (/ (setq i (1+ i)) (float n)))) r) nrm 0) lst))
  )
  (reverse lst)
)

;; side: 0 = poczatek, 1 = koniec
;; wynik: (zmiany punkty-podgladu nowy-koniec) lub nil
(defun pte:ext-calc (e o side / ed typ p q np c r a1 a2 nv ae s dl span pts
                                vs k el lay bg pw qw tmp npo c3 nb np2)
  (setq ed (entget e) typ (cdr (assoc 0 ed)))
  (cond
    ((= typ "LINE")
     (setq p (cdr (assoc (if (= side 1) 11 10) ed))
           q (cdr (assoc (if (= side 1) 10 11) ed))
     )
     (if (setq np (pte:ext-line p q o e))
       (list (list (cons (if (= side 1) 11 10) np)) (list p np) np)
     )
    )
    ((= typ "ARC")
     (setq c    (cdr (assoc 10 ed))
           r    (cdr (assoc 40 ed))
           a1   (cdr (assoc 50 ed))
           a2   (cdr (assoc 51 ed))
           nv   (cdr (assoc 210 ed))
           span (pte:norm (- a2 a1))
           ae   (if (= side 1) a2 a1)
           s    (if (= side 1) 1.0 -1.0)
     )
     (if (setq dl (pte:ext-arc c r ae s span nv o e))
       (progn
         (setq pts (pte:arc-pts c r ae s dl nv))
         (list (list (cons (if (= side 1) 51 50) (pte:norm (+ ae (* s dl))))) pts (last pts))
       )
     )
    )
    ((and (= typ "LWPOLYLINE") (= 0 (logand 1 (cdr (assoc 70 ed)))))
     (setq vs  (pte:pl-verts ed)
           k   (1- (length vs))
           nv  (cdr (assoc 210 ed))
           el  (cond ((cdr (assoc 38 ed))) (0.0))
           lay (cdr (assoc 8 ed))
     )
     (if (= side 1)
       (setq p (car (nth k vs)) q (car (nth (1- k) vs)) bg (cadr (nth (1- k) vs)))
       (setq p (car (nth 0 vs)) q (car (nth 1 vs)) bg (- (cadr (nth 0 vs))))
     )
     (if (< (abs bg) 1e-12)
       ;; ostatni segment prosty
       (progn
         (setq pw  (trans (list (car p) (cadr p) el) nv 0)
               qw  (trans (list (car q) (cadr q) el) nv 0)
               tmp (entmakex (list '(0 . "LINE") (cons 8 lay) (cons 10 qw) (cons 11 pw)))
         )
         (if tmp
           (progn
             (setq np (pte:ext-line pw qw (vlax-ename->vla-object tmp) e))
             (entdel tmp)
             (if np
               (progn
                 (setq npo (trans np 0 nv))
                 (list (pte:vset vs (if (= side 1) k 0) (list (car npo) (cadr npo)) nil)
                       (list pw np)
                       np)
               )
             )
           )
         )
       )
       ;; ostatni segment lukowy
       (progn
         (setq c    (pte:bcen q p bg)
               r    (distance c p)
               ae   (angle c p)
               s    (pte:sign bg)
               span (abs (* 4.0 (atan bg)))
               c3   (list (car c) (cadr c) el)
               tmp  (entmakex (list '(0 . "ARC") (cons 8 lay) (cons 10 c3) (cons 40 r)
                                    '(50 . 0.0) (cons 51 pi) (cons 210 nv)))
         )
         (if tmp
           (progn
             (setq dl (pte:ext-arc c3 r ae s span nv (vlax-ename->vla-object tmp) e))
             (entdel tmp)
             (if dl
               (progn
                 (setq nb  (* s (pte:tan (/ (+ span dl) 4.0)))
                       np2 (polar c (+ ae (* s dl)) r)
                       pts (pte:arc-pts c3 r ae s dl nv)
                 )
                 (list (if (= side 1)
                         (pte:vset (pte:vset vs k np2 nil) (1- k) nil nb)
                         (pte:vset vs 0 np2 (- nb))
                       )
                       pts
                       (last pts))
               )
             )
           )
         )
       )
     )
    )
  )
)

(defun pte:ext-apply (e r)
  (if (= (cdr (assoc 0 (entget e))) "LWPOLYLINE")
    (pte:pl-rebuild e (car r) nil)
    (pte:entmod-chg e (car r))
  )
)

;;; ----------------------------------------------------- podglad / petla ---
;; rekord: (ename id dane punkty znaczniki punkt-na-krzywej)
(defun pte:hover (upt / ss e o typ wp cp dc l cl r ds iv pts side key)
  (if (and (setq ss (ssget upt (list (cons 0 *pte-types*))))
           (setq e (ssname ss 0))
           (not (pte:locked e))
      )
    (progn
      (setq o   (vlax-ename->vla-object e)
            typ (cdr (assoc 0 (entget e)))
            wp  (trans upt 1 0)
            cp  (vlax-curve-getClosestPointTo o wp)
            dc  (vlax-curve-getDistAtPoint o cp)
            l   (pte:len o)
            cl  (vlax-curve-isClosed o)
      )
      (if (= *pte-mode* "U")
        (progn
          (if (setq r (assoc e *pte-cache*))
            (setq ds (cdr r))
            (setq ds          (pte:trim-ds e o)
                  *pte-cache* (cons (cons e ds) *pte-cache*))
          )
          (if (setq iv (pte:iv ds dc l cl))
            (progn
              (setq pts (pte:trim-pts e o (car iv) (cadr iv) l cl))
              (list e iv iv pts (list (car pts) (last pts)) cp)
            )
          )
        )
        (if (not cl)
          (progn
            (setq side (if (> dc (/ l 2.0)) 1 0)
                  key  (list e side)
            )
            (if (setq r (assoc key *pte-cache*))
              (setq r (cadr r))
              (setq r (if (member typ '("LINE" "ARC" "LWPOLYLINE"))
                        (pte:ext-calc e o side)
                        'NATIVE)
                    *pte-cache* (cons (list key r) *pte-cache*))
            )
            (cond ((= r 'NATIVE) (list e side 'NATIVE nil nil cp))
                  (r (list e side r (cadr r) (list (caddr r)) cp))
            )
          )
        )
      )
    )
  )
)

(defun pte:safe-hover (pt / r)
  (setq r (vl-catch-all-apply 'pte:hover (list pt)))
  (if (vl-catch-all-error-p r) nil r)
)

(defun pte:same (a b)
  (or (and (null a) (null b))
      (and a b (equal (car a) (car b)) (equal (cadr a) (cadr b) 1e-6))
  )
)

(defun pte:draw (rec / pts col v s m)
  (setq pts (nth 3 rec)
        col (if (= *pte-mode* "U") *pte-col-trim* *pte-col-ext*)
        s   (/ (getvar "VIEWSIZE") 80.0)
  )
  (while (cadr pts)
    (setq v   (cons (trans (cadr pts) 0 1) (cons (trans (car pts) 0 1) (cons col v)))
          pts (cdr pts)
    )
  )
  ;; znaczniki X w punktach ciecia / nowym koncu
  (foreach p (nth 4 rec)
    (setq m (trans p 0 1)
          v (append (reverse
                      (list (abs col) (list (- (car m) s) (- (cadr m) s)) (list (+ (car m) s) (+ (cadr m) s))
                            (abs col) (list (- (car m) s) (+ (cadr m) s)) (list (+ (car m) s) (- (cadr m) s))))
                    v)
    )
  )
  (if v (grvecs (reverse v)))
)

(defun pte:apply (rec / e new)
  (setq e (car rec))
  (if (= *pte-mode* "U")
    (progn
      (setq new (pte:trim-apply e (vlax-ename->vla-object e) (caddr rec) (nth 5 rec)))
      ;; jesli ciety obiekt byl krawedzia - jego nowe kawalki tez nia sa
      (if (and new (assoc e *pte-bnd*))
        (foreach n new (setq *pte-bnd* (cons (cons n (vlax-ename->vla-object n)) *pte-bnd*)))
      )
    )
    (if (= (caddr rec) 'NATIVE)
      (pte:native "_.EXTEND" e (nth 5 rec))
      (pte:ext-apply e (caddr rec))
    )
  )
  (setq *pte-cache* nil)
  (if *pte-all*
    (setq *pte-bnd* (pte:bnd-all))
    (setq *pte-bnd* (vl-remove-if-not '(lambda (b) (entget (car b))) *pte-bnd*))
  )
)

(defun pte:prompt ()
  (princ (strcat "\n[" (if (= *pte-mode* "U") "UTNIJ" "WYDLUZ")
                 "] Wskaz obiekt  [U=utnij / W=wydluz / Enter=koniec]: "))
)

(defun pte:end ()
  (redraw)
  (if *pte-hl* (pte:hl 4))
  (setq *pte-hl* nil)
  (if *pte-undo*
    (progn (vla-EndUndoMark (vla-get-ActiveDocument (vlax-get-acad-object)))
           (setq *pte-undo* nil))
  )
  (if *pte-oce* (progn (setvar "CMDECHO" *pte-oce*) (setq *pte-oce* nil)))
)

(defun pte:run (mode / *error* ss gr code val rec prev go r)
  (defun *error* (msg)
    (pte:end)
    (if (and msg (not (wcmatch (strcase msg) "*BREAK*,*CANCEL*,*EXIT*,*QUIT*")))
      (princ (strcat "\nBlad: " msg))
    )
    (princ)
  )
  (setq *pte-oce*   (getvar "CMDECHO")
        *pte-mode*  mode
        *pte-cache* nil
        *pte-hl*    nil
  )
  (setvar "CMDECHO" 0)
  (vla-StartUndoMark (vla-get-ActiveDocument (vlax-get-acad-object)))
  (setq *pte-undo* T)

  (princ (strcat "\nEDGEMODE=" (itoa (getvar "EDGEMODE"))
                 "  Wybierz krawedzie " (if (= mode "U") "tnace" "graniczne")
                 " <Enter = wszystkie obiekty>: "))
  (if (setq ss (ssget (list (cons 0 *pte-btypes*))))
    (setq *pte-all* nil
          *pte-bnd* (pte:bnd-get ss)
          *pte-hl*  (< (sslength ss) 1000))
    (setq *pte-all* T
          *pte-bnd* (pte:bnd-all))
  )
  (if *pte-hl* (pte:hl 3))
  (pte:prompt)

  (setq go T)
  (while go
    (setq gr   (grread T 15 2)
          code (car gr)
          val  (cadr gr)
    )
    (cond
      ;; ruch kursora - podglad
      ((= code 5)
       (setq rec (pte:safe-hover val))
       (if (not (pte:same rec prev))
         (progn
           (redraw)
           (if *pte-hl* (pte:hl 3))
           (if rec (pte:draw rec))
           (setq prev rec)
         )
       )
      )
      ;; klikniecie - wykonanie
      ((= code 3)
       (setq rec (pte:safe-hover val) prev nil)
       (redraw)
       (if rec
         (if (vl-catch-all-error-p (setq r (vl-catch-all-apply 'pte:apply (list rec))))
           (princ (strcat "\nNie udalo sie: " (vl-catch-all-error-message r)))
         )
         (princ "\nBrak mozliwej operacji w tym miejscu.")
       )
       (if *pte-hl* (pte:hl 3))
       (pte:prompt)
      )
      ;; klawiatura
      ((= code 2)
       (cond
         ((member val '(13 32)) (setq go nil))
         ((member val '(85 117 84 116))           ; U u T t
          (setq *pte-mode* "U" *pte-cache* nil prev nil)
          (redraw) (if *pte-hl* (pte:hl 3)) (pte:prompt))
         ((member val '(87 119 69 101))           ; W w E e
          (setq *pte-mode* "W" *pte-cache* nil prev nil)
          (redraw) (if *pte-hl* (pte:hl 3)) (pte:prompt))
       )
      )
      ;; prawy przycisk
      ((member code '(11 25)) (setq go nil))
    )
  )
  (pte:end)
  (princ)
)

;;; ------------------------------------------------------------ polecenia ---
(defun c:PTRIM   () (pte:run "U"))
(defun c:PEXTEND () (pte:run "W"))
(defun c:UP      () (pte:run "U"))
(defun c:WP      () (pte:run "W"))

(princ "\nPodgladUW.lsp wczytany. Polecenia: PTRIM (UP) - utnij, PEXTEND (WP) - wydluz.")
(princ)
