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