window.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD 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, version 2.
00006  * OpenTTD 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.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include <stdarg.h>
00014 #include "company_func.h"
00015 #include "gfx_func.h"
00016 #include "console_func.h"
00017 #include "console_gui.h"
00018 #include "viewport_func.h"
00019 #include "progress.h"
00020 #include "blitter/factory.hpp"
00021 #include "zoom_func.h"
00022 #include "vehicle_base.h"
00023 #include "window_func.h"
00024 #include "tilehighlight_func.h"
00025 #include "network/network.h"
00026 #include "querystring_gui.h"
00027 #include "widgets/dropdown_func.h"
00028 #include "strings_func.h"
00029 #include "settings_type.h"
00030 #include "newgrf_debug.h"
00031 #include "hotkeys.h"
00032 #include "toolbar_gui.h"
00033 #include "statusbar_gui.h"
00034 #include "error.h"
00035 #include "game/game.hpp"
00036 
00037 
00038 static Point _drag_delta; 
00039 static Window *_mouseover_last_w = NULL; 
00040 static Window *_last_scroll_window = NULL; 
00041 
00043 Window *_z_front_window = NULL;
00045 Window *_z_back_window  = NULL;
00046 
00048 bool _window_highlight_colour = false;
00049 
00050 /*
00051  * Window that currently has focus. - The main purpose is to generate
00052  * #FocusLost events, not to give next window in z-order focus when a
00053  * window is closed.
00054  */
00055 Window *_focused_window;
00056 
00057 Point _cursorpos_drag_start;
00058 
00059 int _scrollbar_start_pos;
00060 int _scrollbar_size;
00061 byte _scroller_click_timeout = 0;
00062 
00063 bool _scrolling_viewport;  
00064 bool _mouse_hovering;      
00065 
00066 SpecialMouseMode _special_mouse_mode; 
00067 
00069 WindowDesc::WindowDesc(WindowPosition def_pos, int16 def_width, int16 def_height,
00070       WindowClass window_class, WindowClass parent_class, uint32 flags,
00071       const NWidgetPart *nwid_parts, int16 nwid_length) :
00072   default_pos(def_pos),
00073   default_width(def_width),
00074   default_height(def_height),
00075   cls(window_class),
00076   parent_cls(parent_class),
00077   flags(flags),
00078   nwid_parts(nwid_parts),
00079   nwid_length(nwid_length)
00080 {
00081 }
00082 
00083 WindowDesc::~WindowDesc()
00084 {
00085 }
00086 
00096 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
00097 {
00098   const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
00099   if (line_height < 0) line_height = wid->resize_y;
00100   if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
00101   return (clickpos - (int)wid->pos_y - padding) / line_height;
00102 }
00103 
00107 void Window::DisableAllWidgetHighlight()
00108 {
00109   for (uint i = 0; i < this->nested_array_size; i++) {
00110     NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
00111     if (nwid == NULL) continue;
00112 
00113     if (nwid->IsHighlighted()) {
00114       nwid->SetHighlighted(TC_INVALID);
00115       this->SetWidgetDirty(i);
00116     }
00117   }
00118 
00119   CLRBITS(this->flags, WF_HIGHLIGHTED);
00120 }
00121 
00127 void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour)
00128 {
00129   assert(widget_index < this->nested_array_size);
00130 
00131   NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
00132   if (nwid == NULL) return;
00133 
00134   nwid->SetHighlighted(highlighted_colour);
00135   this->SetWidgetDirty(widget_index);
00136 
00137   if (highlighted_colour != TC_INVALID) {
00138     /* If we set a highlight, the window has a highlight */
00139     this->flags |= WF_HIGHLIGHTED;
00140   } else {
00141     /* If we disable a highlight, check all widgets if anyone still has a highlight */
00142     bool valid = false;
00143     for (uint i = 0; i < this->nested_array_size; i++) {
00144       NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
00145       if (nwid == NULL) continue;
00146       if (!nwid->IsHighlighted()) continue;
00147 
00148       valid = true;
00149     }
00150     /* If nobody has a highlight, disable the flag on the window */
00151     if (!valid) CLRBITS(this->flags, WF_HIGHLIGHTED);
00152   }
00153 }
00154 
00160 bool Window::IsWidgetHighlighted(byte widget_index) const
00161 {
00162   assert(widget_index < this->nested_array_size);
00163 
00164   const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
00165   if (nwid == NULL) return false;
00166 
00167   return nwid->IsHighlighted();
00168 }
00169 
00175 const Scrollbar *Window::GetScrollbar(uint widnum) const
00176 {
00177   return this->GetWidget<NWidgetScrollbar>(widnum);
00178 }
00179 
00185 Scrollbar *Window::GetScrollbar(uint widnum)
00186 {
00187   return this->GetWidget<NWidgetScrollbar>(widnum);
00188 }
00189 
00190 
00195 void SetFocusedWindow(Window *w)
00196 {
00197   if (_focused_window == w) return;
00198 
00199   /* Invalidate focused widget */
00200   if (_focused_window != NULL) {
00201     if (_focused_window->nested_focus != NULL) _focused_window->nested_focus->SetDirty(_focused_window);
00202   }
00203 
00204   /* Remember which window was previously focused */
00205   Window *old_focused = _focused_window;
00206   _focused_window = w;
00207 
00208   /* So we can inform it that it lost focus */
00209   if (old_focused != NULL) old_focused->OnFocusLost();
00210   if (_focused_window != NULL) _focused_window->OnFocus();
00211 }
00212 
00218 static bool EditBoxInGlobalFocus()
00219 {
00220   if (_focused_window == NULL) return false;
00221 
00222   /* The console does not have an edit box so a special case is needed. */
00223   if (_focused_window->window_class == WC_CONSOLE) return true;
00224 
00225   return _focused_window->nested_focus != NULL && _focused_window->nested_focus->type == WWT_EDITBOX;
00226 }
00227 
00231 void Window::UnfocusFocusedWidget()
00232 {
00233   if (this->nested_focus != NULL) {
00234     /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
00235     this->nested_focus->SetDirty(this);
00236     this->nested_focus = NULL;
00237   }
00238 }
00239 
00245 bool Window::SetFocusedWidget(byte widget_index)
00246 {
00247   /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
00248   if (widget_index >= this->nested_array_size) return false;
00249 
00250   assert(this->nested_array[widget_index] != NULL); // Setting focus to a non-existing widget is a bad idea.
00251   if (this->nested_focus != NULL) {
00252     if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
00253 
00254     /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
00255     this->nested_focus->SetDirty(this);
00256   }
00257   this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
00258   return true;
00259 }
00260 
00268 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
00269 {
00270   va_list wdg_list;
00271 
00272   va_start(wdg_list, widgets);
00273 
00274   while (widgets != WIDGET_LIST_END) {
00275     SetWidgetDisabledState(widgets, disab_stat);
00276     widgets = va_arg(wdg_list, int);
00277   }
00278 
00279   va_end(wdg_list);
00280 }
00281 
00287 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
00288 {
00289   va_list wdg_list;
00290 
00291   va_start(wdg_list, widgets);
00292 
00293   while (widgets != WIDGET_LIST_END) {
00294     SetWidgetLoweredState(widgets, lowered_stat);
00295     widgets = va_arg(wdg_list, int);
00296   }
00297 
00298   va_end(wdg_list);
00299 }
00300 
00305 void Window::RaiseButtons(bool autoraise)
00306 {
00307   for (uint i = 0; i < this->nested_array_size; i++) {
00308     if (this->nested_array[i] != NULL && ((this->nested_array[i]->type & ~WWB_PUSHBUTTON) < WWT_LAST || this->nested_array[i]->type == NWID_PUSHBUTTON_DROPDOWN) &&
00309         (!autoraise || (this->nested_array[i]->type & WWB_PUSHBUTTON)) && this->IsWidgetLowered(i)) {
00310       this->RaiseWidget(i);
00311       this->SetWidgetDirty(i);
00312     }
00313   }
00314 }
00315 
00320 void Window::SetWidgetDirty(byte widget_index) const
00321 {
00322   /* Sometimes this function is called before the window is even fully initialized */
00323   if (this->nested_array == NULL) return;
00324 
00325   this->nested_array[widget_index]->SetDirty(this);
00326 }
00327 
00333 void Window::HandleButtonClick(byte widget)
00334 {
00335   this->LowerWidget(widget);
00336   this->SetTimeout();
00337   this->SetWidgetDirty(widget);
00338 }
00339 
00340 static void StartWindowDrag(Window *w);
00341 static void StartWindowSizing(Window *w, bool to_left);
00342 
00350 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
00351 {
00352   NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
00353   WidgetType widget_type = (nw != NULL) ? nw->type : WWT_EMPTY;
00354 
00355   bool focused_widget_changed = false;
00356   /* If clicked on a window that previously did dot have focus */
00357   if (_focused_window != w &&                 // We already have focus, right?
00358       (w->desc_flags & WDF_NO_FOCUS) == 0 &&  // Don't lose focus to toolbars
00359       widget_type != WWT_CLOSEBOX) {          // Don't change focused window if 'X' (close button) was clicked
00360     focused_widget_changed = true;
00361     if (_focused_window != NULL) {
00362       _focused_window->OnFocusLost();
00363 
00364       /* The window that lost focus may have had opened a OSK, window so close it, unless the user has clicked on the OSK window. */
00365       if (w->window_class != WC_OSK) DeleteWindowById(WC_OSK, 0);
00366     }
00367     SetFocusedWindow(w);
00368     w->OnFocus();
00369   }
00370 
00371   if (nw == NULL) return; // exit if clicked outside of widgets
00372 
00373   /* don't allow any interaction if the button has been disabled */
00374   if (nw->IsDisabled()) return;
00375 
00376   int widget_index = nw->index; 
00377 
00378   /* Clicked on a widget that is not disabled.
00379    * So unless the clicked widget is the caption bar, change focus to this widget */
00380   if (widget_type != WWT_CAPTION) {
00381     /* Close the OSK window if a edit box loses focus */
00382     if (w->nested_focus != NULL &&  w->nested_focus->type == WWT_EDITBOX && w->nested_focus != nw && w->window_class != WC_OSK) {
00383       DeleteWindowById(WC_OSK, 0);
00384     }
00385 
00386     /* focused_widget_changed is 'now' only true if the window this widget
00387      * is in gained focus. In that case it must remain true, also if the
00388      * local widget focus did not change. As such it's the logical-or of
00389      * both changed states.
00390      *
00391      * If this is not preserved, then the OSK window would be opened when
00392      * a user has the edit box focused and then click on another window and
00393      * then back again on the edit box (to type some text).
00394      */
00395     focused_widget_changed |= w->SetFocusedWidget(widget_index);
00396   }
00397 
00398   /* Close any child drop down menus. If the button pressed was the drop down
00399    * list's own button, then we should not process the click any further. */
00400   if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
00401 
00402   if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
00403 
00404   switch (widget_type) {
00405     case NWID_VSCROLLBAR:
00406     case NWID_HSCROLLBAR:
00407       ScrollbarClickHandler(w, nw, x, y);
00408       break;
00409 
00410     case WWT_EDITBOX:
00411       if (!focused_widget_changed) { // Only open the OSK window if clicking on an already focused edit box
00412         /* Open the OSK window if clicked on an edit box */
00413         QueryStringBaseWindow *qs = dynamic_cast<QueryStringBaseWindow *>(w);
00414         if (qs != NULL) {
00415           qs->OnOpenOSKWindow(widget_index);
00416         }
00417       }
00418       break;
00419 
00420     case WWT_CLOSEBOX: // 'X'
00421       delete w;
00422       return;
00423 
00424     case WWT_CAPTION: // 'Title bar'
00425       StartWindowDrag(w);
00426       return;
00427 
00428     case WWT_RESIZEBOX:
00429       /* When the resize widget is on the left size of the window
00430        * we assume that that button is used to resize to the left. */
00431       StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
00432       nw->SetDirty(w);
00433       return;
00434 
00435     case WWT_DEBUGBOX:
00436       w->ShowNewGRFInspectWindow();
00437       break;
00438 
00439     case WWT_SHADEBOX:
00440       nw->SetDirty(w);
00441       w->SetShaded(!w->IsShaded());
00442       return;
00443 
00444     case WWT_STICKYBOX:
00445       w->flags ^= WF_STICKY;
00446       nw->SetDirty(w);
00447       return;
00448 
00449     default:
00450       break;
00451   }
00452 
00453   /* Widget has no index, so the window is not interested in it. */
00454   if (widget_index < 0) return;
00455 
00456   /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
00457   if (w->IsWidgetHighlighted(widget_index)) {
00458     w->SetWidgetHighlight(widget_index, TC_INVALID);
00459     Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
00460   }
00461 
00462   Point pt = { x, y };
00463   w->OnClick(pt, widget_index, click_count);
00464 }
00465 
00472 static void DispatchRightClickEvent(Window *w, int x, int y)
00473 {
00474   NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
00475   if (wid == NULL) return;
00476 
00477   /* No widget to handle, or the window is not interested in it. */
00478   if (wid->index >= 0) {
00479     Point pt = { x, y };
00480     if (w->OnRightClick(pt, wid->index)) return;
00481   }
00482 
00483   if (_settings_client.gui.hover_delay == 0 && wid->tool_tip != 0) GuiShowTooltips(w, wid->tool_tip, 0, NULL, TCC_RIGHT_CLICK);
00484 }
00485 
00492 static void DispatchHoverEvent(Window *w, int x, int y)
00493 {
00494   NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
00495 
00496   /* No widget to handle */
00497   if (wid == NULL) return;
00498 
00499   /* Show the tooltip if there is any */
00500   if (wid->tool_tip != 0) {
00501     GuiShowTooltips(w, wid->tool_tip);
00502     return;
00503   }
00504 
00505   /* Widget has no index, so the window is not interested in it. */
00506   if (wid->index < 0) return;
00507 
00508   Point pt = { x, y };
00509   w->OnHover(pt, wid->index);
00510 }
00511 
00519 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
00520 {
00521   if (nwid == NULL) return;
00522 
00523   /* Using wheel on caption/shade-box shades or unshades the window. */
00524   if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
00525     w->SetShaded(wheel < 0);
00526     return;
00527   }
00528 
00529   /* Wheeling a vertical scrollbar. */
00530   if (nwid->type == NWID_VSCROLLBAR) {
00531     NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
00532     if (sb->GetCount() > sb->GetCapacity()) {
00533       sb->UpdatePosition(wheel);
00534       w->SetDirty();
00535     }
00536     return;
00537   }
00538 
00539   /* Scroll the widget attached to the scrollbar. */
00540   Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : NULL);
00541   if (sb != NULL && sb->GetCount() > sb->GetCapacity()) {
00542     sb->UpdatePosition(wheel);
00543     w->SetDirty();
00544   }
00545 }
00546 
00552 static bool MayBeShown(const Window *w)
00553 {
00554   /* If we're not modal, everything is okay. */
00555   if (!HasModalProgress()) return true;
00556 
00557   switch (w->window_class) {
00558     case WC_MAIN_WINDOW:    
00559     case WC_MODAL_PROGRESS: 
00560     case WC_CONFIRM_POPUP_QUERY: 
00561       return true;
00562 
00563     default:
00564       return false;
00565   }
00566 }
00567 
00580 static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
00581 {
00582   const Window *v;
00583   FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
00584     if (MayBeShown(v) &&
00585         right > v->left &&
00586         bottom > v->top &&
00587         left < v->left + v->width &&
00588         top < v->top + v->height) {
00589       /* v and rectangle intersect with each other */
00590       int x;
00591 
00592       if (left < (x = v->left)) {
00593         DrawOverlappedWindow(w, left, top, x, bottom);
00594         DrawOverlappedWindow(w, x, top, right, bottom);
00595         return;
00596       }
00597 
00598       if (right > (x = v->left + v->width)) {
00599         DrawOverlappedWindow(w, left, top, x, bottom);
00600         DrawOverlappedWindow(w, x, top, right, bottom);
00601         return;
00602       }
00603 
00604       if (top < (x = v->top)) {
00605         DrawOverlappedWindow(w, left, top, right, x);
00606         DrawOverlappedWindow(w, left, x, right, bottom);
00607         return;
00608       }
00609 
00610       if (bottom > (x = v->top + v->height)) {
00611         DrawOverlappedWindow(w, left, top, right, x);
00612         DrawOverlappedWindow(w, left, x, right, bottom);
00613         return;
00614       }
00615 
00616       return;
00617     }
00618   }
00619 
00620   /* Setup blitter, and dispatch a repaint event to window *wz */
00621   DrawPixelInfo *dp = _cur_dpi;
00622   dp->width = right - left;
00623   dp->height = bottom - top;
00624   dp->left = left - w->left;
00625   dp->top = top - w->top;
00626   dp->pitch = _screen.pitch;
00627   dp->dst_ptr = BlitterFactoryBase::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
00628   dp->zoom = ZOOM_LVL_NORMAL;
00629   w->OnPaint();
00630 }
00631 
00640 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
00641 {
00642   Window *w;
00643   DrawPixelInfo bk;
00644   _cur_dpi = &bk;
00645 
00646   FOR_ALL_WINDOWS_FROM_BACK(w) {
00647     if (MayBeShown(w) &&
00648         right > w->left &&
00649         bottom > w->top &&
00650         left < w->left + w->width &&
00651         top < w->top + w->height) {
00652       /* Window w intersects with the rectangle => needs repaint */
00653       DrawOverlappedWindow(w, left, top, right, bottom);
00654     }
00655   }
00656 }
00657 
00662 void Window::SetDirty() const
00663 {
00664   SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
00665 }
00666 
00673 void Window::ReInit(int rx, int ry)
00674 {
00675   this->SetDirty(); // Mark whole current window as dirty.
00676 
00677   /* Save current size. */
00678   int window_width  = this->width;
00679   int window_height = this->height;
00680 
00681   this->OnInit();
00682   /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
00683   this->nested_root->SetupSmallestSize(this, false);
00684   this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
00685   this->width  = this->nested_root->smallest_x;
00686   this->height = this->nested_root->smallest_y;
00687   this->resize.step_width  = this->nested_root->resize_x;
00688   this->resize.step_height = this->nested_root->resize_y;
00689 
00690   /* Resize as close to the original size + requested resize as possible. */
00691   window_width  = max(window_width  + rx, this->width);
00692   window_height = max(window_height + ry, this->height);
00693   int dx = (this->resize.step_width  == 0) ? 0 : window_width  - this->width;
00694   int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
00695   /* dx and dy has to go by step.. calculate it.
00696    * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
00697   if (this->resize.step_width  > 1) dx -= dx % (int)this->resize.step_width;
00698   if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
00699 
00700   ResizeWindow(this, dx, dy);
00701   /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
00702 }
00703 
00709 void Window::SetShaded(bool make_shaded)
00710 {
00711   if (this->shade_select == NULL) return;
00712 
00713   int desired = make_shaded ? SZSP_HORIZONTAL : 0;
00714   if (this->shade_select->shown_plane != desired) {
00715     if (make_shaded) {
00716       this->unshaded_size.width  = this->width;
00717       this->unshaded_size.height = this->height;
00718       this->shade_select->SetDisplayedPlane(desired);
00719       this->ReInit(0, -this->height);
00720     } else {
00721       this->shade_select->SetDisplayedPlane(desired);
00722       int dx = ((int)this->unshaded_size.width  > this->width)  ? (int)this->unshaded_size.width  - this->width  : 0;
00723       int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
00724       this->ReInit(dx, dy);
00725     }
00726   }
00727 }
00728 
00735 static Window *FindChildWindow(const Window *w, WindowClass wc)
00736 {
00737   Window *v;
00738   FOR_ALL_WINDOWS_FROM_BACK(v) {
00739     if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
00740   }
00741 
00742   return NULL;
00743 }
00744 
00749 void Window::DeleteChildWindows(WindowClass wc) const
00750 {
00751   Window *child = FindChildWindow(this, wc);
00752   while (child != NULL) {
00753     delete child;
00754     child = FindChildWindow(this, wc);
00755   }
00756 }
00757 
00761 Window::~Window()
00762 {
00763   if (_thd.window_class == this->window_class &&
00764       _thd.window_number == this->window_number) {
00765     ResetObjectToPlace();
00766   }
00767 
00768   /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
00769   if (_mouseover_last_w == this) _mouseover_last_w = NULL;
00770 
00771   /* We can't scroll the window when it's closed. */
00772   if (_last_scroll_window == this) _last_scroll_window = NULL;
00773 
00774   /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
00775   if (_focused_window == this) _focused_window = NULL;
00776 
00777   this->DeleteChildWindows();
00778 
00779   if (this->viewport != NULL) DeleteWindowViewport(this);
00780 
00781   this->SetDirty();
00782 
00783   free(this->nested_array); // Contents is released through deletion of #nested_root.
00784   delete this->nested_root;
00785 
00786   this->window_class = WC_INVALID;
00787 }
00788 
00795 Window *FindWindowById(WindowClass cls, WindowNumber number)
00796 {
00797   Window *w;
00798   FOR_ALL_WINDOWS_FROM_BACK(w) {
00799     if (w->window_class == cls && w->window_number == number) return w;
00800   }
00801 
00802   return NULL;
00803 }
00804 
00811 Window *FindWindowByClass(WindowClass cls)
00812 {
00813   Window *w;
00814   FOR_ALL_WINDOWS_FROM_BACK(w) {
00815     if (w->window_class == cls) return w;
00816   }
00817 
00818   return NULL;
00819 }
00820 
00827 void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
00828 {
00829   Window *w = FindWindowById(cls, number);
00830   if (force || w == NULL ||
00831       (w->flags & WF_STICKY) == 0) {
00832     delete w;
00833   }
00834 }
00835 
00840 void DeleteWindowByClass(WindowClass cls)
00841 {
00842   Window *w;
00843 
00844 restart_search:
00845   /* When we find the window to delete, we need to restart the search
00846    * as deleting this window could cascade in deleting (many) others
00847    * anywhere in the z-array */
00848   FOR_ALL_WINDOWS_FROM_BACK(w) {
00849     if (w->window_class == cls) {
00850       delete w;
00851       goto restart_search;
00852     }
00853   }
00854 }
00855 
00862 void DeleteCompanyWindows(CompanyID id)
00863 {
00864   Window *w;
00865 
00866 restart_search:
00867   /* When we find the window to delete, we need to restart the search
00868    * as deleting this window could cascade in deleting (many) others
00869    * anywhere in the z-array */
00870   FOR_ALL_WINDOWS_FROM_BACK(w) {
00871     if (w->owner == id) {
00872       delete w;
00873       goto restart_search;
00874     }
00875   }
00876 
00877   /* Also delete the company specific windows that don't have a company-colour. */
00878   DeleteWindowById(WC_BUY_COMPANY, id);
00879 }
00880 
00888 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
00889 {
00890   Window *w;
00891   FOR_ALL_WINDOWS_FROM_BACK(w) {
00892     if (w->owner != old_owner) continue;
00893 
00894     switch (w->window_class) {
00895       case WC_COMPANY_COLOUR:
00896       case WC_FINANCES:
00897       case WC_STATION_LIST:
00898       case WC_TRAINS_LIST:
00899       case WC_ROADVEH_LIST:
00900       case WC_SHIPS_LIST:
00901       case WC_AIRCRAFT_LIST:
00902       case WC_BUY_COMPANY:
00903       case WC_COMPANY:
00904       case WC_COMPANY_INFRASTRUCTURE:
00905         continue;
00906 
00907       default:
00908         w->owner = new_owner;
00909         break;
00910     }
00911   }
00912 }
00913 
00914 static void BringWindowToFront(Window *w);
00915 
00923 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
00924 {
00925   Window *w = FindWindowById(cls, number);
00926 
00927   if (w != NULL) {
00928     if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
00929 
00930     w->SetWhiteBorder();
00931     BringWindowToFront(w);
00932     w->SetDirty();
00933   }
00934 
00935   return w;
00936 }
00937 
00938 static inline bool IsVitalWindow(const Window *w)
00939 {
00940   switch (w->window_class) {
00941     case WC_MAIN_TOOLBAR:
00942     case WC_STATUS_BAR:
00943     case WC_NEWS_WINDOW:
00944     case WC_SEND_NETWORK_MSG:
00945       return true;
00946 
00947     default:
00948       return false;
00949   }
00950 }
00951 
00960 static uint GetWindowZPriority(const Window *w)
00961 {
00962   assert(w->window_class != WC_INVALID);
00963 
00964   uint z_priority = 0;
00965 
00966   switch (w->window_class) {
00967     case WC_ENDSCREEN:
00968       ++z_priority;
00969 
00970     case WC_HIGHSCORE:
00971       ++z_priority;
00972 
00973     case WC_TOOLTIPS:
00974       ++z_priority;
00975 
00976     case WC_DROPDOWN_MENU:
00977       ++z_priority;
00978 
00979     case WC_MAIN_TOOLBAR:
00980     case WC_STATUS_BAR:
00981       ++z_priority;
00982 
00983     case WC_OSK:
00984       ++z_priority;
00985 
00986     case WC_QUERY_STRING:
00987     case WC_SEND_NETWORK_MSG:
00988       ++z_priority;
00989 
00990     case WC_ERRMSG:
00991     case WC_CONFIRM_POPUP_QUERY:
00992     case WC_MODAL_PROGRESS:
00993     case WC_NETWORK_STATUS_WINDOW:
00994       ++z_priority;
00995 
00996     case WC_GENERATE_LANDSCAPE:
00997     case WC_SAVELOAD:
00998     case WC_GAME_OPTIONS:
00999     case WC_CUSTOM_CURRENCY:
01000     case WC_NETWORK_WINDOW:
01001     case WC_GRF_PARAMETERS:
01002     case WC_AI_LIST:
01003     case WC_AI_SETTINGS:
01004     case WC_TEXTFILE:
01005       ++z_priority;
01006 
01007     case WC_CONSOLE:
01008       ++z_priority;
01009 
01010     case WC_NEWS_WINDOW:
01011       ++z_priority;
01012 
01013     default:
01014       ++z_priority;
01015 
01016     case WC_MAIN_WINDOW:
01017       return z_priority;
01018   }
01019 }
01020 
01025 static void AddWindowToZOrdering(Window *w)
01026 {
01027   assert(w->z_front == NULL && w->z_back == NULL);
01028 
01029   if (_z_front_window == NULL) {
01030     /* It's the only window. */
01031     _z_front_window = _z_back_window = w;
01032     w->z_front = w->z_back = NULL;
01033   } else {
01034     /* Search down the z-ordering for its location. */
01035     Window *v = _z_front_window;
01036     uint last_z_priority = UINT_MAX;
01037     while (v != NULL && (v->window_class == WC_INVALID || GetWindowZPriority(v) > GetWindowZPriority(w))) {
01038       if (v->window_class != WC_INVALID) {
01039         /* Sanity check z-ordering, while we're at it. */
01040         assert(last_z_priority >= GetWindowZPriority(v));
01041         last_z_priority = GetWindowZPriority(v);
01042       }
01043 
01044       v = v->z_back;
01045     }
01046 
01047     if (v == NULL) {
01048       /* It's the new back window. */
01049       w->z_front = _z_back_window;
01050       w->z_back = NULL;
01051       _z_back_window->z_back = w;
01052       _z_back_window = w;
01053     } else if (v == _z_front_window) {
01054       /* It's the new front window. */
01055       w->z_front = NULL;
01056       w->z_back = _z_front_window;
01057       _z_front_window->z_front = w;
01058       _z_front_window = w;
01059     } else {
01060       /* It's somewhere else in the z-ordering. */
01061       w->z_front = v->z_front;
01062       w->z_back = v;
01063       v->z_front->z_back = w;
01064       v->z_front = w;
01065     }
01066   }
01067 }
01068 
01069 
01074 static void RemoveWindowFromZOrdering(Window *w)
01075 {
01076   if (w->z_front == NULL) {
01077     assert(_z_front_window == w);
01078     _z_front_window = w->z_back;
01079   } else {
01080     w->z_front->z_back = w->z_back;
01081   }
01082 
01083   if (w->z_back == NULL) {
01084     assert(_z_back_window == w);
01085     _z_back_window = w->z_front;
01086   } else {
01087     w->z_back->z_front = w->z_front;
01088   }
01089 
01090   w->z_front = w->z_back = NULL;
01091 }
01092 
01098 static void BringWindowToFront(Window *w)
01099 {
01100   RemoveWindowFromZOrdering(w);
01101   AddWindowToZOrdering(w);
01102 
01103   w->SetDirty();
01104 }
01105 
01114 void Window::InitializeData(const WindowDesc *desc, WindowNumber window_number)
01115 {
01116   /* Set up window properties; some of them are needed to set up smallest size below */
01117   this->window_class = desc->cls;
01118   this->SetWhiteBorder();
01119   if (desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
01120   this->owner = INVALID_OWNER;
01121   this->nested_focus = NULL;
01122   this->window_number = window_number;
01123   this->desc_flags = desc->flags;
01124 
01125   this->OnInit();
01126   /* Initialize nested widget tree. */
01127   if (this->nested_array == NULL) {
01128     this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
01129     this->nested_root->SetupSmallestSize(this, true);
01130   } else {
01131     this->nested_root->SetupSmallestSize(this, false);
01132   }
01133   /* Initialize to smallest size. */
01134   this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
01135 
01136   /* Further set up window properties,
01137    * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
01138   this->resize.step_width  = this->nested_root->resize_x;
01139   this->resize.step_height = this->nested_root->resize_y;
01140 
01141   /* Give focus to the opened window unless it is the OSK window or a text box
01142    * of focused window has focus (so we don't interrupt typing). But if the new
01143    * window has a text box, then take focus anyway. */
01144   if (this->window_class != WC_OSK && (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != NULL)) SetFocusedWindow(this);
01145 
01146   /* Insert the window into the correct location in the z-ordering. */
01147   AddWindowToZOrdering(this);
01148 }
01149 
01157 void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
01158 {
01159   this->left = x;
01160   this->top = y;
01161   this->width = sm_width;
01162   this->height = sm_height;
01163 }
01164 
01175 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
01176 {
01177   def_width  = max(def_width,  this->width); // Don't allow default size to be smaller than smallest size
01178   def_height = max(def_height, this->height);
01179   /* Try to make windows smaller when our window is too small.
01180    * w->(width|height) is normally the same as min_(width|height),
01181    * but this way the GUIs can be made a little more dynamic;
01182    * one can use the same spec for multiple windows and those
01183    * can then determine the real minimum size of the window. */
01184   if (this->width != def_width || this->height != def_height) {
01185     /* Think about the overlapping toolbars when determining the minimum window size */
01186     int free_height = _screen.height;
01187     const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
01188     if (wt != NULL) free_height -= wt->height;
01189     wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
01190     if (wt != NULL) free_height -= wt->height;
01191 
01192     int enlarge_x = max(min(def_width  - this->width,  _screen.width - this->width),  0);
01193     int enlarge_y = max(min(def_height - this->height, free_height   - this->height), 0);
01194 
01195     /* X and Y has to go by step.. calculate it.
01196      * The cast to int is necessary else x/y are implicitly casted to
01197      * unsigned int, which won't work. */
01198     if (this->resize.step_width  > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
01199     if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
01200 
01201     ResizeWindow(this, enlarge_x, enlarge_y);
01202     /* ResizeWindow() calls this->OnResize(). */
01203   } else {
01204     /* Always call OnResize; that way the scrollbars and matrices get initialized. */
01205     this->OnResize();
01206   }
01207 
01208   int nx = this->left;
01209   int ny = this->top;
01210 
01211   if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
01212 
01213   const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
01214   ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
01215   nx = max(nx, 0);
01216 
01217   if (this->viewport != NULL) {
01218     this->viewport->left += nx - this->left;
01219     this->viewport->top  += ny - this->top;
01220   }
01221   this->left = nx;
01222   this->top = ny;
01223 
01224   this->SetDirty();
01225 }
01226 
01238 static bool IsGoodAutoPlace1(int left, int top, int width, int height, Point &pos)
01239 {
01240   int right  = width + left;
01241   int bottom = height + top;
01242 
01243   const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
01244   if (left < 0 || (main_toolbar != NULL && top < main_toolbar->height) || right > _screen.width || bottom > _screen.height) return false;
01245 
01246   /* Make sure it is not obscured by any window. */
01247   const Window *w;
01248   FOR_ALL_WINDOWS_FROM_BACK(w) {
01249     if (w->window_class == WC_MAIN_WINDOW) continue;
01250 
01251     if (right > w->left &&
01252         w->left + w->width > left &&
01253         bottom > w->top &&
01254         w->top + w->height > top) {
01255       return false;
01256     }
01257   }
01258 
01259   pos.x = left;
01260   pos.y = top;
01261   return true;
01262 }
01263 
01275 static bool IsGoodAutoPlace2(int left, int top, int width, int height, Point &pos)
01276 {
01277   /* Left part of the rectangle may be at most 1/4 off-screen,
01278    * right part of the rectangle may be at most 1/2 off-screen
01279    */
01280   if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
01281   /* Bottom part of the rectangle may be at most 1/4 off-screen */
01282   if (top < 22 || top > _screen.height - (height >> 2)) return false;
01283 
01284   /* Make sure it is not obscured by any window. */
01285   const Window *w;
01286   FOR_ALL_WINDOWS_FROM_BACK(w) {
01287     if (w->window_class == WC_MAIN_WINDOW) continue;
01288 
01289     if (left + width > w->left &&
01290         w->left + w->width > left &&
01291         top + height > w->top &&
01292         w->top + w->height > top) {
01293       return false;
01294     }
01295   }
01296 
01297   pos.x = left;
01298   pos.y = top;
01299   return true;
01300 }
01301 
01308 static Point GetAutoPlacePosition(int width, int height)
01309 {
01310   Point pt;
01311 
01312   /* First attempt, try top-left of the screen */
01313   const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
01314   if (IsGoodAutoPlace1(0, main_toolbar != NULL ? main_toolbar->height + 2 : 2, width, height, pt)) return pt;
01315 
01316   /* Second attempt, try around all existing windows with a distance of 2 pixels.
01317    * The new window must be entirely on-screen, and not overlap with an existing window.
01318    * Eight starting points are tried, two at each corner.
01319    */
01320   const Window *w;
01321   FOR_ALL_WINDOWS_FROM_BACK(w) {
01322     if (w->window_class == WC_MAIN_WINDOW) continue;
01323 
01324     if (IsGoodAutoPlace1(w->left + w->width + 2, w->top, width, height, pt)) return pt;
01325     if (IsGoodAutoPlace1(w->left - width - 2,    w->top, width, height, pt)) return pt;
01326     if (IsGoodAutoPlace1(w->left, w->top + w->height + 2, width, height, pt)) return pt;
01327     if (IsGoodAutoPlace1(w->left, w->top - height - 2,    width, height, pt)) return pt;
01328     if (IsGoodAutoPlace1(w->left + w->width + 2, w->top + w->height - height, width, height, pt)) return pt;
01329     if (IsGoodAutoPlace1(w->left - width - 2,    w->top + w->height - height, width, height, pt)) return pt;
01330     if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height + 2, width, height, pt)) return pt;
01331     if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height - 2,    width, height, pt)) return pt;
01332   }
01333 
01334   /* Third attempt, try around all existing windows with a distance of 2 pixels.
01335    * The new window may be partly off-screen, and must not overlap with an existing window.
01336    * Only four starting points are tried.
01337    */
01338   FOR_ALL_WINDOWS_FROM_BACK(w) {
01339     if (w->window_class == WC_MAIN_WINDOW) continue;
01340 
01341     if (IsGoodAutoPlace2(w->left + w->width + 2, w->top, width, height, pt)) return pt;
01342     if (IsGoodAutoPlace2(w->left - width - 2,    w->top, width, height, pt)) return pt;
01343     if (IsGoodAutoPlace2(w->left, w->top + w->height + 2, width, height, pt)) return pt;
01344     if (IsGoodAutoPlace2(w->left, w->top - height - 2,    width, height, pt)) return pt;
01345   }
01346 
01347   /* Fourth and final attempt, put window at diagonal starting from (0, 24), try multiples
01348    * of (+5, +5)
01349    */
01350   int left = 0, top = 24;
01351 
01352 restart:
01353   FOR_ALL_WINDOWS_FROM_BACK(w) {
01354     if (w->left == left && w->top == top) {
01355       left += 5;
01356       top += 5;
01357       goto restart;
01358     }
01359   }
01360 
01361   pt.x = left;
01362   pt.y = top;
01363   return pt;
01364 }
01365 
01372 Point GetToolbarAlignedWindowPosition(int window_width)
01373 {
01374   const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
01375   assert(w != NULL);
01376   Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
01377   return pt;
01378 }
01379 
01397 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
01398 {
01399   Point pt;
01400   const Window *w;
01401 
01402   int16 default_width  = max(desc->default_width,  sm_width);
01403   int16 default_height = max(desc->default_height, sm_height);
01404 
01405   if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ &&
01406       (w = FindWindowById(desc->parent_cls, window_number)) != NULL &&
01407       w->left < _screen.width - 20 && w->left > -60 && w->top < _screen.height - 20) {
01408 
01409     pt.x = w->left + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 0 : 10);
01410     if (pt.x > _screen.width + 10 - default_width) {
01411       pt.x = (_screen.width + 10 - default_width) - 20;
01412     }
01413     pt.y = w->top + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? w->height : 10);
01414     return pt;
01415   }
01416 
01417   switch (desc->default_pos) {
01418     case WDP_ALIGN_TOOLBAR: // Align to the toolbar
01419       return GetToolbarAlignedWindowPosition(default_width);
01420 
01421     case WDP_AUTO: // Find a good automatic position for the window
01422       return GetAutoPlacePosition(default_width, default_height);
01423 
01424     case WDP_CENTER: // Centre the window horizontally
01425       pt.x = (_screen.width - default_width) / 2;
01426       pt.y = (_screen.height - default_height) / 2;
01427       break;
01428 
01429     case WDP_MANUAL:
01430       pt.x = 0;
01431       pt.y = 0;
01432       break;
01433 
01434     default:
01435       NOT_REACHED();
01436   }
01437 
01438   return pt;
01439 }
01440 
01441 /* virtual */ Point Window::OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
01442 {
01443   return LocalGetWindowPlacement(desc, sm_width, sm_height, window_number);
01444 }
01445 
01454 void Window::CreateNestedTree(const WindowDesc *desc, bool fill_nested)
01455 {
01456   int biggest_index = -1;
01457   this->nested_root = MakeWindowNWidgetTree(desc->nwid_parts, desc->nwid_length, &biggest_index, &this->shade_select);
01458   this->nested_array_size = (uint)(biggest_index + 1);
01459 
01460   if (fill_nested) {
01461     this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
01462     this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
01463   }
01464 }
01465 
01471 void Window::FinishInitNested(const WindowDesc *desc, WindowNumber window_number)
01472 {
01473   this->InitializeData(desc, window_number);
01474   Point pt = this->OnInitialPosition(desc, this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
01475   this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
01476   this->FindWindowPlacementAndResize(desc->default_width, desc->default_height);
01477 }
01478 
01484 void Window::InitNested(const WindowDesc *desc, WindowNumber window_number)
01485 {
01486   this->CreateNestedTree(desc, false);
01487   this->FinishInitNested(desc, window_number);
01488 }
01489 
01491 Window::Window() : scrolling_scrollbar(-1)
01492 {
01493 }
01494 
01502 Window *FindWindowFromPt(int x, int y)
01503 {
01504   Window *w;
01505   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01506     if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
01507       return w;
01508     }
01509   }
01510 
01511   return NULL;
01512 }
01513 
01517 void InitWindowSystem()
01518 {
01519   IConsoleClose();
01520 
01521   _z_back_window = NULL;
01522   _z_front_window = NULL;
01523   _focused_window = NULL;
01524   _mouseover_last_w = NULL;
01525   _last_scroll_window = NULL;
01526   _scrolling_viewport = false;
01527   _mouse_hovering = false;
01528 
01529   NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
01530   NWidgetScrollbar::InvalidateDimensionCache();
01531 
01532   ShowFirstError();
01533 }
01534 
01538 void UnInitWindowSystem()
01539 {
01540   UnshowCriticalError();
01541 
01542   Window *w;
01543   FOR_ALL_WINDOWS_FROM_FRONT(w) delete w;
01544 
01545   for (w = _z_front_window; w != NULL; /* nothing */) {
01546     Window *to_del = w;
01547     w = w->z_back;
01548     free(to_del);
01549   }
01550 
01551   _z_front_window = NULL;
01552   _z_back_window = NULL;
01553 }
01554 
01558 void ResetWindowSystem()
01559 {
01560   UnInitWindowSystem();
01561   InitWindowSystem();
01562   _thd.Reset();
01563 }
01564 
01565 static void DecreaseWindowCounters()
01566 {
01567   Window *w;
01568   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01569     if (_scroller_click_timeout == 0) {
01570       /* Unclick scrollbar buttons if they are pressed. */
01571       for (uint i = 0; i < w->nested_array_size; i++) {
01572         NWidgetBase *nwid = w->nested_array[i];
01573         if (nwid != NULL && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
01574           NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
01575           if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
01576             sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
01577             w->scrolling_scrollbar = -1;
01578             sb->SetDirty(w);
01579           }
01580         }
01581       }
01582     }
01583     w->OnMouseLoop();
01584   }
01585 
01586   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01587     if ((w->flags & WF_TIMEOUT) && --w->timeout_timer == 0) {
01588       CLRBITS(w->flags, WF_TIMEOUT);
01589 
01590       w->OnTimeout();
01591       if (w->desc_flags & WDF_UNCLICK_BUTTONS) w->RaiseButtons(true);
01592     }
01593   }
01594 }
01595 
01596 static void HandlePlacePresize()
01597 {
01598   if (_special_mouse_mode != WSM_PRESIZE) return;
01599 
01600   Window *w = _thd.GetCallbackWnd();
01601   if (w == NULL) return;
01602 
01603   Point pt = GetTileBelowCursor();
01604   if (pt.x == -1) {
01605     _thd.selend.x = -1;
01606     return;
01607   }
01608 
01609   w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
01610 }
01611 
01616 static EventState HandleMouseDragDrop()
01617 {
01618   if (_special_mouse_mode != WSM_DRAGDROP) return ES_NOT_HANDLED;
01619 
01620   if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
01621 
01622   Window *w = _thd.GetCallbackWnd();
01623   if (w != NULL) {
01624     /* Send an event in client coordinates. */
01625     Point pt;
01626     pt.x = _cursor.pos.x - w->left;
01627     pt.y = _cursor.pos.y - w->top;
01628     if (_left_button_down) {
01629       w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
01630     } else {
01631       w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
01632     }
01633   }
01634 
01635   if (!_left_button_down) ResetObjectToPlace(); // Button released, finished dragging.
01636   return ES_HANDLED;
01637 }
01638 
01640 static void HandleMouseOver()
01641 {
01642   Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
01643 
01644   /* We changed window, put a MOUSEOVER event to the last window */
01645   if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
01646     /* Reset mouse-over coordinates of previous window */
01647     Point pt = { -1, -1 };
01648     _mouseover_last_w->OnMouseOver(pt, 0);
01649   }
01650 
01651   /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
01652   _mouseover_last_w = w;
01653 
01654   if (w != NULL) {
01655     /* send an event in client coordinates. */
01656     Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
01657     const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
01658     if (widget != NULL) w->OnMouseOver(pt, widget->index);
01659   }
01660 }
01661 
01663 static const int MIN_VISIBLE_TITLE_BAR = 13;
01664 
01666 enum PreventHideDirection {
01667   PHD_UP,   
01668   PHD_DOWN, 
01669 };
01670 
01681 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
01682 {
01683   if (v == NULL) return;
01684 
01685   int v_bottom = v->top + v->height;
01686   int v_right = v->left + v->width;
01687   int safe_y = (dir == PHD_UP) ? (v->top - MIN_VISIBLE_TITLE_BAR - rect.top) : (v_bottom + MIN_VISIBLE_TITLE_BAR - rect.bottom); // Compute safe vertical position.
01688 
01689   if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
01690   if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
01691 
01692   /* Vertically, the rectangle is hidden behind v. */
01693   if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
01694     if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
01695     return;
01696   }
01697   if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
01698     if (v_right > _screen.width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
01699     return;
01700   }
01701 
01702   /* Horizontally also hidden, force movement to a safe area. */
01703   if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
01704     *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
01705   } else if (px + rect.right > v_right && v_right <= _screen.width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
01706     *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
01707   } else {
01708     *ny = safe_y;
01709   }
01710 }
01711 
01719 static void EnsureVisibleCaption(Window *w, int nx, int ny)
01720 {
01721   /* Search for the title bar rectangle. */
01722   Rect caption_rect;
01723   const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
01724   if (caption != NULL) {
01725     caption_rect.left   = caption->pos_x;
01726     caption_rect.right  = caption->pos_x + caption->current_x;
01727     caption_rect.top    = caption->pos_y;
01728     caption_rect.bottom = caption->pos_y + caption->current_y;
01729 
01730     /* Make sure the window doesn't leave the screen */
01731     nx = Clamp(nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen.width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
01732     ny = Clamp(ny, 0, _screen.height - MIN_VISIBLE_TITLE_BAR);
01733 
01734     /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
01735     PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
01736     PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR,   0), w->left, PHD_UP);
01737   }
01738 
01739   if (w->viewport != NULL) {
01740     w->viewport->left += nx - w->left;
01741     w->viewport->top  += ny - w->top;
01742   }
01743 
01744   w->left = nx;
01745   w->top  = ny;
01746 }
01747 
01758 void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
01759 {
01760   if (delta_x != 0 || delta_y != 0) {
01761     if (clamp_to_screen) {
01762       /* Determine the new right/bottom position. If that is outside of the bounds of
01763        * the resolution clamp it in such a manner that it stays within the bounds. */
01764       int new_right  = w->left + w->width  + delta_x;
01765       int new_bottom = w->top  + w->height + delta_y;
01766       if (new_right  >= (int)_cur_resolution.width)  delta_x -= Ceil(new_right  - _cur_resolution.width,  max(1U, w->nested_root->resize_x));
01767       if (new_bottom >= (int)_cur_resolution.height) delta_y -= Ceil(new_bottom - _cur_resolution.height, max(1U, w->nested_root->resize_y));
01768     }
01769 
01770     w->SetDirty();
01771 
01772     uint new_xinc = max(0, (w->nested_root->resize_x == 0) ? 0 : (int)(w->nested_root->current_x - w->nested_root->smallest_x) + delta_x);
01773     uint new_yinc = max(0, (w->nested_root->resize_y == 0) ? 0 : (int)(w->nested_root->current_y - w->nested_root->smallest_y) + delta_y);
01774     assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
01775     assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
01776 
01777     w->nested_root->AssignSizePosition(ST_RESIZE, 0, 0, w->nested_root->smallest_x + new_xinc, w->nested_root->smallest_y + new_yinc, _current_text_dir == TD_RTL);
01778     w->width  = w->nested_root->current_x;
01779     w->height = w->nested_root->current_y;
01780   }
01781 
01782   EnsureVisibleCaption(w, w->left, w->top);
01783 
01784   /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
01785   w->OnResize();
01786   w->SetDirty();
01787 }
01788 
01794 int GetMainViewTop()
01795 {
01796   Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
01797   return (w == NULL) ? 0 : w->top + w->height;
01798 }
01799 
01805 int GetMainViewBottom()
01806 {
01807   Window *w = FindWindowById(WC_STATUS_BAR, 0);
01808   return (w == NULL) ? _screen.height : w->top;
01809 }
01810 
01811 static bool _dragging_window; 
01812 
01817 static EventState HandleWindowDragging()
01818 {
01819   /* Get out immediately if no window is being dragged at all. */
01820   if (!_dragging_window) return ES_NOT_HANDLED;
01821 
01822   /* If button still down, but cursor hasn't moved, there is nothing to do. */
01823   if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
01824 
01825   /* Otherwise find the window... */
01826   Window *w;
01827   FOR_ALL_WINDOWS_FROM_BACK(w) {
01828     if (w->flags & WF_DRAGGING) {
01829       /* Stop the dragging if the left mouse button was released */
01830       if (!_left_button_down) {
01831         w->flags &= ~WF_DRAGGING;
01832         break;
01833       }
01834 
01835       w->SetDirty();
01836 
01837       int x = _cursor.pos.x + _drag_delta.x;
01838       int y = _cursor.pos.y + _drag_delta.y;
01839       int nx = x;
01840       int ny = y;
01841 
01842       if (_settings_client.gui.window_snap_radius != 0) {
01843         const Window *v;
01844 
01845         int hsnap = _settings_client.gui.window_snap_radius;
01846         int vsnap = _settings_client.gui.window_snap_radius;
01847         int delta;
01848 
01849         FOR_ALL_WINDOWS_FROM_BACK(v) {
01850           if (v == w) continue; // Don't snap at yourself
01851 
01852           if (y + w->height > v->top && y < v->top + v->height) {
01853             /* Your left border <-> other right border */
01854             delta = abs(v->left + v->width - x);
01855             if (delta <= hsnap) {
01856               nx = v->left + v->width;
01857               hsnap = delta;
01858             }
01859 
01860             /* Your right border <-> other left border */
01861             delta = abs(v->left - x - w->width);
01862             if (delta <= hsnap) {
01863               nx = v->left - w->width;
01864               hsnap = delta;
01865             }
01866           }
01867 
01868           if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
01869             /* Your left border <-> other left border */
01870             delta = abs(v->left - x);
01871             if (delta <= hsnap) {
01872               nx = v->left;
01873               hsnap = delta;
01874             }
01875 
01876             /* Your right border <-> other right border */
01877             delta = abs(v->left + v->width - x - w->width);
01878             if (delta <= hsnap) {
01879               nx = v->left + v->width - w->width;
01880               hsnap = delta;
01881             }
01882           }
01883 
01884           if (x + w->width > v->left && x < v->left + v->width) {
01885             /* Your top border <-> other bottom border */
01886             delta = abs(v->top + v->height - y);
01887             if (delta <= vsnap) {
01888               ny = v->top + v->height;
01889               vsnap = delta;
01890             }
01891 
01892             /* Your bottom border <-> other top border */
01893             delta = abs(v->top - y - w->height);
01894             if (delta <= vsnap) {
01895               ny = v->top - w->height;
01896               vsnap = delta;
01897             }
01898           }
01899 
01900           if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
01901             /* Your top border <-> other top border */
01902             delta = abs(v->top - y);
01903             if (delta <= vsnap) {
01904               ny = v->top;
01905               vsnap = delta;
01906             }
01907 
01908             /* Your bottom border <-> other bottom border */
01909             delta = abs(v->top + v->height - y - w->height);
01910             if (delta <= vsnap) {
01911               ny = v->top + v->height - w->height;
01912               vsnap = delta;
01913             }
01914           }
01915         }
01916       }
01917 
01918       EnsureVisibleCaption(w, nx, ny);
01919 
01920       w->SetDirty();
01921       return ES_HANDLED;
01922     } else if (w->flags & WF_SIZING) {
01923       /* Stop the sizing if the left mouse button was released */
01924       if (!_left_button_down) {
01925         w->flags &= ~WF_SIZING;
01926         w->SetDirty();
01927         break;
01928       }
01929 
01930       /* Compute difference in pixels between cursor position and reference point in the window.
01931        * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
01932        */
01933       int x, y = _cursor.pos.y - _drag_delta.y;
01934       if (w->flags & WF_SIZING_LEFT) {
01935         x = _drag_delta.x - _cursor.pos.x;
01936       } else {
01937         x = _cursor.pos.x - _drag_delta.x;
01938       }
01939 
01940       /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
01941       if (w->resize.step_width  == 0) x = 0;
01942       if (w->resize.step_height == 0) y = 0;
01943 
01944       /* Check the resize button won't go past the bottom of the screen */
01945       if (w->top + w->height + y > _screen.height) {
01946         y = _screen.height - w->height - w->top;
01947       }
01948 
01949       /* X and Y has to go by step.. calculate it.
01950        * The cast to int is necessary else x/y are implicitly casted to
01951        * unsigned int, which won't work. */
01952       if (w->resize.step_width  > 1) x -= x % (int)w->resize.step_width;
01953       if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
01954 
01955       /* Check that we don't go below the minimum set size */
01956       if ((int)w->width + x < (int)w->nested_root->smallest_x) {
01957         x = w->nested_root->smallest_x - w->width;
01958       }
01959       if ((int)w->height + y < (int)w->nested_root->smallest_y) {
01960         y = w->nested_root->smallest_y - w->height;
01961       }
01962 
01963       /* Window already on size */
01964       if (x == 0 && y == 0) return ES_HANDLED;
01965 
01966       /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
01967       _drag_delta.y += y;
01968       if ((w->flags & WF_SIZING_LEFT) && x != 0) {
01969         _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
01970         w->SetDirty();
01971         w->left -= x;  // If dragging left edge, move left window edge in opposite direction by the same amount.
01972         /* ResizeWindow() below ensures marking new position as dirty. */
01973       } else {
01974         _drag_delta.x += x;
01975       }
01976 
01977       /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
01978       ResizeWindow(w, x, y);
01979       return ES_HANDLED;
01980     }
01981   }
01982 
01983   _dragging_window = false;
01984   return ES_HANDLED;
01985 }
01986 
01991 static void StartWindowDrag(Window *w)
01992 {
01993   w->flags |= WF_DRAGGING;
01994   w->flags &= ~WF_CENTERED;
01995   _dragging_window = true;
01996 
01997   _drag_delta.x = w->left - _cursor.pos.x;
01998   _drag_delta.y = w->top  - _cursor.pos.y;
01999 
02000   BringWindowToFront(w);
02001   DeleteWindowById(WC_DROPDOWN_MENU, 0);
02002 }
02003 
02009 static void StartWindowSizing(Window *w, bool to_left)
02010 {
02011   w->flags |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
02012   w->flags &= ~WF_CENTERED;
02013   _dragging_window = true;
02014 
02015   _drag_delta.x = _cursor.pos.x;
02016   _drag_delta.y = _cursor.pos.y;
02017 
02018   BringWindowToFront(w);
02019   DeleteWindowById(WC_DROPDOWN_MENU, 0);
02020 }
02021 
02026 static EventState HandleScrollbarScrolling()
02027 {
02028   Window *w;
02029   FOR_ALL_WINDOWS_FROM_BACK(w) {
02030     if (w->scrolling_scrollbar >= 0) {
02031       /* Abort if no button is clicked any more. */
02032       if (!_left_button_down) {
02033         w->scrolling_scrollbar = -1;
02034         w->SetDirty();
02035         return ES_HANDLED;
02036       }
02037 
02038       int i;
02039       NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->scrolling_scrollbar);
02040       bool rtl = false;
02041 
02042       if (sb->type == NWID_HSCROLLBAR) {
02043         i = _cursor.pos.x - _cursorpos_drag_start.x;
02044         rtl = _current_text_dir == TD_RTL;
02045       } else {
02046         i = _cursor.pos.y - _cursorpos_drag_start.y;
02047       }
02048 
02049       if (sb->disp_flags & ND_SCROLLBAR_BTN) {
02050         if (_scroller_click_timeout == 1) {
02051           _scroller_click_timeout = 3;
02052           sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1);
02053           w->SetDirty();
02054         }
02055         return ES_HANDLED;
02056       }
02057 
02058       /* Find the item we want to move to and make sure it's inside bounds. */
02059       int pos = min(max(0, i + _scrollbar_start_pos) * sb->GetCount() / _scrollbar_size, max(0, sb->GetCount() - sb->GetCapacity()));
02060       if (rtl) pos = max(0, sb->GetCount() - sb->GetCapacity() - pos);
02061       if (pos != sb->GetPosition()) {
02062         sb->SetPosition(pos);
02063         w->SetDirty();
02064       }
02065       return ES_HANDLED;
02066     }
02067   }
02068 
02069   return ES_NOT_HANDLED;
02070 }
02071 
02076 static EventState HandleViewportScroll()
02077 {
02078   bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
02079 
02080   if (!_scrolling_viewport) return ES_NOT_HANDLED;
02081 
02082   /* When we don't have a last scroll window we are starting to scroll.
02083    * When the last scroll window and this are not the same we went
02084    * outside of the window and should not left-mouse scroll anymore. */
02085   if (_last_scroll_window == NULL) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
02086 
02087   if (_last_scroll_window == NULL || !(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down))) {
02088     _cursor.fix_at = false;
02089     _scrolling_viewport = false;
02090     _last_scroll_window = NULL;
02091     return ES_NOT_HANDLED;
02092   }
02093 
02094   if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
02095     /* If the main window is following a vehicle, then first let go of it! */
02096     const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
02097     ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
02098     return ES_NOT_HANDLED;
02099   }
02100 
02101   Point delta;
02102   if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
02103     delta.x = -_cursor.delta.x;
02104     delta.y = -_cursor.delta.y;
02105   } else {
02106     delta.x = _cursor.delta.x;
02107     delta.y = _cursor.delta.y;
02108   }
02109 
02110   if (scrollwheel_scrolling) {
02111     /* We are using scrollwheels for scrolling */
02112     delta.x = _cursor.h_wheel;
02113     delta.y = _cursor.v_wheel;
02114     _cursor.v_wheel = 0;
02115     _cursor.h_wheel = 0;
02116   }
02117 
02118   /* Create a scroll-event and send it to the window */
02119   if (delta.x != 0 || delta.y != 0) _last_scroll_window->OnScroll(delta);
02120 
02121   _cursor.delta.x = 0;
02122   _cursor.delta.y = 0;
02123   return ES_HANDLED;
02124 }
02125 
02136 static bool MaybeBringWindowToFront(Window *w)
02137 {
02138   bool bring_to_front = false;
02139 
02140   if (w->window_class == WC_MAIN_WINDOW ||
02141       IsVitalWindow(w) ||
02142       w->window_class == WC_TOOLTIPS ||
02143       w->window_class == WC_DROPDOWN_MENU) {
02144     return true;
02145   }
02146 
02147   /* Use unshaded window size rather than current size for shaded windows. */
02148   int w_width  = w->width;
02149   int w_height = w->height;
02150   if (w->IsShaded()) {
02151     w_width  = w->unshaded_size.width;
02152     w_height = w->unshaded_size.height;
02153   }
02154 
02155   Window *u;
02156   FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
02157     /* A modal child will prevent the activation of the parent window */
02158     if (u->parent == w && (u->desc_flags & WDF_MODAL)) {
02159       u->SetWhiteBorder();
02160       u->SetDirty();
02161       return false;
02162     }
02163 
02164     if (u->window_class == WC_MAIN_WINDOW ||
02165         IsVitalWindow(u) ||
02166         u->window_class == WC_TOOLTIPS ||
02167         u->window_class == WC_DROPDOWN_MENU) {
02168       continue;
02169     }
02170 
02171     /* Window sizes don't interfere, leave z-order alone */
02172     if (w->left + w_width <= u->left ||
02173         u->left + u->width <= w->left ||
02174         w->top  + w_height <= u->top ||
02175         u->top + u->height <= w->top) {
02176       continue;
02177     }
02178 
02179     bring_to_front = true;
02180   }
02181 
02182   if (bring_to_front) BringWindowToFront(w);
02183   return true;
02184 }
02185 
02190 void HandleKeypress(uint32 raw_key)
02191 {
02192   /* World generation is multithreaded and messes with companies.
02193    * But there is no company related window open anyway, so _current_company is not used. */
02194   assert(HasModalProgress() || IsLocalCompany());
02195 
02196   /* Setup event */
02197   uint16 key     = GB(raw_key,  0, 16);
02198   uint16 keycode = GB(raw_key, 16, 16);
02199 
02200   /*
02201    * The Unicode standard defines an area called the private use area. Code points in this
02202    * area are reserved for private use and thus not portable between systems. For instance,
02203    * Apple defines code points for the arrow keys in this area, but these are only printable
02204    * on a system running OS X. We don't want these keys to show up in text fields and such,
02205    * and thus we have to clear the unicode character when we encounter such a key.
02206    */
02207   if (key >= 0xE000 && key <= 0xF8FF) key = 0;
02208 
02209   /*
02210    * If both key and keycode is zero, we don't bother to process the event.
02211    */
02212   if (key == 0 && keycode == 0) return;
02213 
02214   /* Check if the focused window has a focused editbox */
02215   if (EditBoxInGlobalFocus()) {
02216     /* All input will in this case go to the focused window */
02217     if (_focused_window->OnKeyPress(key, keycode) == ES_HANDLED) return;
02218   }
02219 
02220   /* Call the event, start with the uppermost window, but ignore the toolbar. */
02221   Window *w;
02222   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02223     if (w->window_class == WC_MAIN_TOOLBAR) continue;
02224     if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
02225   }
02226 
02227   w = FindWindowById(WC_MAIN_TOOLBAR, 0);
02228   /* When there is no toolbar w is null, check for that */
02229   if (w != NULL && w->OnKeyPress(key, keycode) == ES_HANDLED) return;
02230 
02231   HandleGlobalHotkeys(key, keycode);
02232 }
02233 
02237 void HandleCtrlChanged()
02238 {
02239   /* Call the event, start with the uppermost window. */
02240   Window *w;
02241   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02242     if (w->OnCTRLStateChange() == ES_HANDLED) return;
02243   }
02244 }
02245 
02252 static int _input_events_this_tick = 0;
02253 
02258 static void HandleAutoscroll()
02259 {
02260   if (_settings_client.gui.autoscroll && _game_mode != GM_MENU && !HasModalProgress()) {
02261     int x = _cursor.pos.x;
02262     int y = _cursor.pos.y;
02263     Window *w = FindWindowFromPt(x, y);
02264     if (w == NULL || w->flags & WF_DISABLE_VP_SCROLL) return;
02265     ViewPort *vp = IsPtInWindowViewport(w, x, y);
02266     if (vp != NULL) {
02267       x -= vp->left;
02268       y -= vp->top;
02269 
02270       /* here allows scrolling in both x and y axis */
02271 #define scrollspeed 3
02272       if (x - 15 < 0) {
02273         w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
02274       } else if (15 - (vp->width - x) > 0) {
02275         w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
02276       }
02277       if (y - 15 < 0) {
02278         w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
02279       } else if (15 - (vp->height - y) > 0) {
02280         w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
02281       }
02282 #undef scrollspeed
02283     }
02284   }
02285 }
02286 
02287 enum MouseClick {
02288   MC_NONE = 0,
02289   MC_LEFT,
02290   MC_RIGHT,
02291   MC_DOUBLE_LEFT,
02292   MC_HOVER,
02293 
02294   MAX_OFFSET_DOUBLE_CLICK = 5,     
02295   TIME_BETWEEN_DOUBLE_CLICK = 500, 
02296   MAX_OFFSET_HOVER = 5,            
02297 };
02298 extern EventState VpHandlePlaceSizingDrag();
02299 
02300 static void ScrollMainViewport(int x, int y)
02301 {
02302   if (_game_mode != GM_MENU) {
02303     Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
02304     assert(w);
02305 
02306     w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
02307     w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
02308   }
02309 }
02310 
02320 static const int8 scrollamt[16][2] = {
02321   { 0,  0}, 
02322   {-2,  0}, 
02323   { 0, -2}, 
02324   {-2, -1}, 
02325   { 2,  0}, 
02326   { 0,  0}, 
02327   { 2, -1}, 
02328   { 0, -2}, 
02329   { 0,  2}, 
02330   {-2,  1}, 
02331   { 0,  0}, 
02332   {-2,  0}, 
02333   { 2,  1}, 
02334   { 0,  2}, 
02335   { 2,  0}, 
02336   { 0,  0}, 
02337 };
02338 
02339 static void HandleKeyScrolling()
02340 {
02341   /*
02342    * Check that any of the dirkeys is pressed and that the focused window
02343    * dont has an edit-box as focused widget.
02344    */
02345   if (_dirkeys && !EditBoxInGlobalFocus()) {
02346     int factor = _shift_pressed ? 50 : 10;
02347     ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
02348   }
02349 }
02350 
02351 static void MouseLoop(MouseClick click, int mousewheel)
02352 {
02353   /* World generation is multithreaded and messes with companies.
02354    * But there is no company related window open anyway, so _current_company is not used. */
02355   assert(HasModalProgress() || IsLocalCompany());
02356 
02357   HandlePlacePresize();
02358   UpdateTileSelection();
02359 
02360   if (VpHandlePlaceSizingDrag()  == ES_HANDLED) return;
02361   if (HandleMouseDragDrop()      == ES_HANDLED) return;
02362   if (HandleWindowDragging()     == ES_HANDLED) return;
02363   if (HandleScrollbarScrolling() == ES_HANDLED) return;
02364   if (HandleViewportScroll()     == ES_HANDLED) return;
02365 
02366   HandleMouseOver();
02367 
02368   bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
02369   if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
02370 
02371   int x = _cursor.pos.x;
02372   int y = _cursor.pos.y;
02373   Window *w = FindWindowFromPt(x, y);
02374   if (w == NULL) return;
02375 
02376   if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
02377   ViewPort *vp = IsPtInWindowViewport(w, x, y);
02378 
02379   /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
02380   if (vp != NULL && (_game_mode == GM_MENU || HasModalProgress())) return;
02381 
02382   if (mousewheel != 0) {
02383     /* Send mousewheel event to window */
02384     w->OnMouseWheel(mousewheel);
02385 
02386     /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
02387     if (vp == NULL) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
02388   }
02389 
02390   if (vp != NULL) {
02391     if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
02392     switch (click) {
02393       case MC_DOUBLE_LEFT:
02394       case MC_LEFT:
02395         DEBUG(misc, 2, "Cursor: 0x%X (%d)", _cursor.sprite, _cursor.sprite);
02396         if (!HandleViewportClicked(vp, x, y) &&
02397             !(w->flags & WF_DISABLE_VP_SCROLL) &&
02398             _settings_client.gui.left_mouse_btn_scrolling) {
02399           _scrolling_viewport = true;
02400           _cursor.fix_at = false;
02401         }
02402         break;
02403 
02404       case MC_RIGHT:
02405         if (!(w->flags & WF_DISABLE_VP_SCROLL)) {
02406           _scrolling_viewport = true;
02407           _cursor.fix_at = true;
02408 
02409           /* clear 2D scrolling caches before we start a 2D scroll */
02410           _cursor.h_wheel = 0;
02411           _cursor.v_wheel = 0;
02412         }
02413         break;
02414 
02415       default:
02416         break;
02417     }
02418   } else {
02419     switch (click) {
02420       case MC_LEFT:
02421       case MC_DOUBLE_LEFT:
02422         DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
02423         break;
02424 
02425       default:
02426         if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
02427         /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
02428          * Simulate a right button click so we can get started. */
02429         /* FALL THROUGH */
02430 
02431       case MC_RIGHT: DispatchRightClickEvent(w, x - w->left, y - w->top); break;
02432 
02433       case MC_HOVER: DispatchHoverEvent(w, x - w->left, y - w->top); break;
02434     }
02435   }
02436 }
02437 
02441 void HandleMouseEvents()
02442 {
02443   /* World generation is multithreaded and messes with companies.
02444    * But there is no company related window open anyway, so _current_company is not used. */
02445   assert(HasModalProgress() || IsLocalCompany());
02446 
02447   static int double_click_time = 0;
02448   static Point double_click_pos = {0, 0};
02449 
02450   /* Mouse event? */
02451   MouseClick click = MC_NONE;
02452   if (_left_button_down && !_left_button_clicked) {
02453     click = MC_LEFT;
02454     if (double_click_time != 0 && _realtime_tick - double_click_time   < TIME_BETWEEN_DOUBLE_CLICK &&
02455         double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK  &&
02456         double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
02457       click = MC_DOUBLE_LEFT;
02458     }
02459     double_click_time = _realtime_tick;
02460     double_click_pos = _cursor.pos;
02461     _left_button_clicked = true;
02462     _input_events_this_tick++;
02463   } else if (_right_button_clicked) {
02464     _right_button_clicked = false;
02465     click = MC_RIGHT;
02466     _input_events_this_tick++;
02467   }
02468 
02469   int mousewheel = 0;
02470   if (_cursor.wheel) {
02471     mousewheel = _cursor.wheel;
02472     _cursor.wheel = 0;
02473     _input_events_this_tick++;
02474   }
02475 
02476   static uint32 hover_time = 0;
02477   static Point hover_pos = {0, 0};
02478 
02479   if (_settings_client.gui.hover_delay > 0) {
02480     if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
02481         hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER  ||
02482         hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
02483       hover_pos = _cursor.pos;
02484       hover_time = _realtime_tick;
02485       _mouse_hovering = false;
02486     } else {
02487       if (hover_time != 0 && _realtime_tick > hover_time + _settings_client.gui.hover_delay * 1000) {
02488         click = MC_HOVER;
02489         _input_events_this_tick++;
02490         _mouse_hovering = true;
02491       }
02492     }
02493   }
02494 
02495   /* Handle sprite picker before any GUI interaction */
02496   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _newgrf_debug_sprite_picker.click_time != _realtime_tick) {
02497     /* Next realtime tick? Then redraw has finished */
02498     _newgrf_debug_sprite_picker.mode = SPM_NONE;
02499     InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
02500   }
02501 
02502   if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
02503     /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
02504     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
02505     _newgrf_debug_sprite_picker.clicked_pixel = blitter->MoveTo(_screen.dst_ptr, _cursor.pos.x, _cursor.pos.y);
02506     _newgrf_debug_sprite_picker.click_time = _realtime_tick;
02507     _newgrf_debug_sprite_picker.sprites.Clear();
02508     _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
02509     MarkWholeScreenDirty();
02510   } else {
02511     MouseLoop(click, mousewheel);
02512   }
02513 
02514   /* We have moved the mouse the required distance,
02515    * no need to move it at any later time. */
02516   _cursor.delta.x = 0;
02517   _cursor.delta.y = 0;
02518 }
02519 
02523 static void CheckSoftLimit()
02524 {
02525   if (_settings_client.gui.window_soft_limit == 0) return;
02526 
02527   for (;;) {
02528     uint deletable_count = 0;
02529     Window *w, *last_deletable = NULL;
02530     FOR_ALL_WINDOWS_FROM_FRONT(w) {
02531       if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
02532 
02533       last_deletable = w;
02534       deletable_count++;
02535     }
02536 
02537     /* We've not reached the soft limit yet. */
02538     if (deletable_count <= _settings_client.gui.window_soft_limit) break;
02539 
02540     assert(last_deletable != NULL);
02541     delete last_deletable;
02542   }
02543 }
02544 
02548 void InputLoop()
02549 {
02550   /* World generation is multithreaded and messes with companies.
02551    * But there is no company related window open anyway, so _current_company is not used. */
02552   assert(HasModalProgress() || IsLocalCompany());
02553 
02554   CheckSoftLimit();
02555   HandleKeyScrolling();
02556 
02557   /* Do the actual free of the deleted windows. */
02558   for (Window *v = _z_front_window; v != NULL; /* nothing */) {
02559     Window *w = v;
02560     v = v->z_back;
02561 
02562     if (w->window_class != WC_INVALID) continue;
02563 
02564     RemoveWindowFromZOrdering(w);
02565     free(w);
02566   }
02567 
02568   if (_scroller_click_timeout != 0) _scroller_click_timeout--;
02569   DecreaseWindowCounters();
02570 
02571   if (_input_events_this_tick != 0) {
02572     /* The input loop is called only once per GameLoop() - so we can clear the counter here */
02573     _input_events_this_tick = 0;
02574     /* there were some inputs this tick, don't scroll ??? */
02575     return;
02576   }
02577 
02578   /* HandleMouseEvents was already called for this tick */
02579   HandleMouseEvents();
02580   HandleAutoscroll();
02581 }
02582 
02586 void UpdateWindows()
02587 {
02588   Window *w;
02589 
02590   static int highlight_timer = 1;
02591   if (--highlight_timer == 0) {
02592     highlight_timer = 15;
02593     _window_highlight_colour = !_window_highlight_colour;
02594   }
02595 
02596   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02597     w->ProcessScheduledInvalidations();
02598     w->ProcessHighlightedInvalidations();
02599   }
02600 
02601   static int we4_timer = 0;
02602   int t = we4_timer + 1;
02603 
02604   if (t >= 100) {
02605     FOR_ALL_WINDOWS_FROM_FRONT(w) {
02606       w->OnHundredthTick();
02607     }
02608     t = 0;
02609   }
02610   we4_timer = t;
02611 
02612   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02613     if ((w->flags & WF_WHITE_BORDER) && --w->white_border_timer == 0) {
02614       CLRBITS(w->flags, WF_WHITE_BORDER);
02615       w->SetDirty();
02616     }
02617   }
02618 
02619   DrawDirtyBlocks();
02620 
02621   FOR_ALL_WINDOWS_FROM_BACK(w) {
02622     /* Update viewport only if window is not shaded. */
02623     if (w->viewport != NULL && !w->IsShaded()) UpdateViewportPosition(w);
02624   }
02625   NetworkDrawChatMessage();
02626   /* Redraw mouse cursor in case it was hidden */
02627   DrawMouseCursor();
02628 }
02629 
02635 void SetWindowDirty(WindowClass cls, WindowNumber number)
02636 {
02637   const Window *w;
02638   FOR_ALL_WINDOWS_FROM_BACK(w) {
02639     if (w->window_class == cls && w->window_number == number) w->SetDirty();
02640   }
02641 }
02642 
02649 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
02650 {
02651   const Window *w;
02652   FOR_ALL_WINDOWS_FROM_BACK(w) {
02653     if (w->window_class == cls && w->window_number == number) {
02654       w->SetWidgetDirty(widget_index);
02655     }
02656   }
02657 }
02658 
02663 void SetWindowClassesDirty(WindowClass cls)
02664 {
02665   Window *w;
02666   FOR_ALL_WINDOWS_FROM_BACK(w) {
02667     if (w->window_class == cls) w->SetDirty();
02668   }
02669 }
02670 
02676 void Window::InvalidateData(int data, bool gui_scope)
02677 {
02678   this->SetDirty();
02679   if (!gui_scope) {
02680     /* Schedule GUI-scope invalidation for next redraw. */
02681     *this->scheduled_invalidation_data.Append() = data;
02682   }
02683   this->OnInvalidateData(data, gui_scope);
02684 }
02685 
02689 void Window::ProcessScheduledInvalidations()
02690 {
02691   for (int *data = this->scheduled_invalidation_data.Begin(); this->window_class != WC_INVALID && data != this->scheduled_invalidation_data.End(); data++) {
02692     this->OnInvalidateData(*data, true);
02693   }
02694   this->scheduled_invalidation_data.Clear();
02695 }
02696 
02700 void Window::ProcessHighlightedInvalidations()
02701 {
02702   if ((this->flags & WF_HIGHLIGHTED) == 0) return;
02703 
02704   for (uint i = 0; i < this->nested_array_size; i++) {
02705     if (this->IsWidgetHighlighted(i)) this->SetWidgetDirty(i);
02706   }
02707 }
02708 
02735 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
02736 {
02737   Window *w;
02738   FOR_ALL_WINDOWS_FROM_BACK(w) {
02739     if (w->window_class == cls && w->window_number == number) {
02740       w->InvalidateData(data, gui_scope);
02741     }
02742   }
02743 }
02744 
02753 void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
02754 {
02755   Window *w;
02756 
02757   FOR_ALL_WINDOWS_FROM_BACK(w) {
02758     if (w->window_class == cls) {
02759       w->InvalidateData(data, gui_scope);
02760     }
02761   }
02762 }
02763 
02767 void CallWindowTickEvent()
02768 {
02769   Window *w;
02770   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02771     w->OnTick();
02772   }
02773 }
02774 
02781 void DeleteNonVitalWindows()
02782 {
02783   Window *w;
02784 
02785 restart_search:
02786   /* When we find the window to delete, we need to restart the search
02787    * as deleting this window could cascade in deleting (many) others
02788    * anywhere in the z-array */
02789   FOR_ALL_WINDOWS_FROM_BACK(w) {
02790     if (w->window_class != WC_MAIN_WINDOW &&
02791         w->window_class != WC_SELECT_GAME &&
02792         w->window_class != WC_MAIN_TOOLBAR &&
02793         w->window_class != WC_STATUS_BAR &&
02794         w->window_class != WC_TOOLTIPS &&
02795         (w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
02796 
02797       delete w;
02798       goto restart_search;
02799     }
02800   }
02801 }
02802 
02810 void DeleteAllNonVitalWindows()
02811 {
02812   Window *w;
02813 
02814   /* Delete every window except for stickied ones, then sticky ones as well */
02815   DeleteNonVitalWindows();
02816 
02817 restart_search:
02818   /* When we find the window to delete, we need to restart the search
02819    * as deleting this window could cascade in deleting (many) others
02820    * anywhere in the z-array */
02821   FOR_ALL_WINDOWS_FROM_BACK(w) {
02822     if (w->flags & WF_STICKY) {
02823       delete w;
02824       goto restart_search;
02825     }
02826   }
02827 }
02828 
02833 void DeleteConstructionWindows()
02834 {
02835   Window *w;
02836 
02837 restart_search:
02838   /* When we find the window to delete, we need to restart the search
02839    * as deleting this window could cascade in deleting (many) others
02840    * anywhere in the z-array */
02841   FOR_ALL_WINDOWS_FROM_BACK(w) {
02842     if (w->desc_flags & WDF_CONSTRUCTION) {
02843       delete w;
02844       goto restart_search;
02845     }
02846   }
02847 
02848   FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
02849 }
02850 
02852 void HideVitalWindows()
02853 {
02854   DeleteWindowById(WC_MAIN_TOOLBAR, 0);
02855   DeleteWindowById(WC_STATUS_BAR, 0);
02856 }
02857 
02859 void ReInitAllWindows()
02860 {
02861   NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
02862   NWidgetScrollbar::InvalidateDimensionCache();
02863 
02864   Window *w;
02865   FOR_ALL_WINDOWS_FROM_BACK(w) {
02866     w->ReInit();
02867   }
02868 #ifdef ENABLE_NETWORK
02869   void NetworkReInitChatBoxSize();
02870   NetworkReInitChatBoxSize();
02871 #endif
02872 
02873   /* Make sure essential parts of all windows are visible */
02874   RelocateAllWindows(_cur_resolution.width, _cur_resolution.height);
02875   MarkWholeScreenDirty();
02876 }
02877 
02885 static int PositionWindow(Window *w, WindowClass clss, int setting)
02886 {
02887   if (w == NULL || w->window_class != clss) {
02888     w = FindWindowById(clss, 0);
02889   }
02890   if (w == NULL) return 0;
02891 
02892   int old_left = w->left;
02893   switch (setting) {
02894     case 1:  w->left = (_screen.width - w->width) / 2; break;
02895     case 2:  w->left = _screen.width - w->width; break;
02896     default: w->left = 0; break;
02897   }
02898   if (w->viewport != NULL) w->viewport->left += w->left - old_left;
02899   SetDirtyBlocks(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
02900   return w->left;
02901 }
02902 
02908 int PositionMainToolbar(Window *w)
02909 {
02910   DEBUG(misc, 5, "Repositioning Main Toolbar...");
02911   return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
02912 }
02913 
02919 int PositionStatusbar(Window *w)
02920 {
02921   DEBUG(misc, 5, "Repositioning statusbar...");
02922   return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
02923 }
02924 
02930 int PositionNewsMessage(Window *w)
02931 {
02932   DEBUG(misc, 5, "Repositioning news message...");
02933   return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
02934 }
02935 
02941 int PositionNetworkChatWindow(Window *w)
02942 {
02943   DEBUG(misc, 5, "Repositioning network chat window...");
02944   return PositionWindow(w, WC_SEND_NETWORK_MSG, _settings_client.gui.statusbar_pos);
02945 }
02946 
02947 
02953 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
02954 {
02955   Window *w;
02956   FOR_ALL_WINDOWS_FROM_BACK(w) {
02957     if (w->viewport != NULL && w->viewport->follow_vehicle == from_index) {
02958       w->viewport->follow_vehicle = to_index;
02959       w->SetDirty();
02960     }
02961   }
02962 }
02963 
02964 
02970 void RelocateAllWindows(int neww, int newh)
02971 {
02972   Window *w;
02973 
02974   FOR_ALL_WINDOWS_FROM_BACK(w) {
02975     int left, top;
02976 
02977     if (w->window_class == WC_MAIN_WINDOW) {
02978       ViewPort *vp = w->viewport;
02979       vp->width = w->width = neww;
02980       vp->height = w->height = newh;
02981       vp->virtual_width = ScaleByZoom(neww, vp->zoom);
02982       vp->virtual_height = ScaleByZoom(newh, vp->zoom);
02983       continue; // don't modify top,left
02984     }
02985 
02986     /* XXX - this probably needs something more sane. For example specifying
02987      * in a 'backup'-desc that the window should always be centered. */
02988     switch (w->window_class) {
02989       case WC_BOOTSTRAP:
02990         ResizeWindow(w, neww, newh);
02991         continue;
02992 
02993       case WC_MAIN_TOOLBAR:
02994         ResizeWindow(w, min(neww, *_preferred_toolbar_size) - w->width, 0, false);
02995 
02996         top = w->top;
02997         left = PositionMainToolbar(w); // changes toolbar orientation
02998         break;
02999 
03000       case WC_NEWS_WINDOW:
03001         top = newh - w->height;
03002         left = PositionNewsMessage(w);
03003         break;
03004 
03005       case WC_STATUS_BAR:
03006         ResizeWindow(w, min(neww, *_preferred_statusbar_size) - w->width, 0, false);
03007 
03008         top = newh - w->height;
03009         left = PositionStatusbar(w);
03010         break;
03011 
03012       case WC_SEND_NETWORK_MSG:
03013         ResizeWindow(w, Clamp(neww, 320, 640) - w->width, 0, false);
03014         top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
03015         left = PositionNetworkChatWindow(w);
03016         break;
03017 
03018       case WC_CONSOLE:
03019         IConsoleResize(w);
03020         continue;
03021 
03022       default: {
03023         if (w->flags & WF_CENTERED) {
03024           top = (newh - w->height) >> 1;
03025           left = (neww - w->width) >> 1;
03026           break;
03027         }
03028 
03029         left = w->left;
03030         if (left + (w->width >> 1) >= neww) left = neww - w->width;
03031         if (left < 0) left = 0;
03032 
03033         top = w->top;
03034         if (top + (w->height >> 1) >= newh) top = newh - w->height;
03035         break;
03036       }
03037     }
03038 
03039     EnsureVisibleCaption(w, left, top);
03040   }
03041 }
03042 
03048 PickerWindowBase::~PickerWindowBase()
03049 {
03050   this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
03051   ResetObjectToPlace();
03052 }