window.cpp

Go to the documentation of this file.
00001 /* $Id: window.cpp 21837 2011-01-18 21:08:19Z 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 "genworld.h"
00021 #include "blitter/factory.hpp"
00022 #include "zoom_func.h"
00023 #include "map_func.h"
00024 #include "vehicle_base.h"
00025 #include "cheat_type.h"
00026 #include "window_func.h"
00027 #include "tilehighlight_func.h"
00028 #include "network/network.h"
00029 #include "querystring_gui.h"
00030 #include "widgets/dropdown_func.h"
00031 #include "strings_func.h"
00032 #include "settings_type.h"
00033 #include "newgrf_debug.h"
00034 #include "hotkeys.h"
00035 #include "toolbar_gui.h"
00036 #include "statusbar_gui.h"
00037 
00038 #include "table/sprites.h"
00039 
00040 static Point _drag_delta; 
00041 static Window *_mouseover_last_w = NULL; 
00042 static Window *_last_scroll_window = NULL; 
00043 
00045 Window *_z_front_window = NULL;
00047 Window *_z_back_window  = NULL;
00048 
00049 /*
00050  * Window that currently has focus. - The main purpose is to generate
00051  * #FocusLost events, not to give next window in z-order focus when a
00052  * window is closed.
00053  */
00054 Window *_focused_window;
00055 
00056 Point _cursorpos_drag_start;
00057 
00058 int _scrollbar_start_pos;
00059 int _scrollbar_size;
00060 byte _scroller_click_timeout = 0;
00061 
00062 bool _scrolling_viewport;  
00063 bool _mouse_hovering;      
00064 
00065 SpecialMouseMode _special_mouse_mode; 
00066 
00068 WindowDesc::WindowDesc(WindowPosition def_pos, int16 def_width, int16 def_height,
00069       WindowClass window_class, WindowClass parent_class, uint32 flags,
00070       const NWidgetPart *nwid_parts, int16 nwid_length) :
00071   default_pos(def_pos),
00072   default_width(def_width),
00073   default_height(def_height),
00074   cls(window_class),
00075   parent_cls(parent_class),
00076   flags(flags),
00077   nwid_parts(nwid_parts),
00078   nwid_length(nwid_length)
00079 {
00080 }
00081 
00082 WindowDesc::~WindowDesc()
00083 {
00084 }
00085 
00095 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
00096 {
00097   const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
00098   if (line_height < 0) line_height = wid->resize_y;
00099   if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
00100   return (clickpos - (int)wid->pos_y - padding) / line_height;
00101 }
00102 
00108 const Scrollbar *Window::GetScrollbar(uint widnum) const
00109 {
00110   return this->GetWidget<NWidgetScrollbar>(widnum);
00111 }
00112 
00118 Scrollbar *Window::GetScrollbar(uint widnum)
00119 {
00120   return this->GetWidget<NWidgetScrollbar>(widnum);
00121 }
00122 
00123 
00128 void SetFocusedWindow(Window *w)
00129 {
00130   if (_focused_window == w) return;
00131 
00132   /* Invalidate focused widget */
00133   if (_focused_window != NULL) {
00134     if (_focused_window->nested_focus != NULL) _focused_window->nested_focus->SetDirty(_focused_window);
00135   }
00136 
00137   /* Remember which window was previously focused */
00138   Window *old_focused = _focused_window;
00139   _focused_window = w;
00140 
00141   /* So we can inform it that it lost focus */
00142   if (old_focused != NULL) old_focused->OnFocusLost();
00143   if (_focused_window != NULL) _focused_window->OnFocus();
00144 }
00145 
00151 static bool EditBoxInGlobalFocus()
00152 {
00153   if (_focused_window == NULL) return false;
00154 
00155   /* The console does not have an edit box so a special case is needed. */
00156   if (_focused_window->window_class == WC_CONSOLE) return true;
00157 
00158   return _focused_window->nested_focus != NULL && _focused_window->nested_focus->type == WWT_EDITBOX;
00159 }
00160 
00164 void Window::UnfocusFocusedWidget()
00165 {
00166   if (this->nested_focus != NULL) {
00167     /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
00168     this->nested_focus->SetDirty(this);
00169     this->nested_focus = NULL;
00170   }
00171 }
00172 
00178 bool Window::SetFocusedWidget(byte widget_index)
00179 {
00180   /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
00181   if (widget_index >= this->nested_array_size) return false;
00182 
00183   assert(this->nested_array[widget_index] != NULL); // Setting focus to a non-existing widget is a bad idea.
00184   if (this->nested_focus != NULL) {
00185     if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
00186 
00187     /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
00188     this->nested_focus->SetDirty(this);
00189   }
00190   this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
00191   return true;
00192 }
00193 
00201 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
00202 {
00203   va_list wdg_list;
00204 
00205   va_start(wdg_list, widgets);
00206 
00207   while (widgets != WIDGET_LIST_END) {
00208     SetWidgetDisabledState(widgets, disab_stat);
00209     widgets = va_arg(wdg_list, int);
00210   }
00211 
00212   va_end(wdg_list);
00213 }
00214 
00220 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
00221 {
00222   va_list wdg_list;
00223 
00224   va_start(wdg_list, widgets);
00225 
00226   while (widgets != WIDGET_LIST_END) {
00227     SetWidgetLoweredState(widgets, lowered_stat);
00228     widgets = va_arg(wdg_list, int);
00229   }
00230 
00231   va_end(wdg_list);
00232 }
00233 
00238 void Window::RaiseButtons(bool autoraise)
00239 {
00240   for (uint i = 0; i < this->nested_array_size; i++) {
00241     if (this->nested_array[i] != NULL && (this->nested_array[i]->type & ~WWB_PUSHBUTTON) < WWT_LAST &&
00242         (!autoraise || (this->nested_array[i]->type & WWB_PUSHBUTTON)) && this->IsWidgetLowered(i)) {
00243       this->RaiseWidget(i);
00244       this->SetWidgetDirty(i);
00245     }
00246   }
00247 }
00248 
00253 void Window::SetWidgetDirty(byte widget_index) const
00254 {
00255   /* Sometimes this function is called before the window is even fully initialized */
00256   if (this->nested_array == NULL) return;
00257 
00258   this->nested_array[widget_index]->SetDirty(this);
00259 }
00260 
00266 void Window::HandleButtonClick(byte widget)
00267 {
00268   this->LowerWidget(widget);
00269   this->flags4 |= WF_TIMEOUT_BEGIN;
00270   this->SetWidgetDirty(widget);
00271 }
00272 
00273 static void StartWindowDrag(Window *w);
00274 static void StartWindowSizing(Window *w, bool to_left);
00275 
00283 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
00284 {
00285   NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
00286   WidgetType widget_type = (nw != NULL) ? nw->type : WWT_EMPTY;
00287 
00288   bool focused_widget_changed = false;
00289   /* If clicked on a window that previously did dot have focus */
00290   if (_focused_window != w &&                 // We already have focus, right?
00291       (w->desc_flags & WDF_NO_FOCUS) == 0 &&  // Don't lose focus to toolbars
00292       widget_type != WWT_CLOSEBOX) {          // Don't change focused window if 'X' (close button) was clicked
00293     focused_widget_changed = true;
00294     if (_focused_window != NULL) {
00295       _focused_window->OnFocusLost();
00296 
00297       /* The window that lost focus may have had opened a OSK, window so close it, unless the user has clicked on the OSK window. */
00298       if (w->window_class != WC_OSK) DeleteWindowById(WC_OSK, 0);
00299     }
00300     SetFocusedWindow(w);
00301     w->OnFocus();
00302   }
00303 
00304   if (nw == NULL) return; // exit if clicked outside of widgets
00305 
00306   /* don't allow any interaction if the button has been disabled */
00307   if (nw->IsDisabled()) return;
00308 
00309   int widget_index = nw->index; 
00310 
00311   /* Clicked on a widget that is not disabled.
00312    * So unless the clicked widget is the caption bar, change focus to this widget */
00313   if (widget_type != WWT_CAPTION) {
00314     /* Close the OSK window if a edit box loses focus */
00315     if (w->nested_focus != NULL &&  w->nested_focus->type == WWT_EDITBOX && w->nested_focus != nw && w->window_class != WC_OSK) {
00316       DeleteWindowById(WC_OSK, 0);
00317     }
00318 
00319     /* focused_widget_changed is 'now' only true if the window this widget
00320      * is in gained focus. In that case it must remain true, also if the
00321      * local widget focus did not change. As such it's the logical-or of
00322      * both changed states.
00323      *
00324      * If this is not preserved, then the OSK window would be opened when
00325      * a user has the edit box focused and then click on another window and
00326      * then back again on the edit box (to type some text).
00327      */
00328     focused_widget_changed |= w->SetFocusedWidget(widget_index);
00329   }
00330 
00331   /* Close any child drop down menus. If the button pressed was the drop down
00332    * list's own button, then we should not process the click any further. */
00333   if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
00334 
00335   if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
00336 
00337   switch (widget_type) {
00338     case NWID_VSCROLLBAR:
00339     case NWID_HSCROLLBAR:
00340       ScrollbarClickHandler(w, nw, x, y);
00341       break;
00342 
00343     case WWT_EDITBOX:
00344       if (!focused_widget_changed) { // Only open the OSK window if clicking on an already focused edit box
00345         /* Open the OSK window if clicked on an edit box */
00346         QueryStringBaseWindow *qs = dynamic_cast<QueryStringBaseWindow *>(w);
00347         if (qs != NULL) {
00348           qs->OnOpenOSKWindow(widget_index);
00349         }
00350       }
00351       break;
00352 
00353     case WWT_CLOSEBOX: // 'X'
00354       delete w;
00355       return;
00356 
00357     case WWT_CAPTION: // 'Title bar'
00358       StartWindowDrag(w);
00359       return;
00360 
00361     case WWT_RESIZEBOX:
00362       /* When the resize widget is on the left size of the window
00363        * we assume that that button is used to resize to the left. */
00364       StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
00365       nw->SetDirty(w);
00366       return;
00367 
00368     case WWT_DEBUGBOX:
00369       w->ShowNewGRFInspectWindow();
00370       break;
00371 
00372     case WWT_SHADEBOX:
00373       nw->SetDirty(w);
00374       w->SetShaded(!w->IsShaded());
00375       return;
00376 
00377     case WWT_STICKYBOX:
00378       w->flags4 ^= WF_STICKY;
00379       nw->SetDirty(w);
00380       return;
00381 
00382     default:
00383       break;
00384   }
00385 
00386   /* Widget has no index, so the window is not interested in it. */
00387   if (widget_index < 0) return;
00388 
00389   Point pt = { x, y };
00390   w->OnClick(pt, widget_index, click_count);
00391 }
00392 
00399 static void DispatchRightClickEvent(Window *w, int x, int y)
00400 {
00401   NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
00402   if (wid == NULL) return;
00403 
00404   /* No widget to handle, or the window is not interested in it. */
00405   if (wid->index >= 0) {
00406     Point pt = { x, y };
00407     if (w->OnRightClick(pt, wid->index)) return;
00408   }
00409 
00410   if (_settings_client.gui.hover_delay == 0 && wid->tool_tip != 0) GuiShowTooltips(w, wid->tool_tip, 0, NULL, TCC_RIGHT_CLICK);
00411 }
00412 
00419 static void DispatchHoverEvent(Window *w, int x, int y)
00420 {
00421   NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
00422 
00423   /* No widget to handle */
00424   if (wid == NULL) return;
00425 
00426   /* Show the tooltip if there is any */
00427   if (wid->tool_tip != 0) {
00428     GuiShowTooltips(w, wid->tool_tip);
00429     return;
00430   }
00431 
00432   /* Widget has no index, so the window is not interested in it. */
00433   if (wid->index < 0) return;
00434 
00435   Point pt = { x, y };
00436   w->OnHover(pt, wid->index);
00437 }
00438 
00446 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
00447 {
00448   if (nwid == NULL) return;
00449 
00450   /* Using wheel on caption/shade-box shades or unshades the window. */
00451   if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
00452     w->SetShaded(wheel < 0);
00453     return;
00454   }
00455 
00456   /* Wheeling a vertical scrollbar. */
00457   if (nwid->type == NWID_VSCROLLBAR) {
00458     NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
00459     if (sb->GetCount() > sb->GetCapacity()) {
00460       sb->UpdatePosition(wheel);
00461       w->SetDirty();
00462     }
00463     return;
00464   }
00465 
00466   /* Scroll the widget attached to the scrollbar. */
00467   Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : NULL);
00468   if (sb != NULL && sb->GetCount() > sb->GetCapacity()) {
00469     sb->UpdatePosition(wheel);
00470     w->SetDirty();
00471   }
00472 }
00473 
00486 static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
00487 {
00488   const Window *v;
00489   FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
00490     if (right > v->left &&
00491         bottom > v->top &&
00492         left < v->left + v->width &&
00493         top < v->top + v->height) {
00494       /* v and rectangle intersect with eeach other */
00495       int x;
00496 
00497       if (left < (x = v->left)) {
00498         DrawOverlappedWindow(w, left, top, x, bottom);
00499         DrawOverlappedWindow(w, x, top, right, bottom);
00500         return;
00501       }
00502 
00503       if (right > (x = v->left + v->width)) {
00504         DrawOverlappedWindow(w, left, top, x, bottom);
00505         DrawOverlappedWindow(w, x, top, right, bottom);
00506         return;
00507       }
00508 
00509       if (top < (x = v->top)) {
00510         DrawOverlappedWindow(w, left, top, right, x);
00511         DrawOverlappedWindow(w, left, x, right, bottom);
00512         return;
00513       }
00514 
00515       if (bottom > (x = v->top + v->height)) {
00516         DrawOverlappedWindow(w, left, top, right, x);
00517         DrawOverlappedWindow(w, left, x, right, bottom);
00518         return;
00519       }
00520 
00521       return;
00522     }
00523   }
00524 
00525   /* Setup blitter, and dispatch a repaint event to window *wz */
00526   DrawPixelInfo *dp = _cur_dpi;
00527   dp->width = right - left;
00528   dp->height = bottom - top;
00529   dp->left = left - w->left;
00530   dp->top = top - w->top;
00531   dp->pitch = _screen.pitch;
00532   dp->dst_ptr = BlitterFactoryBase::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
00533   dp->zoom = ZOOM_LVL_NORMAL;
00534   w->OnPaint();
00535 }
00536 
00545 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
00546 {
00547   Window *w;
00548   DrawPixelInfo bk;
00549   _cur_dpi = &bk;
00550 
00551   FOR_ALL_WINDOWS_FROM_BACK(w) {
00552     if (right > w->left &&
00553         bottom > w->top &&
00554         left < w->left + w->width &&
00555         top < w->top + w->height) {
00556       /* Window w intersects with the rectangle => needs repaint */
00557       DrawOverlappedWindow(w, left, top, right, bottom);
00558     }
00559   }
00560 }
00561 
00566 void Window::SetDirty() const
00567 {
00568   SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
00569 }
00570 
00577 void Window::ReInit(int rx, int ry)
00578 {
00579   this->SetDirty(); // Mark whole current window as dirty.
00580 
00581   /* Save current size. */
00582   int window_width  = this->width;
00583   int window_height = this->height;
00584 
00585   this->OnInit();
00586   /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
00587   this->nested_root->SetupSmallestSize(this, false);
00588   this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
00589   this->width  = this->nested_root->smallest_x;
00590   this->height = this->nested_root->smallest_y;
00591   this->resize.step_width  = this->nested_root->resize_x;
00592   this->resize.step_height = this->nested_root->resize_y;
00593 
00594   /* Resize as close to the original size + requested resize as possible. */
00595   window_width  = max(window_width  + rx, this->width);
00596   window_height = max(window_height + ry, this->height);
00597   int dx = (this->resize.step_width  == 0) ? 0 : window_width  - this->width;
00598   int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
00599   /* dx and dy has to go by step.. calculate it.
00600    * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
00601   if (this->resize.step_width  > 1) dx -= dx % (int)this->resize.step_width;
00602   if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
00603 
00604   ResizeWindow(this, dx, dy);
00605   /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
00606 }
00607 
00613 void Window::SetShaded(bool make_shaded)
00614 {
00615   if (this->shade_select == NULL) return;
00616 
00617   int desired = make_shaded ? SZSP_HORIZONTAL : 0;
00618   if (this->shade_select->shown_plane != desired) {
00619     if (make_shaded) {
00620       this->unshaded_size.width  = this->width;
00621       this->unshaded_size.height = this->height;
00622       this->shade_select->SetDisplayedPlane(desired);
00623       this->ReInit(0, -this->height);
00624     } else {
00625       this->shade_select->SetDisplayedPlane(desired);
00626       int dx = ((int)this->unshaded_size.width  > this->width)  ? (int)this->unshaded_size.width  - this->width  : 0;
00627       int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
00628       this->ReInit(dx, dy);
00629     }
00630   }
00631 }
00632 
00639 static Window *FindChildWindow(const Window *w, WindowClass wc)
00640 {
00641   Window *v;
00642   FOR_ALL_WINDOWS_FROM_BACK(v) {
00643     if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
00644   }
00645 
00646   return NULL;
00647 }
00648 
00653 void Window::DeleteChildWindows(WindowClass wc) const
00654 {
00655   Window *child = FindChildWindow(this, wc);
00656   while (child != NULL) {
00657     delete child;
00658     child = FindChildWindow(this, wc);
00659   }
00660 }
00661 
00665 Window::~Window()
00666 {
00667   if (_thd.window_class == this->window_class &&
00668       _thd.window_number == this->window_number) {
00669     ResetObjectToPlace();
00670   }
00671 
00672   /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
00673   if (_mouseover_last_w == this) _mouseover_last_w = NULL;
00674 
00675   /* We can't scroll the window when it's closed. */
00676   if (_last_scroll_window == this) _last_scroll_window = NULL;
00677 
00678   /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
00679   if (_focused_window == this) _focused_window = NULL;
00680 
00681   this->DeleteChildWindows();
00682 
00683   if (this->viewport != NULL) DeleteWindowViewport(this);
00684 
00685   this->SetDirty();
00686 
00687   free(this->nested_array); // Contents is released through deletion of #nested_root.
00688   delete this->nested_root;
00689 
00690   this->window_class = WC_INVALID;
00691 }
00692 
00699 Window *FindWindowById(WindowClass cls, WindowNumber number)
00700 {
00701   Window *w;
00702   FOR_ALL_WINDOWS_FROM_BACK(w) {
00703     if (w->window_class == cls && w->window_number == number) return w;
00704   }
00705 
00706   return NULL;
00707 }
00708 
00715 Window *FindWindowByClass(WindowClass cls)
00716 {
00717   Window *w;
00718   FOR_ALL_WINDOWS_FROM_BACK(w) {
00719     if (w->window_class == cls) return w;
00720   }
00721 
00722   return NULL;
00723 }
00724 
00731 void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
00732 {
00733   Window *w = FindWindowById(cls, number);
00734   if (force || w == NULL ||
00735       (w->flags4 & WF_STICKY) == 0) {
00736     delete w;
00737   }
00738 }
00739 
00744 void DeleteWindowByClass(WindowClass cls)
00745 {
00746   Window *w;
00747 
00748 restart_search:
00749   /* When we find the window to delete, we need to restart the search
00750    * as deleting this window could cascade in deleting (many) others
00751    * anywhere in the z-array */
00752   FOR_ALL_WINDOWS_FROM_BACK(w) {
00753     if (w->window_class == cls) {
00754       delete w;
00755       goto restart_search;
00756     }
00757   }
00758 }
00759 
00766 void DeleteCompanyWindows(CompanyID id)
00767 {
00768   Window *w;
00769 
00770 restart_search:
00771   /* When we find the window to delete, we need to restart the search
00772    * as deleting this window could cascade in deleting (many) others
00773    * anywhere in the z-array */
00774   FOR_ALL_WINDOWS_FROM_BACK(w) {
00775     if (w->owner == id) {
00776       delete w;
00777       goto restart_search;
00778     }
00779   }
00780 
00781   /* Also delete the company specific windows that don't have a company-colour. */
00782   DeleteWindowById(WC_BUY_COMPANY, id);
00783 }
00784 
00792 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
00793 {
00794   Window *w;
00795   FOR_ALL_WINDOWS_FROM_BACK(w) {
00796     if (w->owner != old_owner) continue;
00797 
00798     switch (w->window_class) {
00799       case WC_COMPANY_COLOUR:
00800       case WC_FINANCES:
00801       case WC_STATION_LIST:
00802       case WC_TRAINS_LIST:
00803       case WC_ROADVEH_LIST:
00804       case WC_SHIPS_LIST:
00805       case WC_AIRCRAFT_LIST:
00806       case WC_BUY_COMPANY:
00807       case WC_COMPANY:
00808         continue;
00809 
00810       default:
00811         w->owner = new_owner;
00812         break;
00813     }
00814   }
00815 }
00816 
00817 static void BringWindowToFront(Window *w);
00818 
00826 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
00827 {
00828   Window *w = FindWindowById(cls, number);
00829 
00830   if (w != NULL) {
00831     if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
00832 
00833     w->flags4 |= WF_WHITE_BORDER_MASK;
00834     BringWindowToFront(w);
00835     w->SetDirty();
00836   }
00837 
00838   return w;
00839 }
00840 
00841 static inline bool IsVitalWindow(const Window *w)
00842 {
00843   switch (w->window_class) {
00844     case WC_MAIN_TOOLBAR:
00845     case WC_STATUS_BAR:
00846     case WC_NEWS_WINDOW:
00847     case WC_SEND_NETWORK_MSG:
00848       return true;
00849 
00850     default:
00851       return false;
00852   }
00853 }
00854 
00864 static void BringWindowToFront(Window *w)
00865 {
00866   Window *v = _z_front_window;
00867 
00868   /* Bring the window just below the vital windows */
00869   for (; v != NULL && v != w && IsVitalWindow(v); v = v->z_back) { }
00870 
00871   if (v == NULL || w == v) return; // window is already in the right position
00872 
00873   /* w cannot be at the top already! */
00874   assert(w != _z_front_window);
00875 
00876   if (w->z_back == NULL) {
00877     _z_back_window = w->z_front;
00878   } else {
00879     w->z_back->z_front = w->z_front;
00880   }
00881   w->z_front->z_back = w->z_back;
00882 
00883   w->z_front = v->z_front;
00884   w->z_back = v;
00885 
00886   if (v->z_front == NULL) {
00887     _z_front_window = w;
00888   } else {
00889     v->z_front->z_back = w;
00890   }
00891   v->z_front = w;
00892 
00893   w->SetDirty();
00894 }
00895 
00904 void Window::InitializeData(const WindowDesc *desc, WindowNumber window_number)
00905 {
00906   /* Set up window properties; some of them are needed to set up smallest size below */
00907   this->window_class = desc->cls;
00908   this->flags4 |= WF_WHITE_BORDER_MASK; // just opened windows have a white border
00909   if (desc->default_pos == WDP_CENTER) this->flags4 |= WF_CENTERED;
00910   this->owner = INVALID_OWNER;
00911   this->nested_focus = NULL;
00912   this->window_number = window_number;
00913   this->desc_flags = desc->flags;
00914 
00915   this->OnInit();
00916   /* Initialize nested widget tree. */
00917   if (this->nested_array == NULL) {
00918     this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
00919     this->nested_root->SetupSmallestSize(this, true);
00920   } else {
00921     this->nested_root->SetupSmallestSize(this, false);
00922   }
00923   /* Initialize to smallest size. */
00924   this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
00925 
00926   /* Further set up window properties,
00927    * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
00928   this->resize.step_width  = this->nested_root->resize_x;
00929   this->resize.step_height = this->nested_root->resize_y;
00930 
00931   /* Give focus to the opened window unless it is the OSK window or a text box
00932    * of focused window has focus (so we don't interrupt typing). But if the new
00933    * window has a text box, then take focus anyway. */
00934   if (this->window_class != WC_OSK && (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != NULL)) SetFocusedWindow(this);
00935 
00936   /* Hacky way of specifying always-on-top windows. These windows are
00937    * always above other windows because they are moved below them.
00938    * status-bar is above news-window because it has been created earlier.
00939    * Also, as the chat-window is excluded from this, it will always be
00940    * the last window, thus always on top.
00941    * XXX - Yes, ugly, probably needs something like w->always_on_top flag
00942    * to implement correctly, but even then you need some kind of distinction
00943    * between on-top of chat/news and status windows, because these conflict */
00944   Window *w = _z_front_window;
00945   if (w != NULL && this->window_class != WC_SEND_NETWORK_MSG && this->window_class != WC_HIGHSCORE && this->window_class != WC_ENDSCREEN) {
00946     if (FindWindowById(WC_MAIN_TOOLBAR, 0)     != NULL) w = w->z_back;
00947     if (FindWindowById(WC_STATUS_BAR, 0)       != NULL) w = w->z_back;
00948     if (FindWindowById(WC_NEWS_WINDOW, 0)      != NULL) w = w->z_back;
00949     if (FindWindowByClass(WC_SEND_NETWORK_MSG) != NULL) w = w->z_back;
00950 
00951     if (w == NULL) {
00952       _z_back_window->z_front = this;
00953       this->z_back = _z_back_window;
00954       _z_back_window = this;
00955     } else {
00956       if (w->z_front == NULL) {
00957         _z_front_window = this;
00958       } else {
00959         this->z_front = w->z_front;
00960         w->z_front->z_back = this;
00961       }
00962 
00963       this->z_back = w;
00964       w->z_front = this;
00965     }
00966   } else {
00967     this->z_back = _z_front_window;
00968     if (_z_front_window != NULL) {
00969       _z_front_window->z_front = this;
00970     } else {
00971       _z_back_window = this;
00972     }
00973     _z_front_window = this;
00974   }
00975 }
00976 
00984 void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
00985 {
00986   this->left = x;
00987   this->top = y;
00988   this->width = sm_width;
00989   this->height = sm_height;
00990 }
00991 
01002 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
01003 {
01004   def_width  = max(def_width,  this->width); // Don't allow default size to be smaller than smallest size
01005   def_height = max(def_height, this->height);
01006   /* Try to make windows smaller when our window is too small.
01007    * w->(width|height) is normally the same as min_(width|height),
01008    * but this way the GUIs can be made a little more dynamic;
01009    * one can use the same spec for multiple windows and those
01010    * can then determine the real minimum size of the window. */
01011   if (this->width != def_width || this->height != def_height) {
01012     /* Think about the overlapping toolbars when determining the minimum window size */
01013     int free_height = _screen.height;
01014     const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
01015     if (wt != NULL) free_height -= wt->height;
01016     wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
01017     if (wt != NULL) free_height -= wt->height;
01018 
01019     int enlarge_x = max(min(def_width  - this->width,  _screen.width - this->width),  0);
01020     int enlarge_y = max(min(def_height - this->height, free_height   - this->height), 0);
01021 
01022     /* X and Y has to go by step.. calculate it.
01023      * The cast to int is necessary else x/y are implicitly casted to
01024      * unsigned int, which won't work. */
01025     if (this->resize.step_width  > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
01026     if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
01027 
01028     ResizeWindow(this, enlarge_x, enlarge_y);
01029     /* ResizeWindow() calls this->OnResize(). */
01030   } else {
01031     /* Always call OnResize; that way the scrollbars and matrices get initialized. */
01032     this->OnResize();
01033   }
01034 
01035   int nx = this->left;
01036   int ny = this->top;
01037 
01038   if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
01039 
01040   const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
01041   ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
01042   nx = max(nx, 0);
01043 
01044   if (this->viewport != NULL) {
01045     this->viewport->left += nx - this->left;
01046     this->viewport->top  += ny - this->top;
01047   }
01048   this->left = nx;
01049   this->top = ny;
01050 
01051   this->SetDirty();
01052 }
01053 
01065 static bool IsGoodAutoPlace1(int left, int top, int width, int height, Point &pos)
01066 {
01067   int right  = width + left;
01068   int bottom = height + top;
01069 
01070   const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
01071   if (left < 0 || (main_toolbar != NULL && top < main_toolbar->height) || right > _screen.width || bottom > _screen.height) return false;
01072 
01073   /* Make sure it is not obscured by any window. */
01074   const Window *w;
01075   FOR_ALL_WINDOWS_FROM_BACK(w) {
01076     if (w->window_class == WC_MAIN_WINDOW) continue;
01077 
01078     if (right > w->left &&
01079         w->left + w->width > left &&
01080         bottom > w->top &&
01081         w->top + w->height > top) {
01082       return false;
01083     }
01084   }
01085 
01086   pos.x = left;
01087   pos.y = top;
01088   return true;
01089 }
01090 
01102 static bool IsGoodAutoPlace2(int left, int top, int width, int height, Point &pos)
01103 {
01104   /* Left part of the rectangle may be at most 1/4 off-screen,
01105    * right part of the rectangle may be at most 1/2 off-screen
01106    */
01107   if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
01108   /* Bottom part of the rectangle may be at most 1/4 off-screen */
01109   if (top < 22 || top > _screen.height - (height >> 2)) return false;
01110 
01111   /* Make sure it is not obscured by any window. */
01112   const Window *w;
01113   FOR_ALL_WINDOWS_FROM_BACK(w) {
01114     if (w->window_class == WC_MAIN_WINDOW) continue;
01115 
01116     if (left + width > w->left &&
01117         w->left + w->width > left &&
01118         top + height > w->top &&
01119         w->top + w->height > top) {
01120       return false;
01121     }
01122   }
01123 
01124   pos.x = left;
01125   pos.y = top;
01126   return true;
01127 }
01128 
01135 static Point GetAutoPlacePosition(int width, int height)
01136 {
01137   Point pt;
01138 
01139   /* First attempt, try top-left of the screen */
01140   const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
01141   if (IsGoodAutoPlace1(0, main_toolbar != NULL ? main_toolbar->height + 2 : 2, width, height, pt)) return pt;
01142 
01143   /* Second attempt, try around all existing windows with a distance of 2 pixels.
01144    * The new window must be entirely on-screen, and not overlap with an existing window.
01145    * Eight starting points are tried, two at each corner.
01146    */
01147   const Window *w;
01148   FOR_ALL_WINDOWS_FROM_BACK(w) {
01149     if (w->window_class == WC_MAIN_WINDOW) continue;
01150 
01151     if (IsGoodAutoPlace1(w->left + w->width + 2, w->top, width, height, pt)) return pt;
01152     if (IsGoodAutoPlace1(w->left - width - 2,    w->top, width, height, pt)) return pt;
01153     if (IsGoodAutoPlace1(w->left, w->top + w->height + 2, width, height, pt)) return pt;
01154     if (IsGoodAutoPlace1(w->left, w->top - height - 2,    width, height, pt)) return pt;
01155     if (IsGoodAutoPlace1(w->left + w->width + 2, w->top + w->height - height, width, height, pt)) return pt;
01156     if (IsGoodAutoPlace1(w->left - width - 2,    w->top + w->height - height, width, height, pt)) return pt;
01157     if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height + 2, width, height, pt)) return pt;
01158     if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height - 2,    width, height, pt)) return pt;
01159   }
01160 
01161   /* Third attempt, try around all existing windows with a distance of 2 pixels.
01162    * The new window may be partly off-screen, and must not overlap with an existing window.
01163    * Only four starting points are tried.
01164    */
01165   FOR_ALL_WINDOWS_FROM_BACK(w) {
01166     if (w->window_class == WC_MAIN_WINDOW) continue;
01167 
01168     if (IsGoodAutoPlace2(w->left + w->width + 2, w->top, width, height, pt)) return pt;
01169     if (IsGoodAutoPlace2(w->left - width - 2,    w->top, width, height, pt)) return pt;
01170     if (IsGoodAutoPlace2(w->left, w->top + w->height + 2, width, height, pt)) return pt;
01171     if (IsGoodAutoPlace2(w->left, w->top - height - 2,    width, height, pt)) return pt;
01172   }
01173 
01174   /* Fourth and final attempt, put window at diagonal starting from (0, 24), try multiples
01175    * of (+5, +5)
01176    */
01177   int left = 0, top = 24;
01178 
01179 restart:
01180   FOR_ALL_WINDOWS_FROM_BACK(w) {
01181     if (w->left == left && w->top == top) {
01182       left += 5;
01183       top += 5;
01184       goto restart;
01185     }
01186   }
01187 
01188   pt.x = left;
01189   pt.y = top;
01190   return pt;
01191 }
01192 
01199 Point GetToolbarAlignedWindowPosition(int window_width)
01200 {
01201   const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
01202   assert(w != NULL);
01203   Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
01204   return pt;
01205 }
01206 
01224 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
01225 {
01226   Point pt;
01227   const Window *w;
01228 
01229   int16 default_width  = max(desc->default_width,  sm_width);
01230   int16 default_height = max(desc->default_height, sm_height);
01231 
01232   if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ &&
01233       (w = FindWindowById(desc->parent_cls, window_number)) != NULL &&
01234       w->left < _screen.width - 20 && w->left > -60 && w->top < _screen.height - 20) {
01235 
01236     pt.x = w->left + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 0 : 10);
01237     if (pt.x > _screen.width + 10 - default_width) {
01238       pt.x = (_screen.width + 10 - default_width) - 20;
01239     }
01240     pt.y = w->top + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? w->height : 10);
01241     return pt;
01242   }
01243 
01244   switch (desc->default_pos) {
01245     case WDP_ALIGN_TOOLBAR: // Align to the toolbar
01246       return GetToolbarAlignedWindowPosition(default_width);
01247 
01248     case WDP_AUTO: // Find a good automatic position for the window
01249       return GetAutoPlacePosition(default_width, default_height);
01250 
01251     case WDP_CENTER: // Centre the window horizontally
01252       pt.x = (_screen.width - default_width) / 2;
01253       pt.y = (_screen.height - default_height) / 2;
01254       break;
01255 
01256     case WDP_MANUAL:
01257       pt.x = 0;
01258       pt.y = 0;
01259       break;
01260 
01261     default:
01262       NOT_REACHED();
01263   }
01264 
01265   return pt;
01266 }
01267 
01268 /* virtual */ Point Window::OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
01269 {
01270   return LocalGetWindowPlacement(desc, sm_width, sm_height, window_number);
01271 }
01272 
01281 void Window::CreateNestedTree(const WindowDesc *desc, bool fill_nested)
01282 {
01283   int biggest_index = -1;
01284   this->nested_root = MakeWindowNWidgetTree(desc->nwid_parts, desc->nwid_length, &biggest_index, &this->shade_select);
01285   this->nested_array_size = (uint)(biggest_index + 1);
01286 
01287   if (fill_nested) {
01288     this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
01289     this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
01290   }
01291 }
01292 
01298 void Window::FinishInitNested(const WindowDesc *desc, WindowNumber window_number)
01299 {
01300   this->InitializeData(desc, window_number);
01301   Point pt = this->OnInitialPosition(desc, this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
01302   this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
01303   this->FindWindowPlacementAndResize(desc->default_width, desc->default_height);
01304 }
01305 
01311 void Window::InitNested(const WindowDesc *desc, WindowNumber window_number)
01312 {
01313   this->CreateNestedTree(desc, false);
01314   this->FinishInitNested(desc, window_number);
01315 }
01316 
01318 Window::Window() : scrolling_scrollbar(-1)
01319 {
01320 }
01321 
01329 Window *FindWindowFromPt(int x, int y)
01330 {
01331   Window *w;
01332   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01333     if (IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
01334       return w;
01335     }
01336   }
01337 
01338   return NULL;
01339 }
01340 
01344 void InitWindowSystem()
01345 {
01346   IConsoleClose();
01347 
01348   _z_back_window = NULL;
01349   _z_front_window = NULL;
01350   _focused_window = NULL;
01351   _mouseover_last_w = NULL;
01352   _last_scroll_window = NULL;
01353   _scrolling_viewport = false;
01354   _mouse_hovering = false;
01355 
01356   NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
01357 }
01358 
01362 void UnInitWindowSystem()
01363 {
01364   Window *w;
01365   FOR_ALL_WINDOWS_FROM_FRONT(w) delete w;
01366 
01367   for (w = _z_front_window; w != NULL; /* nothing */) {
01368     Window *to_del = w;
01369     w = w->z_back;
01370     free(to_del);
01371   }
01372 
01373   _z_front_window = NULL;
01374   _z_back_window = NULL;
01375 }
01376 
01380 void ResetWindowSystem()
01381 {
01382   UnInitWindowSystem();
01383   InitWindowSystem();
01384   _thd.Reset();
01385 }
01386 
01387 static void DecreaseWindowCounters()
01388 {
01389   Window *w;
01390   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01391     if (_scroller_click_timeout == 0) {
01392       /* Unclick scrollbar buttons if they are pressed. */
01393       for (uint i = 0; i < w->nested_array_size; i++) {
01394         NWidgetBase *nwid = w->nested_array[i];
01395         if (nwid != NULL && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
01396           NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
01397           if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
01398             sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
01399             sb->SetDirty(w);
01400           }
01401         }
01402       }
01403     }
01404     w->OnMouseLoop();
01405   }
01406 
01407   FOR_ALL_WINDOWS_FROM_FRONT(w) {
01408     if ((w->flags4 & WF_TIMEOUT_MASK) && !(--w->flags4 & WF_TIMEOUT_MASK)) {
01409       w->OnTimeout();
01410       if (w->desc_flags & WDF_UNCLICK_BUTTONS) w->RaiseButtons(true);
01411     }
01412   }
01413 }
01414 
01415 static void HandlePlacePresize()
01416 {
01417   if (_special_mouse_mode != WSM_PRESIZE) return;
01418 
01419   Window *w = _thd.GetCallbackWnd();
01420   if (w == NULL) return;
01421 
01422   Point pt = GetTileBelowCursor();
01423   if (pt.x == -1) {
01424     _thd.selend.x = -1;
01425     return;
01426   }
01427 
01428   w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
01429 }
01430 
01435 static EventState HandleMouseDragDrop()
01436 {
01437   if (_special_mouse_mode != WSM_DRAGDROP) return ES_NOT_HANDLED;
01438 
01439   if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
01440 
01441   Window *w = _thd.GetCallbackWnd();
01442   if (w != NULL) {
01443     /* Send an event in client coordinates. */
01444     Point pt;
01445     pt.x = _cursor.pos.x - w->left;
01446     pt.y = _cursor.pos.y - w->top;
01447     if (_left_button_down) {
01448       w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
01449     } else {
01450       w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
01451     }
01452   }
01453 
01454   if (!_left_button_down) ResetObjectToPlace(); // Button released, finished dragging.
01455   return ES_HANDLED;
01456 }
01457 
01459 static void HandleMouseOver()
01460 {
01461   Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
01462 
01463   /* We changed window, put a MOUSEOVER event to the last window */
01464   if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
01465     /* Reset mouse-over coordinates of previous window */
01466     Point pt = { -1, -1 };
01467     _mouseover_last_w->OnMouseOver(pt, 0);
01468   }
01469 
01470   /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
01471   _mouseover_last_w = w;
01472 
01473   if (w != NULL) {
01474     /* send an event in client coordinates. */
01475     Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
01476     const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
01477     if (widget != NULL) w->OnMouseOver(pt, widget->index);
01478   }
01479 }
01480 
01482 static const int MIN_VISIBLE_TITLE_BAR = 13;
01483 
01485 enum PreventHideDirection {
01486   PHD_UP,   
01487   PHD_DOWN, 
01488 };
01489 
01500 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
01501 {
01502   if (v == NULL) return;
01503 
01504   int v_bottom = v->top + v->height;
01505   int v_right = v->left + v->width;
01506   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.
01507 
01508   if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
01509   if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
01510 
01511   /* Vertically, the rectangle is hidden behind v. */
01512   if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
01513     if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
01514     return;
01515   }
01516   if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
01517     if (v_right > _screen.width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
01518     return;
01519   }
01520 
01521   /* Horizontally also hidden, force movement to a safe area. */
01522   if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
01523     *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
01524   } else if (px + rect.right > v_right && v_right <= _screen.width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
01525     *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
01526   } else {
01527     *ny = safe_y;
01528   }
01529 }
01530 
01538 static void EnsureVisibleCaption(Window *w, int nx, int ny)
01539 {
01540   /* Search for the title bar rectangle. */
01541   Rect caption_rect;
01542   const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
01543   if (caption != NULL) {
01544     caption_rect.left   = caption->pos_x;
01545     caption_rect.right  = caption->pos_x + caption->current_x;
01546     caption_rect.top    = caption->pos_y;
01547     caption_rect.bottom = caption->pos_y + caption->current_y;
01548 
01549     /* Make sure the window doesn't leave the screen */
01550     nx = Clamp(nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen.width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
01551     ny = Clamp(ny, 0, _screen.height - MIN_VISIBLE_TITLE_BAR);
01552 
01553     /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
01554     PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
01555     PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR,   0), w->left, PHD_UP);
01556 
01557     if (w->viewport != NULL) {
01558       w->viewport->left += nx - w->left;
01559       w->viewport->top  += ny - w->top;
01560     }
01561   }
01562   w->left = nx;
01563   w->top  = ny;
01564 }
01565 
01575 void ResizeWindow(Window *w, int delta_x, int delta_y)
01576 {
01577   if (delta_x != 0 || delta_y != 0) {
01578     w->SetDirty();
01579 
01580     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);
01581     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);
01582     assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
01583     assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
01584 
01585     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);
01586     w->width  = w->nested_root->current_x;
01587     w->height = w->nested_root->current_y;
01588   }
01589 
01590   EnsureVisibleCaption(w, w->left, w->top);
01591 
01592   /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
01593   w->OnResize();
01594   w->SetDirty();
01595 }
01596 
01602 int GetMainViewTop()
01603 {
01604   Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
01605   return (w == NULL) ? 0 : w->top + w->height;
01606 }
01607 
01613 int GetMainViewBottom()
01614 {
01615   Window *w = FindWindowById(WC_STATUS_BAR, 0);
01616   return (w == NULL) ? _screen.height : w->top;
01617 }
01618 
01619 static bool _dragging_window; 
01620 
01625 static EventState HandleWindowDragging()
01626 {
01627   /* Get out immediately if no window is being dragged at all. */
01628   if (!_dragging_window) return ES_NOT_HANDLED;
01629 
01630   /* If button still down, but cursor hasn't moved, there is nothing to do. */
01631   if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
01632 
01633   /* Otherwise find the window... */
01634   Window *w;
01635   FOR_ALL_WINDOWS_FROM_BACK(w) {
01636     if (w->flags4 & WF_DRAGGING) {
01637       /* Stop the dragging if the left mouse button was released */
01638       if (!_left_button_down) {
01639         w->flags4 &= ~WF_DRAGGING;
01640         break;
01641       }
01642 
01643       w->SetDirty();
01644 
01645       int x = _cursor.pos.x + _drag_delta.x;
01646       int y = _cursor.pos.y + _drag_delta.y;
01647       int nx = x;
01648       int ny = y;
01649 
01650       if (_settings_client.gui.window_snap_radius != 0) {
01651         const Window *v;
01652 
01653         int hsnap = _settings_client.gui.window_snap_radius;
01654         int vsnap = _settings_client.gui.window_snap_radius;
01655         int delta;
01656 
01657         FOR_ALL_WINDOWS_FROM_BACK(v) {
01658           if (v == w) continue; // Don't snap at yourself
01659 
01660           if (y + w->height > v->top && y < v->top + v->height) {
01661             /* Your left border <-> other right border */
01662             delta = abs(v->left + v->width - x);
01663             if (delta <= hsnap) {
01664               nx = v->left + v->width;
01665               hsnap = delta;
01666             }
01667 
01668             /* Your right border <-> other left border */
01669             delta = abs(v->left - x - w->width);
01670             if (delta <= hsnap) {
01671               nx = v->left - w->width;
01672               hsnap = delta;
01673             }
01674           }
01675 
01676           if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
01677             /* Your left border <-> other left border */
01678             delta = abs(v->left - x);
01679             if (delta <= hsnap) {
01680               nx = v->left;
01681               hsnap = delta;
01682             }
01683 
01684             /* Your right border <-> other right border */
01685             delta = abs(v->left + v->width - x - w->width);
01686             if (delta <= hsnap) {
01687               nx = v->left + v->width - w->width;
01688               hsnap = delta;
01689             }
01690           }
01691 
01692           if (x + w->width > v->left && x < v->left + v->width) {
01693             /* Your top border <-> other bottom border */
01694             delta = abs(v->top + v->height - y);
01695             if (delta <= vsnap) {
01696               ny = v->top + v->height;
01697               vsnap = delta;
01698             }
01699 
01700             /* Your bottom border <-> other top border */
01701             delta = abs(v->top - y - w->height);
01702             if (delta <= vsnap) {
01703               ny = v->top - w->height;
01704               vsnap = delta;
01705             }
01706           }
01707 
01708           if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
01709             /* Your top border <-> other top border */
01710             delta = abs(v->top - y);
01711             if (delta <= vsnap) {
01712               ny = v->top;
01713               vsnap = delta;
01714             }
01715 
01716             /* Your bottom border <-> other bottom border */
01717             delta = abs(v->top + v->height - y - w->height);
01718             if (delta <= vsnap) {
01719               ny = v->top + v->height - w->height;
01720               vsnap = delta;
01721             }
01722           }
01723         }
01724       }
01725 
01726       EnsureVisibleCaption(w, nx, ny);
01727 
01728       w->SetDirty();
01729       return ES_HANDLED;
01730     } else if (w->flags4 & WF_SIZING) {
01731       /* Stop the sizing if the left mouse button was released */
01732       if (!_left_button_down) {
01733         w->flags4 &= ~WF_SIZING;
01734         w->SetDirty();
01735         break;
01736       }
01737 
01738       /* Compute difference in pixels between cursor position and reference point in the window.
01739        * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
01740        */
01741       int x, y = _cursor.pos.y - _drag_delta.y;
01742       if (w->flags4 & WF_SIZING_LEFT) {
01743         x = _drag_delta.x - _cursor.pos.x;
01744       } else {
01745         x = _cursor.pos.x - _drag_delta.x;
01746       }
01747 
01748       /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
01749       if (w->resize.step_width  == 0) x = 0;
01750       if (w->resize.step_height == 0) y = 0;
01751 
01752       /* Check the resize button won't go past the bottom of the screen */
01753       if (w->top + w->height + y > _screen.height) {
01754         y = _screen.height - w->height - w->top;
01755       }
01756 
01757       /* X and Y has to go by step.. calculate it.
01758        * The cast to int is necessary else x/y are implicitly casted to
01759        * unsigned int, which won't work. */
01760       if (w->resize.step_width  > 1) x -= x % (int)w->resize.step_width;
01761       if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
01762 
01763       /* Check that we don't go below the minimum set size */
01764       if ((int)w->width + x < (int)w->nested_root->smallest_x) {
01765         x = w->nested_root->smallest_x - w->width;
01766       }
01767       if ((int)w->height + y < (int)w->nested_root->smallest_y) {
01768         y = w->nested_root->smallest_y - w->height;
01769       }
01770 
01771       /* Window already on size */
01772       if (x == 0 && y == 0) return ES_HANDLED;
01773 
01774       /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
01775       _drag_delta.y += y;
01776       if ((w->flags4 & WF_SIZING_LEFT) && x != 0) {
01777         _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
01778         w->SetDirty();
01779         w->left -= x;  // If dragging left edge, move left window edge in opposite direction by the same amount.
01780         /* ResizeWindow() below ensures marking new position as dirty. */
01781       } else {
01782         _drag_delta.x += x;
01783       }
01784 
01785       /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
01786       ResizeWindow(w, x, y);
01787       return ES_HANDLED;
01788     }
01789   }
01790 
01791   _dragging_window = false;
01792   return ES_HANDLED;
01793 }
01794 
01799 static void StartWindowDrag(Window *w)
01800 {
01801   w->flags4 |= WF_DRAGGING;
01802   w->flags4 &= ~WF_CENTERED;
01803   _dragging_window = true;
01804 
01805   _drag_delta.x = w->left - _cursor.pos.x;
01806   _drag_delta.y = w->top  - _cursor.pos.y;
01807 
01808   BringWindowToFront(w);
01809   DeleteWindowById(WC_DROPDOWN_MENU, 0);
01810 }
01811 
01817 static void StartWindowSizing(Window *w, bool to_left)
01818 {
01819   w->flags4 |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
01820   w->flags4 &= ~WF_CENTERED;
01821   _dragging_window = true;
01822 
01823   _drag_delta.x = _cursor.pos.x;
01824   _drag_delta.y = _cursor.pos.y;
01825 
01826   BringWindowToFront(w);
01827   DeleteWindowById(WC_DROPDOWN_MENU, 0);
01828 }
01829 
01834 static EventState HandleScrollbarScrolling()
01835 {
01836   Window *w;
01837   FOR_ALL_WINDOWS_FROM_BACK(w) {
01838     if (w->scrolling_scrollbar >= 0) {
01839       /* Abort if no button is clicked any more. */
01840       if (!_left_button_down) {
01841         w->scrolling_scrollbar = -1;
01842         w->SetDirty();
01843         return ES_HANDLED;
01844       }
01845 
01846       int i;
01847       NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->scrolling_scrollbar);
01848       bool rtl = false;
01849 
01850       if (sb->type == NWID_HSCROLLBAR) {
01851         i = _cursor.pos.x - _cursorpos_drag_start.x;
01852         rtl = _current_text_dir == TD_RTL;
01853       } else {
01854         i = _cursor.pos.y - _cursorpos_drag_start.y;
01855       }
01856 
01857       if (sb->disp_flags & ND_SCROLLBAR_BTN) {
01858         if (_scroller_click_timeout == 1) {
01859           _scroller_click_timeout = 3;
01860           sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1);
01861           w->SetDirty();
01862         }
01863         return ES_HANDLED;
01864       }
01865 
01866       /* Find the item we want to move to and make sure it's inside bounds. */
01867       int pos = min(max(0, i + _scrollbar_start_pos) * sb->GetCount() / _scrollbar_size, max(0, sb->GetCount() - sb->GetCapacity()));
01868       if (rtl) pos = max(0, sb->GetCount() - sb->GetCapacity() - pos);
01869       if (pos != sb->GetPosition()) {
01870         sb->SetPosition(pos);
01871         w->SetDirty();
01872       }
01873       return ES_HANDLED;
01874     }
01875   }
01876 
01877   return ES_NOT_HANDLED;
01878 }
01879 
01884 static EventState HandleViewportScroll()
01885 {
01886   bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
01887 
01888   if (!_scrolling_viewport) return ES_NOT_HANDLED;
01889 
01890   /* When we don't have a last scroll window we are starting to scroll.
01891    * When the last scroll window and this are not the same we went
01892    * outside of the window and should not left-mouse scroll anymore. */
01893   if (_last_scroll_window == NULL) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
01894 
01895   if (_last_scroll_window == NULL || !(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down))) {
01896     _cursor.fix_at = false;
01897     _scrolling_viewport = false;
01898     _last_scroll_window = NULL;
01899     return ES_NOT_HANDLED;
01900   }
01901 
01902   if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
01903     /* If the main window is following a vehicle, then first let go of it! */
01904     const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
01905     ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
01906     return ES_NOT_HANDLED;
01907   }
01908 
01909   Point delta;
01910   if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
01911     delta.x = -_cursor.delta.x;
01912     delta.y = -_cursor.delta.y;
01913   } else {
01914     delta.x = _cursor.delta.x;
01915     delta.y = _cursor.delta.y;
01916   }
01917 
01918   if (scrollwheel_scrolling) {
01919     /* We are using scrollwheels for scrolling */
01920     delta.x = _cursor.h_wheel;
01921     delta.y = _cursor.v_wheel;
01922     _cursor.v_wheel = 0;
01923     _cursor.h_wheel = 0;
01924   }
01925 
01926   /* Create a scroll-event and send it to the window */
01927   if (delta.x != 0 || delta.y != 0) _last_scroll_window->OnScroll(delta);
01928 
01929   _cursor.delta.x = 0;
01930   _cursor.delta.y = 0;
01931   return ES_HANDLED;
01932 }
01933 
01944 static bool MaybeBringWindowToFront(Window *w)
01945 {
01946   bool bring_to_front = false;
01947 
01948   if (w->window_class == WC_MAIN_WINDOW ||
01949       IsVitalWindow(w) ||
01950       w->window_class == WC_TOOLTIPS ||
01951       w->window_class == WC_DROPDOWN_MENU) {
01952     return true;
01953   }
01954 
01955   /* Use unshaded window size rather than current size for shaded windows. */
01956   int w_width  = w->width;
01957   int w_height = w->height;
01958   if (w->IsShaded()) {
01959     w_width  = w->unshaded_size.width;
01960     w_height = w->unshaded_size.height;
01961   }
01962 
01963   Window *u;
01964   FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
01965     /* A modal child will prevent the activation of the parent window */
01966     if (u->parent == w && (u->desc_flags & WDF_MODAL)) {
01967       u->flags4 |= WF_WHITE_BORDER_MASK;
01968       u->SetDirty();
01969       return false;
01970     }
01971 
01972     if (u->window_class == WC_MAIN_WINDOW ||
01973         IsVitalWindow(u) ||
01974         u->window_class == WC_TOOLTIPS ||
01975         u->window_class == WC_DROPDOWN_MENU) {
01976       continue;
01977     }
01978 
01979     /* Window sizes don't interfere, leave z-order alone */
01980     if (w->left + w_width <= u->left ||
01981         u->left + u->width <= w->left ||
01982         w->top  + w_height <= u->top ||
01983         u->top + u->height <= w->top) {
01984       continue;
01985     }
01986 
01987     bring_to_front = true;
01988   }
01989 
01990   if (bring_to_front) BringWindowToFront(w);
01991   return true;
01992 }
01993 
01998 void HandleKeypress(uint32 raw_key)
01999 {
02000   /* World generation is multithreaded and messes with companies.
02001    * But there is no company related window open anyway, so _current_company is not used. */
02002   assert(IsGeneratingWorld() || IsLocalCompany());
02003 
02004   /* Setup event */
02005   uint16 key     = GB(raw_key,  0, 16);
02006   uint16 keycode = GB(raw_key, 16, 16);
02007 
02008   /*
02009    * The Unicode standard defines an area called the private use area. Code points in this
02010    * area are reserved for private use and thus not portable between systems. For instance,
02011    * Apple defines code points for the arrow keys in this area, but these are only printable
02012    * on a system running OS X. We don't want these keys to show up in text fields and such,
02013    * and thus we have to clear the unicode character when we encounter such a key.
02014    */
02015   if (key >= 0xE000 && key <= 0xF8FF) key = 0;
02016 
02017   /*
02018    * If both key and keycode is zero, we don't bother to process the event.
02019    */
02020   if (key == 0 && keycode == 0) return;
02021 
02022   /* Check if the focused window has a focused editbox */
02023   if (EditBoxInGlobalFocus()) {
02024     /* All input will in this case go to the focused window */
02025     if (_focused_window->OnKeyPress(key, keycode) == ES_HANDLED) return;
02026   }
02027 
02028   /* Call the event, start with the uppermost window, but ignore the toolbar. */
02029   Window *w;
02030   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02031     if (w->window_class == WC_MAIN_TOOLBAR) continue;
02032     if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
02033   }
02034 
02035   w = FindWindowById(WC_MAIN_TOOLBAR, 0);
02036   /* When there is no toolbar w is null, check for that */
02037   if (w != NULL && w->OnKeyPress(key, keycode) == ES_HANDLED) return;
02038 
02039   HandleGlobalHotkeys(key, keycode);
02040 }
02041 
02045 void HandleCtrlChanged()
02046 {
02047   /* Call the event, start with the uppermost window. */
02048   Window *w;
02049   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02050     if (w->OnCTRLStateChange() == ES_HANDLED) return;
02051   }
02052 }
02053 
02060 static int _input_events_this_tick = 0;
02061 
02066 static void HandleAutoscroll()
02067 {
02068   if (_settings_client.gui.autoscroll && _game_mode != GM_MENU && !IsGeneratingWorld()) {
02069     int x = _cursor.pos.x;
02070     int y = _cursor.pos.y;
02071     Window *w = FindWindowFromPt(x, y);
02072     if (w == NULL || w->flags4 & WF_DISABLE_VP_SCROLL) return;
02073     ViewPort *vp = IsPtInWindowViewport(w, x, y);
02074     if (vp != NULL) {
02075       x -= vp->left;
02076       y -= vp->top;
02077 
02078       /* here allows scrolling in both x and y axis */
02079 #define scrollspeed 3
02080       if (x - 15 < 0) {
02081         w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
02082       } else if (15 - (vp->width - x) > 0) {
02083         w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
02084       }
02085       if (y - 15 < 0) {
02086         w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
02087       } else if (15 - (vp->height - y) > 0) {
02088         w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
02089       }
02090 #undef scrollspeed
02091     }
02092   }
02093 }
02094 
02095 enum MouseClick {
02096   MC_NONE = 0,
02097   MC_LEFT,
02098   MC_RIGHT,
02099   MC_DOUBLE_LEFT,
02100   MC_HOVER,
02101 
02102   MAX_OFFSET_DOUBLE_CLICK = 5,     
02103   TIME_BETWEEN_DOUBLE_CLICK = 500, 
02104   MAX_OFFSET_HOVER = 5,            
02105 };
02106 extern EventState VpHandlePlaceSizingDrag();
02107 
02108 static void ScrollMainViewport(int x, int y)
02109 {
02110   if (_game_mode != GM_MENU) {
02111     Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
02112     assert(w);
02113 
02114     w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
02115     w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
02116   }
02117 }
02118 
02128 static const int8 scrollamt[16][2] = {
02129   { 0,  0}, 
02130   {-2,  0}, 
02131   { 0, -2}, 
02132   {-2, -1}, 
02133   { 2,  0}, 
02134   { 0,  0}, 
02135   { 2, -1}, 
02136   { 0, -2}, 
02137   { 0,  2}, 
02138   {-2,  1}, 
02139   { 0,  0}, 
02140   {-2,  0}, 
02141   { 2,  1}, 
02142   { 0,  2}, 
02143   { 2,  0}, 
02144   { 0,  0}, 
02145 };
02146 
02147 static void HandleKeyScrolling()
02148 {
02149   /*
02150    * Check that any of the dirkeys is pressed and that the focused window
02151    * dont has an edit-box as focused widget.
02152    */
02153   if (_dirkeys && !EditBoxInGlobalFocus()) {
02154     int factor = _shift_pressed ? 50 : 10;
02155     ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
02156   }
02157 }
02158 
02159 static void MouseLoop(MouseClick click, int mousewheel)
02160 {
02161   /* World generation is multithreaded and messes with companies.
02162    * But there is no company related window open anyway, so _current_company is not used. */
02163   assert(IsGeneratingWorld() || IsLocalCompany());
02164 
02165   HandlePlacePresize();
02166   UpdateTileSelection();
02167 
02168   if (VpHandlePlaceSizingDrag()  == ES_HANDLED) return;
02169   if (HandleMouseDragDrop()      == ES_HANDLED) return;
02170   if (HandleWindowDragging()     == ES_HANDLED) return;
02171   if (HandleScrollbarScrolling() == ES_HANDLED) return;
02172   if (HandleViewportScroll()     == ES_HANDLED) return;
02173 
02174   HandleMouseOver();
02175 
02176   bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
02177   if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
02178 
02179   int x = _cursor.pos.x;
02180   int y = _cursor.pos.y;
02181   Window *w = FindWindowFromPt(x, y);
02182   if (w == NULL) return;
02183 
02184   if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
02185   ViewPort *vp = IsPtInWindowViewport(w, x, y);
02186 
02187   /* Don't allow any action in a viewport if either in menu of in generating world */
02188   if (vp != NULL && (_game_mode == GM_MENU || IsGeneratingWorld())) return;
02189 
02190   if (mousewheel != 0) {
02191     if (_settings_client.gui.scrollwheel_scrolling == 0) {
02192       /* Send mousewheel event to window */
02193       w->OnMouseWheel(mousewheel);
02194     }
02195 
02196     /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
02197     if (vp == NULL) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
02198   }
02199 
02200   if (vp != NULL) {
02201     if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
02202     switch (click) {
02203       case MC_DOUBLE_LEFT:
02204       case MC_LEFT:
02205         DEBUG(misc, 2, "Cursor: 0x%X (%d)", _cursor.sprite, _cursor.sprite);
02206         if (!HandleViewportClicked(vp, x, y) &&
02207             !(w->flags4 & WF_DISABLE_VP_SCROLL) &&
02208             _settings_client.gui.left_mouse_btn_scrolling) {
02209           _scrolling_viewport = true;
02210           _cursor.fix_at = false;
02211         }
02212         break;
02213 
02214       case MC_RIGHT:
02215         if (!(w->flags4 & WF_DISABLE_VP_SCROLL)) {
02216           _scrolling_viewport = true;
02217           _cursor.fix_at = true;
02218 
02219           /* clear 2D scrolling caches before we start a 2D scroll */
02220           _cursor.h_wheel = 0;
02221           _cursor.v_wheel = 0;
02222         }
02223         break;
02224 
02225       default:
02226         break;
02227     }
02228   } else {
02229     switch (click) {
02230       case MC_LEFT:
02231       case MC_DOUBLE_LEFT:
02232         DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
02233         break;
02234 
02235       default:
02236         if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
02237         /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
02238          * Simulate a right button click so we can get started. */
02239         /* FALL THROUGH */
02240 
02241       case MC_RIGHT: DispatchRightClickEvent(w, x - w->left, y - w->top); break;
02242 
02243       case MC_HOVER: DispatchHoverEvent(w, x - w->left, y - w->top); break;
02244     }
02245   }
02246 }
02247 
02251 void HandleMouseEvents()
02252 {
02253   /* World generation is multithreaded and messes with companies.
02254    * But there is no company related window open anyway, so _current_company is not used. */
02255   assert(IsGeneratingWorld() || IsLocalCompany());
02256 
02257   static int double_click_time = 0;
02258   static Point double_click_pos = {0, 0};
02259 
02260   /* Mouse event? */
02261   MouseClick click = MC_NONE;
02262   if (_left_button_down && !_left_button_clicked) {
02263     click = MC_LEFT;
02264     if (double_click_time != 0 && _realtime_tick - double_click_time   < TIME_BETWEEN_DOUBLE_CLICK &&
02265         double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK  &&
02266         double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
02267       click = MC_DOUBLE_LEFT;
02268     }
02269     double_click_time = _realtime_tick;
02270     double_click_pos = _cursor.pos;
02271     _left_button_clicked = true;
02272     _input_events_this_tick++;
02273   } else if (_right_button_clicked) {
02274     _right_button_clicked = false;
02275     click = MC_RIGHT;
02276     _input_events_this_tick++;
02277   }
02278 
02279   int mousewheel = 0;
02280   if (_cursor.wheel) {
02281     mousewheel = _cursor.wheel;
02282     _cursor.wheel = 0;
02283     _input_events_this_tick++;
02284   }
02285 
02286   static uint32 hover_time = 0;
02287   static Point hover_pos = {0, 0};
02288 
02289   if (_settings_client.gui.hover_delay > 0) {
02290     if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
02291         hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER  ||
02292         hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
02293       hover_pos = _cursor.pos;
02294       hover_time = _realtime_tick;
02295       _mouse_hovering = false;
02296     } else {
02297       if (hover_time != 0 && _realtime_tick > hover_time + _settings_client.gui.hover_delay * 1000) {
02298         click = MC_HOVER;
02299         _input_events_this_tick++;
02300         _mouse_hovering = true;
02301       }
02302     }
02303   }
02304 
02305   /* Handle sprite picker before any GUI interaction */
02306   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _newgrf_debug_sprite_picker.click_time != _realtime_tick) {
02307     /* Next realtime tick? Then redraw has finished */
02308     _newgrf_debug_sprite_picker.mode = SPM_NONE;
02309     InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
02310   }
02311 
02312   if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
02313     /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
02314     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
02315     _newgrf_debug_sprite_picker.clicked_pixel = blitter->MoveTo(_screen.dst_ptr, _cursor.pos.x, _cursor.pos.y);
02316     _newgrf_debug_sprite_picker.click_time = _realtime_tick;
02317     _newgrf_debug_sprite_picker.sprites.Clear();
02318     _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
02319     MarkWholeScreenDirty();
02320   } else {
02321     MouseLoop(click, mousewheel);
02322   }
02323 
02324   /* We have moved the mouse the required distance,
02325    * no need to move it at any later time. */
02326   _cursor.delta.x = 0;
02327   _cursor.delta.y = 0;
02328 }
02329 
02333 static void CheckSoftLimit()
02334 {
02335   if (_settings_client.gui.window_soft_limit == 0) return;
02336 
02337   for (;;) {
02338     uint deletable_count = 0;
02339     Window *w, *last_deletable = NULL;
02340     FOR_ALL_WINDOWS_FROM_FRONT(w) {
02341       if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags4 & WF_STICKY)) continue;
02342 
02343       last_deletable = w;
02344       deletable_count++;
02345     }
02346 
02347     /* We've ot reached the soft limit yet */
02348     if (deletable_count <= _settings_client.gui.window_soft_limit) break;
02349 
02350     assert(last_deletable != NULL);
02351     delete last_deletable;
02352   }
02353 }
02354 
02358 void InputLoop()
02359 {
02360   /* World generation is multithreaded and messes with companies.
02361    * But there is no company related window open anyway, so _current_company is not used. */
02362   assert(IsGeneratingWorld() || IsLocalCompany());
02363 
02364   CheckSoftLimit();
02365   HandleKeyScrolling();
02366 
02367   /* Do the actual free of the deleted windows. */
02368   for (Window *v = _z_front_window; v != NULL; /* nothing */) {
02369     Window *w = v;
02370     v = v->z_back;
02371 
02372     if (w->window_class != WC_INVALID) continue;
02373 
02374     /* Find the window in the z-array, and effectively remove it
02375      * by moving all windows after it one to the left. This must be
02376      * done before removing the child so we cannot cause recursion
02377      * between the deletion of the parent and the child. */
02378     if (w->z_front == NULL) {
02379       _z_front_window = w->z_back;
02380     } else {
02381       w->z_front->z_back = w->z_back;
02382     }
02383     if (w->z_back == NULL) {
02384       _z_back_window  = w->z_front;
02385     } else {
02386       w->z_back->z_front = w->z_front;
02387     }
02388     free(w);
02389   }
02390 
02391   if (_scroller_click_timeout != 0) _scroller_click_timeout--;
02392   DecreaseWindowCounters();
02393 
02394   if (_input_events_this_tick != 0) {
02395     /* The input loop is called only once per GameLoop() - so we can clear the counter here */
02396     _input_events_this_tick = 0;
02397     /* there were some inputs this tick, don't scroll ??? */
02398     return;
02399   }
02400 
02401   /* HandleMouseEvents was already called for this tick */
02402   HandleMouseEvents();
02403   HandleAutoscroll();
02404 }
02405 
02409 void UpdateWindows()
02410 {
02411   Window *w;
02412   static int we4_timer = 0;
02413   int t = we4_timer + 1;
02414 
02415   if (t >= 100) {
02416     FOR_ALL_WINDOWS_FROM_FRONT(w) {
02417       w->OnHundredthTick();
02418     }
02419     t = 0;
02420   }
02421   we4_timer = t;
02422 
02423   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02424     if (w->flags4 & WF_WHITE_BORDER_MASK) {
02425       w->flags4 -= WF_WHITE_BORDER_ONE;
02426 
02427       if (!(w->flags4 & WF_WHITE_BORDER_MASK)) w->SetDirty();
02428     }
02429   }
02430 
02431   DrawDirtyBlocks();
02432 
02433   FOR_ALL_WINDOWS_FROM_BACK(w) {
02434     /* Update viewport only if window is not shaded. */
02435     if (w->viewport != NULL && !w->IsShaded()) UpdateViewportPosition(w);
02436   }
02437   NetworkDrawChatMessage();
02438   /* Redraw mouse cursor in case it was hidden */
02439   DrawMouseCursor();
02440 }
02441 
02447 void SetWindowDirty(WindowClass cls, WindowNumber number)
02448 {
02449   const Window *w;
02450   FOR_ALL_WINDOWS_FROM_BACK(w) {
02451     if (w->window_class == cls && w->window_number == number) w->SetDirty();
02452   }
02453 }
02454 
02461 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
02462 {
02463   const Window *w;
02464   FOR_ALL_WINDOWS_FROM_BACK(w) {
02465     if (w->window_class == cls && w->window_number == number) {
02466       w->SetWidgetDirty(widget_index);
02467     }
02468   }
02469 }
02470 
02475 void SetWindowClassesDirty(WindowClass cls)
02476 {
02477   Window *w;
02478   FOR_ALL_WINDOWS_FROM_BACK(w) {
02479     if (w->window_class == cls) w->SetDirty();
02480   }
02481 }
02482 
02489 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data)
02490 {
02491   Window *w;
02492   FOR_ALL_WINDOWS_FROM_BACK(w) {
02493     if (w->window_class == cls && w->window_number == number) w->InvalidateData(data);
02494   }
02495 }
02496 
02502 void InvalidateWindowClassesData(WindowClass cls, int data)
02503 {
02504   Window *w;
02505 
02506   FOR_ALL_WINDOWS_FROM_BACK(w) {
02507     if (w->window_class == cls) w->InvalidateData(data);
02508   }
02509 }
02510 
02514 void CallWindowTickEvent()
02515 {
02516   Window *w;
02517   FOR_ALL_WINDOWS_FROM_FRONT(w) {
02518     w->OnTick();
02519   }
02520 }
02521 
02528 void DeleteNonVitalWindows()
02529 {
02530   Window *w;
02531 
02532 restart_search:
02533   /* When we find the window to delete, we need to restart the search
02534    * as deleting this window could cascade in deleting (many) others
02535    * anywhere in the z-array */
02536   FOR_ALL_WINDOWS_FROM_BACK(w) {
02537     if (w->window_class != WC_MAIN_WINDOW &&
02538         w->window_class != WC_SELECT_GAME &&
02539         w->window_class != WC_MAIN_TOOLBAR &&
02540         w->window_class != WC_STATUS_BAR &&
02541         w->window_class != WC_TOOLBAR_MENU &&
02542         w->window_class != WC_TOOLTIPS &&
02543         (w->flags4 & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
02544 
02545       delete w;
02546       goto restart_search;
02547     }
02548   }
02549 }
02550 
02558 void DeleteAllNonVitalWindows()
02559 {
02560   Window *w;
02561 
02562   /* Delete every window except for stickied ones, then sticky ones as well */
02563   DeleteNonVitalWindows();
02564 
02565 restart_search:
02566   /* When we find the window to delete, we need to restart the search
02567    * as deleting this window could cascade in deleting (many) others
02568    * anywhere in the z-array */
02569   FOR_ALL_WINDOWS_FROM_BACK(w) {
02570     if (w->flags4 & WF_STICKY) {
02571       delete w;
02572       goto restart_search;
02573     }
02574   }
02575 }
02576 
02581 void DeleteConstructionWindows()
02582 {
02583   Window *w;
02584 
02585 restart_search:
02586   /* When we find the window to delete, we need to restart the search
02587    * as deleting this window could cascade in deleting (many) others
02588    * anywhere in the z-array */
02589   FOR_ALL_WINDOWS_FROM_BACK(w) {
02590     if (w->desc_flags & WDF_CONSTRUCTION) {
02591       delete w;
02592       goto restart_search;
02593     }
02594   }
02595 
02596   FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
02597 }
02598 
02600 void HideVitalWindows()
02601 {
02602   DeleteWindowById(WC_TOOLBAR_MENU, 0);
02603   DeleteWindowById(WC_MAIN_TOOLBAR, 0);
02604   DeleteWindowById(WC_STATUS_BAR, 0);
02605 }
02606 
02608 void ReInitAllWindows()
02609 {
02610   NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
02611 
02612   Window *w;
02613   FOR_ALL_WINDOWS_FROM_BACK(w) {
02614     w->ReInit();
02615   }
02616 #ifdef ENABLE_NETWORK
02617   void NetworkReInitChatBoxSize();
02618   NetworkReInitChatBoxSize();
02619 #endif
02620 
02621   /* Make sure essential parts of all windows are visible */
02622   RelocateAllWindows(_cur_resolution.width, _cur_resolution.height);
02623   MarkWholeScreenDirty();
02624 }
02625 
02633 static int PositionWindow(Window *w, WindowClass clss, int setting)
02634 {
02635   if (w == NULL || w->window_class != clss) {
02636     w = FindWindowById(clss, 0);
02637   }
02638   if (w == NULL) return 0;
02639 
02640   int old_left = w->left;
02641   switch (setting) {
02642     case 1:  w->left = (_screen.width - w->width) / 2; break;
02643     case 2:  w->left = _screen.width - w->width; break;
02644     default: w->left = 0; break;
02645   }
02646   if (w->viewport != NULL) w->viewport->left += w->left - old_left;
02647   SetDirtyBlocks(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
02648   return w->left;
02649 }
02650 
02656 int PositionMainToolbar(Window *w)
02657 {
02658   DEBUG(misc, 5, "Repositioning Main Toolbar...");
02659   return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
02660 }
02661 
02667 int PositionStatusbar(Window *w)
02668 {
02669   DEBUG(misc, 5, "Repositioning statusbar...");
02670   return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
02671 }
02672 
02678 int PositionNewsMessage(Window *w)
02679 {
02680   DEBUG(misc, 5, "Repositioning news message...");
02681   return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
02682 }
02683 
02684 
02690 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
02691 {
02692   Window *w;
02693   FOR_ALL_WINDOWS_FROM_BACK(w) {
02694     if (w->viewport != NULL && w->viewport->follow_vehicle == from_index) {
02695       w->viewport->follow_vehicle = to_index;
02696       w->SetDirty();
02697     }
02698   }
02699 }
02700 
02701 
02707 void RelocateAllWindows(int neww, int newh)
02708 {
02709   Window *w;
02710 
02711   FOR_ALL_WINDOWS_FROM_BACK(w) {
02712     int left, top;
02713 
02714     if (w->window_class == WC_MAIN_WINDOW) {
02715       ViewPort *vp = w->viewport;
02716       vp->width = w->width = neww;
02717       vp->height = w->height = newh;
02718       vp->virtual_width = ScaleByZoom(neww, vp->zoom);
02719       vp->virtual_height = ScaleByZoom(newh, vp->zoom);
02720       continue; // don't modify top,left
02721     }
02722 
02723     /* XXX - this probably needs something more sane. For example specifying
02724      * in a 'backup'-desc that the window should always be centered. */
02725     switch (w->window_class) {
02726       case WC_MAIN_TOOLBAR:
02727         ResizeWindow(w, min(neww, *_preferred_toolbar_size) - w->width, 0);
02728 
02729         top = w->top;
02730         left = PositionMainToolbar(w); // changes toolbar orientation
02731         break;
02732 
02733       case WC_NEWS_WINDOW:
02734         top = newh - w->height;
02735         left = PositionNewsMessage(w);
02736         break;
02737 
02738       case WC_STATUS_BAR:
02739         ResizeWindow(w, min(neww, *_preferred_statusbar_size) - w->width, 0);
02740 
02741         top = newh - w->height;
02742         left = PositionStatusbar(w);
02743         break;
02744 
02745       case WC_SEND_NETWORK_MSG:
02746         ResizeWindow(w, Clamp(neww, 320, 640) - w->width, 0);
02747         top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
02748         left = (neww - w->width) >> 1;
02749         break;
02750 
02751       case WC_CONSOLE:
02752         IConsoleResize(w);
02753         continue;
02754 
02755       default: {
02756         if (w->flags4 & WF_CENTERED) {
02757           top = (newh - w->height) >> 1;
02758           left = (neww - w->width) >> 1;
02759           break;
02760         }
02761 
02762         left = w->left;
02763         if (left + (w->width >> 1) >= neww) left = neww - w->width;
02764         if (left < 0) left = 0;
02765 
02766         top = w->top;
02767         if (top + (w->height >> 1) >= newh) top = newh - w->height;
02768 
02769         const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
02770         if (wt != NULL) {
02771           if (top < wt->height && wt->left < (w->left + w->width) && (wt->left + wt->width) > w->left) top = wt->height;
02772           if (top >= newh) top = newh - 1;
02773         } else {
02774           if (top < 0) top = 0;
02775         }
02776         break;
02777       }
02778     }
02779 
02780     if (w->viewport != NULL) {
02781       w->viewport->left += left - w->left;
02782       w->viewport->top += top - w->top;
02783     }
02784 
02785     w->left = left;
02786     w->top = top;
02787   }
02788 }
02789 
02795 PickerWindowBase::~PickerWindowBase()
02796 {
02797   this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
02798   ResetObjectToPlace();
02799 }

Generated on Thu Jan 20 22:57:44 2011 for OpenTTD by  doxygen 1.6.1