core/MenuManager.cpp
author David Anderson <dvander@alliedmods.net>
Sun May 13 04:43:52 2007 +0000 (2007-05-13)
changeset 778 07e49a8cf046
parent 776 c031ed44193c
child 780 570fa34723bf
permissions -rw-r--r--
fixed various linux compilation problems
added menus to the makefile
     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 			for (unsigned int i=0; i<padding; i++)
   517 			{
   518 				position = display->DrawItem(padItem);
   519 				slots[position].type = ItemSel_None;
   520 			}
   521 		}
   522 
   523 		/* Put a fake spacer before control stuff, if possible */
   524 		{
   525 			ItemDrawInfo draw("", ITEMDRAW_RAWLINE|ITEMDRAW_SPACER);
   526 			display->DrawItem(draw);
   527 		}
   528 
   529 		/* PREVIOUS */
   530 		ItemDrawInfo dr(text, 0);
   531 		if (displayPrev || canDrawDisabled)
   532 		{
   533 			CorePlayerTranslate(client, text, sizeof(text), "Back", NULL);
   534 			dr.style = displayPrev ? 0 : ITEMDRAW_DISABLED;
   535 			position = display->DrawItem(dr);
   536 			slots[position].type = ItemSel_Back;
   537 		} else if ((displayNext || canDrawDisabled) || exitButton) {
   538 			/* If we can't display this, 
   539 			 * but there is a "next" or "exit" button, we need to pad!
   540 			 */
   541 			position = display->DrawItem(padItem);
   542 			slots[position].type = ItemSel_None;
   543 		}
   544 
   545 		/* NEXT */
   546 		if (displayNext || canDrawDisabled)
   547 		{
   548 			CorePlayerTranslate(client, text, sizeof(text), "Next", NULL);
   549 			dr.style = displayNext ? 0 : ITEMDRAW_DISABLED;
   550 			position = display->DrawItem(dr);
   551 			slots[position].type = ItemSel_Next;
   552 		} else if (exitButton) {
   553 			/* If we can't display this,
   554 			 * but there is an exit button, we need to pad!
   555 			 */
   556 			position = display->DrawItem(padItem);
   557 			slots[position].type = ItemSel_None;
   558 		}
   559 
   560 		/* EXIT */
   561 		if (exitButton)
   562 		{
   563 			CorePlayerTranslate(client, text, sizeof(text), "Exit", NULL);
   564 			dr.style = 0;
   565 			position = display->DrawItem(dr);
   566 			slots[position].type = ItemSel_Exit;
   567 		}
   568 	}
   569 
   570 	/* Lastly, fill in any slots we could have missed */
   571 	for (unsigned int i = position + 1; i < 10; i++)
   572 	{
   573 		slots[i].type = ItemSel_None;
   574 	}
   575 
   576 	/* Do title stuff */
   577 	mh->OnMenuDisplay(menu, client, display);
   578 	display->DrawTitle(menu->GetDefaultTitle(), true);
   579 
   580 	return display;
   581 }
   582 
   583 unsigned int MenuManager::BroadcastMenu(IBaseMenu *menu, 
   584 										IMenuHandler *handler, 
   585 										int clients[], 
   586 										unsigned int numClients, 
   587 										unsigned int time)
   588 {
   589 	BroadcastHandler *bh;
   590 
   591 	if (m_BroadcastHandlers.empty())
   592 	{
   593 		bh = new BroadcastHandler(handler);
   594 	} else {
   595 		bh = m_BroadcastHandlers.front();
   596 		m_BroadcastHandlers.pop();
   597 		bh->m_pHandler = handler;
   598 		bh->numClients = 0;
   599 	}
   600 
   601 	handler->OnMenuStart(menu);
   602 
   603 	unsigned int total = 0;
   604 	for (unsigned int i=0; i<numClients; i++)
   605 	{
   606 		/* Only continue if displaying works */
   607 		if (!menu->Display(clients[i], bh, time))
   608 		{
   609 			continue;
   610 		}
   611 
   612 		/* :TODO: Allow sourcetv only, not all bots */
   613 		CPlayer *player = g_Players.GetPlayerByIndex(clients[i]);
   614 		if (player->IsFakeClient())
   615 		{
   616 			continue;
   617 		}
   618 
   619 		total++;
   620 	}
   621 
   622 	if (!total)
   623 	{
   624 		/* End the broadcast here */
   625 		handler->OnMenuEnd(menu);
   626 		FreeBroadcastHandler(bh);
   627 	}
   628 
   629 	return total;
   630 }
   631 
   632 unsigned int MenuManager::VoteMenu(IBaseMenu *menu,
   633 								   IMenuVoteHandler *handler,
   634 								   int clients[],
   635 								   unsigned int numClients,
   636 								   unsigned int time)
   637 {
   638 	VoteHandler *vh;
   639 
   640 	if (m_VoteHandlers.empty())
   641 	{
   642 		vh = new VoteHandler(handler);
   643 	} else {
   644 		vh = m_VoteHandlers.front();
   645 		m_VoteHandlers.pop();
   646 		vh->m_pHandler = handler;
   647 		vh->numClients = 0;
   648 	}
   649 
   650 	vh->Initialize(menu);
   651 	handler->OnMenuStart(menu);
   652 
   653 	unsigned int total = 0;
   654 	for (unsigned int i=0; i<numClients; i++)
   655 	{
   656 		/* Only continue if displaying works */
   657 		if (!menu->Display(clients[i], vh, time))
   658 		{
   659 			continue;
   660 		}
   661 
   662 		/* :TODO: Allow sourcetv only, not all bots */
   663 		CPlayer *player = g_Players.GetPlayerByIndex(clients[i]);
   664 		if (player->IsFakeClient())
   665 		{
   666 			continue;
   667 		}
   668 
   669 		total++;
   670 	}
   671 
   672 	if (!total)
   673 	{
   674 		/* End the broadcast here */
   675 		handler->OnMenuEnd(menu);
   676 		FreeVoteHandler(vh);
   677 	}
   678 
   679 	return total;
   680 }
   681 
   682 void MenuManager::FreeBroadcastHandler(BroadcastHandler *bh)
   683 {
   684 	m_BroadcastHandlers.push(bh);
   685 }
   686 
   687 void MenuManager::FreeVoteHandler(VoteHandler *vh)
   688 {
   689 	m_VoteHandlers.push(vh);
   690 }
   691 
   692 IMenuStyle *MenuManager::GetDefaultStyle()
   693 {
   694 	return m_pDefaultStyle;
   695 }
   696