view src/scrollbar-msw.c @ 5353:38e24b8be4ea

Improve the lexical scoping in #'block, #'return-from. lisp/ChangeLog addition: 2011-02-07 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el: * bytecomp.el (byte-compile-initial-macro-environment): Shadow `block', `return-from' here, we implement them differently when byte-compiling. * bytecomp.el (byte-compile-active-blocks): New. * bytecomp.el (byte-compile-block-1): New. * bytecomp.el (byte-compile-return-from-1): New. * bytecomp.el (return-from-1): New. * bytecomp.el (block-1): New. These are two aliases that exist to have their own associated byte-compile functions, which functions implement `block' and `return-from'. * cl-extra.el (cl-macroexpand-all): Fix a bug here when macros in the environment have been compiled. * cl-macs.el (block): * cl-macs.el (return): * cl-macs.el (return-from): Be more careful about lexical scope in these macros. * cl.el: * cl.el ('cl-block-wrapper): Removed. * cl.el ('cl-block-throw): Removed. These aren't needed in code generated by this XEmacs. They shouldn't be needed in code generated by XEmacs 21.4, but if it turns out the packages do need them, we can put them back. 2011-01-30 Mike Sperber <mike@xemacs.org> * font-lock.el (font-lock-fontify-pending-extents): Don't fail if `font-lock-mode' is unset, which can happen in the middle of `revert-buffer'. 2011-01-23 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (delete): * cl-macs.el (delq): * cl-macs.el (remove): * cl-macs.el (remq): Don't use the compiler macro if these functions were given the wrong number of arguments, as happens in lisp-tests.el. * cl-seq.el (remove, remq): Removed. I added these to subr.el, and forgot to remove them from here. 2011-01-22 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-setq, byte-compile-set): Remove kludge allowing keywords' values to be set, all the code that does that is gone. * cl-compat.el (elt-satisfies-test-p): * faces.el (set-face-parent): * faces.el (face-doc-string): * gtk-font-menu.el: * gtk-font-menu.el (gtk-reset-device-font-menus): * msw-font-menu.el: * msw-font-menu.el (mswindows-reset-device-font-menus): * package-get.el (package-get-installedp): * select.el (select-convert-from-image-data): * sound.el: * sound.el (load-sound-file): * x-font-menu.el (x-reset-device-font-menus-core): Don't quote keywords, they're self-quoting, and the win from backward-compatibility is sufficiently small now that the style problem overrides it. 2011-01-22 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (block, return-from): Require that NAME be a symbol in these macros, as always documented in the #'block docstring and as required by Common Lisp. * descr-text.el (unidata-initialize-unihan-database): Correct the use of non-symbols in #'block and #'return-from in this function. 2011-01-15 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (concatenate): Accept more complicated TYPEs in this function, handing the sequences over to #'coerce if we don't understand them here. * cl-macs.el (inline): Don't proclaim #'concatenate as inline, its compiler macro is more useful than doing that. 2011-01-11 Aidan Kehoe <kehoea@parhasard.net> * subr.el (delete, delq, remove, remq): Move #'remove, #'remq here, they don't belong in cl-seq.el; move #'delete, #'delq here from fns.c, implement them in terms of #'delete*, allowing support for sequences generally. * update-elc.el (do-autoload-commands): Use #'delete*, not #'delq here, now the latter's no longer dumped. * cl-macs.el (delete, delq): Add compiler macros transforming #'delete and #'delq to #'delete* calls. 2011-01-10 Aidan Kehoe <kehoea@parhasard.net> * dialog.el (make-dialog-box): Correct a misplaced parenthesis here, thank you Mats Lidell in 87zkr9gqrh.fsf@mail.contactor.se ! 2011-01-02 Aidan Kehoe <kehoea@parhasard.net> * dialog.el (make-dialog-box): * list-mode.el (display-completion-list): These functions used to use cl-parsing-keywords; change them to use defun* instead, fixing the build. (Not sure what led to me not including this change in d1b17a33450b!) 2011-01-02 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (define-star-compiler-macros): Make sure the form has ITEM and LIST specified before attempting to change to calls with explicit tests; necessary for some tests in lisp-tests.el to compile correctly. (stable-union, stable-intersection): Add compiler macros for these functions, in the same way we do for most of the other functions in cl-seq.el. 2011-01-01 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (dolist, dotimes, do-symbols, macrolet) (symbol-macrolet): Define these macros with defmacro* instead of parsing the argument list by hand, for the sake of style and readability; use backquote where appropriate, instead of calling #'list and and friends, for the same reason. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * x-misc.el (device-x-display): Provide this function, documented in the Lispref for years, but not existing previously. Thank you Julian Bradfield, thank you Jeff Mincy. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * cl-seq.el: Move the heavy lifting from this file to C. Dump the cl-parsing-keywords macro, but don't use defun* for the functions we define that do take keywords, dynamic scope lossage makes that not practical. * subr.el (sort, fillarray): Move these aliases here. (map-plist): #'nsublis is now built-in, but at this point #'eql isn't necessarily available as a test; use #'eq. * obsolete.el (cl-delete-duplicates): Make this available for old compiler macros and old code. (memql): Document that this is equivalent to #'member*, and worse. * cl.el (adjoin, subst): Removed. These are in C. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * simple.el (assoc-ignore-case): Remove a duplicate definition of this function (it's already in subr.el). * iso8859-1.el (char-width): On non-Mule, make this function equivalent to that produced by (constantly 1), but preserve its docstring. * subr.el (subst-char-in-string): Define this in terms of #'substitute, #'nsubstitute. (string-width): Define this using #'reduce and #'char-width. (char-width): Give this a simpler definition, it makes far more sense to check for mule at load time and redefine, as we do in iso8859-1.el. (store-substring): Implement this in terms of #'replace, now #'replace is cheap. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * update-elc.el (lisp-files-needed-for-byte-compilation) (lisp-files-needing-early-byte-compilation): cl-macs belongs in the former, not the latter, it is as fundamental as bytecomp.el. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * cl.el: Provde the Common Lisp program-error, type-error as error symbols. This doesn't nearly go far enough for anyone using the Common Lisp errors. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (delete-duplicates): If the form has an incorrect number of arguments, don't attempt a compiler macroexpansion. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (cl-safe-expr-p): Forms that start with the symbol lambda are also safe. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (= < > <= >=): For these functions' compiler macros, the optimisation is safe even if the first and the last arguments have side effects, since they're only used the once. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (inline-side-effect-free-compiler-macros): Unroll a loop here at macro-expansion time, so these compiler macros are compiled. Use #'eql instead of #'eq in a couple of places for better style. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (notany, notevery): Avoid some dynamic scope stupidity with local variable names in these functions, when they weren't prefixed with cl-; go into some more detail in the doc strings. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (side-effect-free-fns): #'remove, #'remq are free of side-effects. (side-effect-and-error-free-fns): Drop dot, dot-marker from the list. 2010-11-17 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (coerce): In the argument list, name the first argument OBJECT, not X; the former name was always used in the doc string and is clearer. Handle vector type specifications which include the length of the target sequence, error if there's a mismatch. * cl-macs.el (cl-make-type-test): Handle type specifications starting with the symbol 'eql. 2010-11-14 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (eql): Don't remove the byte-compile property of this symbol. That was necessary to override a bug in bytecomp.el where #'eql was confused with #'eq, which bug we no longer have. If neither expression is constant, don't attempt to handle the expression in this compiler macro, leave it to byte-compile-eql, which produces better code anyway. * bytecomp.el (eq): #'eql is not the function associated with the byte-eq byte code. (byte-compile-eql): Add an explicit compile method for this function, for cases where the cl-macs compiler macro hasn't reduced it to #'eq or #'equal. 2010-10-25 Aidan Kehoe <kehoea@parhasard.net> Add compiler macros and compilation sanity-checking for various functions that take keywords. * byte-optimize.el (side-effect-free-fns): #'symbol-value is side-effect free and not error free. * bytecomp.el (byte-compile-normal-call): Check keyword argument lists for sanity; store information about the positions where keyword arguments start using the new byte-compile-keyword-start property. * cl-macs.el (cl-const-expr-val): Take a new optional argument, cl-not-constant, defaulting to nil, in this function; return it if the expression is not constant. (cl-non-fixnum-number-p): Make this into a separate function, we want to pass it to #'every. (eql): Use it. (define-star-compiler-macros): Use the same code to generate the member*, assoc* and rassoc* compiler macros; special-case some code in #'add-to-list in subr.el. (remove, remq): Add compiler macros for these two functions, in preparation for #'remove being in C. (define-foo-if-compiler-macros): Transform (remove-if-not ...) calls to (remove ... :if-not) at compile time, which will be a real win once the latter is in C. (define-substitute-if-compiler-macros) (define-subst-if-compiler-macros): Similarly for these functions. (delete-duplicates): Change this compiler macro to use #'plists-equal; if we don't have information about the type of SEQUENCE at compile time, don't bother attempting to inline the call, the function will be in C soon enough. (equalp): Remove an old commented-out compiler macro for this, if we want to see it it's in version control. (subst-char-in-string): Transform this to a call to nsubstitute or nsubstitute, if that is appropriate. * cl.el (ldiff): Don't call setf here, this makes for a load-time dependency problem in cl-macs.el 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * term/vt100.el: Refer to XEmacs, not GNU Emacs, in permissions. * term/bg-mouse.el: * term/sup-mouse.el: Put copyright notice in canonical "Copyright DATE AUTHOR" form. Refer to XEmacs, not GNU Emacs, in permissions. * site-load.el: Add permission boilerplate. * mule/canna-leim.el: * alist.el: Refer to XEmacs, not APEL/this program, in permissions. * mule/canna-leim.el: Remove my copyright, I've assigned it to the FSF. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * gtk.el: * gtk-widget-accessors.el: * gtk-package.el: * gtk-marshal.el: * gtk-compose.el: * gnome.el: Add copyright notice based on internal evidence. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * easymenu.el: Add reference to COPYING to permission notice. * gutter.el: * gutter-items.el: * menubar-items.el: Fix typo "Xmacs" in permissions notice. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * auto-save.el: * font.el: * fontconfig.el: * mule/kinsoku.el: Add "part of XEmacs" text to permission notice. 2010-10-14 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (side-effect-free-fns): * cl-macs.el (remf, getf): * cl-extra.el (tailp, cl-set-getf, cl-do-remf): * cl.el (ldiff, endp): Tighten up Common Lisp compatibility for #'ldiff, #'endp, #'tailp; add circularity checking for the first two. #'cl-set-getf and #'cl-do-remf were Lisp implementations of #'plist-put and #'plist-remprop; change the names to aliases, changes the macros that use them to using #'plist-put and #'plist-remprop directly. 2010-10-12 Aidan Kehoe <kehoea@parhasard.net> * abbrev.el (fundamental-mode-abbrev-table, global-abbrev-table): Create both these abbrev tables using the usual #'define-abbrev-table calls, rather than attempting to special-case them. * cl-extra.el: Force cl-macs to be loaded here, if cl-extra.el is being loaded interpreted. Previously other, later files would redundantly call (load "cl-macs") when interpreted, it's more reasonable to do it here, once. * cmdloop.el (read-quoted-char-radix): Use defcustom here, we don't have any dump-order dependencies that would prevent that. * custom.el (eval-when-compile): Don't load cl-macs when interpreted or when byte-compiling, rely on cl-extra.el in the former case and the appropriate entry in bytecomp-load-hook in the latter. Get rid of custom-declare-variable-list, we have no dump-time dependencies that would require it. * faces.el (eval-when-compile): Don't load cl-macs when interpreted or when byte-compiling. * packages.el: Remove some inaccurate comments. * post-gc.el (cleanup-simple-finalizers): Use #'delete-if-not here, now the order of preloaded-file-list has been changed to make it available. * subr.el (custom-declare-variable-list): Remove. No need for it. Also remove a stub define-abbrev-table from this file, given the current order of preloaded-file-list there's no need for it. 2010-10-10 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-constp) Forms quoted with FUNCTION are also constant. (byte-compile-initial-macro-environment): In #'the, if FORM is constant and does not match TYPE, warn at byte-compile time. 2010-10-10 Aidan Kehoe <kehoea@parhasard.net> * backquote.el (bq-vector-contents, bq-list*): Remove; the former is equivalent to (append VECTOR nil), the latter to (list* ...). (bq-process-2): Use (append VECTOR nil) instead of using #'bq-vector-contents to convert to a list. (bq-process-1): Now we use list* instead of bq-list * subr.el (list*): Moved from cl.el, since it is now required to be available the first time a backquoted form is encountered. * cl.el (list*): Move to subr.el. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * test-harness.el (Check-Message): Add an omitted comma here, thank you the buildbot. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * hash-table.el (hash-table-key-list, hash-table-value-list) (hash-table-key-value-alist, hash-table-key-value-plist): Remove some useless #'nreverse calls in these files; our hash tables have no order, it's not helpful to pretend they do. * behavior.el (read-behavior): Do the same in this file, in some code evidently copied from hash-table.el. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * info.el (Info-insert-dir): * format.el (format-deannotate-region): * files.el (cd, save-buffers-kill-emacs): Use #'some, #'every and related functions for applying boolean operations to lists, instead of rolling our own ones that cons and don't short-circuit. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-initial-macro-environment): * cl-macs.el (the): Rephrase the docstring, make its implementation when compiling files a little nicer. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * descr-text.el (unidata-initialize-unicodedata-database) (unidata-initialize-unihan-database, describe-char-unicode-data) (describe-char-unicode-data): Wrap calls to the database functions with (with-fboundp ...), avoiding byte compile warnings on builds without support for the database functions. (describe-char): (reduce #'max ...), not (apply #'max ...), no need to cons needlessly. (describe-char): Remove a redundant lambda wrapping #'extent-properties. (describe-char-unicode-data): Call #'nsubst when replacing "" with nil in the result of #'split-string, instead of consing inside mapcar. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * x-faces.el (x-available-font-sizes): * specifier.el (let-specifier): * package-ui.el (pui-add-required-packages): * msw-faces.el (mswindows-available-font-sizes): * modeline.el (modeline-minor-mode-menu): * minibuf.el (minibuf-directory-files): Replace the O2N (delq nil (mapcar (lambda (W) (and X Y)) Z)) with the ON (mapcan (lambda (W) (and X (list Y))) Z) in these files. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (= < > <= >=): When these functions are handed more than two arguments, and those arguments have no side effects, transform to a series of two argument calls, avoiding funcall in the byte-compiled code. * mule/mule-cmds.el (finish-set-language-environment): Take advantage of this change in a function called 256 times at startup. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-function-form, byte-compile-quote) (byte-compile-quote-form): Warn at compile time, and error at runtime, if a (quote ...) or a (function ...) form attempts to quote more than one object. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (byte-optimize-apply): Transform (apply 'nconc (mapcar ...)) to (mapcan ...); warn about use of the first idiom. * update-elc.el (do-autoload-commands): * packages.el (packages-find-package-library-path): * frame.el (frame-list): * extents.el (extent-descendants): * etags.el (buffer-tag-table-files): * dumped-lisp.el (preloaded-file-list): * device.el (device-list): * bytecomp-runtime.el (proclaim-inline, proclaim-notinline) Use #'mapcan, not (apply #'nconc (mapcar ...) in all these files. * bytecomp-runtime.el (eval-when-compile, eval-and-compile): In passing, mention that these macros also evaluate the body when interpreted. tests/ChangeLog addition: 2011-02-07 Aidan Kehoe <kehoea@parhasard.net> * automated/lisp-tests.el: Test lexical scope for `block', `return-from'; add a Known-Bug-Expect-Failure for a contorted example that fails when byte-compiled.
author Aidan Kehoe <kehoea@parhasard.net>
date Mon, 07 Feb 2011 12:01:24 +0000
parents 71ee43b8a74d
children 308d34e9f07d
line wrap: on
line source

/* scrollbar implementation -- mswindows interface.
   Copyright (C) 1994, 1995 Board of Trustees, University of Illinois.
   Copyright (C) 1994 Amdahl Corporation.
   Copyright (C) 1995 Sun Microsystems, Inc.
   Copyright (C) 1995 Darrell Kindred <dkindred+@cmu.edu>.
   Copyright (C) 2001, 2002, 2010 Ben Wing.

This file is part of XEmacs.

XEmacs is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.

XEmacs is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with XEmacs; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

/* Synched up with: Not in FSF. */

/* This file essentially Mule-ized (except perhaps some Unicode splitting).
   5-2000. */

#include <config.h>
#include "lisp.h"

#include "device.h"
#include "elhash.h"
#include "events.h"
#include "frame-impl.h"
#include "opaque.h"
#include "scrollbar.h"
#include "specifier.h"
#include "window-impl.h"

#include "console-msw-impl.h"
#include "scrollbar-msw.h"

/* We use a similar sort of vertical scrollbar drag hack for mswindows
 * scrollbars as is used for Motif or Lucid scrollbars under X.
 * We do character-based instead of line-based scrolling, which can mean that
 * without the hack it is impossible to drag to the end of a buffer. */
#define VERTICAL_SCROLLBAR_DRAG_HACK

static int vertical_drag_in_progress = 0;
extern Lisp_Object mswindows_find_frame (HWND hwnd);

/* As long as the HWND is around, the scrollbar instance must be GC-protected.
   We have gotten crashes, apparently from trying to access a dead, freed
   frame inside of a window mirror pointed to by the scrollbar structure. */
static Lisp_Object Vmswindows_scrollbar_instance_table;

static void
mswindows_create_scrollbar_instance (struct frame *f, int vertical,
				     struct scrollbar_instance *sb)
{
  int orientation;
  Lisp_Object ptr;

  sb->scrollbar_data = xnew_and_zero (struct mswindows_scrollbar_data);

  if (vertical)
    orientation = SBS_VERT;
  else
    orientation = SBS_HORZ;

  SCROLLBAR_MSW_HANDLE (sb) =
    qxeCreateWindowEx (0, XETEXT ("SCROLLBAR"), 0, orientation|WS_CHILD,
		       CW_USEDEFAULT, CW_USEDEFAULT,
		       CW_USEDEFAULT, CW_USEDEFAULT,
		       FRAME_MSWINDOWS_HANDLE (f),
		       NULL, NULL, NULL);
  SCROLLBAR_MSW_INFO (sb).cbSize = sizeof (SCROLLINFO);
  SCROLLBAR_MSW_INFO (sb).fMask = SIF_ALL;
  GetScrollInfo (SCROLLBAR_MSW_HANDLE (sb), SB_CTL,
		 &SCROLLBAR_MSW_INFO (sb));
  ptr = make_opaque_ptr (SCROLLBAR_MSW_HANDLE (sb));
  Fputhash (ptr, wrap_scrollbar_instance (sb),
	    Vmswindows_scrollbar_instance_table);
  qxeSetWindowLong (SCROLLBAR_MSW_HANDLE (sb), GWL_USERDATA,
		 (LONG) STORE_LISP_IN_VOID (ptr));
}

static void
mswindows_free_scrollbar_instance (struct scrollbar_instance *sb)
{
  if (sb->scrollbar_data)
    {
      void *opaque =
	(void *) qxeGetWindowLong (SCROLLBAR_MSW_HANDLE (sb), GWL_USERDATA);
      Lisp_Object ptr;

      ptr = GET_LISP_FROM_VOID (opaque);
      assert (OPAQUE_PTRP (ptr));
      ptr = Fremhash (ptr, Vmswindows_scrollbar_instance_table);
      assert (!NILP (ptr));
      DestroyWindow (SCROLLBAR_MSW_HANDLE (sb));
      xfree (sb->scrollbar_data);
      sb->scrollbar_data = 0;
    }
}

static void
unshow_that_mofo (void *handle)
{
  ShowScrollBar ((HWND) handle, SB_CTL, 0);
}

static void
mswindows_release_scrollbar_instance (struct scrollbar_instance *sb)
{
  if (gc_in_progress)
    /* #### way bogus!  need to remove the offending call.
       see mark_redisplay(). */
    register_post_gc_action (unshow_that_mofo,
			     (void *) SCROLLBAR_MSW_HANDLE (sb));
  else
    ShowScrollBar (SCROLLBAR_MSW_HANDLE (sb), SB_CTL, 0);
  SCROLLBAR_MSW_SIZE (sb) = 0;
}

#define UPDATE_POS_FIELD(field)						   \
  if (new_##field >= 0 && SCROLLBAR_MSW_DATA (sb)->field != new_##field) { \
    SCROLLBAR_MSW_DATA (sb)->field = new_##field;			   \
    pos_changed = 1;							   \
  }

static void
mswindows_update_scrollbar_instance_values (struct window *UNUSED (w),
					    struct scrollbar_instance *sb,
					    int UNUSED (new_line_increment),
					    int UNUSED (new_page_increment),
					    int new_minimum, int new_maximum,
					    int new_slider_size,
					    int new_slider_position,
					    int new_scrollbar_width,
					    int new_scrollbar_height,
					    int new_scrollbar_x,
					    int new_scrollbar_y)
{
  int pos_changed = 0;
  int vert = qxeGetWindowLong (SCROLLBAR_MSW_HANDLE (sb), GWL_STYLE) & SBS_VERT;

#if 0
  stderr_out ("[%d, %d], page = %d, pos = %d, inhibit = %d\n", new_minimum, new_maximum,
	      new_slider_size, new_slider_position,inhibit_slider_size_change);
#endif

  /* These might be optimized, but since at least one will change at each
     call, it's probably not worth it. */
  SCROLLBAR_MSW_INFO (sb).nMin = new_minimum;
  SCROLLBAR_MSW_INFO (sb).nMax = new_maximum;
  SCROLLBAR_MSW_INFO (sb).nPage = new_slider_size + 1; /* +1 for DISABLENOSCROLL */
  SCROLLBAR_MSW_INFO (sb).nPos = new_slider_position;
#ifndef VERTICAL_SCROLLBAR_DRAG_HACK
  SCROLLBAR_MSW_INFO (sb).fMask = ((vert && vertical_drag_in_progress)
				   ? SIF_RANGE | SIF_POS
				   : SIF_ALL | SIF_DISABLENOSCROLL);
#else
  SCROLLBAR_MSW_INFO (sb).fMask = SIF_ALL | SIF_DISABLENOSCROLL;

  /* Ignore XEmacs' requests to update the thumb position and size; they don't
   * bear any relation to reality because we're reporting made-up positions */
  if (!(vert && vertical_drag_in_progress))
#endif
    SetScrollInfo (SCROLLBAR_MSW_HANDLE (sb), SB_CTL, &SCROLLBAR_MSW_INFO (sb),
		   TRUE);

  UPDATE_POS_FIELD (scrollbar_x);
  UPDATE_POS_FIELD (scrollbar_y);
  UPDATE_POS_FIELD (scrollbar_width);
  UPDATE_POS_FIELD (scrollbar_height);

  if (pos_changed)
    {
      MoveWindow (SCROLLBAR_MSW_HANDLE (sb),
		  new_scrollbar_x, new_scrollbar_y,
		  new_scrollbar_width, new_scrollbar_height,
		  TRUE);
    }
}

static void
mswindows_update_scrollbar_instance_status (struct window *UNUSED (w),
					    int UNUSED (active), int size,
					    struct scrollbar_instance *sb)
{
  if (SCROLLBAR_MSW_SIZE (sb) != size)
    {
      SCROLLBAR_MSW_SIZE (sb) = size;
      ShowScrollBar (SCROLLBAR_MSW_HANDLE (sb), SB_CTL,
		     SCROLLBAR_MSW_SIZE (sb));
      SCROLLBAR_MSW_INFO(sb).fMask |= SIF_DISABLENOSCROLL;
      SetScrollInfo(SCROLLBAR_MSW_HANDLE (sb), SB_CTL, &SCROLLBAR_MSW_INFO (sb), TRUE);
    }
}

void
mswindows_handle_scrollbar_event (HWND hwnd, int code, int UNUSED (pos))
{
  struct frame *f;
  Lisp_Object win, frame;
  struct scrollbar_instance *sb = 0;
  void *v;
  SCROLLINFO scrollinfo;
  int vert = qxeGetWindowLong (hwnd, GWL_STYLE) & SBS_VERT;
  int value;

  v = (void *) qxeGetWindowLong (hwnd, GWL_USERDATA);
  if (!v)
    {
      /* apparently this can happen, as it was definitely necessary
	 to put the check in for sb below (VERTICAL_SCROLLBAR_DRAG_HACK) */
      frame = mswindows_find_frame (hwnd);
      f = XFRAME (frame);
      win = FRAME_SELECTED_WINDOW (f);
    }
  else
    {
      Lisp_Object ptr;
      ptr = GET_LISP_FROM_VOID (v);
      assert (OPAQUE_PTRP (ptr));
      ptr = Fgethash (ptr, Vmswindows_scrollbar_instance_table, Qnil);
      sb = XSCROLLBAR_INSTANCE (ptr);
      /* #### we're still hitting an abort here with 0 as the second
         parameter, although only occasionally.  It seems that sometimes we
         receive events for scrollbars that don't exist anymore.  I assume
         it must happen like this: The user does something that causes a
         scrollbar to disappear (e.g. Alt-TAB, causing recomputation of
         everything in the new frame) and then immediately uses the mouse
         wheel, generating scrollbar events.  Both events get posted before
         we have a chance to process them, and in processing the first, the
         scrollbar mentioned in the second disappears. */
      win = real_window (sb->mirror, 1);
      if (NILP (win))
	return;
      frame = WINDOW_FRAME (XWINDOW (win));
      f = XFRAME (frame);
    }

  /* SB_LINEDOWN == SB_CHARLEFT etc. This is the way they will
     always be - any Windows is binary compatible backward with
     old programs */

  switch (code)
    {
    case SB_LINEDOWN:
      mswindows_enqueue_misc_user_event
	(frame, vert ? Qscrollbar_line_down : Qscrollbar_char_right, win);
      break;

    case SB_LINEUP:
      mswindows_enqueue_misc_user_event
	(frame, vert ? Qscrollbar_line_up : Qscrollbar_char_left, win);
      break;

    case SB_PAGEDOWN:
      mswindows_enqueue_misc_user_event
	(win, vert ? Qscrollbar_page_down : Qscrollbar_page_right,
	 vert ? Fcons (win, Qnil) : win);
      break;

    case SB_PAGEUP:
      mswindows_enqueue_misc_user_event
	(frame,
	 vert ? Qscrollbar_page_up : Qscrollbar_page_left,
	 vert ? Fcons (win, Qnil) : win);
      break;

    case SB_BOTTOM:
      mswindows_enqueue_misc_user_event
	(frame, vert ? Qscrollbar_to_bottom : Qscrollbar_to_right, win);
      break;

    case SB_TOP:
      mswindows_enqueue_misc_user_event
	(frame, vert ? Qscrollbar_to_top : Qscrollbar_to_left, win);
      break;

    case SB_THUMBTRACK:
    case SB_THUMBPOSITION:
      scrollinfo.cbSize = sizeof(SCROLLINFO);
      scrollinfo.fMask = SIF_ALL;
      GetScrollInfo (hwnd, SB_CTL, &scrollinfo);
      vertical_drag_in_progress = vert;
#ifdef VERTICAL_SCROLLBAR_DRAG_HACK
      if (vert && (scrollinfo.nTrackPos > scrollinfo.nPos))
        /* new buffer position =
	 *  buffer position at start of drag +
	 *   ((text remaining in buffer at start of drag) *
	 *    (amount that the thumb has been moved) /
	 *    (space that remained past end of the thumb at start of drag)) */
	value = (int)
	  (scrollinfo.nPos
	   + (((double)
	      (scrollinfo.nMax - scrollinfo.nPos)
	       * (scrollinfo.nTrackPos - scrollinfo.nPos))
	      / (scrollinfo.nMax - scrollinfo.nPage - scrollinfo.nPos)))
	  - 2;	/* ensure that the last line doesn't disappear off screen */
      else
#endif
        value = scrollinfo.nTrackPos;
      mswindows_enqueue_misc_user_event
	(frame,
	 vert ? Qscrollbar_vertical_drag : Qscrollbar_horizontal_drag,
	 Fcons (win, make_int (value)));
      break;

    case SB_ENDSCROLL:
#ifdef VERTICAL_SCROLLBAR_DRAG_HACK
      if (vertical_drag_in_progress && sb)
	/* User has just dropped the thumb - finally update it */
	SetScrollInfo (SCROLLBAR_MSW_HANDLE (sb), SB_CTL,
		       &SCROLLBAR_MSW_INFO (sb), TRUE);
#endif
      vertical_drag_in_progress = 0;
      break;
    }
}

static int
can_scroll (struct scrollbar_instance *scrollbar)
{
  return scrollbar != NULL
	&& IsWindowVisible (SCROLLBAR_MSW_HANDLE (scrollbar))
	&& IsWindowEnabled (SCROLLBAR_MSW_HANDLE (scrollbar));
}

int
mswindows_handle_mousewheel_event (Lisp_Object frame, int keys, int delta,
				   POINTS where)
{
  int hasVertBar, hasHorzBar;	/* Indicates presence of scroll bars */
  unsigned wheelScrollLines = 0; /* Number of lines per wheel notch */
  Lisp_Object win = Qnil, corpore, sano;
  struct window_mirror *mirror;
  int mene, _mene, tekel, upharsin;
  Charbpos mens, sana;
  Charcount in;
  struct window *needle_in_haystack = 0;
  POINT donde_esta;

  donde_esta.x = where.x;
  donde_esta.y = where.y;

  /* Find the window to scroll */

  /* The mouse event could actually occur outside of the emacs
     frame. */
  if (ScreenToClient (FRAME_MSWINDOWS_HANDLE (XFRAME (frame)), 
		      &donde_esta) != 0)
    {
      /* stderr_out ("donde_esta: %d %d\n", donde_esta.x, donde_esta.y); */
      pixel_to_glyph_translation (XFRAME (frame), donde_esta.x, donde_esta.y,
				  &mene, &_mene, &tekel, &upharsin,
				  &needle_in_haystack,
				  &mens, &sana, &in, &corpore, &sano);
      
      if (needle_in_haystack)
	{
	  win = wrap_window (needle_in_haystack);
	  /* stderr_out ("found needle\n");
	     debug_print (win); */
	}
    }
  
  if (!needle_in_haystack)
    {
      win = FRAME_SELECTED_WINDOW (XFRAME (frame));
      needle_in_haystack = XWINDOW (win);
    }

  mirror = find_window_mirror (needle_in_haystack);

  /* Check that there is something to scroll */
  hasVertBar = can_scroll (mirror->scrollbar_vertical_instance);
  hasHorzBar = can_scroll (mirror->scrollbar_horizontal_instance);
  if (!hasVertBar && !hasHorzBar)
    return FALSE;

  /* No support for panning and zooming, so ignore */
  if (keys & (MK_SHIFT | MK_CONTROL))
    return FALSE;

  /* Get the number of lines per wheel delta */
  qxeSystemParametersInfo (SPI_GETWHEELSCROLLLINES, 0, &wheelScrollLines, 0);

  /* Calculate the amount to scroll */
  if (wheelScrollLines == WHEEL_PAGESCROLL)
    {
      /* Scroll by a page */
      Lisp_Object function;
      if (hasVertBar)
	function = delta > 0 ? Qscrollbar_page_up : Qscrollbar_page_down;
      else
	function = delta > 0 ? Qscrollbar_page_left : Qscrollbar_page_right;
      mswindows_enqueue_misc_user_event (frame, function, Fcons (win, Qnil));
    }
  else /* Scroll by a number of lines */
    {
      /* Calc the number of lines to scroll */
      int toScroll = MulDiv (delta, wheelScrollLines, WHEEL_DELTA);

      /* Do the scroll */
      Lisp_Object function;
      if (hasVertBar)
	function = delta > 0 ? Qscrollbar_line_up : Qscrollbar_line_down;
      else
	function = delta > 0 ? Qscrollbar_char_left : Qscrollbar_char_right;
      if (toScroll < 0)
	toScroll = -toScroll;
      while (toScroll--)
	mswindows_enqueue_misc_user_event (frame, function, win);
    }

  return TRUE;
}

#ifdef MEMORY_USAGE_STATS

static Bytecount
mswindows_compute_scrollbar_instance_usage (struct device *UNUSED (d),
					    struct scrollbar_instance *inst,
					    struct usage_stats *ustats)
{
  struct mswindows_scrollbar_data *data =
    (struct mswindows_scrollbar_data *) inst->scrollbar_data;

  return malloced_storage_size (data, sizeof (*data), ustats);
}

#endif /* MEMORY_USAGE_STATS */

/************************************************************************/
/*          Device-specific ghost specifiers initialization             */
/************************************************************************/

DEFUN ("mswindows-init-scrollbar-metrics", Fmswindows_init_scrollbar_metrics,
       1, 1, 0, /*
*/
       (locale))
{
  if (DEVICEP (locale))
    {
      add_spec_to_ghost_specifier (Vscrollbar_width,
				   make_int (GetSystemMetrics (SM_CXVSCROLL)),
				   locale, Qmswindows, Qnil);
      add_spec_to_ghost_specifier (Vscrollbar_height,
				   make_int (GetSystemMetrics (SM_CYHSCROLL)),
				   locale, Qmswindows, Qnil);
    }
  return Qnil;
}


/************************************************************************/
/*                            initialization                            */
/************************************************************************/

void
console_type_create_scrollbar_mswindows (void)
{
  CONSOLE_HAS_METHOD (mswindows, create_scrollbar_instance);
  CONSOLE_HAS_METHOD (mswindows, free_scrollbar_instance);
  CONSOLE_HAS_METHOD (mswindows, release_scrollbar_instance);
  CONSOLE_HAS_METHOD (mswindows, update_scrollbar_instance_values);
  CONSOLE_HAS_METHOD (mswindows, update_scrollbar_instance_status);
/*  CONSOLE_HAS_METHOD (mswindows, scrollbar_width_changed_in_frame); */
#ifdef MEMORY_USAGE_STATS
  CONSOLE_HAS_METHOD (mswindows, compute_scrollbar_instance_usage);
#endif
}

void
syms_of_scrollbar_mswindows (void)
{
  DEFSUBR (Fmswindows_init_scrollbar_metrics);
}

void
vars_of_scrollbar_mswindows (void)
{
  Fprovide (intern ("mswindows-scrollbars"));

  staticpro (&Vmswindows_scrollbar_instance_table);
  Vmswindows_scrollbar_instance_table =
    make_lisp_hash_table (100, HASH_TABLE_NON_WEAK, Qeq);
}