core/MenuManager.cpp
author David Anderson <dvander@alliedmods.net>
Sun May 13 18:55:59 2007 +0000 (2007-05-13)
changeset 787 52283fe61d42
parent 785 bca431afd754
child 790 9b1474d03470
permissions -rw-r--r--
changed IMenuDisplay/CreateDisplay to IMenuPanel/CreatePanel
     1 /**
     2  * vim: set ts=4 :
     3  * ===============================================================
     4  * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     5  * ===============================================================
     6  *
     7  * This file is not open source and may not be copied without explicit
     8  * written permission of AlliedModders LLC.  This file may not be redistributed 
     9  * in whole or significant part.
    10  * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
    11  *
    12  * Version: $Id$
    13  */
    14 
    15 
    16 #include <stdarg.h>
    17 #include <time.h>
    18 #include "MenuManager.h"
    19 #include "sm_stringutil.h"
    20 #include "sourcemm_api.h"
    21 #include "PlayerManager.h"
    22 #include "MenuStyle_Valve.h"
    23 #include "ShareSys.h"
    24 
    25 MenuManager g_Menus;
    26 
    27 /*************************************
    28  *************************************
    29  **** BROADCAST HANDLING WRAPPERS ****
    30  *************************************
    31  *************************************/
    32 
    33 BroadcastHandler::BroadcastHandler(IMenuHandler *handler) : m_pHandler(handler), numClients(0)
    34 {
    35 }
    36 
    37 unsigned int BroadcastHandler::GetMenuAPIVersion2()
    38 {
    39 	return m_pHandler->GetMenuAPIVersion2();
    40 }
    41 
    42 void BroadcastHandler::OnMenuCancel(IBaseMenu *menu, int client, MenuCancelReason reason)
    43 {
    44 	m_pHandler->OnMenuCancel(menu, client, reason);
    45 }
    46 
    47 void BroadcastHandler::OnMenuDisplay(IBaseMenu *menu, int client, IMenuPanel *display)
    48 {
    49 	numClients++;
    50 	m_pHandler->OnMenuDisplay(menu, client, display);
    51 }
    52 
    53 void BroadcastHandler::OnBroadcastEnd(IBaseMenu *menu)
    54 {
    55 	g_Menus.FreeBroadcastHandler(this);
    56 }
    57 
    58 void BroadcastHandler::OnMenuSelect(IBaseMenu *menu, int client, unsigned int item)
    59 {
    60 	m_pHandler->OnMenuSelect(menu, client, item);
    61 }
    62 
    63 void BroadcastHandler::OnMenuEnd(IBaseMenu *menu)
    64 {
    65 	assert(numClients > 0);
    66 
    67 	/* Only fire if all clients have gotten a menu end */
    68 	if (--numClients == 0)
    69 	{
    70 		IMenuHandler *pHandler = m_pHandler;
    71 		OnBroadcastEnd(menu);
    72 		pHandler->OnMenuEnd(menu);
    73 	}
    74 }
    75 
    76 VoteHandler::VoteHandler(IMenuVoteHandler *handler) 
    77 : BroadcastHandler(handler), m_pVoteHandler(handler)
    78 {
    79 }
    80 
    81 void VoteHandler::Initialize(IBaseMenu *menu)
    82 {
    83 	unsigned int numItems = menu->GetItemCount();
    84 
    85 	if (m_counts.size() >= numItems)
    86 	{
    87 		for (size_t i=0; i<numItems; i++)
    88 		{
    89 			m_counts[i] = 0;
    90 		}
    91 	} else {
    92 		for (size_t i=0; i<m_counts.size(); i++)
    93 		{
    94 			m_counts[i] = 0;
    95 		}
    96 		m_counts.resize(numItems, 0);
    97 	}
    98 }
    99 
   100 void VoteHandler::OnMenuSelect(IBaseMenu *menu, int client, unsigned int item)
   101 {
   102 	if (item < numItems)
   103 	{
   104 		m_counts[item]++;
   105 	}
   106 
   107 	BroadcastHandler::OnMenuSelect(menu, client, item);
   108 }
   109 
   110 void VoteHandler::OnBroadcastEnd(IBaseMenu *menu)
   111 {
   112 	m_ties.clear();
   113 
   114 	size_t highest = 0;
   115 	for (size_t i=1; i<numItems; i++)
   116 	{
   117 		if (m_counts[i] > m_counts[highest])
   118 		{
   119 			m_ties.clear();
   120 			highest = i;
   121 		} else if (m_counts[i] == m_counts[highest]) {
   122 			m_ties.push_back(i);
   123 		}
   124 	}
   125 
   126 	if (m_ties.size())
   127 	{
   128 		m_ties.push_back(highest);
   129 		srand(static_cast<unsigned int>(time(NULL)));
   130 		highest = m_ties[rand() % m_ties.size()];
   131 	}
   132 
   133 	m_pVoteHandler->OnMenuVoteEnd(menu, highest);
   134 
   135 	g_Menus.FreeVoteHandler(this);
   136 }
   137 
   138 /*******************************
   139  *******************************
   140  ******** MENU MANAGER *********
   141  *******************************
   142  *******************************/
   143 
   144 MenuManager::MenuManager()
   145 {
   146 	m_Styles.push_back(&g_ValveMenuStyle);
   147 	SetDefaultStyle(&g_ValveMenuStyle);
   148 }
   149 
   150 void MenuManager::OnSourceModAllInitialized()
   151 {
   152 	g_ShareSys.AddInterface(NULL, this);
   153 }
   154 
   155 void MenuManager::OnSourceModAllShutdown()
   156 {
   157 	while (!m_BroadcastHandlers.empty())
   158 	{
   159 		delete m_BroadcastHandlers.front();
   160 		m_BroadcastHandlers.pop();
   161 	}
   162 
   163 	while (!m_VoteHandlers.empty())
   164 	{
   165 		delete m_VoteHandlers.front();
   166 		m_VoteHandlers.pop();
   167 	}
   168 }
   169 
   170 bool MenuManager::SetDefaultStyle(IMenuStyle *style)
   171 {
   172 	if (!style)
   173 	{
   174 		return false;
   175 	}
   176 
   177 	m_pDefaultStyle = style;
   178 
   179 	return true;
   180 }
   181 
   182 IMenuStyle *MenuManager::GetStyle(unsigned int index)
   183 {
   184 	if (index >= GetStyleCount())
   185 	{
   186 		return NULL;
   187 	}
   188 
   189 	return m_Styles[index];
   190 }
   191 
   192 void MenuManager::AddStyle(IMenuStyle *style)
   193 {
   194 	m_Styles.push_back(style);
   195 }
   196 
   197 unsigned int MenuManager::GetStyleCount()
   198 {
   199 	return (unsigned int)m_Styles.size();
   200 }
   201 
   202 IMenuStyle *MenuManager::FindStyleByName(const char *name)
   203 {
   204 	unsigned int count = GetStyleCount();
   205 	for (unsigned int i=0; i<count; i++)
   206 	{
   207 		IMenuStyle *ptr = GetStyle(i);
   208 		if (strcasecmp(ptr->GetStyleName(), name) == 0)
   209 		{
   210 			return ptr;
   211 		}
   212 	}
   213 
   214 	return NULL;
   215 }
   216 
   217 inline bool IsSlotItem(IMenuPanel *display,
   218 					   unsigned int style)
   219 {
   220 	if (!display->CanDrawItem(style))
   221 	{
   222 	return false;
   223 	}
   224 	if ((style & ITEMDRAW_IGNORE) == ITEMDRAW_IGNORE)
   225 	{
   226 		return false;
   227 	}
   228 	if (style & ITEMDRAW_RAWLINE)
   229 	{
   230 		return false;
   231 	}
   232 
   233 	return true;
   234 }
   235 
   236 IMenuPanel *MenuManager::RenderMenu(int client, menu_states_t &md, ItemOrder order)
   237 {
   238 	IBaseMenu *menu = md.menu;
   239 
   240 	if (!menu)
   241 	{
   242 		return NULL;
   243 	}
   244 
   245 	struct
   246 	{
   247 		unsigned int position;
   248 		ItemDrawInfo draw;
   249 	} drawItems[10];
   250 
   251 	/* Figure out how many items to draw */
   252 	IMenuStyle *style = menu->GetDrawStyle();
   253 	unsigned int pgn = menu->GetPagination();
   254 	unsigned int maxItems = style->GetMaxPageItems();
   255 	if (pgn != MENU_NO_PAGINATION)
   256 	{
   257 		maxItems = pgn;
   258 	}
   259 
   260 	unsigned int totalItems = menu->GetItemCount();
   261 	unsigned int startItem = 0;
   262 
   263 	/* For pagination, find the starting point. */
   264 	if (pgn != MENU_NO_PAGINATION)
   265 	{
   266 		if (order == ItemOrder_Ascending)
   267 		{
   268 			startItem = md.lastItem;
   269 			/* This shouldn't happen with well-coded menus.
   270 			 * If the item is out of bounds, switch the order to
   271 			 * Items_Descending and make us start from the top.
   272 			 */
   273 			if (startItem >= totalItems)
   274 			{
   275 				startItem = totalItems - 1;
   276 				order = ItemOrder_Descending;
   277 			}
   278 		} else if (order == ItemOrder_Descending) {
   279 			startItem = md.firstItem;
   280 			/* This shouldn't happen with well-coded menus.
   281 			 * If searching backwards doesn't give us enough room,
   282 			 * start from the beginning and change to ascending.
   283 			 */
   284 			if (startItem <= maxItems)
   285 			{
   286 				startItem = 0;
   287 				order = ItemOrder_Ascending;
   288 			}
   289 		}
   290 	}
   291 
   292 	/* Get our Display pointer and initialize some crap */
   293 	IMenuPanel *display = menu->CreatePanel();
   294 	IMenuHandler *mh = md.mh;
   295 	bool foundExtra = false;
   296 	unsigned int extraItem = 0;
   297 
   298 	/**
   299 	 * We keep searching until:
   300 	 * 1) There are no more items
   301 	 * 2) We reach one OVER the maximum number of slot items
   302 	 * 3) We have reached maxItems and pagination is MENU_NO_PAGINATION
   303 	 */
   304 	unsigned int i = startItem;
   305 	unsigned int foundItems = 0;
   306 	while (true)
   307 	{
   308 		ItemDrawInfo &dr = drawItems[foundItems].draw;
   309 		/* Is the item valid? */
   310 		if (menu->GetItemInfo(i, &dr) != NULL)
   311 		{
   312 			/* Ask the user to change the style, if necessary */
   313 			mh->OnMenuDrawItem(menu, client, i, dr.style);
   314 			/* Check if it's renderable */
   315 			if (IsSlotItem(display, dr.style))
   316 			{
   317 				/* If we've already found the max number of items,
   318 				 * This means we should just cancel out and log our
   319 				 * "last item."
   320 				 */
   321 				if (foundItems >= maxItems)
   322 				{
   323 					foundExtra = true;
   324 					extraItem = i;
   325 					break;
   326 				}
   327 				drawItems[foundItems++].position = i;
   328 			}
   329 		}
   330 		/* If there's no pagination, stop once the menu is full. */
   331 		if (pgn == MENU_NO_PAGINATION)
   332 		{
   333 			/* If we've filled up, then stop */
   334 			if (foundItems >= maxItems)
   335 			{
   336 				break;
   337 			}
   338 		}
   339 		/* If we're descending and this is the first item, stop */
   340 		if (order == ItemOrder_Descending)
   341 		{
   342 			if (i == 0)
   343 			{
   344 				break;
   345 			}
   346 			i--;
   347 		} 
   348 		/* If we're ascending and this is the last item, stop */
   349 		else if (order == ItemOrder_Ascending)
   350 		{
   351 			if (i >= totalItems - 1)
   352 			{
   353 				break;
   354 			}
   355 			i++;
   356 		}
   357 	}
   358 
   359 	/* There were no items to draw! */
   360 	if (!foundItems)
   361 	{
   362 		display->DeleteThis();
   363 		return NULL;
   364 	}
   365 
   366 	/* Check initial buttons */
   367 	bool displayPrev = false;
   368 	bool displayNext = false;
   369 	if (foundExtra)
   370 	{
   371 		if (order == ItemOrder_Descending)
   372 		{
   373 			displayPrev = true;
   374 			md.firstItem = extraItem;
   375 		} else if (order == ItemOrder_Ascending) {
   376 			displayNext = true;
   377 			md.lastItem = extraItem;
   378 		}
   379 	}
   380 
   381 	/**
   382 	 * If we're paginated, we have to find if there is another page.
   383 	 * Sadly, the only way to do this is to try drawing more items!
   384 	 */
   385 	if (pgn != MENU_NO_PAGINATION)
   386 	{
   387 		unsigned int lastItem = 0;
   388 		ItemDrawInfo dr;
   389 		/* Find the last feasible item to search from. */
   390 		if (order == ItemOrder_Descending)
   391 		{
   392 			lastItem = drawItems[0].position;
   393 			if (lastItem >= totalItems - 1)
   394 			{
   395 				goto skip_search;
   396 			}
   397 			while (++lastItem < totalItems)
   398 			{
   399 				if (menu->GetItemInfo(lastItem, &dr) != NULL)
   400 				{
   401 					mh->OnMenuDrawItem(menu, client, lastItem, dr.style);
   402 					if (IsSlotItem(display, dr.style))
   403 					{
   404 						displayNext = true;
   405 						md.lastItem = lastItem;
   406 						break;
   407 					}
   408 				}
   409 			}
   410 		} else if (order == ItemOrder_Ascending) {
   411 			lastItem = drawItems[0].position;
   412 			if (lastItem == 0)
   413 			{
   414 				goto skip_search;
   415 			}
   416 			lastItem--;
   417 			while (lastItem-- != 0)
   418 			{
   419 				if (menu->GetItemInfo(lastItem, &dr) != NULL)
   420 				{
   421 					mh->OnMenuDrawItem(menu, client, lastItem, dr.style);
   422 					if (IsSlotItem(display, dr.style))
   423 					{
   424 						displayPrev = true;
   425 						md.firstItem = lastItem;
   426 						break;
   427 					}
   428 				}
   429 			}
   430 		}
   431 	}
   432 skip_search:
   433 
   434 	/* Draw the item according to the order */
   435 	menu_slots_t *slots = md.slots;
   436 	unsigned int position = 0;			/* Keep track of the last position */
   437 	if (order == ItemOrder_Ascending)
   438 	{
   439 		for (unsigned int i=0; i<foundItems; i++)
   440 		{
   441 			ItemDrawInfo &dr = drawItems[i].draw;
   442 			menu->GetItemInfo(drawItems[i].position, &dr);
   443 			mh->OnMenuDisplayItem(menu, client, drawItems[i].position, &(dr.display));
   444 			if ((position = display->DrawItem(dr)) != 0)
   445 			{
   446 				slots[position].item = drawItems[i].position;
   447 				slots[position].type = ItemSel_Item;
   448 			}
   449 		}
   450 	} else if (order == ItemOrder_Descending) {
   451 		unsigned int i = foundItems;
   452 		/* NOTE: There will always be at least one item because
   453 		 * of the check earlier.
   454 		 */
   455 		while (i--)
   456 		{
   457 			ItemDrawInfo &dr = drawItems[i].draw;
   458 			menu->GetItemInfo(drawItems[i].position, &dr);
   459 			mh->OnMenuDisplayItem(menu, client, drawItems[i].position, &(dr.display));
   460 			if ((position = display->DrawItem(dr)) != 0)
   461 			{
   462 				slots[position].item = drawItems[i].position;
   463 				slots[position].type = ItemSel_Item;
   464 			}
   465 		}
   466 	}
   467 
   468 	/* Now, we need to check if we need to add anything extra */
   469 	if (pgn != MENU_NO_PAGINATION)
   470 	{
   471 		bool canDrawDisabled = display->CanDrawItem(ITEMDRAW_DISABLED|ITEMDRAW_CONTROL);
   472 		bool exitButton = menu->GetExitButton();
   473 		char text[50];
   474 
   475 		/* Calculate how many items we are allowed for control stuff */
   476 		unsigned int padding = style->GetMaxPageItems() - maxItems;
   477 		
   478 		/* Add the number of available slots */
   479 		padding += (maxItems - foundItems);
   480 
   481 		/* Someday, if we are able to re-enable this, we will be very lucky men. */
   482 #if 0
   483 		if (!style->FeatureExists(MenuStyleFeature_ImplicitExit))
   484 		{
   485 #endif
   486 		/* Even if we don't draw an exit button, we invalidate the slot. */
   487 		padding--;
   488 #if 0
   489 		} else {
   490 			/* Otherwise, we don't draw anything and leave the slot available */
   491 			exitButton = false;
   492 		}
   493 #endif
   494 
   495 		/* Subtract two slots for the displayNext/displayPrev padding */
   496 		padding -= 2;
   497 
   498 		/**
   499 		 * We allow next/prev to be undrawn if neither exists.
   500 		 * Thus, we only need padding if one of them will be drawn,
   501 		 * or the exit button will be drawn.
   502 		 */
   503 		ItemDrawInfo padItem(NULL, ITEMDRAW_SPACER);
   504 		if (exitButton || (displayNext || displayPrev))
   505 		{
   506 			/* Add spacers so we can pad to the end */
   507 			for (unsigned int i=0; i<padding; i++)
   508 			{
   509 				position = display->DrawItem(padItem);
   510 				slots[position].type = ItemSel_None;
   511 			}
   512 		}
   513 
   514 		/* Put a fake spacer before control stuff, if possible */
   515 		{
   516 			ItemDrawInfo draw("", ITEMDRAW_RAWLINE|ITEMDRAW_SPACER);
   517 			display->DrawItem(draw);
   518 		}
   519 
   520 		ItemDrawInfo dr(text, 0);
   521 		/**
   522 		 * If we have one or the other, we need to have spacers for both.
   523 		 */
   524 		if (displayPrev || displayNext)
   525 		{
   526 			/* PREVIOUS */
   527 			ItemDrawInfo padCtrlItem(NULL, ITEMDRAW_SPACER|ITEMDRAW_CONTROL);
   528 			if (displayPrev || canDrawDisabled)
   529 			{
   530 				CorePlayerTranslate(client, text, sizeof(text), "Back", NULL);
   531 				dr.style = (displayPrev ? 0 : ITEMDRAW_DISABLED)|ITEMDRAW_CONTROL;
   532 				position = display->DrawItem(dr);
   533 				slots[position].type = ItemSel_Back;
   534 			} else if (displayNext || exitButton) {
   535 				/* If we can't display this, and there is an exit button,
   536 				 * we need to pad!
   537 				 */
   538 				position = display->DrawItem(padCtrlItem);
   539 				slots[position].type = ItemSel_None;
   540 			}
   541 
   542 			/* NEXT */
   543 			if (displayNext || canDrawDisabled)
   544 			{
   545 				CorePlayerTranslate(client, text, sizeof(text), "Next", NULL);
   546 				dr.style = (displayNext ? 0 : ITEMDRAW_DISABLED)|ITEMDRAW_CONTROL;
   547 				position = display->DrawItem(dr);
   548 				slots[position].type = ItemSel_Next;
   549 			} else if (exitButton) {
   550 				/* If we can't display this,
   551 				 * but there is an "exit" button, we need to pad!
   552 				 */
   553 				position = display->DrawItem(padCtrlItem);
   554 				slots[position].type = ItemSel_None;
   555 			}
   556 		} else {
   557 			/* Otherwise, bump to two slots! */
   558 			ItemDrawInfo numBump(NULL, ITEMDRAW_NOTEXT);
   559 			position = display->DrawItem(numBump);
   560 			slots[position].type = ItemSel_None;
   561 			position = display->DrawItem(numBump);
   562 			slots[position].type = ItemSel_None;
   563 		}
   564 
   565 		/* EXIT */
   566 		if (exitButton)
   567 		{
   568 			CorePlayerTranslate(client, text, sizeof(text), "Exit", NULL);
   569 			dr.style = ITEMDRAW_CONTROL;
   570 			position = display->DrawItem(dr);
   571 			slots[position].type = ItemSel_Exit;
   572 		}
   573 	}
   574 
   575 	/* Lastly, fill in any slots we could have missed */
   576 	for (unsigned int i = position + 1; i < 10; i++)
   577 	{
   578 		slots[i].type = ItemSel_None;
   579 	}
   580 
   581 	/* Do title stuff */
   582 	mh->OnMenuDisplay(menu, client, display);
   583 	display->DrawTitle(menu->GetDefaultTitle(), true);
   584 
   585 	return display;
   586 }
   587 
   588 unsigned int MenuManager::BroadcastMenu(IBaseMenu *menu, 
   589 										IMenuHandler *handler, 
   590 										int clients[], 
   591 										unsigned int numClients, 
   592 										unsigned int time)
   593 {
   594 	BroadcastHandler *bh;
   595 
   596 	if (m_BroadcastHandlers.empty())
   597 	{
   598 		bh = new BroadcastHandler(handler);
   599 	} else {
   600 		bh = m_BroadcastHandlers.front();
   601 		m_BroadcastHandlers.pop();
   602 		bh->m_pHandler = handler;
   603 		bh->numClients = 0;
   604 	}
   605 
   606 	handler->OnMenuStart(menu);
   607 
   608 	unsigned int total = 0;
   609 	for (unsigned int i=0; i<numClients; i++)
   610 	{
   611 		/* Only continue if displaying works */
   612 		if (!menu->Display(clients[i], bh, time))
   613 		{
   614 			continue;
   615 		}
   616 
   617 		/* :TODO: Allow sourcetv only, not all bots */
   618 		CPlayer *player = g_Players.GetPlayerByIndex(clients[i]);
   619 		if (player->IsFakeClient())
   620 		{
   621 			continue;
   622 		}
   623 
   624 		total++;
   625 	}
   626 
   627 	if (!total)
   628 	{
   629 		/* End the broadcast here */
   630 		handler->OnMenuEnd(menu);
   631 		FreeBroadcastHandler(bh);
   632 	}
   633 
   634 	return total;
   635 }
   636 
   637 unsigned int MenuManager::VoteMenu(IBaseMenu *menu,
   638 								   IMenuVoteHandler *handler,
   639 								   int clients[],
   640 								   unsigned int numClients,
   641 								   unsigned int time)
   642 {
   643 	VoteHandler *vh;
   644 
   645 	if (m_VoteHandlers.empty())
   646 	{
   647 		vh = new VoteHandler(handler);
   648 	} else {
   649 		vh = m_VoteHandlers.front();
   650 		m_VoteHandlers.pop();
   651 		vh->m_pHandler = handler;
   652 		vh->numClients = 0;
   653 	}
   654 
   655 	vh->Initialize(menu);
   656 	handler->OnMenuStart(menu);
   657 
   658 	unsigned int total = 0;
   659 	for (unsigned int i=0; i<numClients; i++)
   660 	{
   661 		/* Only continue if displaying works */
   662 		if (!menu->Display(clients[i], vh, time))
   663 		{
   664 			continue;
   665 		}
   666 
   667 		/* :TODO: Allow sourcetv only, not all bots */
   668 		CPlayer *player = g_Players.GetPlayerByIndex(clients[i]);
   669 		if (player->IsFakeClient())
   670 		{
   671 			continue;
   672 		}
   673 
   674 		total++;
   675 	}
   676 
   677 	if (!total)
   678 	{
   679 		/* End the broadcast here */
   680 		handler->OnMenuEnd(menu);
   681 		FreeVoteHandler(vh);
   682 	}
   683 
   684 	return total;
   685 }
   686 
   687 void MenuManager::FreeBroadcastHandler(BroadcastHandler *bh)
   688 {
   689 	m_BroadcastHandlers.push(bh);
   690 }
   691 
   692 void MenuManager::FreeVoteHandler(VoteHandler *vh)
   693 {
   694 	m_VoteHandlers.push(vh);
   695 }
   696 
   697 IMenuStyle *MenuManager::GetDefaultStyle()
   698 {
   699 	return m_pDefaultStyle;
   700 }
   701