(define-structure restore-workspace-focus

    (export)

    (open user
          rep
          rep.regexp
          rep.system
          sawfish.wm
          sawfish.wm.util.display-window
          sawfish.wm.util.window-order
          sawfish.wm.util.selection
          sawfish.wm.workspace)

  (define *avoid-focus* "^(gnome-panel|desktop_window)$")

  (defun restore-focus ()
    "Restore focus to most recently used window except dock windows and desktop"
    (interactive)
    (let ((all-wins (window-order current-workspace))
          (tmp nil)
          (win nil)
          (wins '()))
      (while all-wins
        (setq win (car all-wins)
              tmp (aref (get-x-text-property win 'WM_CLASS) 0))
        (if (and (window-visible-p win)
                 (not (string-match *avoid-focus* tmp)))
            (setq wins (append wins (list win))))
        (setq all-wins (cdr all-wins)))
      (setq tmp (car wins))
      (when tmp
        (activate-window tmp)
        (raise-window tmp))))

  (add-hook 'enter-workspace-hook restore-focus)
  (add-hook 'destroy-notify-hook restore-focus)
  (add-hook 'iconify-window-hook restore-focus)

  )
