window.cpp

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

Generated on Thu Dec 23 23:41:35 2010 for OpenTTD by  doxygen 1.6.1