;;;
;;; Replace the write function for classes to minimize the amount of
;;; information written to the file by removing default values from the
;;; output.
;;;

;;; Maintain a list of default instances of a class.  This catches all
;;; of the inherited variables as well.

(setq _cmw_widget_template_window_ nil)	; for QNX Photon
(setq _cmw_class_templates_ nil)


;;;
;;; If we are running Photon, reparent prior to making a new widget.
;;;

(defun cmw_running_photon ()
  (if (and (not (undefined_p PtInit))
	   (function_p PtInit))
      t
    nil))

(defun cmw_reparent (newparent)
  (if (cmw_running_photon)
      (PtSetParentWidget newparent)))

;;;
;;; Declare a set of variables that we do not want to write to disk.
;;;

(if (cmw_running_photon)
    (setq _cmw_unwritten_resources_
	  '(dummy data _callbacks handles selected area trend_data
		  ;; For now, dont save icons - we cant handle children
		  icon_window
		  ))
  (setq _cmw_unwritten_resources_ nil))

;;;
;;; Create dummy widget templates so we only write the things that are
;;; not defaults to the output file.
;;;

(defun cmw_create_default_instance (myclass)
  (let (dad prevparent templ newinst)
    (if (and (not _cmw_widget_template_window_)
	     (cmw_running_photon))
	(progn
	  ;; (princ "Creating a default " (class_name myclass) "\n")
	  (setq prevparent (cmw_reparent nil))
	  (setq _cmw_widget_template_window_ (new PtWindow))
	  (-> (@ _cmw_widget_template_window_ pos) x 0)
	  (-> (@ _cmw_widget_template_window_ pos) y 0)
	  (-> (@ _cmw_widget_template_window_ dim) w 500)
	  (-> (@ _cmw_widget_template_window_ dim) h 500)
	  (setq _cmw_class_templates_
		(cons (cons PtWindow _cmw_widget_template_window_) nil))
	  (cmw_reparent prevparent)
	  )
      )
    (if (or (not (cmw_running_photon)) (not (eq myclass PtWindow)))
	(progn
	  ;; (princ "Creating a default " (class_name myclass) "\n")
	  (setq prevparent (cmw_reparent _cmw_widget_template_window_))
	  (setq templ (cons myclass (setq newinst (new myclass))))
	  (setq _cmw_class_templates_ (cons templ _cmw_class_templates_))
	  (cmw_reparent prevparent)
	  )
      (setq newinst _cmw_widget_template_window_)
      )
    newinst
    )
  )

;;;
;;; Return T to write the instance variable, Nil to ignore it.
;;;

(defun _ivar_filter (inst &noeval ivar)
  (let (myclass template)
    (if (instance_p inst)
	(progn
	  (setq myclass (class_of inst))
	  (setq template (cdar (assoc myclass _cmw_class_templates_)))
	  (if (not template)
	      (setq template (cmw_create_default_instance myclass)))
	  (if (or (find (car ivar) _cmw_unwritten_resources_)
		  (equal (cdr ivar) (:@ template (car ivar))))
	      nil t)
	  )
      nil)
    )
  )
