]> git.lizzy.rs Git - dragonfireclient.git/blob - src/guiFormSpecMenu.cpp
Detached inventories
[dragonfireclient.git] / src / guiFormSpecMenu.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20
21 #include "guiFormSpecMenu.h"
22 #include "constants.h"
23 #include "gamedef.h"
24 #include "keycode.h"
25 #include "strfnd.h"
26 #include <IGUICheckBox.h>
27 #include <IGUIEditBox.h>
28 #include <IGUIButton.h>
29 #include <IGUIStaticText.h>
30 #include <IGUIFont.h>
31 #include "log.h"
32 #include "tile.h" // ITextureSource
33 #include "util/string.h"
34 #include "util/numeric.h"
35
36 #include "gettext.h"
37
38 void drawItemStack(video::IVideoDriver *driver,
39                 gui::IGUIFont *font,
40                 const ItemStack &item,
41                 const core::rect<s32> &rect,
42                 const core::rect<s32> *clip,
43                 IGameDef *gamedef)
44 {
45         if(item.empty())
46                 return;
47         
48         const ItemDefinition &def = item.getDefinition(gamedef->idef());
49         video::ITexture *texture = def.inventory_texture;
50
51         // Draw the inventory texture
52         if(texture != NULL)
53         {
54                 const video::SColor color(255,255,255,255);
55                 const video::SColor colors[] = {color,color,color,color};
56                 driver->draw2DImage(texture, rect,
57                         core::rect<s32>(core::position2d<s32>(0,0),
58                         core::dimension2di(texture->getOriginalSize())),
59                         clip, colors, true);
60         }
61
62         if(def.type == ITEM_TOOL && item.wear != 0)
63         {
64                 // Draw a progressbar
65                 float barheight = rect.getHeight()/16;
66                 float barpad_x = rect.getWidth()/16;
67                 float barpad_y = rect.getHeight()/16;
68                 core::rect<s32> progressrect(
69                         rect.UpperLeftCorner.X + barpad_x,
70                         rect.LowerRightCorner.Y - barpad_y - barheight,
71                         rect.LowerRightCorner.X - barpad_x,
72                         rect.LowerRightCorner.Y - barpad_y);
73
74                 // Shrink progressrect by amount of tool damage
75                 float wear = item.wear / 65535.0;
76                 int progressmid =
77                         wear * progressrect.UpperLeftCorner.X +
78                         (1-wear) * progressrect.LowerRightCorner.X;
79
80                 // Compute progressbar color
81                 //   wear = 0.0: green
82                 //   wear = 0.5: yellow
83                 //   wear = 1.0: red
84                 video::SColor color(255,255,255,255);
85                 int wear_i = MYMIN(floor(wear * 600), 511);
86                 wear_i = MYMIN(wear_i + 10, 511);
87                 if(wear_i <= 255)
88                         color.set(255, wear_i, 255, 0);
89                 else
90                         color.set(255, 255, 511-wear_i, 0);
91
92                 core::rect<s32> progressrect2 = progressrect;
93                 progressrect2.LowerRightCorner.X = progressmid;
94                 driver->draw2DRectangle(color, progressrect2, clip);
95
96                 color = video::SColor(255,0,0,0);
97                 progressrect2 = progressrect;
98                 progressrect2.UpperLeftCorner.X = progressmid;
99                 driver->draw2DRectangle(color, progressrect2, clip);
100         }
101
102         if(font != NULL && item.count >= 2)
103         {
104                 // Get the item count as a string
105                 std::string text = itos(item.count);
106                 v2u32 dim = font->getDimension(narrow_to_wide(text).c_str());
107                 v2s32 sdim(dim.X,dim.Y);
108
109                 core::rect<s32> rect2(
110                         /*rect.UpperLeftCorner,
111                         core::dimension2d<u32>(rect.getWidth(), 15)*/
112                         rect.LowerRightCorner - sdim,
113                         sdim
114                 );
115
116                 video::SColor bgcolor(128,0,0,0);
117                 driver->draw2DRectangle(bgcolor, rect2, clip);
118
119                 video::SColor color(255,255,255,255);
120                 font->draw(text.c_str(), rect2, color, false, false, clip);
121         }
122 }
123
124 /*
125         GUIFormSpecMenu
126 */
127
128 GUIFormSpecMenu::GUIFormSpecMenu(gui::IGUIEnvironment* env,
129                 gui::IGUIElement* parent, s32 id,
130                 IMenuManager *menumgr,
131                 InventoryManager *invmgr,
132                 IGameDef *gamedef
133 ):
134         GUIModalMenu(env, parent, id, menumgr),
135         m_invmgr(invmgr),
136         m_gamedef(gamedef),
137         m_form_src(NULL),
138         m_text_dst(NULL),
139         m_selected_item(NULL),
140         m_selected_amount(0),
141         m_selected_dragging(false),
142         m_tooltip_element(NULL)
143 {
144 }
145
146 GUIFormSpecMenu::~GUIFormSpecMenu()
147 {
148         removeChildren();
149
150         delete m_selected_item;
151         delete m_form_src;
152         delete m_text_dst;
153 }
154
155 void GUIFormSpecMenu::removeChildren()
156 {
157         const core::list<gui::IGUIElement*> &children = getChildren();
158         core::list<gui::IGUIElement*> children_copy;
159         for(core::list<gui::IGUIElement*>::ConstIterator
160                         i = children.begin(); i != children.end(); i++)
161         {
162                 children_copy.push_back(*i);
163         }
164         for(core::list<gui::IGUIElement*>::Iterator
165                         i = children_copy.begin();
166                         i != children_copy.end(); i++)
167         {
168                 (*i)->remove();
169         }
170         /*{
171                 gui::IGUIElement *e = getElementFromId(256);
172                 if(e != NULL)
173                         e->remove();
174         }*/
175         if(m_tooltip_element)
176         {
177                 m_tooltip_element->remove();
178                 m_tooltip_element = NULL;
179         }
180 }
181
182 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
183 {
184         // Remove children
185         removeChildren();
186         
187         v2s32 size(100,100);
188         s32 helptext_h = 15;
189         core::rect<s32> rect;
190
191         // Base position of contents of form
192         v2s32 basepos = getBasePos();
193         // State of basepos, 0 = not set, 1= set by formspec, 2 = set by size[] element
194         // Used to adjust form size automatically if needed
195         // A proceed button is added if there is no size[] element
196         int bp_set = 0;
197         
198         /* Convert m_init_draw_spec to m_inventorylists */
199         
200         m_inventorylists.clear();
201         m_images.clear();
202         m_fields.clear();
203
204         Strfnd f(m_formspec_string);
205         while(f.atend() == false)
206         {
207                 std::string type = trim(f.next("["));
208                 if(type == "invsize" || type == "size")
209                 {
210                         v2f invsize;
211                         invsize.X = stof(f.next(","));
212                         if(type == "size")
213                         {
214                                 invsize.Y = stof(f.next("]"));
215                         }
216                         else{
217                                 invsize.Y = stof(f.next(";"));
218                                 errorstream<<"WARNING: invsize is deprecated, use size"<<std::endl;
219                                 f.next("]");
220                         }
221                         infostream<<"size ("<<invsize.X<<","<<invsize.Y<<")"<<std::endl;
222
223                         padding = v2s32(screensize.Y/40, screensize.Y/40);
224                         spacing = v2s32(screensize.Y/12, screensize.Y/13);
225                         imgsize = v2s32(screensize.Y/15, screensize.Y/15);
226                         size = v2s32(
227                                 padding.X*2+spacing.X*(invsize.X-1.0)+imgsize.X,
228                                 padding.Y*2+spacing.Y*(invsize.Y-1.0)+imgsize.Y + (helptext_h-5)
229                         );
230                         rect = core::rect<s32>(
231                                         screensize.X/2 - size.X/2,
232                                         screensize.Y/2 - size.Y/2,
233                                         screensize.X/2 + size.X/2,
234                                         screensize.Y/2 + size.Y/2
235                         );
236                         DesiredRect = rect;
237                         recalculateAbsolutePosition(false);
238                         basepos = getBasePos();
239                         bp_set = 2;
240                 }
241                 else if(type == "list")
242                 {
243                         std::string name = f.next(";");
244                         InventoryLocation loc;
245                         if(name == "context" || name == "current_name")
246                                 loc = m_current_inventory_location;
247                         else
248                                 loc.deSerialize(name);
249                         std::string listname = f.next(";");
250                         v2s32 pos = basepos;
251                         pos.X += stof(f.next(",")) * (float)spacing.X;
252                         pos.Y += stof(f.next(";")) * (float)spacing.Y;
253                         v2s32 geom;
254                         geom.X = stoi(f.next(","));
255                         geom.Y = stoi(f.next(";"));
256                         infostream<<"list inv="<<name<<", listname="<<listname
257                                         <<", pos=("<<pos.X<<","<<pos.Y<<")"
258                                         <<", geom=("<<geom.X<<","<<geom.Y<<")"
259                                         <<std::endl;
260                         std::string start_i_s = f.next("]");
261                         s32 start_i = 0;
262                         if(start_i_s != "")
263                                 start_i = stoi(start_i_s);
264                         if(bp_set != 2)
265                                 errorstream<<"WARNING: invalid use of list without a size[] element"<<std::endl;
266                         m_inventorylists.push_back(ListDrawSpec(loc, listname, pos, geom, start_i));
267                 }
268                 else if(type == "image")
269                 {
270                         v2s32 pos = basepos;
271                         pos.X += stof(f.next(",")) * (float)spacing.X;
272                         pos.Y += stof(f.next(";")) * (float)spacing.Y;
273                         v2s32 geom;
274                         geom.X = stof(f.next(",")) * (float)imgsize.X;
275                         geom.Y = stof(f.next(";")) * (float)imgsize.Y;
276                         std::string name = f.next("]");
277                         infostream<<"image name="<<name
278                                         <<", pos=("<<pos.X<<","<<pos.Y<<")"
279                                         <<", geom=("<<geom.X<<","<<geom.Y<<")"
280                                         <<std::endl;
281                         if(bp_set != 2)
282                                 errorstream<<"WARNING: invalid use of button without a size[] element"<<std::endl;
283                         m_images.push_back(ImageDrawSpec(name, pos, geom));
284                 }
285                 else if(type == "field")
286                 {
287                         std::string fname = f.next(";");
288                         std::string flabel = f.next(";");
289                         
290                         if(fname.find(",") == std::string::npos && flabel.find(",") == std::string::npos)
291                         {
292                                 if(!bp_set)
293                                 {
294                                         rect = core::rect<s32>(
295                                                 screensize.X/2 - 580/2,
296                                                 screensize.Y/2 - 300/2,
297                                                 screensize.X/2 + 580/2,
298                                                 screensize.Y/2 + 300/2
299                                         );
300                                         DesiredRect = rect;
301                                         recalculateAbsolutePosition(false);
302                                         basepos = getBasePos();
303                                         bp_set = 1;
304                                 }
305                                 else if(bp_set == 2)
306                                         errorstream<<"WARNING: invalid use of unpositioned field in inventory"<<std::endl;
307
308                                 v2s32 pos = basepos;
309                                 pos.Y = ((m_fields.size()+2)*60);
310                                 v2s32 size = DesiredRect.getSize();
311                                 rect = core::rect<s32>(size.X/2-150, pos.Y, (size.X/2-150)+300, pos.Y+30);
312                         }
313                         else
314                         {
315                                 v2s32 pos;
316                                 pos.X = stof(fname.substr(0,fname.find(","))) * (float)spacing.X;
317                                 pos.Y = stof(fname.substr(fname.find(",")+1)) * (float)spacing.Y;
318                                 v2s32 geom;
319                                 geom.X = (stof(flabel.substr(0,flabel.find(","))) * (float)spacing.X)-(spacing.X-imgsize.X);
320                                 pos.Y += (stof(flabel.substr(flabel.find(",")+1)) * (float)imgsize.Y)/2;
321
322                                 rect = core::rect<s32>(pos.X, pos.Y-15, pos.X+geom.X, pos.Y+15);
323                                 
324                                 fname = f.next(";");
325                                 flabel = f.next(";");
326                                 if(bp_set != 2)
327                                         errorstream<<"WARNING: invalid use of positioned field without a size[] element"<<std::endl;
328                                 
329                         }
330
331                         std::string odefault = f.next("]");
332                         std::string fdefault;
333                         
334                         // fdefault may contain a variable reference, which
335                         // needs to be resolved from the node metadata
336                         if(m_form_src)
337                                 fdefault = m_form_src->resolveText(odefault);
338                         else
339                                 fdefault = odefault;
340
341                         FieldSpec spec = FieldSpec(
342                                 narrow_to_wide(fname.c_str()),
343                                 narrow_to_wide(flabel.c_str()),
344                                 narrow_to_wide(fdefault.c_str()),
345                                 258+m_fields.size()
346                         );
347                         
348                         // three cases: field and no label, label and no field, label and field
349                         if (flabel == "") 
350                         {
351                                 spec.send = true;
352                                 gui::IGUIElement *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
353                                 Environment->setFocus(e);
354
355                                 irr::SEvent evt;
356                                 evt.EventType = EET_KEY_INPUT_EVENT;
357                                 evt.KeyInput.Key = KEY_END;
358                                 evt.KeyInput.PressedDown = true;
359                                 e->OnEvent(evt);
360                         }
361                         else if (fname == "")
362                         {
363                                 // set spec field id to 0, this stops submit searching for a value that isn't there
364                                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
365                         }
366                         else
367                         {
368                                 spec.send = true;
369                                 gui::IGUIElement *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
370                                 Environment->setFocus(e);
371                                 rect.UpperLeftCorner.Y -= 15;
372                                 rect.LowerRightCorner.Y -= 15;
373                                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
374
375                                 irr::SEvent evt;
376                                 evt.EventType = EET_KEY_INPUT_EVENT;
377                                 evt.KeyInput.Key = KEY_END;
378                                 evt.KeyInput.PressedDown = true;
379                                 e->OnEvent(evt);
380                         }
381                         
382                         m_fields.push_back(spec);
383                 }
384                 else if(type == "label")
385                 {
386                         v2s32 pos;
387                         pos.X = stof(f.next(",")) * (float)spacing.X;
388                         pos.Y = stof(f.next(";")) * (float)spacing.Y;
389
390                         rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+300, pos.Y+((imgsize.Y/2)+15));
391                         
392                         std::string flabel = f.next("]");
393                         if(bp_set != 2)
394                                 errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;
395
396                         FieldSpec spec = FieldSpec(
397                                 narrow_to_wide(""),
398                                 narrow_to_wide(flabel.c_str()),
399                                 narrow_to_wide(""),
400                                 258+m_fields.size()
401                         );
402                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
403                         m_fields.push_back(spec);
404                 }
405                 else if(type == "button" || type == "button_exit")
406                 {
407                         v2s32 pos;
408                         pos.X = stof(f.next(",")) * (float)spacing.X;
409                         pos.Y = stof(f.next(";")) * (float)spacing.Y;
410                         v2s32 geom;
411                         geom.X = (stof(f.next(",")) * (float)spacing.X)-(spacing.X-imgsize.X);
412                         pos.Y += (stof(f.next(";")) * (float)imgsize.Y)/2;
413
414                         rect = core::rect<s32>(pos.X, pos.Y-15, pos.X+geom.X, pos.Y+15);
415                         
416                         std::string fname = f.next(";");
417                         std::string flabel = f.next("]");
418                         if(bp_set != 2)
419                                 errorstream<<"WARNING: invalid use of button without a size[] element"<<std::endl;
420
421                         FieldSpec spec = FieldSpec(
422                                 narrow_to_wide(fname.c_str()),
423                                 narrow_to_wide(flabel.c_str()),
424                                 narrow_to_wide(""),
425                                 258+m_fields.size()
426                         );
427                         spec.is_button = true;
428                         if(type == "button_exit")
429                                 spec.is_exit = true;
430                         Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
431                         m_fields.push_back(spec);
432                 }
433                 else if(type == "image_button" || type == "image_button_exit")
434                 {
435                         v2s32 pos;
436                         pos.X = stof(f.next(",")) * (float)spacing.X;
437                         pos.Y = stof(f.next(";")) * (float)spacing.Y;
438                         v2s32 geom;
439                         geom.X = (stof(f.next(",")) * (float)spacing.X)-(spacing.X-imgsize.X);
440                         geom.Y = (stof(f.next(";")) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
441
442                         rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
443                         
444                         std::string fimage = f.next(";");
445                         std::string fname = f.next(";");
446                         std::string flabel = f.next("]");
447                         if(bp_set != 2)
448                                 errorstream<<"WARNING: invalid use of image_button without a size[] element"<<std::endl;
449
450                         FieldSpec spec = FieldSpec(
451                                 narrow_to_wide(fname.c_str()),
452                                 narrow_to_wide(flabel.c_str()),
453                                 narrow_to_wide(fimage.c_str()),
454                                 258+m_fields.size()
455                         );
456                         spec.is_button = true;
457                         if(type == "image_button_exit")
458                                 spec.is_exit = true;
459                         
460                         video::ITexture *texture = m_gamedef->tsrc()->getTextureRaw(fimage);
461                         gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
462                         e->setImage(texture);
463                         e->setPressedImage(texture);
464                         e->setScaleImage(true);
465                         
466                         m_fields.push_back(spec);
467                 }
468                 else
469                 {
470                         // Ignore others
471                         std::string ts = f.next("]");
472                         infostream<<"Unknown DrawSpec: type="<<type<<", data=\""<<ts<<"\""
473                                         <<std::endl;
474                 }
475         }
476
477         // If there's inventory, put the usage string at the bottom
478         if (m_inventorylists.size())
479         {
480                 changeCtype("");
481                 core::rect<s32> rect(0, 0, size.X-padding.X*2, helptext_h);
482                 rect = rect + v2s32(size.X/2 - rect.getWidth()/2,
483                                 size.Y-rect.getHeight()-5);
484                 const wchar_t *text = wgettext("Left click: Move all items, Right click: Move single item");
485                 Environment->addStaticText(text, rect, false, true, this, 256);
486                 changeCtype("C");
487         }
488         // If there's fields, add a Proceed button
489         if (m_fields.size() && bp_set != 2) 
490         {
491                 // if the size wasn't set by an invsize[] or size[] adjust it now to fit all the fields
492                 rect = core::rect<s32>(
493                         screensize.X/2 - 580/2,
494                         screensize.Y/2 - 300/2,
495                         screensize.X/2 + 580/2,
496                         screensize.Y/2 + 240/2+(m_fields.size()*60)
497                 );
498                 DesiredRect = rect;
499                 recalculateAbsolutePosition(false);
500                 basepos = getBasePos();
501
502                 changeCtype("");
503                 {
504                         v2s32 pos = basepos;
505                         pos.Y = ((m_fields.size()+2)*60);
506
507                         v2s32 size = DesiredRect.getSize();
508                         rect = core::rect<s32>(size.X/2-70, pos.Y, (size.X/2-70)+140, pos.Y+30);
509                         Environment->addButton(rect, this, 257, wgettext("Proceed"));
510                 }
511                 changeCtype("C");
512         }
513         // Add tooltip
514         {
515                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
516                 m_tooltip_element = Environment->addStaticText(L"",core::rect<s32>(0,0,110,18));
517                 m_tooltip_element->enableOverrideColor(true);
518                 m_tooltip_element->setBackgroundColor(video::SColor(255,110,130,60));
519                 m_tooltip_element->setDrawBackground(true);
520                 m_tooltip_element->setDrawBorder(true);
521                 m_tooltip_element->setOverrideColor(video::SColor(255,255,255,255));
522                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
523                 m_tooltip_element->setWordWrap(false);
524         }
525 }
526
527 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
528 {
529         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
530         
531         for(u32 i=0; i<m_inventorylists.size(); i++)
532         {
533                 const ListDrawSpec &s = m_inventorylists[i];
534
535                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
536                 {
537                         s32 item_i = i + s.start_item_i;
538                         s32 x = (i%s.geom.X) * spacing.X;
539                         s32 y = (i/s.geom.X) * spacing.Y;
540                         v2s32 p0(x,y);
541                         core::rect<s32> rect = imgrect + s.pos + p0;
542                         if(rect.isPointInside(p))
543                         {
544                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
545                         }
546                 }
547         }
548
549         return ItemSpec(InventoryLocation(), "", -1);
550 }
551
552 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase)
553 {
554         video::IVideoDriver* driver = Environment->getVideoDriver();
555
556         // Get font
557         gui::IGUIFont *font = NULL;
558         gui::IGUISkin* skin = Environment->getSkin();
559         if (skin)
560                 font = skin->getFont();
561         
562         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
563         if(!inv){
564                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
565                                 <<"The inventory location "
566                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
567                                 <<std::endl;
568                 return;
569         }
570         InventoryList *ilist = inv->getList(s.listname);
571         if(!ilist){
572                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
573                                 <<"The inventory list \""<<s.listname<<"\" @ \""
574                                 <<s.inventoryloc.dump()<<"\" doesn't exist"
575                                 <<std::endl;
576                 return;
577         }
578         
579         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
580         
581         for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
582         {
583                 u32 item_i = i + s.start_item_i;
584                 if(item_i >= ilist->getSize())
585                         break;
586                 s32 x = (i%s.geom.X) * spacing.X;
587                 s32 y = (i/s.geom.X) * spacing.Y;
588                 v2s32 p(x,y);
589                 core::rect<s32> rect = imgrect + s.pos + p;
590                 ItemStack item;
591                 if(ilist)
592                         item = ilist->getItem(item_i);
593
594                 bool selected = m_selected_item
595                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
596                         && m_selected_item->listname == s.listname
597                         && m_selected_item->i == i;
598                 bool hovering = rect.isPointInside(m_pointer);
599
600                 if(phase == 0)
601                 {
602                         if(hovering && m_selected_item)
603                         {
604                                 video::SColor bgcolor(255,192,192,192);
605                                 driver->draw2DRectangle(bgcolor, rect, &AbsoluteClippingRect);
606                         }
607                         else
608                         {
609                                 video::SColor bgcolor(255,128,128,128);
610                                 driver->draw2DRectangle(bgcolor, rect, &AbsoluteClippingRect);
611                         }
612                 }
613
614                 if(phase == 1)
615                 {
616                         // Draw item stack
617                         if(selected)
618                         {
619                                 item.takeItem(m_selected_amount);
620                         }
621                         if(!item.empty())
622                         {
623                                 drawItemStack(driver, font, item,
624                                                 rect, &AbsoluteClippingRect, m_gamedef);
625                         }
626
627                         // Draw tooltip
628                         std::string tooltip_text = "";
629                         if(hovering && !m_selected_item)
630                                 tooltip_text = item.getDefinition(m_gamedef->idef()).description;
631                         if(tooltip_text != "")
632                         {
633                                 m_tooltip_element->setVisible(true);
634                                 this->bringToFront(m_tooltip_element);
635                                 m_tooltip_element->setText(narrow_to_wide(tooltip_text).c_str());
636                                 s32 tooltip_x = m_pointer.X + 15;
637                                 s32 tooltip_y = m_pointer.Y + 15;
638                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + 15;
639                                 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
640                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
641                                                 core::position2d<s32>(tooltip_x, tooltip_y),
642                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
643                         }
644                 }
645         }
646 }
647
648 void GUIFormSpecMenu::drawSelectedItem()
649 {
650         if(!m_selected_item)
651                 return;
652
653         video::IVideoDriver* driver = Environment->getVideoDriver();
654
655         // Get font
656         gui::IGUIFont *font = NULL;
657         gui::IGUISkin* skin = Environment->getSkin();
658         if (skin)
659                 font = skin->getFont();
660         
661         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
662         assert(inv);
663         InventoryList *list = inv->getList(m_selected_item->listname);
664         assert(list);
665         ItemStack stack = list->getItem(m_selected_item->i);
666         stack.count = m_selected_amount;
667
668         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
669         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
670         drawItemStack(driver, font, stack, rect, NULL, m_gamedef);
671 }
672
673 void GUIFormSpecMenu::drawMenu()
674 {
675         if(m_form_src){
676                 std::string newform = m_form_src->getForm();
677                 if(newform != m_formspec_string){
678                         m_formspec_string = newform;
679                         regenerateGui(m_screensize_old);
680                 }
681         }
682
683         updateSelectedItem();
684
685         gui::IGUISkin* skin = Environment->getSkin();
686         if (!skin)
687                 return;
688         video::IVideoDriver* driver = Environment->getVideoDriver();
689         
690         video::SColor bgcolor(140,0,0,0);
691         driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect);
692
693         m_tooltip_element->setVisible(false);
694
695         /*
696                 Draw items
697                 Phase 0: Item slot rectangles
698                 Phase 1: Item images; prepare tooltip
699         */
700         
701         for(int phase=0; phase<=1; phase++)
702         for(u32 i=0; i<m_inventorylists.size(); i++)
703         {
704                 drawList(m_inventorylists[i], phase);
705         }
706
707         for(u32 i=0; i<m_images.size(); i++)
708         {
709                 const ImageDrawSpec &spec = m_images[i];
710                 video::ITexture *texture =
711                                 m_gamedef->tsrc()->getTextureRaw(spec.name);
712                 // Image size on screen
713                 core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
714                 // Image rectangle on screen
715                 core::rect<s32> rect = imgrect + spec.pos;
716                 const video::SColor color(255,255,255,255);
717                 const video::SColor colors[] = {color,color,color,color};
718                 driver->draw2DImage(texture, rect,
719                         core::rect<s32>(core::position2d<s32>(0,0),
720                                         core::dimension2di(texture->getOriginalSize())),
721                         NULL/*&AbsoluteClippingRect*/, colors, true);
722         }
723
724         /*
725                 Draw dragged item stack
726         */
727         drawSelectedItem();
728
729         /*
730                 Call base class
731         */
732         gui::IGUIElement::draw();
733 }
734
735 void GUIFormSpecMenu::updateSelectedItem()
736 {
737         // If the selected stack has become empty for some reason, deselect it.
738         // If the selected stack has become smaller, adjust m_selected_amount.
739         if(m_selected_item)
740         {
741                 bool selection_valid = false;
742                 if(m_selected_item->isValid())
743                 {
744                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
745                         if(inv)
746                         {
747                                 InventoryList *list = inv->getList(m_selected_item->listname);
748                                 if(list && (u32) m_selected_item->i < list->getSize())
749                                 {
750                                         ItemStack stack = list->getItem(m_selected_item->i);
751                                         if(m_selected_amount > stack.count)
752                                                 m_selected_amount = stack.count;
753                                         if(!stack.empty())
754                                                 selection_valid = true;
755                                 }
756                         }
757                 }
758                 if(!selection_valid)
759                 {
760                         delete m_selected_item;
761                         m_selected_item = NULL;
762                         m_selected_amount = 0;
763                         m_selected_dragging = false;
764                 }
765         }
766
767         // If craftresult is nonempty and nothing else is selected, select it now.
768         if(!m_selected_item)
769         {
770                 for(u32 i=0; i<m_inventorylists.size(); i++)
771                 {
772                         const ListDrawSpec &s = m_inventorylists[i];
773                         if(s.listname == "craftpreview")
774                         {
775                                 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
776                                 InventoryList *list = inv->getList("craftresult");
777                                 if(list && list->getSize() >= 1 && !list->getItem(0).empty())
778                                 {
779                                         m_selected_item = new ItemSpec;
780                                         m_selected_item->inventoryloc = s.inventoryloc;
781                                         m_selected_item->listname = "craftresult";
782                                         m_selected_item->i = 0;
783                                         m_selected_amount = 0;
784                                         m_selected_dragging = false;
785                                         break;
786                                 }
787                         }
788                 }
789         }
790
791         // If craftresult is selected, keep the whole stack selected
792         if(m_selected_item && m_selected_item->listname == "craftresult")
793         {
794                 Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
795                 assert(inv);
796                 InventoryList *list = inv->getList(m_selected_item->listname);
797                 assert(list);
798                 m_selected_amount = list->getItem(m_selected_item->i).count;
799         }
800 }
801
802 void GUIFormSpecMenu::acceptInput()
803 {
804         if(m_text_dst)
805         {
806                 std::map<std::string, std::string> fields;
807                 gui::IGUIElement *e;
808                 for(u32 i=0; i<m_fields.size(); i++)
809                 {
810                         const FieldSpec &s = m_fields[i];
811                         if(s.send) 
812                         {
813                                 if(s.is_button)
814                                 {
815                                         fields[wide_to_narrow(s.fname.c_str())] = wide_to_narrow(s.flabel.c_str());
816                                 }
817                                 else
818                                 {
819                                         e = getElementFromId(s.fid);
820                                         if(e != NULL)
821                                         {
822                                                 fields[wide_to_narrow(s.fname.c_str())] = wide_to_narrow(e->getText());
823                                         }
824                                 }
825                         }
826                 }
827                 m_text_dst->gotText(fields);
828         }
829 }
830
831 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
832 {
833         if(event.EventType==EET_KEY_INPUT_EVENT)
834         {
835                 KeyPress kp(event.KeyInput);
836                 if (event.KeyInput.PressedDown && (kp == EscapeKey ||
837                         kp == getKeySetting("keymap_inventory")))
838                 {
839                         quitMenu();
840                         return true;
841                 }
842                 if(event.KeyInput.Key==KEY_RETURN && event.KeyInput.PressedDown)
843                 {
844                         acceptInput();
845                         quitMenu();
846                         return true;
847                 }
848         }
849         if(event.EventType==EET_MOUSE_INPUT_EVENT
850                         && event.MouseInput.Event == EMIE_MOUSE_MOVED)
851         {
852                 // Mouse moved
853                 m_pointer = v2s32(event.MouseInput.X, event.MouseInput.Y);
854         }
855         if(event.EventType==EET_MOUSE_INPUT_EVENT
856                         && event.MouseInput.Event != EMIE_MOUSE_MOVED)
857         {
858                 // Mouse event other than movement
859
860                 v2s32 p(event.MouseInput.X, event.MouseInput.Y);
861                 m_pointer = p;
862
863                 // Get selected item and hovered/clicked item (s)
864
865                 updateSelectedItem();
866                 ItemSpec s = getItemAtPos(p);
867
868                 Inventory *inv_selected = NULL;
869                 Inventory *inv_s = NULL;
870
871                 if(m_selected_item)
872                 {
873                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
874                         assert(inv_selected);
875                         assert(inv_selected->getList(m_selected_item->listname) != NULL);
876                 }
877
878                 u32 s_count = 0;
879
880                 if(s.isValid())
881                 do{ // breakable
882                         inv_s = m_invmgr->getInventory(s.inventoryloc);
883
884                         if(!inv_s){
885                                 errorstream<<"InventoryMenu: The selected inventory location "
886                                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
887                                                 <<std::endl;
888                                 s.i = -1;  // make it invalid again
889                                 break;
890                         }
891
892                         InventoryList *list = inv_s->getList(s.listname);
893                         if(list == NULL){
894                                 errorstream<<"InventoryMenu: The selected inventory list \""
895                                                 <<s.listname<<"\" does not exist"<<std::endl;
896                                 s.i = -1;  // make it invalid again
897                                 break;
898                         }
899
900                         if((u32)s.i >= list->getSize()){
901                                 errorstream<<"InventoryMenu: The selected inventory list \""
902                                                 <<s.listname<<"\" is too small (i="<<s.i<<", size="
903                                                 <<list->getSize()<<")"<<std::endl;
904                                 s.i = -1;  // make it invalid again
905                                 break;
906                         }
907
908                         s_count = list->getItem(s.i).count;
909                 }while(0);
910
911                 bool identical = (m_selected_item != NULL) && s.isValid() &&
912                         (inv_selected == inv_s) &&
913                         (m_selected_item->listname == s.listname) &&
914                         (m_selected_item->i == s.i);
915
916                 // buttons: 0 = left, 1 = right, 2 = middle
917                 // up/down: 0 = down (press), 1 = up (release), 2 = unknown event
918                 int button = 0;
919                 int updown = 2;
920                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
921                         { button = 0; updown = 0; }
922                 else if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
923                         { button = 1; updown = 0; }
924                 else if(event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN)
925                         { button = 2; updown = 0; }
926                 else if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
927                         { button = 0; updown = 1; }
928                 else if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
929                         { button = 1; updown = 1; }
930                 else if(event.MouseInput.Event == EMIE_MMOUSE_LEFT_UP)
931                         { button = 2; updown = 1; }
932
933                 // Set this number to a positive value to generate a move action
934                 // from m_selected_item to s.
935                 u32 move_amount = 0;
936
937                 // Set this number to a positive value to generate a drop action
938                 // from m_selected_item.
939                 u32 drop_amount = 0;
940
941                 // Set this number to a positive value to generate a craft action at s.
942                 u32 craft_amount = 0;
943
944                 if(updown == 0)
945                 {
946                         // Some mouse button has been pressed
947
948                         //infostream<<"Mouse button "<<button<<" pressed at p=("
949                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
950
951                         m_selected_dragging = false;
952
953                         if(s.isValid() && s.listname == "craftpreview")
954                         {
955                                 // Craft preview has been clicked: craft
956                                 craft_amount = (button == 2 ? 10 : 1);
957                         }
958                         else if(m_selected_item == NULL)
959                         {
960                                 if(s_count != 0)
961                                 {
962                                         // Non-empty stack has been clicked: select it
963                                         m_selected_item = new ItemSpec(s);
964
965                                         if(button == 1)  // right
966                                                 m_selected_amount = (s_count + 1) / 2;
967                                         else if(button == 2)  // middle
968                                                 m_selected_amount = MYMIN(s_count, 10);
969                                         else  // left
970                                                 m_selected_amount = s_count;
971
972                                         m_selected_dragging = true;
973                                 }
974                         }
975                         else  // m_selected_item != NULL
976                         {
977                                 assert(m_selected_amount >= 1);
978
979                                 if(s.isValid())
980                                 {
981                                         // Clicked a slot: move
982                                         if(button == 1)  // right
983                                                 move_amount = 1;
984                                         else if(button == 2)  // middle
985                                                 move_amount = MYMIN(m_selected_amount, 10);
986                                         else  // left
987                                                 move_amount = m_selected_amount;
988
989                                         if(identical)
990                                         {
991                                                 if(move_amount >= m_selected_amount)
992                                                         m_selected_amount = 0;
993                                                 else
994                                                         m_selected_amount -= move_amount;
995                                                 move_amount = 0;
996                                         }
997                                 }
998                                 else if(getAbsoluteClippingRect().isPointInside(m_pointer))
999                                 {
1000                                         // Clicked somewhere else: deselect
1001                                         m_selected_amount = 0;
1002                                 }
1003                                 else
1004                                 {
1005                                         // Clicked outside of the window: drop
1006                                         if(button == 1)  // right
1007                                                 drop_amount = 1;
1008                                         else if(button == 2)  // middle
1009                                                 drop_amount = MYMIN(m_selected_amount, 10);
1010                                         else  // left
1011                                                 drop_amount = m_selected_amount;
1012                                 }
1013                         }
1014                 }
1015                 else if(updown == 1)
1016                 {
1017                         // Some mouse button has been released
1018
1019                         //infostream<<"Mouse button "<<button<<" released at p=("
1020                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
1021
1022                         if(m_selected_item != NULL && m_selected_dragging && s.isValid())
1023                         {
1024                                 if(!identical)
1025                                 {
1026                                         // Dragged to different slot: move all selected
1027                                         move_amount = m_selected_amount;
1028                                 }
1029                         }
1030                         else if(m_selected_item != NULL && m_selected_dragging &&
1031                                 !(getAbsoluteClippingRect().isPointInside(m_pointer)))
1032                         {
1033                                 // Dragged outside of window: drop all selected
1034                                 drop_amount = m_selected_amount;
1035                         }
1036
1037                         m_selected_dragging = false;
1038                 }
1039
1040                 // Possibly send inventory action to server
1041                 if(move_amount > 0)
1042                 {
1043                         // Send IACTION_MOVE
1044
1045                         assert(m_selected_item && m_selected_item->isValid());
1046                         assert(s.isValid());
1047
1048                         assert(inv_selected && inv_s);
1049                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
1050                         InventoryList *list_to = inv_s->getList(s.listname);
1051                         assert(list_from && list_to);
1052                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
1053                         ItemStack stack_to = list_to->getItem(s.i);
1054
1055                         // Check how many items can be moved
1056                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
1057                         ItemStack leftover = stack_to.addItem(stack_from, m_gamedef->idef());
1058                         if(leftover.count == stack_from.count)
1059                         {
1060                                 // Swap the stacks
1061                                 m_selected_amount -= stack_to.count;
1062                         }
1063                         else if(leftover.empty())
1064                         {
1065                                 // Item fits
1066                                 m_selected_amount -= move_amount;
1067                         }
1068                         else
1069                         {
1070                                 // Item only fits partially
1071                                 move_amount -= leftover.count;
1072                                 m_selected_amount -= move_amount;
1073                         }
1074
1075                         infostream<<"Handing IACTION_MOVE to manager"<<std::endl;
1076                         IMoveAction *a = new IMoveAction();
1077                         a->count = move_amount;
1078                         a->from_inv = m_selected_item->inventoryloc;
1079                         a->from_list = m_selected_item->listname;
1080                         a->from_i = m_selected_item->i;
1081                         a->to_inv = s.inventoryloc;
1082                         a->to_list = s.listname;
1083                         a->to_i = s.i;
1084                         m_invmgr->inventoryAction(a);
1085                 }
1086                 else if(drop_amount > 0)
1087                 {
1088                         // Send IACTION_DROP
1089
1090                         assert(m_selected_item && m_selected_item->isValid());
1091                         assert(inv_selected);
1092                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
1093                         assert(list_from);
1094                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
1095
1096                         // Check how many items can be dropped
1097                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
1098                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
1099                         m_selected_amount -= drop_amount;
1100
1101                         infostream<<"Handing IACTION_DROP to manager"<<std::endl;
1102                         IDropAction *a = new IDropAction();
1103                         a->count = drop_amount;
1104                         a->from_inv = m_selected_item->inventoryloc;
1105                         a->from_list = m_selected_item->listname;
1106                         a->from_i = m_selected_item->i;
1107                         m_invmgr->inventoryAction(a);
1108                 }
1109                 else if(craft_amount > 0)
1110                 {
1111                         // Send IACTION_CRAFT
1112
1113                         assert(s.isValid());
1114                         assert(inv_s);
1115
1116                         infostream<<"Handing IACTION_CRAFT to manager"<<std::endl;
1117                         ICraftAction *a = new ICraftAction();
1118                         a->count = craft_amount;
1119                         a->craft_inv = s.inventoryloc;
1120                         m_invmgr->inventoryAction(a);
1121                 }
1122
1123                 // If m_selected_amount has been decreased to zero, deselect
1124                 if(m_selected_amount == 0)
1125                 {
1126                         delete m_selected_item;
1127                         m_selected_item = NULL;
1128                         m_selected_amount = 0;
1129                         m_selected_dragging = false;
1130                 }
1131         }
1132         if(event.EventType==EET_GUI_EVENT)
1133         {
1134                 if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
1135                                 && isVisible())
1136                 {
1137                         if(!canTakeFocus(event.GUIEvent.Element))
1138                         {
1139                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
1140                                                 <<std::endl;
1141                                 // Returning true disables focus change
1142                                 return true;
1143                         }
1144                 }
1145                 if(event.GUIEvent.EventType==gui::EGET_BUTTON_CLICKED)
1146                 {
1147                         switch(event.GUIEvent.Caller->getID())
1148                         {
1149                         case 257:
1150                                 acceptInput();
1151                                 quitMenu();
1152                                 // quitMenu deallocates menu
1153                                 return true;
1154                         }
1155                         // find the element that was clicked
1156                         for(u32 i=0; i<m_fields.size(); i++)
1157                         {
1158                                 FieldSpec &s = m_fields[i];
1159                                 // if its a button, set the send field so 
1160                                 // lua knows which button was pressed
1161                                 if (s.is_button && s.fid == event.GUIEvent.Caller->getID())
1162                                 {
1163                                         s.send = true;
1164                                         acceptInput();
1165                                         if(s.is_exit){
1166                                                 quitMenu();
1167                                                 return true;
1168                                         }else{
1169                                                 s.send = false;
1170                                                 return true;
1171                                         }
1172                                 }
1173                         }
1174                 }
1175                 if(event.GUIEvent.EventType==gui::EGET_EDITBOX_ENTER)
1176                 {
1177                         if(event.GUIEvent.Caller->getID() > 257)
1178                         {
1179                                 acceptInput();
1180                                 quitMenu();
1181                                 // quitMenu deallocates menu
1182                                 return true;
1183                         }
1184                 }
1185         }
1186
1187         return Parent ? Parent->OnEvent(event) : false;
1188 }
1189