window.cpp

Go to the documentation of this file.
00001 /* $Id: window.cpp 19258 2010-02-25 21:18:38Z rubidium $ */
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 "openttd.h"
00015 #include "company_func.h"
00016 #include "gfx_func.h"
00017 #include "console_func.h"
00018 #include "console_gui.h"
00019 #include "viewport_func.h"
00020 #include "variables.h"
00021 #include "genworld.h"
00022 #include "blitter/factory.hpp"
00023 #include "zoom_func.h"
00024 #include "map_func.h"
00025 #include "vehicle_base.h"
00026 #include "cheat_type.h"
00027 #include "window_func.h"
00028 #include "tilehighlight_func.h"
00029 #include "network/network.h"
00030 #include "querystring_gui.h"
00031 #include "widgets/dropdown_func.h"
00032 #include "strings_func.h"
00033 #include "settings_type.h"
00034 
00035 #include "table/sprites.h"
00036 
00037 static Point _drag_delta; 
00038 static Window *_mouseover_last_w = NULL; 
00039 
00041 Window *_z_front_window = NULL;
00043 Window *_z_back_window  = NULL;
00044 
00045 /*
00046  * Window that currently have focus. - The main purpose is to generate
00047  * FocusLost events, not to give next window in z-order focus when a
00048  * window is closed.
00049  */
00050 Window *_focused_window;
00051 
00052 Point _cursorpos_drag_start;
00053 
00054 int _scrollbar_start_pos;
00055 int _scrollbar_size;
00056 byte _scroller_click_timeout;
00057 
00058 bool _scrolling_scrollbar;
00059 bool _scrolling_viewport;
00060 
00061 byte _special_mouse_mode;
00062 
00064 WindowDesc::WindowDesc(WindowPosition def_pos, int16 def_width, int16 def_height,
00065       WindowClass window_class, WindowClass parent_class, uint32 flags,
00066       const NWidgetPart *nwid_parts, int16 nwid_length) :
00067   default_pos(def_pos),
00068   default_width(def_width),
00069   default_height(def_height),
00070   cls(window_class),
00071   parent_cls(parent_class),
00072   flags(flags),
00073   nwid_parts(nwid_parts),
00074   nwid_length(nwid_length)
00075 {
00076 }
00077 
00078 WindowDesc::~WindowDesc()
00079 {
00080 }
00081 
00089 void Scrollbar::SetCapacityFromWidget(Window *w, int widget, int padding)
00090 {
00091   NWidgetBase *nwid = w->GetWidget<NWidgetBase>(widget);
00092   if (this->is_vertical) {
00093     this->SetCapacity(((int)nwid->current_y - padding) / (int)nwid->resize_y);
00094   } else {
00095     this->SetCapacity(((int)nwid->current_x - padding) / (int)nwid->resize_x);
00096   }
00097 }
00098 
00103 void SetFocusedWindow(Window *w)
00104 {
00105   if (_focused_window == w) return;
00106 
00107   /* Invalidate focused widget */
00108   if (_focused_window != NULL) {
00109     if (_focused_window->nested_focus != NULL) _focused_window->nested_focus->SetDirty(_focused_window);
00110   }
00111 
00112   /* Remember which window was previously focused */
00113   Window *old_focused = _focused_window;
00114   _focused_window = w;
00115 
00116   /* So we can inform it that it lost focus */
00117   if (old_focused != NULL) old_focused->OnFocusLost();
00118   if (_focused_window != NULL) _focused_window->OnFocus();
00119 }
00120 
00126 bool EditBoxInGlobalFocus()
00127 {
00128   if (_focused_window == NULL) return false;
00129 
00130   /* The console does not have an edit box so a special case is needed. */
00131   if (_focused_window->window_class == WC_CONSOLE) return true;
00132 
00133   return _focused_window->nested_focus != NULL && _focused_window->nested_focus->type == WWT_EDITBOX;
00134 }
00135 
00139 void Window::UnfocusFocusedWidget()
00140 {
00141   if (this->nested_focus != NULL) {
00142     /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
00143     this->nested_focus->SetDirty(this);
00144     this->nested_focus = NULL;
00145   }
00146 }
00147 
00153 bool Window::SetFocusedWidget(byte widget_index)
00154 {
00155   /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
00156   if (widget_index >= this->nested_array_size) return false;
00157 
00158   assert(this->nested_array[widget_index] != NULL); // Setting focus to a non-existing widget is a bad idea.
00159   if (this->nested_focus != NULL) {
00160     if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
00161 
00162     /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
00163     this->nested_focus->SetDirty(this);
00164   }
00165   this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
00166   return true;
00167 }
00168 
00176 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
00177 {
00178   va_list wdg_list;
00179 
00180   va_start(wdg_list, widgets);
00181 
00182   while (widgets != WIDGET_LIST_END) {
00183     SetWidgetDisabledState(widgets, disab_stat);
00184     widgets = va_arg(wdg_list, int);
00185   }
00186 
00187   va_end(wdg_list);
00188 }
00189 
00195 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
00196 {
00197   va_list wdg_list;
00198 
00199   va_start(wdg_list, widgets);
00200 
00201   while (widgets != WIDGET_LIST_END) {
00202     SetWidgetLoweredState(widgets, lowered_stat);
00203     widgets = va_arg(wdg_list, int);
00204   }
00205 
00206   va_end(wdg_list);
00207 }
00208 
00213 void Window::RaiseButtons(bool autoraise)
00214 {
00215   for (uint i = 0; i < this->nested_array_size; i++) {
00216     if (this->nested_array[i] != NULL && (this->nested_array[i]->type & ~WWB_PUSHBUTTON) < WWT_LAST &&
00217         (!autoraise || (this->nested_array[i]->type & WWB_PUSHBUTTON)) && this->IsWidgetLowered(i)) {
00218       this->RaiseWidget(i);
00219       this->SetWidgetDirty(i);
00220     }
00221   }
00222 }
00223 
00228 void Window::SetWidgetDirty(byte widget_index) const
00229 {
00230   /* Sometimes this function is called before the window is even fully initialized */
00231   if (this->nested_array == NULL) return;
00232 
00233   this->nested_array[widget_index]->SetDirty(this);
00234 }
00235 
00241 void Window::HandleButtonClick(byte widget)
00242 {
00243   this->LowerWidget(widget);
00244   this->flags4 |= WF_TIMEOUT_BEGIN;
00245   this->SetWidgetDirty(widget);
00246 }
00247 
00248 static void StartWindowDrag(Window *w);
00249 static void StartWindowSizing(Window *w, bool to_left);
00250 
00258 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
00259 {
00260   const NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
00261   WidgetType widget_type = (nw != NULL) ? nw->type : WWT_EMPTY;
00262 
00263   bool focused_widget_changed = false;
00264   /* If clicked on a window that previously did dot have focus */
00265   if (_focused_window != w &&                 // We already have focus, right?
00266       (w->desc_flags & WDF_NO_FOCUS) == 0 &&  // Don't lose focus to toolbars
00267       widget_type != WWT_CLOSEBOX) {          // Don't change focused window if 'X' (close button) was clicked
00268     focused_widget_changed = true;
00269     if (_focused_window != NULL) {
00270       _focused_window->OnFocusLost();
00271 
00272       /* The window that lost focus may have had opened a OSK, window so close it, unless the user has clicked on the OSK window. */
00273       if (w->window_class != WC_OSK) DeleteWindowById(WC_OSK, 0);
00274     }
00275     SetFocusedWindow(w);
00276     w->OnFocus();
00277   }
00278 
00279   if (nw == NULL) return; // exit if clicked outside of widgets
00280 
00281   /* don't allow any interaction if the button has been disabled */
00282   if (nw->IsDisabled()) return;
00283 
00284   int widget_index = nw->index; 
00285 
00286   /* Clicked on a widget that is not disabled.
00287    * So unless the clicked widget is the caption bar, change focus to this widget */
00288   if (widget_type != WWT_CAPTION) {
00289     /* Close the OSK window if a edit box loses focus */
00290     if (w->nested_focus != NULL &&  w->nested_focus->type == WWT_EDITBOX && w->nested_focus != nw && w->window_class != WC_OSK) {
00291       DeleteWindowById(WC_OSK, 0);
00292     }
00293 
00294     /* focused_widget_changed is 'now' only true if the window this widget
00295      * is in gained focus. In that case it must remain true, also if the
00296      * local widget focus did not change. As such it's the logical-or of
00297      * both changed states.
00298      *
00299      * If this is not preserved, then the OSK window would be opened when
00300      * a user has the edit box focused and then click on another window and
00301      * then back again on the edit box (to type some text).
00302      */
00303     focused_widget_changed |= w->SetFocusedWidget(widget_index);
00304   }
00305 
00306   /* Close any child drop down menus. If the button pressed was the drop down
00307    * list's own button, then we should not process the click any further. */
00308   if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
00309 
00310   switch (widget_type) {
00311     /* special widget handling for buttons*/
00312     case WWT_PANEL   | WWB_PUSHBUTTON: // WWT_PUSHBTN
00313     case WWT_IMGBTN  | WWB_PUSHBUTTON: // WWT_PUSHIMGBTN
00314     case WWT_TEXTBTN | WWB_PUSHBUTTON: // WWT_PUSHTXTBTN
00315       w->HandleButtonClick(widget_index);
00316       break;
00317 
00318     case WWT_SCROLLBAR:
00319     case WWT_SCROLL2BAR:
00320     case WWT_HSCROLLBAR:
00321       ScrollbarClickHandler(w, nw, x, y);
00322       break;
00323 
00324     case WWT_EDITBOX:
00325       if (!focused_widget_changed) { // Only open the OSK window if clicking on an already focused edit box
00326         /* Open the OSK window if clicked on an edit box */
00327         QueryStringBaseWindow *qs = dynamic_cast<QueryStringBaseWindow *>(w);
00328         if (qs != NULL) {
00329           qs->OnOpenOSKWindow(widget_index);
00330         }
00331       }
00332       break;
00333 
00334     case WWT_CLOSEBOX: // 'X'
00335       delete w;
00336       return;
00337 
00338     case WWT_CAPTION: // 'Title bar'
00339       StartWindowDrag(w);
00340       return;
00341 
00342     case WWT_RESIZEBOX:
00343       /* When the resize widget is on the left size of the window
00344        * we assume that that button is used to resize to the left. */
00345       StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
00346       nw->SetDirty(w);
00347       return;
00348 
00349     case WWT_SHADEBOX:
00350       nw->SetDirty(w);
00351       w->SetShaded(!w->IsShaded());
00352       return;
00353 
00354     case WWT_STICKYBOX:
00355       w->flags4 ^= WF_STICKY;
00356       nw->SetDirty(w);
00357       return;
00358 
00359     default:
00360       break;
00361   }
00362 
00363   /* Widget has no index, so the window is not interested in it. */
00364   if (widget_index < 0) return;
00365 
00366   Point pt = { x, y };
00367   w->OnClick(pt, widget_index, click_count);
00368 }
00369 
00376 static void DispatchRightClickEvent(Window *w, int x, int y)
00377 {
00378   NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
00379 
00380   /* No widget to handle */
00381   if (wid == NULL) return;
00382 
00383   /* Show the tooltip if there is any */
00384   if (wid->tool_tip != 0) {
00385     GuiShowTooltips(wid->tool_tip);
00386     return;
00387   }
00388 
00389   /* Widget has no index, so the window is not interested in it. */
00390   if (wid->index < 0) return;
00391 
00392   Point pt = { x, y };
00393   w->OnRightClick(pt, wid->index);
00394 }
00395 
00403 static void DispatchMouseWheelEvent(Window *w, const NWidgetCore *nwid, int wheel)
00404 {
00405   if (nwid == NULL) return;
00406 
00407   /* Using wheel on caption/shade-box shades or unshades the window. */
00408   if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
00409     w->SetShaded(!w->IsShaded());
00410     return;
00411   }
00412 
00413   /* Scroll the widget attached to the scrollbar. */
00414   Scrollbar *sb = nwid->FindScrollbar(w);
00415   if (sb != NULL && sb->GetCount() > sb->GetCapacity()) {
00416     sb->UpdatePosition(wheel);
00417     w->SetDirty();
00418   }
00419 }
00420 
00433 static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
00434 {
00435   const Window *v;
00436   FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
00437     if (right > v->left &&
00438         bottom > v->top &&
00439         left < v->left + v->width &&
00440         top < v->top + v->height) {
00441       /* v and rectangle intersect with eeach other */
00442       int x;
00443 
00444       if (left < (x = v->left)) {
00445         DrawOverlappedWindow(w, left, top, x, bottom);
00446         DrawOverlappedWindow(w, x, top, right, bottom);
00447         return;
00448       }
00449 
00450       if (right > (x = v->left + v->width)) {
00451         DrawOverlappedWindow(w, left, top, x, bottom);
00452         DrawOverlappedWindow(w, x, top, right, bottom);
00453         return;
00454       }
00455 
00456       if (top < (x = v->top)) {
00457         DrawOverlappedWindow(w, left, top, right, x);
00458         DrawOverlappedWindow(w, left, x, right, bottom);
00459         return;
00460       }
00461 
00462       if (bottom > (x = v->top + v->height)) {
00463         DrawOverlappedWindow(w, left, top, right, x);
00464         DrawOverlappedWindow(w, left, x, right, bottom);
00465         return;
00466       }
00467 
00468       return;
00469     }
00470   }
00471 
00472   /* Setup blitter, and dispatch a repaint event to window *wz */
00473   DrawPixelInfo *dp = _cur_dpi;
00474   dp->width = right - left;
00475   dp->height = bottom - top;
00476   dp->left = left - w->left;
00477   dp->top = top - w->top;
00478   dp->pitch = _screen.pitch;
00479   dp->dst_ptr = BlitterFactoryBase::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
00480   dp->zoom = ZOOM_LVL_NORMAL;
00481   w->OnPaint();
00482 }
00483 
00492 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
00493 {
00494   Window *w;
00495   DrawPixelInfo bk;
00496   _cur_dpi = &bk;
00497 
00498   FOR_ALL_WINDOWS_FROM_BACK(w) {
00499     if (right > w->left &&
00500         bottom > w->top &&
00501         left < w->left + w->width &&
00502         top < w->top + w->height) {
00503       /* Window w intersects with the rectangle => needs repaint */
00504       DrawOverlappedWindow(w, left, top, right, bottom);
00505     }
00506   }
00507 }
00508 
00513 void Window::SetDirty() const
00514 {
00515   SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
00516 }
00517 
00523 void Window::ReInit(int rx, int ry)
00524 {
00525   this->SetDirty(); // Mark whole current window as dirty.
00526 
00527   /* Save current size. */
00528   int window_width  = this->width;
00529   int window_height = this->height;
00530 
00531   this->OnInit();
00532   /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
00533   this->nested_root->SetupSmallestSize(this, false);
00534   this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _dynlang.text_dir == TD_RTL);
00535   this->width  = this->nested_root->smallest_x;
00536   this->height = this->nested_root->smallest_y;
00537   this->resize.step_width  = this->nested_root->resize_x;
00538   this->resize.step_height = this->nested_root->resize_y;
00539 
00540   /* Resize as close to the original size + requested resize as possible. */
00541   window_width  = max(window_width  + rx, this->width);
00542   window_height = max(window_height + ry, this->height);
00543   int dx = (this->resize.step_width  == 0) ? 0 : window_width  - this->width;
00544   int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
00545   /* dx and dy has to go by step.. calculate it.
00546    * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
00547   if (this->resize.step_width  > 1) dx -= dx % (int)this->resize.step_width;
00548   if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
00549 
00550   ResizeWindow(this, dx, dy);
00551   this->OnResize();
00552   this->SetDirty();
00553 }
00554 
00559 void Window::SetShaded(bool make_shaded)
00560 {
00561   if (this->shade_select == NULL) return;
00562 
00563   int desired = make_shaded ? SZSP_HORIZONTAL : 0;
00564   if (this->shade_select->shown_plane != desired) {
00565     if (make_shaded) {
00566       this->unshaded_size.width  = this->width;
00567       this->unshaded_size.height = this->height;
00568       this->shade_select->SetDisplayedPlane(desired);
00569       this->ReInit(0, -this->height);
00570     } else {
00571       this->shade_select->SetDisplayedPlane(desired);
00572       int dx = ((int)this->unshaded_size.width  > this->width)  ? (int)this->unshaded_size.width  - this->width  : 0;
00573       int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
00574       this->ReInit(dx, dy);
00575     }
00576   }
00577 }
00578 
00584 static Window *FindChildWindow(const Window *w, WindowClass wc)
00585 {
00586   Window *v;
00587   FOR_ALL_WINDOWS_FROM_BACK(v) {
00588     if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
00589   }
00590 
00591   return NULL;
00592 }
00593 
00598 void Window::DeleteChildWindows(WindowClass wc) const
00599 {
00600   Window *child = FindChildWindow(this, wc);
00601   while (child != NULL) {
00602     delete child;
00603     child = FindChildWindow(this, wc);
00604   }
00605 }
00606 
00610 Window::~Window()
00611 {
00612   if (_thd.place_mode != HT_NONE &&
00613       _thd.window_class == this->window_class &&
00614       _thd.window_number == this->window_number) {
00615     ResetObjectToPlace();
00616   }
00617 
00618   /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
00619   if (_mouseover_last_w == this) _mouseover_last_w = NULL;
00620 
00621   /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
00622   if (_focused_window == this) _focused_window = NULL;
00623 
00624   this->DeleteChildWindows();
00625 
00626   if (this->viewport != NULL) DeleteWindowViewport(this);
00627 
00628   this->SetDirty();
00629 
00630   free(this->nested_array); // Contents is released through deletion of #nested_root.
00631   delete this->nested_root;
00632 
00633   this->window_class = WC_INVALID;
00634 }
00635 
00642 Window *FindWindowById(WindowClass cls, WindowNumber number)
00643 {
00644   Window *w;
00645   FOR_ALL_WINDOWS_FROM_BACK(w) {
00646     if (w->window_class == cls && w->window_number == number) return w;
00647   }
00648 
00649   return NULL;
00650 }
00651 
00658 Window *FindWindowByClass(WindowClass cls)
00659 {
00660   Window *w;
00661   FOR_ALL_WINDOWS_FROM_BACK(w) {
00662     if (w->window_class == cls) return w;
00663   }
00664 
00665   return NULL;
00666 }
00667 
00674 void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
00675 {
00676   Window *w = FindWindowById(cls, number);
00677   if (force || w == NULL ||
00678       (w->flags4 & WF_STICKY) == 0) {
00679     delete w;
00680   }
00681 }
00682 
00687 void DeleteWindowByClass(WindowClass cls)
00688 {
00689   Window *w;
00690 
00691 restart_search:
00692   /* When we find the window to delete, we need to restart the search
00693    * as deleting this window could cascade in deleting (many) others
00694    * anywhere in the z-array */
00695   FOR_ALL_WINDOWS_FROM_BACK(w) {
00696     if (w->window_class == cls) {
00697       delete w;
00698       goto restart_search;
00699     }
00700   }
00701 }
00702 
00707 void DeleteCompanyWindows(CompanyID id)
00708 {
00709   Window *w;
00710 
00711 restart_search:
00712   /* When we find the window to delete, we need to restart the search
00713    * as deleting this window could cascade in deleting (many) others
00714    * anywhere in the z-array */
00715   FOR_ALL_WINDOWS_FROM_BACK(w) {
00716     if (w->owner == id) {
00717       delete w;
00718       goto restart_search;
00719     }
00720   }
00721 
00722   /* Also delete the company specific windows, that don't have a company-colour */
00723   DeleteWindowById(WC_BUY_COMPANY, id);
00724 }
00725 
00731 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
00732 {
00733   Window *w;
00734   FOR_ALL_WINDOWS_FROM_BACK(w) {
00735     if (w->owner != old_owner) continue;
00736 
00737     switch (w->window_class) {
00738       case WC_COMPANY_COLOUR:
00739       case WC_FINANCES:
00740       case WC_STATION_LIST:
00741       case WC_TRAINS_LIST:
00742       case WC_ROADVEH_LIST:
00743       case WC_SHIPS_LIST:
00744       case WC_AIRCRAFT_LIST:
00745       case WC_BUY_COMPANY:
00746       case WC_COMPANY:
00747         continue;
00748 
00749       default:
00750         w->owner = new_owner;
00751         break;
00752     }
00753   }
00754 }
00755 
00756 static void BringWindowToFront(Window *w);
00757 
00763 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
00764 {
00765   Window *w = FindWindowById(cls, number);
00766 
00767   if (w != NULL) {
00768     if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
00769 
00770     w->flags4 |= WF_WHITE_BORDER_MASK;
00771     BringWindowToFront(w);
00772     w->SetDirty();
00773   }
00774 
00775   return w;
00776 }
00777 
00778 static inline bool IsVitalWindow(const Window *w)
00779 {
00780   switch (w->window_class) {
00781     case WC_MAIN_TOOLBAR:
00782     case WC_STATUS_BAR:
00783     case WC_NEWS_WINDOW:
00784     case WC_SEND_NETWORK_MSG:
00785       return true;
00786 
00787     default:
00788       return false;
00789   }
00790 }
00791 
00800 static void BringWindowToFront(Window *w)
00801 {
00802   Window *v = _z_front_window;
00803 
00804   /* Bring the window just below the vital windows */
00805   for (; v != NULL && v != w && IsVitalWindow(v); v = v->z_back) { }
00806 
00807   if (v == NULL || w == v) return; // window is already in the right position
00808 
00809   /* w cannot be at the top already! */
00810   assert(w != _z_front_window);
00811 
00812   if (w->z_back == NULL) {
00813     _z_back_window = w->z_front;
00814   } else {
00815     w->z_back->z_front = w->z_front;
00816   }
00817   w->z_front->z_back = w->z_back;
00818 
00819   w->z_front = v->z_front;
00820   w->z_back = v;
00821 
00822   if (v->z_front == NULL) {
00823     _z_front_window = w;
00824   } else {
00825     v->z_front->z_back = w;
00826   }
00827   v->z_front = w;
00828 
00829   w->SetDirty();
00830 }
00831 
00841 void Window::InitializeData(WindowClass cls, int window_number, uint32 desc_flags)
00842 {
00843   /* Set up window properties; some of them are needed to set up smallest size below */
00844   this->window_class = cls;
00845   this->flags4 |= WF_WHITE_BORDER_MASK; // just opened windows have a white border
00846   this->owner = INVALID_OWNER;
00847   this->nested_focus = NULL;
00848   this->window_number = window_number;
00849   this->desc_flags = desc_flags;
00850 
00851   this->OnInit();
00852   /* Initialize nested widget tree. */
00853   if (this->nested_array == NULL) {
00854     this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
00855     this->nested_root->SetupSmallestSize(this, true);
00856   } else {
00857     this->nested_root->SetupSmallestSize(this, false);
00858   }
00859   /* Initialize to smallest size. */
00860   this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _dynlang.text_dir == TD_RTL);
00861 
00862   /* Further set up window properties,
00863    * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
00864   this->resize.step_width  = this->nested_root->resize_x;
00865   this->resize.step_height = this->nested_root->resize_y;
00866 
00867   /* Give focus to the opened window unless it is the OSK window or a text box
00868    * of focused window has focus (so we don't interrupt typing). But if the new
00869    * window has a text box, then take focus anyway. */
00870   if (this->window_class != WC_OSK && (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != NULL)) SetFocusedWindow(this);
00871 
00872   /* Hacky way of specifying always-on-top windows. These windows are
00873    * always above other windows because they are moved below them.
00874    * status-bar is above news-window because it has been created earlier.
00875    * Also, as the chat-window is excluded from this, it will always be
00876    * the last window, thus always on top.
00877    * XXX - Yes, ugly, probably needs something like w->always_on_top flag
00878    * to implement correctly, but even then you need some kind of distinction
00879    * between on-top of chat/news and status windows, because these conflict */
00880   Window *w = _z_front_window;
00881   if (w != NULL && this->window_class != WC_SEND_NETWORK_MSG && this->window_class != WC_HIGHSCORE && this->window_class != WC_ENDSCREEN) {
00882     if (FindWindowById(WC_MAIN_TOOLBAR, 0)     != NULL) w = w->z_back;
00883     if (FindWindowById(WC_STATUS_BAR, 0)       != NULL) w = w->z_back;
00884     if (FindWindowById(WC_NEWS_WINDOW, 0)      != NULL) w = w->z_back;
00885     if (FindWindowByClass(WC_SEND_NETWORK_MSG) != NULL) w = w->z_back;
00886 
00887     if (w == NULL) {
00888       _z_back_window->z_front = this;
00889       this->z_back = _z_back_window;
00890       _z_back_window = this;
00891     } else {
00892       if (w->z_front == NULL) {
00893         _z_front_window = this;
00894       } else {
00895         this->z_front = w->z_front;
00896         w->z_front->z_back = this;
00897       }
00898 
00899       this->z_back = w;
00900       w->z_front = this;
00901     }
00902   } else {
00903     this->z_back = _z_front_window;
00904     if (_z_front_window != NULL) {
00905       _z_front_window->z_front = this;
00906     } else {
00907       _z_back_window = this;
00908     }
00909     _z_front_window = this;
00910   }
00911 }
00912 
00920 void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
00921 {
00922   this->left = x;
00923   this->top = y;
00924   this->width = sm_width;
00925   this->height = sm_height;
00926 }
00927 
00938 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
00939 {
00940   def_width  = max(def_width,  this->width); // Don't allow default size to be smaller than smallest size
00941   def_height = max(def_height, this->height);
00942   /* Try to make windows smaller when our window is too small.
00943    * w->(width|height) is normally the same as min_(width|height),
00944    * but this way the GUIs can be made a little more dynamic;
00945    * one can use the same spec for multiple windows and those
00946    * can then determine the real minimum size of the window. */
00947   if (this->width != def_width || this->height != def_height) {
00948     /* Think about the overlapping toolbars when determining the minimum window size */
00949     int free_height = _screen.height;
00950     const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
00951     if (wt != NULL) free_height -= wt->height;
00952     wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
00953     if (wt != NULL) free_height -= wt->height;
00954 
00955     int enlarge_x = max(min(def_width  - this->width,  _screen.width - this->width),  0);
00956     int enlarge_y = max(min(def_height - this->height, free_height   - this->height), 0);
00957 
00958     /* X and Y has to go by step.. calculate it.
00959      * The cast to int is necessary else x/y are implicitly casted to
00960      * unsigned int, which won't work. */
00961     if (this->resize.step_width  > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
00962     if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
00963 
00964     ResizeWindow(this, enlarge_x, enlarge_y);
00965   }
00966 
00967   /* Always call OnResize; that way the scrollbars and matrices get initialized */
00968   this->OnResize();
00969 
00970   int nx = this->left;
00971   int ny = this->top;
00972 
00973   if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
00974 
00975   const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
00976   ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
00977   nx = max(nx, 0);
00978 
00979   if (this->viewport != NULL) {
00980     this->viewport->left += nx - this->left;
00981     this->viewport->top  += ny - this->top;
00982   }
00983   this->left = nx;
00984   this->top = ny;
00985 
00986   this->SetDirty();
00987 }
00988 
01000 static bool IsGoodAutoPlace1(int left, int top, int width, int height, Point &pos)
01001 {
01002   int right  = width + left;
01003   int bottom = height + top;
01004 
01005   if (left < 0 || top < 22 || right > _screen.width || bottom > _screen.height) return false;
01006 
01007   /* Make sure it is not obscured by any window. */
01008   const Window *w;
01009   FOR_ALL_WINDOWS_FROM_BACK(w) {
01010     if (w->window_class == WC_MAIN_WINDOW) continue;
01011 
01012     if (right > w->left &&
01013         w->left + w->width > left &&
01014         bottom > w->top &&
01015         w->top + w->height > top) {
01016       return false;
01017     }
01018   }
01019 
01020   pos.x = left;
01021   pos.y = top;
01022   return true;
01023 }
01024 
01036 static bool IsGoodAutoPlace2(int left, int top, int width, int height, Point &pos)
01037 {
01038   /* Left part of the rectangle may be at most 1/4 off-screen,
01039    * right part of the rectangle may be at most 1/2 off-screen
01040    */
01041   if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
01042   /* Bottom part of the rectangle may be at most 1/4 off-screen */
01043   if (top < 22 || top > _screen.height - (height >> 2)) return false;
01044 
01045   /* Make sure it is not obscured by any window. */
01046   const Window *w;
01047   FOR_ALL_WINDOWS_FROM_BACK(w) {
01048     if (w->window_class == WC_MAIN_WINDOW) continue;
01049 
01050     if (left + width > w->left &&
01051         w->left + w->width > left &&
01052         top + height > w->top &&
01053         w->top + w->height > top) {
01054       return false;
01055     }
01056   }
01057 
01058   pos.x = left;
01059   pos.y = top;
01060   return true;
01061 }
01062 
01069 static Point GetAutoPlacePosition(int width, int height)
01070 {
01071   Point pt;
01072 
01073   /* First attempt, try top-left of the screen */
01074   if (IsGoodAutoPlace1(0, 24, width, height, pt)) return pt;
01075 
01076   /* Second attempt, try around all existing windows with a distance of 2 pixels.
01077    * The new window must be entirely on-screen, and not overlap with an existing window.
01078    * Eight starting points are tried, two at each corner.
01079    */
01080   const Window *w;
01081   FOR_ALL_WINDOWS_FROM_BACK(w) {
01082     if (w->window_class == WC_MAIN_WINDOW) continue;
01083 
01084     if (IsGoodAutoPlace1(w->left + w->width + 2, w->top, width, height, pt)) return pt;
01085     if (IsGoodAutoPlace1(w->left - width - 2,    w->top, width, height, pt)) return pt;
01086     if (IsGoodAutoPlace1(w->left, w->top + w->height + 2, width, height, pt)) return pt;
01087     if (IsGoodAutoPlace1(w->left, w->top - height - 2,    width, height, pt)) return pt;
01088     if (IsGoodAutoPlace1(w->left + w->width + 2, w->top + w->height - height, width, height, pt)) return pt;
01089     if (IsGoodAutoPlace1(w->left - width - 2,    w->top + w->height - height, width, height, pt)) return pt;
01090     if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height + 2, width, height, pt)) return pt;
01091     if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height - 2,    width, height, pt)) return pt;
01092   }
01093 
01094   /* Third attempt, try around all existing windows with a distance of 2 pixels.
01095    * The new window may be partly off-screen, and must not overlap with an existing window.
01096    * Only four starting points are tried.
01097    */
01098   FOR_ALL_WINDOWS_FROM_BACK(w) {
01099     if (w->window_class == WC_MAIN_WINDOW) continue;
01100 
01101     if (IsGoodAutoPlace2(w->left + w->width + 2, w->top, width, height, pt)) return pt;
01102     if (IsGoodAutoPlace2(w->left - width - 2,    w->top, width, height, pt)) return pt;
01103     if (IsGoodAutoPlace2(w->left, w->top + w->height + 2, width, height, pt)) return pt;
01104     if (IsGoodAutoPlace2(w->left, w->top - height - 2,    width, height, pt)) return pt;
01105   }
01106 
01107   /* Fourth and final attempt, put window at diagonal starting from (0, 24), try multiples
01108    * of (+5, +5)
01109    */
01110   int left = 0, top = 24;
01111 
01112 restart:
01113   FOR_ALL_WINDOWS_FROM_BACK(w) {
01114     if (w->left == left && w->top == top) {
01115       left += 5;
01116       top += 5;
01117       goto restart;
01118     }
01119   }
01120 
01121   pt.x = left;
01122   pt.y = top;
01123   return pt;
01124 }
01125 
01132 Point GetToolbarAlignedWindowPosition(int window_width)
01133 {
01134   const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
01135   assert(w != NULL);
01136   Point pt = { _dynlang.text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
01137   return pt;
01138 }
01139 
01157 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
01158 {
01159   Point pt;
01160   const Window *w;
01161 
01162   int16 default_width  = max(desc->default_width,  sm_width);
01163   int16 default_height = max(desc->default_height, sm_height);
01164 
01165   if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ &&
01166       (w = FindWindowById(desc->parent_cls, window_number)) != NULL &&
01167       w->left < _screen.width - 20 && w->left > -60 && w->top < _screen.height - 20) {
01168 
01169     pt.x = w->left + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 0 : 10);
01170     if (pt.x > _screen.width + 10 - default_width) {
01171       pt.x = (_screen.width + 10 - default_width) - 20;
01172     }
01173     pt.y = w->top + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? w->height : 10);
01174     return pt;
01175   }
01176 
01177   switch (desc->default_pos) {
01178     case WDP_ALIGN_TOOLBAR: // Align to the toolbar
01179       return GetToolbarAlignedWindowPosition(default_width);
01180 
01181     case WDP_AUTO: // Find a good automatic position for the window
01182       return GetAutoPlacePosition(default_width, default_height);
01183 
01184     case WDP_CENTER: // Centre the window horizontally
01185       pt.x = (_screen.width - default_width) / 2;
01186       pt.y = (_screen.height - default_height) / 2;
01187       break;
01188 
01189     case WDP_MANUAL:
01190       pt.x = 0;
01191       pt.y = 0;
01192       break;
01193 
01194     default:
01195       NOT_REACHED();
01196   }
01197 
01198   return pt;
01199 }
01200 
01201 /* virtual */ Point Window::OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
01202 {
01203   return LocalGetWindowPlacement(desc, sm_width, sm_height, window_number);
01204 }
01205 
01214 void Window::CreateNestedTree(const WindowDesc *desc, bool fill_nested)
01215 {
01216   int biggest_index = -1;
01217   this->nested_root = MakeWindowNWidgetTree(desc->nwid_parts, desc->nwid_length, &biggest_index, &this->shade_select);
01218   this->nested_array_size = (uint)(biggest_index + 1);
01219 
01220   if (fill_nested) {
01221     this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
01222     this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
01223   }
01224 }
01225 
01231 void Window::FinishInitNested(const WindowDesc *desc, WindowNumber window_number)
01232 {
01233   this->InitializeData(desc->cls, window_number, desc->flags);
01234   Point pt = this->OnInitialPosition(desc, this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
01235   this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
01236   this->FindWindowPlacementAndResize(desc->default_width, desc->default_height);
01237 }
01238 
01244 void Window::InitNested(const WindowDesc *desc, WindowNumber window_number)
01245 {
01246   this->CreateNestedTree(desc, false);
01247   this->FinishInitNested(desc, window_number);
01248 }
01249 
01251 Window::Window() : hscroll(false), vscroll(true), vscroll2(true)
01252 {
01253 }
01254 
01260 Window *FindWindowFromPt(int x, int y)
01261 {
01262   Window *w;
01263   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01264     if (IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
01265       return w;
01266     }
01267   }
01268 
01269   return NULL;
01270 }
01271 
01275 void InitWindowSystem()
01276 {
01277   IConsoleClose();
01278 
01279   _z_back_window = NULL;
01280   _z_front_window = NULL;
01281   _focused_window = NULL;
01282   _mouseover_last_w = NULL;
01283   _scrolling_viewport = 0;
01284 
01285   NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
01286 }
01287 
01291 void UnInitWindowSystem()
01292 {
01293   Window *w;
01294   FOR_ALL_WINDOWS_FROM_FRONT(w) delete w;
01295 
01296   for (w = _z_front_window; w != NULL; /* nothing */) {
01297     Window *to_del = w;
01298     w = w->z_back;
01299     free(to_del);
01300   }
01301 
01302   _z_front_window = NULL;
01303   _z_back_window = NULL;
01304 }
01305 
01309 void ResetWindowSystem()
01310 {
01311   UnInitWindowSystem();
01312   InitWindowSystem();
01313   _thd.pos.x = 0;
01314   _thd.pos.y = 0;
01315   _thd.new_pos.x = 0;
01316   _thd.new_pos.y = 0;
01317 }
01318 
01319 static void DecreaseWindowCounters()
01320 {
01321   Window *w;
01322   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01323     /* Unclick scrollbar buttons if they are pressed. */
01324     if (w->flags4 & (WF_SCROLL_DOWN | WF_SCROLL_UP)) {
01325       w->flags4 &= ~(WF_SCROLL_DOWN | WF_SCROLL_UP);
01326       w->SetDirty();
01327     }
01328     w->OnMouseLoop();
01329   }
01330 
01331   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01332     if ((w->flags4 & WF_TIMEOUT_MASK) && !(--w->flags4 & WF_TIMEOUT_MASK)) {
01333       w->OnTimeout();
01334       if (w->desc_flags & WDF_UNCLICK_BUTTONS) w->RaiseButtons(true);
01335     }
01336   }
01337 }
01338 
01339 Window *GetCallbackWnd()
01340 {
01341   return FindWindowById(_thd.window_class, _thd.window_number);
01342 }
01343 
01344 static void HandlePlacePresize()
01345 {
01346   if (_special_mouse_mode != WSM_PRESIZE) return;
01347 
01348   Window *w = GetCallbackWnd();
01349   if (w == NULL) return;
01350 
01351   Point pt = GetTileBelowCursor();
01352   if (pt.x == -1) {
01353     _thd.selend.x = -1;
01354     return;
01355   }
01356 
01357   w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
01358 }
01359 
01360 static bool HandleDragDrop()
01361 {
01362   if (_special_mouse_mode != WSM_DRAGDROP) return true;
01363   if (_left_button_down) return false;
01364 
01365   Window *w = GetCallbackWnd();
01366 
01367   if (w != NULL) {
01368     /* send an event in client coordinates. */
01369     Point pt;
01370     pt.x = _cursor.pos.x - w->left;
01371     pt.y = _cursor.pos.y - w->top;
01372     w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
01373   }
01374 
01375   ResetObjectToPlace();
01376 
01377   return false;
01378 }
01379 
01380 static bool HandleMouseOver()
01381 {
01382   Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
01383 
01384   /* We changed window, put a MOUSEOVER event to the last window */
01385   if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
01386     /* Reset mouse-over coordinates of previous window */
01387     Point pt = { -1, -1 };
01388     _mouseover_last_w->OnMouseOver(pt, 0);
01389   }
01390 
01391   /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
01392   _mouseover_last_w = w;
01393 
01394   if (w != NULL) {
01395     /* send an event in client coordinates. */
01396     Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
01397     const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
01398     if (widget != NULL) w->OnMouseOver(pt, widget->index);
01399   }
01400 
01401   /* Mouseover never stops execution */
01402   return true;
01403 }
01404 
01414 void ResizeWindow(Window *w, int delta_x, int delta_y)
01415 {
01416   if (delta_x == 0 && delta_y == 0) return;
01417 
01418   w->SetDirty();
01419 
01420   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);
01421   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);
01422   assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
01423   assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
01424 
01425   w->nested_root->AssignSizePosition(ST_RESIZE, 0, 0, w->nested_root->smallest_x + new_xinc, w->nested_root->smallest_y + new_yinc, _dynlang.text_dir == TD_RTL);
01426   w->width  = w->nested_root->current_x;
01427   w->height = w->nested_root->current_y;
01428   w->SetDirty();
01429 }
01430 
01435 int GetMainViewTop()
01436 {
01437   Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
01438   return (w == NULL) ? 0 : w->top + w->height;
01439 }
01440 
01445 int GetMainViewBottom()
01446 {
01447   Window *w = FindWindowById(WC_STATUS_BAR, 0);
01448   return (w == NULL) ? _screen.height : w->top;
01449 }
01450 
01452 static const int MIN_VISIBLE_TITLE_BAR = 13;
01453 
01455 enum PreventHideDirection {
01456   PHD_UP,   
01457   PHD_DOWN, 
01458 };
01459 
01470 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
01471 {
01472   if (v == NULL) return;
01473 
01474   int v_bottom = v->top + v->height;
01475   int v_right = v->left + v->width;
01476   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.
01477 
01478   if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
01479   if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
01480 
01481   /* Vertically, the rectangle is hidden behind v. */
01482   if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
01483     if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
01484     return;
01485   }
01486   if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
01487     if (v_right > _screen.width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
01488     return;
01489   }
01490 
01491   /* Horizontally also hidden, force movement to a safe area. */
01492   if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
01493     *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
01494   } else if (px + rect.right > v_right && v_right <= _screen.width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
01495     *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
01496   } else {
01497     *ny = safe_y;
01498   }
01499 }
01500 
01501 static bool _dragging_window; 
01502 
01503 static bool HandleWindowDragging()
01504 {
01505   /* Get out immediately if no window is being dragged at all. */
01506   if (!_dragging_window) return true;
01507 
01508   /* If button still down, but cursor hasn't moved, there is nothing to do. */
01509   if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return false;
01510 
01511   /* Otherwise find the window... */
01512   Window *w;
01513   FOR_ALL_WINDOWS_FROM_BACK(w) {
01514     if (w->flags4 & WF_DRAGGING) {
01515       /* Stop the dragging if the left mouse button was released */
01516       if (!_left_button_down) {
01517         w->flags4 &= ~WF_DRAGGING;
01518         break;
01519       }
01520 
01521       w->SetDirty();
01522 
01523       int x = _cursor.pos.x + _drag_delta.x;
01524       int y = _cursor.pos.y + _drag_delta.y;
01525       int nx = x;
01526       int ny = y;
01527 
01528       if (_settings_client.gui.window_snap_radius != 0) {
01529         const Window *v;
01530 
01531         int hsnap = _settings_client.gui.window_snap_radius;
01532         int vsnap = _settings_client.gui.window_snap_radius;
01533         int delta;
01534 
01535         FOR_ALL_WINDOWS_FROM_BACK(v) {
01536           if (v == w) continue; // Don't snap at yourself
01537 
01538           if (y + w->height > v->top && y < v->top + v->height) {
01539             /* Your left border <-> other right border */
01540             delta = abs(v->left + v->width - x);
01541             if (delta <= hsnap) {
01542               nx = v->left + v->width;
01543               hsnap = delta;
01544             }
01545 
01546             /* Your right border <-> other left border */
01547             delta = abs(v->left - x - w->width);
01548             if (delta <= hsnap) {
01549               nx = v->left - w->width;
01550               hsnap = delta;
01551             }
01552           }
01553 
01554           if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
01555             /* Your left border <-> other left border */
01556             delta = abs(v->left - x);
01557             if (delta <= hsnap) {
01558               nx = v->left;
01559               hsnap = delta;
01560             }
01561 
01562             /* Your right border <-> other right border */
01563             delta = abs(v->left + v->width - x - w->width);
01564             if (delta <= hsnap) {
01565               nx = v->left + v->width - w->width;
01566               hsnap = delta;
01567             }
01568           }
01569 
01570           if (x + w->width > v->left && x < v->left + v->width) {
01571             /* Your top border <-> other bottom border */
01572             delta = abs(v->top + v->height - y);
01573             if (delta <= vsnap) {
01574               ny = v->top + v->height;
01575               vsnap = delta;
01576             }
01577 
01578             /* Your bottom border <-> other top border */
01579             delta = abs(v->top - y - w->height);
01580             if (delta <= vsnap) {
01581               ny = v->top - w->height;
01582               vsnap = delta;
01583             }
01584           }
01585 
01586           if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
01587             /* Your top border <-> other top border */
01588             delta = abs(v->top - y);
01589             if (delta <= vsnap) {
01590               ny = v->top;
01591               vsnap = delta;
01592             }
01593 
01594             /* Your bottom border <-> other bottom border */
01595             delta = abs(v->top + v->height - y - w->height);
01596             if (delta <= vsnap) {
01597               ny = v->top + v->height - w->height;
01598               vsnap = delta;
01599             }
01600           }
01601         }
01602       }
01603 
01604       /* Search for the title bar rectangle. */
01605       Rect caption_rect;
01606       const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
01607       assert(caption != NULL);
01608       caption_rect.left   = caption->pos_x;
01609       caption_rect.right  = caption->pos_x + caption->current_x;
01610       caption_rect.top    = caption->pos_y;
01611       caption_rect.bottom = caption->pos_y + caption->current_y;
01612 
01613       /* Make sure the window doesn't leave the screen */
01614       nx = Clamp(nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen.width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
01615       ny = Clamp(ny, 0, _screen.height - MIN_VISIBLE_TITLE_BAR);
01616 
01617       /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
01618       PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
01619       PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR,   0), w->left, PHD_UP);
01620 
01621       if (w->viewport != NULL) {
01622         w->viewport->left += nx - w->left;
01623         w->viewport->top  += ny - w->top;
01624       }
01625       w->left = nx;
01626       w->top  = ny;
01627 
01628       w->SetDirty();
01629       return false;
01630     } else if (w->flags4 & WF_SIZING) {
01631       /* Stop the sizing if the left mouse button was released */
01632       if (!_left_button_down) {
01633         w->flags4 &= ~WF_SIZING;
01634         w->SetDirty();
01635         break;
01636       }
01637 
01638       /* Compute difference in pixels between cursor position and reference point in the window.
01639        * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
01640        */
01641       int x, y = _cursor.pos.y - _drag_delta.y;
01642       if (w->flags4 & WF_SIZING_LEFT) {
01643         x = _drag_delta.x - _cursor.pos.x;
01644       } else {
01645         x = _cursor.pos.x - _drag_delta.x;
01646       }
01647 
01648       /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
01649       if (w->resize.step_width  == 0) x = 0;
01650       if (w->resize.step_height == 0) y = 0;
01651 
01652       /* X and Y has to go by step.. calculate it.
01653        * The cast to int is necessary else x/y are implicitly casted to
01654        * unsigned int, which won't work. */
01655       if (w->resize.step_width  > 1) x -= x % (int)w->resize.step_width;
01656       if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
01657 
01658       /* Check that we don't go below the minimum set size */
01659       if ((int)w->width + x < (int)w->nested_root->smallest_x) {
01660         x = w->nested_root->smallest_x - w->width;
01661       }
01662       if ((int)w->height + y < (int)w->nested_root->smallest_y) {
01663         y = w->nested_root->smallest_y - w->height;
01664       }
01665 
01666       /* Window already on size */
01667       if (x == 0 && y == 0) return false;
01668 
01669       /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
01670       _drag_delta.y += y;
01671       if ((w->flags4 & WF_SIZING_LEFT) && x != 0) {
01672         _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
01673         w->SetDirty();
01674         w->left -= x;  // If dragging left edge, move left window edge in opposite direction by the same amount.
01675         /* ResizeWindow() below ensures marking new position as dirty. */
01676       } else {
01677         _drag_delta.x += x;
01678       }
01679 
01680       /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
01681       ResizeWindow(w, x, y);
01682       w->OnResize();
01683       return false;
01684     }
01685   }
01686 
01687   _dragging_window = false;
01688   return false;
01689 }
01690 
01695 static void StartWindowDrag(Window *w)
01696 {
01697   w->flags4 |= WF_DRAGGING;
01698   _dragging_window = true;
01699 
01700   _drag_delta.x = w->left - _cursor.pos.x;
01701   _drag_delta.y = w->top  - _cursor.pos.y;
01702 
01703   BringWindowToFront(w);
01704   DeleteWindowById(WC_DROPDOWN_MENU, 0);
01705 }
01706 
01712 static void StartWindowSizing(Window *w, bool to_left)
01713 {
01714   w->flags4 |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
01715   _dragging_window = true;
01716 
01717   _drag_delta.x = _cursor.pos.x;
01718   _drag_delta.y = _cursor.pos.y;
01719 
01720   BringWindowToFront(w);
01721   DeleteWindowById(WC_DROPDOWN_MENU, 0);
01722 }
01723 
01724 
01725 static bool HandleScrollbarScrolling()
01726 {
01727   Window *w;
01728 
01729   /* Get out quickly if no item is being scrolled */
01730   if (!_scrolling_scrollbar) return true;
01731 
01732   /* Find the scrolling window */
01733   FOR_ALL_WINDOWS_FROM_BACK(w) {
01734     if (w->flags4 & WF_SCROLL_MIDDLE) {
01735       /* Abort if no button is clicked any more. */
01736       if (!_left_button_down) {
01737         w->flags4 &= ~WF_SCROLL_MIDDLE;
01738         w->SetDirty();
01739         break;
01740       }
01741 
01742       int i;
01743       Scrollbar *sb;
01744       bool rtl = false;
01745 
01746       if (w->flags4 & WF_HSCROLL) {
01747         sb = &w->hscroll;
01748         i = _cursor.pos.x - _cursorpos_drag_start.x;
01749         rtl = _dynlang.text_dir == TD_RTL;
01750       } else if (w->flags4 & WF_SCROLL2) {
01751         sb = &w->vscroll2;
01752         i = _cursor.pos.y - _cursorpos_drag_start.y;
01753       } else {
01754         sb = &w->vscroll;
01755         i = _cursor.pos.y - _cursorpos_drag_start.y;
01756       }
01757 
01758       /* Find the item we want to move to and make sure it's inside bounds. */
01759       int pos = min(max(0, i + _scrollbar_start_pos) * sb->GetCount() / _scrollbar_size, max(0, sb->GetCount() - sb->GetCapacity()));
01760       if (rtl) pos = max(0, sb->GetCount() - sb->GetCapacity() - pos);
01761       if (pos != sb->GetPosition()) {
01762         sb->SetPosition(pos);
01763         w->SetDirty();
01764       }
01765       return false;
01766     }
01767   }
01768 
01769   _scrolling_scrollbar = false;
01770   return false;
01771 }
01772 
01773 static bool HandleViewportScroll()
01774 {
01775   bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
01776 
01777   if (!_scrolling_viewport) return true;
01778 
01779   Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
01780 
01781   if (!(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) || w == NULL) {
01782     _cursor.fix_at = false;
01783     _scrolling_viewport = false;
01784     return true;
01785   }
01786 
01787   if (w == FindWindowById(WC_MAIN_WINDOW, 0) && w->viewport->follow_vehicle != INVALID_VEHICLE) {
01788     /* If the main window is following a vehicle, then first let go of it! */
01789     const Vehicle *veh = Vehicle::Get(w->viewport->follow_vehicle);
01790     ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
01791     return true;
01792   }
01793 
01794   Point delta;
01795   if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
01796     delta.x = -_cursor.delta.x;
01797     delta.y = -_cursor.delta.y;
01798   } else {
01799     delta.x = _cursor.delta.x;
01800     delta.y = _cursor.delta.y;
01801   }
01802 
01803   if (scrollwheel_scrolling) {
01804     /* We are using scrollwheels for scrolling */
01805     delta.x = _cursor.h_wheel;
01806     delta.y = _cursor.v_wheel;
01807     _cursor.v_wheel = 0;
01808     _cursor.h_wheel = 0;
01809   }
01810 
01811   /* Create a scroll-event and send it to the window */
01812   if (delta.x != 0 || delta.y != 0) w->OnScroll(delta);
01813 
01814   _cursor.delta.x = 0;
01815   _cursor.delta.y = 0;
01816   return false;
01817 }
01818 
01827 static bool MaybeBringWindowToFront(Window *w)
01828 {
01829   bool bring_to_front = false;
01830 
01831   if (w->window_class == WC_MAIN_WINDOW ||
01832       IsVitalWindow(w) ||
01833       w->window_class == WC_TOOLTIPS ||
01834       w->window_class == WC_DROPDOWN_MENU) {
01835     return true;
01836   }
01837 
01838   /* Use unshaded window size rather than current size for shaded windows. */
01839   int w_width  = w->width;
01840   int w_height = w->height;
01841   if (w->IsShaded()) {
01842     w_width  = w->unshaded_size.width;
01843     w_height = w->unshaded_size.height;
01844   }
01845 
01846   Window *u;
01847   FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
01848     /* A modal child will prevent the activation of the parent window */
01849     if (u->parent == w && (u->desc_flags & WDF_MODAL)) {
01850       u->flags4 |= WF_WHITE_BORDER_MASK;
01851       u->SetDirty();
01852       return false;
01853     }
01854 
01855     if (u->window_class == WC_MAIN_WINDOW ||
01856         IsVitalWindow(u) ||
01857         u->window_class == WC_TOOLTIPS ||
01858         u->window_class == WC_DROPDOWN_MENU) {
01859       continue;
01860     }
01861 
01862     /* Window sizes don't interfere, leave z-order alone */
01863     if (w->left + w_width <= u->left ||
01864         u->left + u->width <= w->left ||
01865         w->top  + w_height <= u->top ||
01866         u->top + u->height <= w->top) {
01867       continue;
01868     }
01869 
01870     bring_to_front = true;
01871   }
01872 
01873   if (bring_to_front) BringWindowToFront(w);
01874   return true;
01875 }
01876 
01880 void HandleKeypress(uint32 raw_key)
01881 {
01882   /*
01883    * During the generation of the world, there might be
01884    * another thread that is currently building for example
01885    * a road. To not interfere with those tasks, we should
01886    * NOT change the _current_company here.
01887    *
01888    * This is not necessary either, as the only events that
01889    * can be handled are the 'close application' events
01890    */
01891   if (!IsGeneratingWorld()) _current_company = _local_company;
01892 
01893   /* Setup event */
01894   uint16 key     = GB(raw_key,  0, 16);
01895   uint16 keycode = GB(raw_key, 16, 16);
01896 
01897   /*
01898    * The Unicode standard defines an area called the private use area. Code points in this
01899    * area are reserved for private use and thus not portable between systems. For instance,
01900    * Apple defines code points for the arrow keys in this area, but these are only printable
01901    * on a system running OS X. We don't want these keys to show up in text fields and such,
01902    * and thus we have to clear the unicode character when we encounter such a key.
01903    */
01904   if (key >= 0xE000 && key <= 0xF8FF) key = 0;
01905 
01906   /*
01907    * If both key and keycode is zero, we don't bother to process the event.
01908    */
01909   if (key == 0 && keycode == 0) return;
01910 
01911   /* Check if the focused window has a focused editbox */
01912   if (EditBoxInGlobalFocus()) {
01913     /* All input will in this case go to the focused window */
01914     if (_focused_window->OnKeyPress(key, keycode) == Window::ES_HANDLED) return;
01915   }
01916 
01917   /* Call the event, start with the uppermost window, but ignore the toolbar. */
01918   Window *w;
01919   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01920     if (w->window_class == WC_MAIN_TOOLBAR) continue;
01921     if (w->OnKeyPress(key, keycode) == Window::ES_HANDLED) return;
01922   }
01923 
01924   w = FindWindowById(WC_MAIN_TOOLBAR, 0);
01925   /* When there is no toolbar w is null, check for that */
01926   if (w != NULL) w->OnKeyPress(key, keycode);
01927 }
01928 
01932 void HandleCtrlChanged()
01933 {
01934   /* Call the event, start with the uppermost window. */
01935   Window *w;
01936   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01937     if (w->OnCTRLStateChange() == Window::ES_HANDLED) return;
01938   }
01939 }
01940 
01947 static int _input_events_this_tick = 0;
01948 
01953 static void HandleAutoscroll()
01954 {
01955   if (_settings_client.gui.autoscroll && _game_mode != GM_MENU && !IsGeneratingWorld()) {
01956     int x = _cursor.pos.x;
01957     int y = _cursor.pos.y;
01958     Window *w = FindWindowFromPt(x, y);
01959     if (w == NULL || w->flags4 & WF_DISABLE_VP_SCROLL) return;
01960     ViewPort *vp = IsPtInWindowViewport(w, x, y);
01961     if (vp != NULL) {
01962       x -= vp->left;
01963       y -= vp->top;
01964 
01965       /* here allows scrolling in both x and y axis */
01966 #define scrollspeed 3
01967       if (x - 15 < 0) {
01968         w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
01969       } else if (15 - (vp->width - x) > 0) {
01970         w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
01971       }
01972       if (y - 15 < 0) {
01973         w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
01974       } else if (15 - (vp->height - y) > 0) {
01975         w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
01976       }
01977 #undef scrollspeed
01978     }
01979   }
01980 }
01981 
01982 enum MouseClick {
01983   MC_NONE = 0,
01984   MC_LEFT,
01985   MC_RIGHT,
01986   MC_DOUBLE_LEFT,
01987 
01988   MAX_OFFSET_DOUBLE_CLICK = 5,     
01989   TIME_BETWEEN_DOUBLE_CLICK = 500, 
01990 };
01991 
01992 extern bool VpHandlePlaceSizingDrag();
01993 
01994 static void ScrollMainViewport(int x, int y)
01995 {
01996   if (_game_mode != GM_MENU) {
01997     Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
01998     assert(w);
01999 
02000     w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
02001     w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
02002   }
02003 }
02004 
02014 static const int8 scrollamt[16][2] = {
02015   { 0,  0}, 
02016   {-2,  0}, 
02017   { 0, -2}, 
02018   {-2, -1}, 
02019   { 2,  0}, 
02020   { 0,  0}, 
02021   { 2, -1}, 
02022   { 0, -2}, 
02023   { 0,  2}, 
02024   {-2,  1}, 
02025   { 0,  0}, 
02026   {-2,  0}, 
02027   { 2,  1}, 
02028   { 0,  2}, 
02029   { 2,  0}, 
02030   { 0,  0}, 
02031 };
02032 
02033 static void HandleKeyScrolling()
02034 {
02035   /*
02036    * Check that any of the dirkeys is pressed and that the focused window
02037    * dont has an edit-box as focused widget.
02038    */
02039   if (_dirkeys && !EditBoxInGlobalFocus()) {
02040     int factor = _shift_pressed ? 50 : 10;
02041     ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
02042   }
02043 }
02044 
02045 static void MouseLoop(MouseClick click, int mousewheel)
02046 {
02047   HandlePlacePresize();
02048   UpdateTileSelection();
02049 
02050   if (!VpHandlePlaceSizingDrag())  return;
02051   if (!HandleDragDrop())           return;
02052   if (!HandleWindowDragging())     return;
02053   if (!HandleScrollbarScrolling()) return;
02054   if (!HandleViewportScroll())     return;
02055   if (!HandleMouseOver())          return;
02056 
02057   bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
02058   if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
02059 
02060   int x = _cursor.pos.x;
02061   int y = _cursor.pos.y;
02062   Window *w = FindWindowFromPt(x, y);
02063   if (w == NULL) return;
02064 
02065   if (!MaybeBringWindowToFront(w)) return;
02066   ViewPort *vp = IsPtInWindowViewport(w, x, y);
02067 
02068   /* Don't allow any action in a viewport if either in menu of in generating world */
02069   if (vp != NULL && (_game_mode == GM_MENU || IsGeneratingWorld())) return;
02070 
02071   if (mousewheel != 0) {
02072     if (_settings_client.gui.scrollwheel_scrolling == 0) {
02073       /* Send mousewheel event to window */
02074       w->OnMouseWheel(mousewheel);
02075     }
02076 
02077     /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
02078     if (vp == NULL) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
02079   }
02080 
02081   if (vp != NULL) {
02082     if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
02083     switch (click) {
02084       case MC_DOUBLE_LEFT:
02085       case MC_LEFT:
02086         DEBUG(misc, 2, "Cursor: 0x%X (%d)", _cursor.sprite, _cursor.sprite);
02087         if (_thd.place_mode != HT_NONE &&
02088             /* query button and place sign button work in pause mode */
02089             _cursor.sprite != SPR_CURSOR_QUERY &&
02090             _cursor.sprite != SPR_CURSOR_SIGN &&
02091             _pause_mode != PM_UNPAUSED &&
02092             !_cheats.build_in_pause.value) {
02093           return;
02094         }
02095 
02096         if (_thd.place_mode == HT_NONE) {
02097           if (!HandleViewportClicked(vp, x, y) &&
02098               !(w->flags4 & WF_DISABLE_VP_SCROLL) &&
02099               _settings_client.gui.left_mouse_btn_scrolling) {
02100             _scrolling_viewport = true;
02101             _cursor.fix_at = false;
02102           }
02103         } else {
02104           PlaceObject();
02105         }
02106         break;
02107 
02108       case MC_RIGHT:
02109         if (!(w->flags4 & WF_DISABLE_VP_SCROLL)) {
02110           _scrolling_viewport = true;
02111           _cursor.fix_at = true;
02112 
02113           /* clear 2D scrolling caches before we start a 2D scroll */
02114           _cursor.h_wheel = 0;
02115           _cursor.v_wheel = 0;
02116         }
02117         break;
02118 
02119       default:
02120         break;
02121     }
02122   } else {
02123     switch (click) {
02124       case MC_LEFT:
02125       case MC_DOUBLE_LEFT:
02126         DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
02127         break;
02128 
02129       default:
02130         if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
02131         /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
02132          * Simulate a right button click so we can get started. */
02133 
02134         /* fallthough */
02135       case MC_RIGHT: DispatchRightClickEvent(w, x - w->left, y - w->top); break;
02136     }
02137   }
02138 }
02139 
02143 void HandleMouseEvents()
02144 {
02145   static int double_click_time = 0;
02146   static int double_click_x = 0;
02147   static int double_click_y = 0;
02148 
02149   /*
02150    * During the generation of the world, there might be
02151    * another thread that is currently building for example
02152    * a road. To not interfere with those tasks, we should
02153    * NOT change the _current_company here.
02154    *
02155    * This is not necessary either, as the only events that
02156    * can be handled are the 'close application' events
02157    */
02158   if (!IsGeneratingWorld()) _current_company = _local_company;
02159 
02160   /* Mouse event? */
02161   MouseClick click = MC_NONE;
02162   if (_left_button_down && !_left_button_clicked) {
02163     click = MC_LEFT;
02164     if (double_click_time != 0 && _realtime_tick - double_click_time   < TIME_BETWEEN_DOUBLE_CLICK &&
02165         double_click_x != 0    && abs(_cursor.pos.x - double_click_x) < MAX_OFFSET_DOUBLE_CLICK  &&
02166         double_click_y != 0    && abs(_cursor.pos.y - double_click_y) < MAX_OFFSET_DOUBLE_CLICK) {
02167       click = MC_DOUBLE_LEFT;
02168     }
02169     double_click_time = _realtime_tick;
02170     double_click_x = _cursor.pos.x;
02171     double_click_y = _cursor.pos.y;
02172     _left_button_clicked = true;
02173     _input_events_this_tick++;
02174   } else if (_right_button_clicked) {
02175     _right_button_clicked = false;
02176     click = MC_RIGHT;
02177     _input_events_this_tick++;
02178   }
02179 
02180   int mousewheel = 0;
02181   if (_cursor.wheel) {
02182     mousewheel = _cursor.wheel;
02183     _cursor.wheel = 0;
02184     _input_events_this_tick++;
02185   }
02186 
02187   MouseLoop(click, mousewheel);
02188 
02189   /* We have moved the mouse the required distance,
02190    * no need to move it at any later time. */
02191   _cursor.delta.x = 0;
02192   _cursor.delta.y = 0;
02193 }
02194 
02198 static void CheckSoftLimit()
02199 {
02200   if (_settings_client.gui.window_soft_limit == 0) return;
02201 
02202   for (;;) {
02203     uint deletable_count = 0;
02204     Window *w, *last_deletable = NULL;
02205     FOR_ALL_WINDOWS_FROM_FRONT(w) {
02206       if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags4 & WF_STICKY)) continue;
02207 
02208       last_deletable = w;
02209       deletable_count++;
02210     }
02211 
02212     /* We've ot reached the soft limit yet */
02213     if (deletable_count <= _settings_client.gui.window_soft_limit) break;
02214 
02215     assert(last_deletable != NULL);
02216     delete last_deletable;
02217   }
02218 }
02219 
02223 void InputLoop()
02224 {
02225   CheckSoftLimit();
02226   HandleKeyScrolling();
02227 
02228   /* Do the actual free of the deleted windows. */
02229   for (Window *v = _z_front_window; v != NULL; /* nothing */) {
02230     Window *w = v;
02231     v = v->z_back;
02232 
02233     if (w->window_class != WC_INVALID) continue;
02234 
02235     /* Find the window in the z-array, and effectively remove it
02236      * by moving all windows after it one to the left. This must be
02237      * done before removing the child so we cannot cause recursion
02238      * between the deletion of the parent and the child. */
02239     if (w->z_front == NULL) {
02240       _z_front_window = w->z_back;
02241     } else {
02242       w->z_front->z_back = w->z_back;
02243     }
02244     if (w->z_back == NULL) {
02245       _z_back_window  = w->z_front;
02246     } else {
02247       w->z_back->z_front = w->z_front;
02248     }
02249     free(w);
02250   }
02251 
02252   DecreaseWindowCounters();
02253 
02254   if (_input_events_this_tick != 0) {
02255     /* The input loop is called only once per GameLoop() - so we can clear the counter here */
02256     _input_events_this_tick = 0;
02257     /* there were some inputs this tick, don't scroll ??? */
02258     return;
02259   }
02260 
02261   /* HandleMouseEvents was already called for this tick */
02262   HandleMouseEvents();
02263   HandleAutoscroll();
02264 }
02265 
02269 void UpdateWindows()
02270 {
02271   Window *w;
02272   static int we4_timer = 0;
02273   int t = we4_timer + 1;
02274 
02275   if (t >= 100) {
02276     FOR_ALL_WINDOWS_FROM_FRONT(w) {
02277       w->OnHundredthTick();
02278     }
02279     t = 0;
02280   }
02281   we4_timer = t;
02282 
02283   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02284     if (w->flags4 & WF_WHITE_BORDER_MASK) {
02285       w->flags4 -= WF_WHITE_BORDER_ONE;
02286 
02287       if (!(w->flags4 & WF_WHITE_BORDER_MASK)) w->SetDirty();
02288     }
02289   }
02290 
02291   DrawDirtyBlocks();
02292 
02293   FOR_ALL_WINDOWS_FROM_BACK(w) {
02294     /* Update viewport only if window is not shaded. */
02295     if (w->viewport != NULL && !w->IsShaded()) UpdateViewportPosition(w);
02296   }
02297   NetworkDrawChatMessage();
02298   /* Redraw mouse cursor in case it was hidden */
02299   DrawMouseCursor();
02300 }
02301 
02307 void SetWindowDirty(WindowClass cls, WindowNumber number)
02308 {
02309   const Window *w;
02310   FOR_ALL_WINDOWS_FROM_BACK(w) {
02311     if (w->window_class == cls && w->window_number == number) w->SetDirty();
02312   }
02313 }
02314 
02321 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
02322 {
02323   const Window *w;
02324   FOR_ALL_WINDOWS_FROM_BACK(w) {
02325     if (w->window_class == cls && w->window_number == number) {
02326       w->SetWidgetDirty(widget_index);
02327     }
02328   }
02329 }
02330 
02335 void SetWindowClassesDirty(WindowClass cls)
02336 {
02337   Window *w;
02338   FOR_ALL_WINDOWS_FROM_BACK(w) {
02339     if (w->window_class == cls) w->SetDirty();
02340   }
02341 }
02342 
02349 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data)
02350 {
02351   Window *w;
02352   FOR_ALL_WINDOWS_FROM_BACK(w) {
02353     if (w->window_class == cls && w->window_number == number) w->InvalidateData(data);
02354   }
02355 }
02356 
02362 void InvalidateWindowClassesData(WindowClass cls, int data)
02363 {
02364   Window *w;
02365 
02366   FOR_ALL_WINDOWS_FROM_BACK(w) {
02367     if (w->window_class == cls) w->InvalidateData(data);
02368   }
02369 }
02370 
02374 void CallWindowTickEvent()
02375 {
02376   if (_scroller_click_timeout > 3) {
02377     _scroller_click_timeout -= 3;
02378   } else {
02379     _scroller_click_timeout = 0;
02380   }
02381 
02382   Window *w;
02383   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02384     w->OnTick();
02385   }
02386 }
02387 
02394 void DeleteNonVitalWindows()
02395 {
02396   Window *w;
02397 
02398 restart_search:
02399   /* When we find the window to delete, we need to restart the search
02400    * as deleting this window could cascade in deleting (many) others
02401    * anywhere in the z-array */
02402   FOR_ALL_WINDOWS_FROM_BACK(w) {
02403     if (w->window_class != WC_MAIN_WINDOW &&
02404         w->window_class != WC_SELECT_GAME &&
02405         w->window_class != WC_MAIN_TOOLBAR &&
02406         w->window_class != WC_STATUS_BAR &&
02407         w->window_class != WC_TOOLBAR_MENU &&
02408         w->window_class != WC_TOOLTIPS &&
02409         (w->flags4 & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
02410 
02411       delete w;
02412       goto restart_search;
02413     }
02414   }
02415 }
02416 
02422 void DeleteAllNonVitalWindows()
02423 {
02424   Window *w;
02425 
02426   /* Delete every window except for stickied ones, then sticky ones as well */
02427   DeleteNonVitalWindows();
02428 
02429 restart_search:
02430   /* When we find the window to delete, we need to restart the search
02431    * as deleting this window could cascade in deleting (many) others
02432    * anywhere in the z-array */
02433   FOR_ALL_WINDOWS_FROM_BACK(w) {
02434     if (w->flags4 & WF_STICKY) {
02435       delete w;
02436       goto restart_search;
02437     }
02438   }
02439 }
02440 
02445 void DeleteConstructionWindows()
02446 {
02447   Window *w;
02448 
02449 restart_search:
02450   /* When we find the window to delete, we need to restart the search
02451    * as deleting this window could cascade in deleting (many) others
02452    * anywhere in the z-array */
02453   FOR_ALL_WINDOWS_FROM_BACK(w) {
02454     if (w->desc_flags & WDF_CONSTRUCTION) {
02455       delete w;
02456       goto restart_search;
02457     }
02458   }
02459 
02460   FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
02461 }
02462 
02464 void HideVitalWindows()
02465 {
02466   DeleteWindowById(WC_TOOLBAR_MENU, 0);
02467   DeleteWindowById(WC_MAIN_TOOLBAR, 0);
02468   DeleteWindowById(WC_STATUS_BAR, 0);
02469 }
02470 
02472 void ReInitAllWindows()
02473 {
02474   NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
02475 
02476   Window *w;
02477   FOR_ALL_WINDOWS_FROM_BACK(w) {
02478     w->ReInit();
02479   }
02480 
02481   /* Make sure essential parts of all windows are visible */
02482   RelocateAllWindows(_cur_resolution.width, _cur_resolution.height);
02483   MarkWholeScreenDirty();
02484 }
02485 
02491 int PositionMainToolbar(Window *w)
02492 {
02493   DEBUG(misc, 5, "Repositioning Main Toolbar...");
02494 
02495   if (w == NULL || w->window_class != WC_MAIN_TOOLBAR) {
02496     w = FindWindowById(WC_MAIN_TOOLBAR, 0);
02497   }
02498 
02499   switch (_settings_client.gui.toolbar_pos) {
02500     case 1:  w->left = (_screen.width - w->width) / 2; break;
02501     case 2:  w->left = _screen.width - w->width; break;
02502     default: w->left = 0;
02503   }
02504   SetDirtyBlocks(0, 0, _screen.width, w->height); // invalidate the whole top part
02505   return w->left;
02506 }
02507 
02508 
02514 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
02515 {
02516   Window *w;
02517   FOR_ALL_WINDOWS_FROM_BACK(w) {
02518     if (w->viewport != NULL && w->viewport->follow_vehicle == from_index) {
02519       w->viewport->follow_vehicle = to_index;
02520       w->SetDirty();
02521     }
02522   }
02523 }
02524 
02525 
02531 void RelocateAllWindows(int neww, int newh)
02532 {
02533   Window *w;
02534 
02535   FOR_ALL_WINDOWS_FROM_BACK(w) {
02536     int left, top;
02537 
02538     if (w->window_class == WC_MAIN_WINDOW) {
02539       ViewPort *vp = w->viewport;
02540       vp->width = w->width = neww;
02541       vp->height = w->height = newh;
02542       vp->virtual_width = ScaleByZoom(neww, vp->zoom);
02543       vp->virtual_height = ScaleByZoom(newh, vp->zoom);
02544       continue; // don't modify top,left
02545     }
02546 
02547     /* XXX - this probably needs something more sane. For example specying
02548      * in a 'backup'-desc that the window should always be centred. */
02549     switch (w->window_class) {
02550       case WC_MAIN_TOOLBAR:
02551         if (neww - w->width != 0) {
02552           ResizeWindow(w, min(neww, 640) - w->width, 0);
02553           w->OnResize();
02554         }
02555 
02556         top = w->top;
02557         left = PositionMainToolbar(w); // changes toolbar orientation
02558         break;
02559 
02560       case WC_SELECT_GAME:
02561       case WC_GAME_OPTIONS:
02562       case WC_NETWORK_WINDOW:
02563         top = (newh - w->height) >> 1;
02564         left = (neww - w->width) >> 1;
02565         break;
02566 
02567       case WC_NEWS_WINDOW:
02568         top = newh - w->height;
02569         left = (neww - w->width) >> 1;
02570         break;
02571 
02572       case WC_STATUS_BAR:
02573         ResizeWindow(w, Clamp(neww, 320, 640) - w->width, 0);
02574         top = newh - w->height;
02575         left = (neww - w->width) >> 1;
02576         break;
02577 
02578       case WC_SEND_NETWORK_MSG:
02579         ResizeWindow(w, Clamp(neww, 320, 640) - w->width, 0);
02580         top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
02581         left = (neww - w->width) >> 1;
02582         break;
02583 
02584       case WC_CONSOLE:
02585         IConsoleResize(w);
02586         continue;
02587 
02588       default: {
02589         left = w->left;
02590         if (left + (w->width >> 1) >= neww) left = neww - w->width;
02591         if (left < 0) left = 0;
02592 
02593         top = w->top;
02594         if (top + (w->height >> 1) >= newh) top = newh - w->height;
02595 
02596         const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
02597         if (wt != NULL) {
02598           if (top < wt->height && wt->left < (w->left + w->width) && (wt->left + wt->width) > w->left) top = wt->height;
02599           if (top >= newh) top = newh - 1;
02600         } else {
02601           if (top < 0) top = 0;
02602         }
02603       } break;
02604     }
02605 
02606     if (w->viewport != NULL) {
02607       w->viewport->left += left - w->left;
02608       w->viewport->top += top - w->top;
02609     }
02610 
02611     w->left = left;
02612     w->top = top;
02613   }
02614 }
02615 
02620 PickerWindowBase::~PickerWindowBase()
02621 {
02622   this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
02623   ResetObjectToPlace();
02624 }

Generated on Wed Mar 3 23:32:30 2010 for OpenTTD by  doxygen 1.6.1