<commit_before>
;;;; prelude

(ns org.turtle.geometry.TurtleGraphics
  (:gen-class :main false
              :name org.turtle.geometry.TurtleGraphics
              :extends android.app.Activity
              :implements [clojure.lang.IDeref
                           android.view.SurfaceHolder$Callback]
              :exposes-methods {onCreate superOnCreate
                                onCreateOptionsMenu superOnCreateOptionsMenu
                                onMenuItemSelected superOnMenuItemSelected
                                onResume superOnResume
                                onPause superOnPause
                                onDestroy superOnDestroy
                                onBackPressed superOnBackPressed}
              :state ^{:tag ActivityState} state
              :init init
              :constructors {[] []})
  (:import [android.app Activity]
           [android.content Context]
           [android.graphics Bitmap Bitmap$Config BitmapFactory Canvas
            Color Matrix Paint Paint$Cap Paint$Style Rect]
           [android.text SpannableStringBuilder]
           [android.view
            GestureDetector GestureDetector$SimpleOnGestureListener
            ScaleGestureDetector ScaleGestureDetector$OnScaleGestureListener]
           [android.view Menu MenuInflater MenuItem]
           [android.view KeyEvent LayoutInflater MotionEvent
            SurfaceHolder SurfaceView
            View View$OnKeyListener View$OnTouchListener
            ViewGroup Window]
           [android.widget Button EditText ProgressBar
            TabHost TabHost$TabSpec TabHost$TabContentFactory TextView]
           [android.util AttributeSet]
           [android.util.Log]

           [java.io BufferedWriter StringWriter]
           [java.util.concurrent
            ConcurrentLinkedQueue
            LinkedBlockingQueue
            ThreadPoolExecutor
            TimeUnit]


           ;; [org.antlr.runtime ANTLRStringStream
           ;;  CommonTokenStream]
           ;; [org.turtle TurtleLexer TurtleParser]
           )
  (:require [neko.init]
            [neko.compilation])
  (:use [clojure.pprint :only (with-pprint-dispatch
                                pprint
                                *print-right-margin*
                                code-dispatch)]
        [clojure.test :only (function?)]
        [clojure.math.numeric-tower :only (sqrt)]
        [org.turtle.geometry.utils]
        [neko.init]
        [android.clojure.util :only (defrecord*
                                      make-double-tap-handler
                                      make-ui-dimmer)]
        [android.clojure.graphic :only (color->paint
                                        ;; draw-grid
                                        with-saved-matrix)]))

(defn log
  ([msg] (android.util.Log/d "TurtleGeometry" msg))
  ([msg & args] (log (apply format msg args))))

(defmacro draw-with-page-transform [canvas-var transform-matrix & body]
  `(with-saved-matrix ~canvas-var
     (.concat ~canvas-var ~transform-matrix)
     ~@body))

(defmacro with-centered-canvas [canvas-var & body]
  `(with-saved-matrix ~canvas-var
     (.translate ~canvas-var
                 (int (/ (.getWidth ~canvas-var) 2))
                 (int (/ (.getHeight ~canvas-var) 2)))
     ~@body))

(defn make-identity-transform ^Matrix []
  (Matrix.))

(defn rotate-right-90 ^Bitmap [^Bitmap b]
  (let [height (.getHeight b)
        width (.getWidth b)
        half-width (/ width 2.0)
        half-height (/ height 2.0)
        m ^Matrix (make-identity-transform)]
    (.preTranslate m (+ half-width) (+ half-height))
    (.setRotate m 90)
    (.postTranslate m (- half-width) (- half-height))
    (Bitmap/createBitmap b 0 0 width height m false)))

(defn matrix-mult ^Matrix [^Matrix m1 ^Matrix m2]
  (let [tmp (Matrix. m1)]
    (.postConcat tmp m2)
    tmp))

(defn ^Paint line-paint [color]
  (let [p ^Paint (color->paint color)]
    (doto p
      ;; (.setStrokeWidth ,,, 2)
      (.setStyle ,,, Paint$Style/STROKE)
      (.setStrokeCap ,,, Paint$Cap/ROUND)
      (.setAntiAlias ,,, true))
    p))

(defn antialiasing-paint ^Paint []
  (let [p (Paint.)]
    (.setAntiAlias p true)
    p))

;;;; activity functions

(def ^{:dynamic true} *activity* (atom nil))
;; (def ^{:dynamic true} *task-runner* (atom nil))

;; (defn show-progress-bar [^org.turtle.geometry.TurtleGraphics activity]
;;   (.setProgressBarIndeterminateVisibility activity true))

;; (defn hide-progress-bar [^org.turtle.geometry.TurtleGraphics activity]
;;   (.setProgressBarIndeterminateVisibility activity false))

(defrecord DrawState [surface-available?
                      ^Bitmap intermediate-bitmap
                      ^Canvas draw-canvas])

(defrecord TurtleState [position      ;; [x y]
                        prev-position ;; [x y]
                        angle         ;; in degrees
                        pen-up?
                        color ;; current color

                        ;; seq of [[startx starty] [endx endy] color] line segments produced by turtle
                        lines])

(defrecord UserOptions [^boolean show-graphics-when-run
                        ^boolean track-scaling-touches])

(def ^{:const true} initial-turtle-state
  (TurtleState. [0 0] [0 0] 0 false Color/BLACK []))


(defrecord* ActivityState [^SurfaceView draw-area
                           ^EditText program-source-editor
                           ^TextView error-output
                           ^EditText duration-entry
                           ^Menu activity-menu
                           ^TabHost activity-tab-host

                           ^DrawState draw-state
                           ^UserOptions user-options

                           ^Matrix intermediate-transform
                           ^Thread turtle-program-thread
                           ^Matrix draw-area-view-transform
                           ^Bitmap turtle-bitmap
                           ^TurtleState turtle-state])

(defn -deref ^ActivityState [^org.turtle.geometry.TurtleGraphics this]
  @(.state this))

(defn -init []
  [[] (atom (ActivityState. nil
                            nil
                            nil
                            nil
                            nil
                            nil

                            nil
                            nil

                            nil
                            nil
                            nil
                            nil
                            nil))])



(defn text-input->int [^EditText input-field]
  (Integer/valueOf ^String
                   (.. input-field
                       (getText)
                       (toString))))

(defn report-error [^org.turtle.geometry.TurtleGraphics activity
                    ^String msg]
  (.setText (error-output @activity) msg))

(defn get-animation-duration [^org.turtle.geometry.TurtleGraphics activity]
  (text-input->int (duration-entry @activity)))

(declare eval-turtle-program draw-scene
         clear-intermed-bitmap redraw-indermed-bitmap)

(defn make-scale-transform ^Matrix
  [^org.turtle.geometry.TurtleGraphics activity
   scale-factor]<commit_msg>added switching to errors tab when error is reported<commit_after>
;;;; prelude

(ns org.turtle.geometry.TurtleGraphics
  (:gen-class :main false
              :name org.turtle.geometry.TurtleGraphics
              :extends android.app.Activity
              :implements [clojure.lang.IDeref
                           android.view.SurfaceHolder$Callback]
              :exposes-methods {onCreate superOnCreate
                                onCreateOptionsMenu superOnCreateOptionsMenu
                                onMenuItemSelected superOnMenuItemSelected
                                onResume superOnResume
                                onPause superOnPause
                                onDestroy superOnDestroy
                                onBackPressed superOnBackPressed}
              :state ^{:tag ActivityState} state
              :init init
              :constructors {[] []})
  (:import [android.app Activity]
           [android.content Context]
           [android.graphics Bitmap Bitmap$Config BitmapFactory Canvas
            Color Matrix Paint Paint$Cap Paint$Style Rect]
           [android.text SpannableStringBuilder]
           [android.view
            GestureDetector GestureDetector$SimpleOnGestureListener
            ScaleGestureDetector ScaleGestureDetector$OnScaleGestureListener]
           [android.view Menu MenuInflater MenuItem]
           [android.view KeyEvent LayoutInflater MotionEvent
            SurfaceHolder SurfaceView
            View View$OnKeyListener View$OnTouchListener
            ViewGroup Window]
           [android.widget Button EditText ProgressBar
            TabHost TabHost$TabSpec TabHost$TabContentFactory TextView]
           [android.util AttributeSet]
           [android.util.Log]

           [java.io BufferedWriter StringWriter]
           [java.util.concurrent
            ConcurrentLinkedQueue
            LinkedBlockingQueue
            ThreadPoolExecutor
            TimeUnit]


           ;; [org.antlr.runtime ANTLRStringStream
           ;;  CommonTokenStream]
           ;; [org.turtle TurtleLexer TurtleParser]
           )
  (:require [neko.init]
            [neko.compilation])
  (:use [clojure.pprint :only (with-pprint-dispatch
                                pprint
                                *print-right-margin*
                                code-dispatch)]
        [clojure.test :only (function?)]
        [clojure.math.numeric-tower :only (sqrt)]
        [org.turtle.geometry.utils]
        [neko.init]
        [android.clojure.util :only (defrecord*
                                      make-double-tap-handler
                                      make-ui-dimmer)]
        [android.clojure.graphic :only (color->paint
                                        ;; draw-grid
                                        with-saved-matrix)]))

(defn log
  ([msg] (android.util.Log/d "TurtleGeometry" msg))
  ([msg & args] (log (apply format msg args))))

(defmacro draw-with-page-transform [canvas-var transform-matrix & body]
  `(with-saved-matrix ~canvas-var
     (.concat ~canvas-var ~transform-matrix)
     ~@body))

(defmacro with-centered-canvas [canvas-var & body]
  `(with-saved-matrix ~canvas-var
     (.translate ~canvas-var
                 (int (/ (.getWidth ~canvas-var) 2))
                 (int (/ (.getHeight ~canvas-var) 2)))
     ~@body))

(defn make-identity-transform ^Matrix []
  (Matrix.))

(defn rotate-right-90 ^Bitmap [^Bitmap b]
  (let [height (.getHeight b)
        width (.getWidth b)
        half-width (/ width 2.0)
        half-height (/ height 2.0)
        m ^Matrix (make-identity-transform)]
    (.preTranslate m (+ half-width) (+ half-height))
    (.setRotate m 90)
    (.postTranslate m (- half-width) (- half-height))
    (Bitmap/createBitmap b 0 0 width height m false)))

(defn matrix-mult ^Matrix [^Matrix m1 ^Matrix m2]
  (let [tmp (Matrix. m1)]
    (.postConcat tmp m2)
    tmp))

(defn ^Paint line-paint [color]
  (let [p ^Paint (color->paint color)]
    (doto p
      ;; (.setStrokeWidth ,,, 2)
      (.setStyle ,,, Paint$Style/STROKE)
      (.setStrokeCap ,,, Paint$Cap/ROUND)
      (.setAntiAlias ,,, true))
    p))

(defn antialiasing-paint ^Paint []
  (let [p (Paint.)]
    (.setAntiAlias p true)
    p))

;;;; activity functions

(def ^{:dynamic true} *activity* (atom nil))
;; (def ^{:dynamic true} *task-runner* (atom nil))

;; (defn show-progress-bar [^org.turtle.geometry.TurtleGraphics activity]
;;   (.setProgressBarIndeterminateVisibility activity true))

;; (defn hide-progress-bar [^org.turtle.geometry.TurtleGraphics activity]
;;   (.setProgressBarIndeterminateVisibility activity false))

(defrecord DrawState [surface-available?
                      ^Bitmap intermediate-bitmap
                      ^Canvas draw-canvas])

(defrecord TurtleState [position      ;; [x y]
                        prev-position ;; [x y]
                        angle         ;; in degrees
                        pen-up?
                        color ;; current color

                        ;; seq of [[startx starty] [endx endy] color] line segments produced by turtle
                        lines])

(defrecord UserOptions [^boolean show-graphics-when-run
                        ^boolean track-scaling-touches])

(def ^{:const true} initial-turtle-state
  (TurtleState. [0 0] [0 0] 0 false Color/BLACK []))


(defrecord* ActivityState [^SurfaceView draw-area
                           ^EditText program-source-editor
                           ^TextView error-output
                           ^EditText duration-entry
                           ^Menu activity-menu
                           ^TabHost activity-tab-host

                           ^DrawState draw-state
                           ^UserOptions user-options

                           ^Matrix intermediate-transform
                           ^Thread turtle-program-thread
                           ^Matrix draw-area-view-transform
                           ^Bitmap turtle-bitmap
                           ^TurtleState turtle-state])

(defn -deref ^ActivityState [^org.turtle.geometry.TurtleGraphics this]
  @(.state this))

(defn -init []
  [[] (atom (ActivityState. nil
                            nil
                            nil
                            nil
                            nil
                            nil

                            nil
                            nil

                            nil
                            nil
                            nil
                            nil
                            nil))])



(defn text-input->int [^EditText input-field]
  (Integer/valueOf ^String
                   (.. input-field
                       (getText)
                       (toString))))

(defn report-error
  ([activity msg]
     (report-error activity msg true))
  ([^org.turtle.geometry.TurtleGraphics activity
     ^String msg
    switch-to-errors-tab]
     (.setText (error-output @activity) msg)
     (when switch-to-errors-tab
       (.setCurrentTabByTag (activity-tab-host @activity)
                            (.getString activity
                                        (resource :string
                                                  :errors_tab_label))))))

(defn get-animation-duration [^org.turtle.geometry.TurtleGraphics activity]
  (text-input->int (duration-entry @activity)))

(declare eval-turtle-program draw-scene
         clear-intermed-bitmap redraw-indermed-bitmap)

(defn make-scale-transform ^Matrix
  [^org.turtle.geometry.TurtleGraphics activity
   scale-factor]
{'fraction_non_alphanumeric': 0.0968004338394794, 'fraction_numerical': 0.002982646420824295, 'mean_word_length': 1.540992077161557, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 13, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4223912', 'n_tokens_mistral': 4078, 'n_tokens_neox': 3747, 'n_words': 878}