Example #1
0
short CheckLangStringForText( char *searchText, char *lineStr1, char *lineStr2, short i, int scrollOffset, int &nonRealTokenOffset, int &item ) 
{
	// See if the token number is a real language token or just a category seperator token
	if ( !RealLangToken( i ) )
		nonRealTokenOffset++;
	else // We have a real token
	{
		// Select a position in the list view to check for the search text
		int pos = i-nonRealTokenOffset-1+item; 
		int count = ListView_GetItemCount( hWndLangBuilderListView );
		if ( pos >= count )
		{
			item -= count;
			pos = i-nonRealTokenOffset-1+item;
		}
		// Get both the text in the Default English, and the current language we are searching
		ListView_GetItemText( hWndLangBuilderListView, pos, DEFAULT_ENGLISH_LISTVIEW_POS, lineStr1, LANG_LINE_SIZE );
		ListView_GetItemText( hWndLangBuilderListView, pos, EDIT_LANGUAGE_LISTVIEW_POS, lineStr2, LANG_LINE_SIZE );
		if ( strstri( lineStr1, searchText ) || strstri( lineStr2, searchText ) )
		{
			SelectFoundTextInList( item, pos, scrollOffset );
			return 1;
		}
	}
	return 0;
}
Example #2
0
/* Decide whether a particular string is engraved at a specified
 * location; a case-insensitive substring match used.
 * Ignore headstones, in case the player names herself "Elbereth".
 */
int sengr_at(const char *s, xchar x, xchar y)
{
	struct engr *ep = engr_at(level, x,y);

	return (ep && ep->engr_type != HEADSTONE &&
		ep->engr_time <= moves && strstri(ep->engr_txt, s) != 0);
}
Example #3
0
short SaveLangFileAs( char *filename )
{
	char fileWithPath[1024];
	// Check the exe directory first - as this is where users should have their lang directory
	GetLangV41File( fileWithPath, gPath, PATHSEPSTR, 0 ); 
	if ( ValidatePath( fileWithPath ) )
	{
		// Now check for a lang directory which is located back a directory - this where we have our lang directory
		GetLangV41File( fileWithPath, gPath, PATHBACKDIR, 0 ); 
	}
	if ( ValidatePath( fileWithPath ) )
	{
		// Try the current directory - basically, a last resort...
		GetLangV41File( fileWithPath, 0, 0, 0 ); 
	}
	if ( GetLangSaveFolderName( fileWithPath, filename ) )
	{
		ReadNewLangStringsFromLangList();
		char *pos;
		pos = strstri( fileWithPath, LANG_EXT );
		if ( !pos )
			mystrcat( fileWithPath, LANG_EXT );
		if ( SaveNewLangStringsToLangFile( fileWithPath ) )
		{
			FileFromPath( fileWithPath, MyPrefStruct.language );
			strcpyuntil( MyPrefStruct.language, MyPrefStruct.language, '.' );
			return 1;
		}
	}
	return 0;
}
Example #4
0
 void
 interject_assistance(
 int num,
 int interjection_type,
 genericptr_t ptr1,
 genericptr_t ptr2)
 {
     switch (num) {
     case 1: {
         char *panicmsg = (char *)ptr1;
         char *datadir = (char *)ptr2;
         char *tempdir = nh_getenv("TEMP");
         interjection_type = INTERJECT_PANIC;
         interjection[INTERJECT_PANIC] = 1;
         /*
          * ptr1 = the panic message about to be delivered.
          * ptr2 = the directory prefix of the dungeon file
          *        that failed to open.
          * Check to see if datadir matches tempdir or a
          * common windows temp location. If it does, inform
          * the user that they are probably trying to run the
          * game from within their unzip utility, so the required
          * files really don't exist at the location. Instruct
          * them to unpack them first.
          */
         if (panicmsg && datadir) {
             if (!strncmpi(datadir, "C:\\WINDOWS\\TEMP", 15) ||
                 strstri(datadir, "TEMP") ||
                 (tempdir && strstri(datadir, tempdir))) {
                 (void)strncpy(interjection_buf[INTERJECT_PANIC],
                     "\nOne common cause of this error is attempting to execute\n"
                     "the game by double-clicking on it while it is displayed\n"
                     "inside an unzip utility.\n\n"
                     "You have to unzip the contents of the zip file into a\n"
                     "folder on your system, and then run \"NetHack.exe\" or \n"
                     "\"NetHackW.exe\" from there.\n\n"
                     "If that is not the situation, you are encouraged to\n"
                     "report the error as shown above.\n\n", 1023);
             }
         }
     }
         break;
     }
 }
Example #5
0
/*
 * Append new_str to the end of buf if new_str doesn't already exist as
 * a substring of buf.  Return 1 if the string was appended, 0 otherwise.
 * It is expected that buf is of size BUFSZ.
 */
static int append_str (char *buf, const char *new_str) {
    int space_left;     /* space remaining in buf */

    if (strstri(buf, new_str)) return 0;

    space_left = BUFSZ - strlen(buf) - 1;
    (void) strncat(buf, " or ", space_left);
    (void) strncat(buf, new_str, space_left - 4);
    return 1;
}
Example #6
0
int main(int argc, char** argv)
{
    char * str = "path_to_file_name.mP4";
    char * subStr = ".mp4";
    if (strstri(str, subStr) != NULL) {
        printf("%s is in %s\n", subStr, str);
    } else {
        printf("%s is not in %s\n", subStr, str);
    }
    return 0;
}
Example #7
0
int open_url_listview(HWND hwnd)
{
	int index,len;
	index=SendDlgItemMessage(hwnd,IDC_LIST1,LB_GETCARETINDEX,0,0);
	if(index>=0){
		char *str=0;
		int found_url=FALSE;
		len=SendDlgItemMessage(hwnd,IDC_LIST1,LB_GETTEXTLEN,index,0);
		if(len==LB_ERR)
			len=0x10000;
		str=malloc(len+1);
		if(str!=0){
			unsigned char *url;
			str[0]=0;
			SendDlgItemMessage(hwnd,IDC_LIST1,LB_GETTEXT,index,str);
			str[len]=0;
			url=strstri(str,"http://");
			if(url==0)
				url=strstri(str,"https://");
			if(url){
				int i,max;
				max=strlen(url);
				for(i=0;i<max;i++){
					if(url[i]<=' '){
						url[i]=0;
						break;
					}
				}
				ShellExecute(NULL,"open",url,NULL,NULL,SW_SHOWNORMAL);
				found_url=TRUE;
			}
			free(str);
		}
		if(!found_url)
			view_context(hwnd);
	}
	return FALSE;
}
Example #8
0
RandomItemList RandomItemMgr::Query(RandomItemType type)
{
    RandomItemList items;

    ItemTemplateContainer const* itemTemplates = sObjectMgr->GetItemTemplateStore();
    for (ItemTemplateContainer::const_iterator i = itemTemplates->begin(); i != itemTemplates->end(); ++i)
    {
        uint32 itemId = i->first;
        ItemTemplate const* proto = &i->second;
        if (!proto)
            continue;

        if (proto->Duration & 0x80000000)
            continue;

        if (sAhBotConfig.ignoreItemIds.find(proto->ItemId) != sAhBotConfig.ignoreItemIds.end())
            continue;

        if (strstri(proto->Name1.c_str(), "qa") || strstri(proto->Name1.c_str(), "test") || strstri(proto->Name1.c_str(), "deprecated"))
            continue;

        if ((proto->RequiredLevel && proto->RequiredLevel > sAhBotConfig.maxRequiredLevel) || proto->ItemLevel > sAhBotConfig.maxItemLevel)
            continue;

        if (predicates[type] && !predicates[type]->Apply(proto))
            continue;

        if (!auctionbot.GetSellPrice(proto))
            continue;

        items.push_back(itemId);
    }

    if (items.empty())
        sLog->outMessage("gtask", LOG_LEVEL_ERROR, "no items available for random item query %u", type);

    return items;
}
Example #9
0
void SearchContext::makePretty(SearchEntry &entry)
{
    if(entry.filename_.empty())
        return;

    std::string s;
    TextBlockList blocks;

    if(lastFilename_ != entry.filename_)
    {
        s = entry.filename_.c_str();
        if(params_.flags & SF_TRIM_FILENAMES)
        {
            std::string &startingPath = params_.paths[0];
            if(strstri((char *)s.c_str(), startingPath.c_str()) == s.c_str())
            {
                s = s.substr(startingPath.length());
                if(s.length() && (s[0] == '\\'))
                {
                    s.erase(s.begin());
                }
            }
        }

        s.insert(0, "\n");
        s += ":\n";
        blocks.addBlock(s, config_.contextColor_);

        lastFilename_ = entry.filename_;
    }
    else if(entry.line_ != (lastLine_ + 1))
    {
        blocks.addBlock("  ...\n", config_.contextColor_);
    }

    lastLine_ = entry.line_;

    char lineNo[64];
    sprintf(lineNo, "%5d%s ", entry.line_, entry.contextOnly_ ? " " : ":");
    blocks.addBlock(lineNo, config_.contextColor_);

    for(TextBlockList::iterator it = entry.textBlocks.begin(); it != entry.textBlocks.end(); ++it)
    {
        blocks.push_back(*it);
    }

    blocks.addBlock("\n", config_.textColor_);

    blocks.swap(entry.textBlocks);
}
Example #10
0
int InterpretMediaPlayerString( char *out, char *agentstr )
{
	//char clientstr[512];
	char *wcPtr;
	char *clientstr = out;
	long i;

	// For NSPlayer, mplayer2.exe wmplayer.exe
	if ( (wcPtr = strstri(agentstr, "player" ))) {
		i = mystrcpy( clientstr, "WindowsMedia ");
		getVersion( clientstr+i, wcPtr, 10 );
	} else
	if ( (wcPtr = strstri(agentstr, "play32" ))) {
		i = mystrcpy( clientstr, "Realplayer ");
		getVersion( clientstr+i, wcPtr, 10 );
	} else
	if ( (wcPtr = strstri(agentstr, "RealMedia" ))) {
		i = mystrcpy( clientstr, "RealMedia ");	
		getVersion( clientstr+i, wcPtr, 10 );
	} else
	if ( (wcPtr = strstri(agentstr, "Winamp" ))) {
		i = mystrcpy( clientstr, "Winamp " );	
		getVersion( clientstr+i, wcPtr, 10 );
	} else
	if ( (wcPtr = strstri(agentstr, "qtver=" ))) {
		i = mystrcpy( clientstr, "QuickTime " );
		wcPtr+=6;
		strcpyuntil( clientstr+i, wcPtr, ';' );
	} 
	else
	{
		return 0;
	}

	return 1;
}
Example #11
0
static int set_title(HWND hwnd,TABLE_WINDOW *win)
{
	char str[255]={0};
	char *lbrack="",*rbrack="";
	if(is_sql_reserved(win->table) || strchr(win->table,' ')){
		if(strstri(win->name,"DSN=visual foxpro")!=0){
			lbrack=rbrack="`";
		}
		else{
			lbrack="[";rbrack="]";
		}
	}
	_snprintf(str,sizeof(str),"Add Row %s%s%s",lbrack,win->table,rbrack);
	str[sizeof(str)-1]=0;
	return SetWindowText(hwnd,str);
}
Example #12
0
void ParseMail()
{
    dword line_off, new_buf;
    char tline[256];

    if ( mailend-mailstart > 9) if (strncmp(mailend-5,"\n.\n",5)==0) // note that c-- assembles "\n.\n" to 0x0d, 0x0a, 0x2e, 0x0d, 0x0a
        {
            aim = STOP;
            mailend -= 5;
            DSBYTE[mailend] = '\0';
            if (strstr(mailstart, "+OK")!=mailstart)
            {
                aim = GET_ANSWER_RETR;
                mailend = mailstart;
                debug("GET_ANSWER_RETR != +OK, retry GET_ANSWER_RETR");
                return;
            }
            mailsize = mailend - mailstart;
            debug("Getting QP");
            if (strstri(mailstart, "quoted-printable")!=0)
            {
                new_buf = malloc(mailsize);
                qp_decode stdcall (mailstart, new_buf, mailsize);
                if (EAX==-1) debug("Too small buffer to convert QUOTED-PRINTABLE");
                else
                {
                    free(mailstart);
                    mailstart = new_buf;
                    mailsize = strlen(mailstart);
                    mailend = mailsize + mailstart;
                }
            }
            debug("ProcessBase64");
            ProcessBase64();
            debug("GetHeaders: From, To, Date, Subject");
            GetHeader(#from, "\nFrom:");
            GetHeader(#to,   "\nTo:");
            GetHeader(#date, "\nDate:");
            GetHeader(#subj, "\nSubject:");
            debug("Get mdata");
            mdata = strstr(mailstart, "\x0a\x0d") + 3;
            debug("ConvertToDOS");
            ConvertToDOS(mdata, mailstart);
            debug("SetAtrFromCurr");
            atr.SetAtrFromCurr(mail_list.current+1);
            DrawMailBox();
        }
// constructor - opens all mzXML files with cRAMP. For efficiency, the queries from multiple files are merged and
// sorted by precursor m/z before searching. 
SpectraSTMzXMLSearchTask::SpectraSTMzXMLSearchTask(vector<string>& searchFileNames, SpectraSTSearchParams& params, SpectraSTLib* lib) :
  SpectraSTSearchTask(searchFileNames, params,lib),
  m_files(searchFileNames.size()),
  m_scans(),
  m_isMzData(false),
  m_numScansInFile(0),
  m_numNotSelectedInFile(0),
  m_numMissingInFile(0),
  m_numMS1InFile(0),
  m_numFailedFilterInFile(0),
  m_numSearchedInFile(0),
  m_numLikelyGoodInFile(0) {
  
  char* rampExt = rampValidFileType(m_searchFileNames[0].c_str());
  if (strstri(rampExt, ".mzdata")) { // accommodates .mzdata.gz
    m_isMzData = true;
  }
  

}
Example #14
0
std::string SearchContext::generateDisplay(SearchEntry &entry, int &textOffset)
{
	char middle[64];
	sprintf(middle, "(%d): ", entry.line_);

	std::string s = entry.filename_.c_str();
	if(params_.flags & SF_TRIM_FILENAMES)
	{
		std::string &startingPath = params_.paths[0];
		if(strstri((char *)s.c_str(), startingPath.c_str()) == s.c_str())
		{
			s = s.substr(startingPath.length() + 1);
		}
	}

	s += middle;
	textOffset = s.length();
	s += entry.match_;
	s += "\n";
    return s;
}
Example #15
0
int GetClientWorker(char *Clientstr,ClientIcon *cli)
{
	int i;
	if (!cli) return 0;
	cli->ClientID=-1;
	cli->idxClientIcon=-1;
	
	for (i=0;i<ClientNumber;i++)
        
	{
		if (strstri(Clientstr,ClientNames[i]))
		{
			cli->ClientID=i;
            cli->idxClientIcon=ClientImageListIdx[i];

			return 0;
		}

	}

	return 0;
}
Example #16
0
/*----------------------------------------------------------------------------------------*/
int16	parse_items( uint8 *zeile, uint8 *data, uint8 *value )
{
	uint8		*p = zeile, *q = zeile;
	int16		dlen = (int16)strlen( data );

	while( p != NULL )
	{
		p = strstri(q, data);
	/*	printf( "%s >%s< p=0x%p\n", zeile, data, p ); */
	
		if( p && ((p==zeile) || p[-1] != '\"') && (p[dlen] == '=') )
		{
			get_str( p+dlen+1, value );
			return 1;
		}
		else if( p != NULL )
			q = p+1;
		else
			value[0] = EOS;
	}

	return 0;
}
int GetEudoraAddressFromNickname(char *pNickname, 
								 char *pAddress, 
								 int nAddressSize)
{
	FILE *fh;
	char buffer[MAX_LINEBUF+1];
	char *pEOL;
	char *pSystemCommandLine, *pEudoraPath = NULL, *pEudoraExe;
	int	 nNicknameLen;
	int	 nOffset;
	int	 rc = 1;

	assert(pNickname);
	assert(pAddress);

	//DebugBreak();

	nNicknameLen = strlen(pNickname);

	//Get the pointer to the system's static buf:
	pSystemCommandLine = GetCommandLine();

	//plus 2 because "nndbase.txt" is one character more than "eudora.exe".
	if((pEudoraPath = (char*)malloc(strlen(pSystemCommandLine) + 2)))
	{
		strcpy(pEudoraPath, pSystemCommandLine);
		if((pEudoraExe = strstri(pEudoraPath, "\\eudora.exe")))
		{
			*pEudoraExe = '\0';
			strcat(pEudoraPath, "\\nndbase.txt");
		}
		else
		{
			free(pEudoraPath);
			pEudoraPath = NULL;
		}
	}

	if(pEudoraPath)
	{
		//Win95 puts this string in quotes.  #@&*^%@#^%!
		if(*pEudoraPath == '\"')
			nOffset = 1;
		else
			nOffset = 0;

		fh = fopen((pEudoraPath + nOffset), "rt");
		free(pEudoraPath);
	}
	else
	{
		fh = fopen("\\eudora\\nnbase.txt", "rt");
	}

	if (!fh) {
		return -1;
	}

	while (!feof(fh)) {
		if (fgets(buffer, MAX_LINEBUF, fh) == NULL) {
			break;
		}
		if ((pEOL = strchr(buffer, '\n')) == NULL) {
			// no end of line...line too big
			rc = -2;
			break;
		} else {
			// stamp over it with a null
			*pEOL = '\0';
		}


		nOffset = 6;
		// look for "alias ", that will follow the nickname and 
		// then the email address
		// alias nickname [email protected]

		if (!strncmp(buffer, "alias ", nOffset)) {
			// see if the nickname matches
			if (!strncmp(buffer+nOffset, pNickname, nNicknameLen) && 
				buffer[nOffset+nNicknameLen] == ' ') {
				// step past the nickname + white space, and 
				//copy the email address
				nOffset += nNicknameLen+1;
				strncpy(pAddress, buffer+nOffset, nAddressSize);
				//These things seem to have trailing commas a lot...
				if(*(pAddress + strlen(pAddress) - 1) == ',')
					*(pAddress + strlen(pAddress) - 1) = '\0';
				rc = 0;
				break;
			}
		}
	}
	fclose(fh);
	return(rc);
}
Example #18
0
static LONG_PTR WINAPI DlgProc(HANDLE hDlg,int Msg,int Param1,LONG_PTR Param2)
{
  static TCHAR Filter[MAX_PATH];
  static TCHAR spFilter[MAX_PATH];
  static FarListTitles ListTitle;

  switch(Msg)
  {
    case DN_RESIZECONSOLE:
    {
      Info.SendDlgMessage(hDlg,DM_ENABLEREDRAW,FALSE,0);
      ResizeDialog(hDlg);
      Info.SendDlgMessage(hDlg,DM_ENABLEREDRAW,TRUE,0);
    }
    return TRUE;

    case DMU_UPDATE:
    {
      int OldPos = static_cast<int>(Info.SendDlgMessage(hDlg,DM_LISTGETCURPOS,LIST_BOX,0));

      if (Param1)
        UpDateInfo();

      ListSize = 0;
      int NewPos = -1;
      if (OldPos >= 0 && OldPos < nCount)
      {
        if (!*Filter || strstri(p[OldPos].Keys[DisplayName],Filter)) //без учета регистра в OEM кодировке
          NewPos = OldPos;
      }
      for (int i = 0; i < nCount; i++)
      {
        const TCHAR* DispName = p[i].Keys[DisplayName], *Find;
        if (*Filter)
          Find = strstri(DispName,Filter);
        else
          Find = DispName;
        if (Find != nullptr) //без учета регистра в OEM кодировке
        {
          FLI[i].Flags &= ~LIF_HIDDEN;
          if (Param2 && (i == OldPos))
          {
            if (FLI[i].Flags & LIF_CHECKED)
            {
              FLI[i].Flags &= ~LIF_CHECKED;
            }
            else
            {
              FLI[i].Flags |= LIF_CHECKED;
            }
          }
          //без учета регистра - а кодировка ANSI
          if (NewPos == -1 && Find == DispName)
            NewPos = i;
          ListSize++;
        }
        else
          FLI[i].Flags |= LIF_HIDDEN;
      }
      if (Param1 == 0 && Param2)
      {
        // Снятие или установка пометки (Ins)
        if (Param2 == 1)
        {
          for (int i = (OldPos+1); i < nCount; i++)
          {
            if (!(FLI[i].Flags & LIF_HIDDEN))
            {
              OldPos = i; break;
            }
          }
          NewPos = OldPos;
        }
        // Снятие или установка пометки (RClick)
        else if (Param2 == 2)
        {
          NewPos = OldPos;
        }
      }
      else if (NewPos == -1)
      {
        NewPos = OldPos;
      }

      Info.SendDlgMessage(hDlg,DM_ENABLEREDRAW,FALSE,0);

      Info.SendDlgMessage(hDlg,DM_LISTSET,LIST_BOX,reinterpret_cast<LONG_PTR>(&FL));

      StringCchPrintf(spFilter,ARRAYSIZE(spFilter), GetMsg(MFilter),Filter,ListSize,nCount);
      ListTitle.Title = spFilter;
      ListTitle.TitleLen = lstrlen(spFilter);
      Info.SendDlgMessage(hDlg,DM_LISTSETTITLES,LIST_BOX,reinterpret_cast<LONG_PTR>(&ListTitle));

      ResizeDialog(hDlg);

      struct FarListPos FLP;
      FLP.SelectPos = NewPos;
      FLP.TopPos = -1;
      Info.SendDlgMessage(hDlg,DM_LISTSETCURPOS,LIST_BOX,reinterpret_cast<LONG_PTR>(&FLP));

      Info.SendDlgMessage(hDlg,DM_ENABLEREDRAW,TRUE,0);
    }
    break;

    case DN_INITDIALOG:
    {
      StringCchCopy(Filter,ARRAYSIZE(Filter),_T(""));
      ListTitle.Bottom = const_cast<TCHAR*>(GetMsg(MBottomLine));
      ListTitle.BottomLen = lstrlen(GetMsg(MBottomLine));

      //подстраиваемся под размеры консоли
      Info.SendDlgMessage(hDlg,DM_ENABLEREDRAW,FALSE,0);
      ResizeDialog(hDlg);
      Info.SendDlgMessage(hDlg,DM_ENABLEREDRAW,TRUE,0);
      //заполняем диалог
      Info.SendDlgMessage(hDlg,DMU_UPDATE,1,0);
    }
    break;

    case DN_MOUSECLICK:
    {
      if (Param1 == LIST_BOX)
      {
        MOUSE_EVENT_RECORD *mer = (MOUSE_EVENT_RECORD *)Param2;
        if (mer->dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
        {
          // find list on-screen coords (excluding frame and border)
          SMALL_RECT list_rect;
          Info.SendDlgMessage(hDlg, DM_GETDLGRECT, 0, reinterpret_cast<LONG_PTR>(&list_rect));
          list_rect.Left += 2;
          list_rect.Top += 1;
          list_rect.Right -= 2;
          list_rect.Bottom -= 1;
          if ((mer->dwEventFlags == 0) && (mer->dwMousePosition.X > list_rect.Left) && (mer->dwMousePosition.X < list_rect.Right) && (mer->dwMousePosition.Y > list_rect.Top) && (mer->dwMousePosition.Y < list_rect.Bottom))
          {
            DlgProc(hDlg, DN_KEY, LIST_BOX, KEY_ENTER);
            return TRUE;
          }
          // pass message to scrollbar if needed
          if ((mer->dwMousePosition.X == list_rect.Right) && (mer->dwMousePosition.Y > list_rect.Top) && (mer->dwMousePosition.Y < list_rect.Bottom)) return FALSE;
          return TRUE;
        }
        else if (mer->dwButtonState == RIGHTMOST_BUTTON_PRESSED)
        {
          Info.SendDlgMessage(hDlg,DMU_UPDATE,0,2);
          return TRUE;
        }
      }
    }
    break;

    case DN_KEY:
      switch (Param2)
      {
        case KEY_F8:
        {
          if (ListSize)
          {
            TCHAR DlgText[MAX_PATH + 200];
            StringCchPrintf(DlgText, ARRAYSIZE(DlgText), GetMsg(MConfirm), p[Info.SendDlgMessage(hDlg,DM_LISTGETCURPOS,LIST_BOX,NULL)].Keys[DisplayName]);
            if (EMessage((const TCHAR * const *) DlgText, 0, 2) == 0)
            {
              if (!DeleteEntry(static_cast<int>(Info.SendDlgMessage(hDlg,DM_LISTGETCURPOS,LIST_BOX,NULL))))
                DrawMessage(FMSG_WARNING, 1, "%s",GetMsg(MPlugIn),GetMsg(MDelRegErr),GetMsg(MBtnOk),NULL);
              Info.SendDlgMessage(hDlg,DMU_UPDATE,1,0);
            }
          }
        }
        return TRUE;

        case (KEY_F9|KEY_SHIFT|KEY_ALT):
        case (KEY_F9):
        {
          Configure(0);
        }
        return TRUE;

        case KEY_CTRLR:
        {
          Info.SendDlgMessage(hDlg,DMU_UPDATE,1,0);
        }
        return TRUE;

        case KEY_INS:
        {
          Info.SendDlgMessage(hDlg,DMU_UPDATE,0,1);
        }
        return TRUE;

        case KEY_ENTER:
        case KEY_SHIFTENTER:
        {
          if (ListSize)
          {
            int liChanged = 0;
            int liSelected = 0, liFirst = -1;

            for (int i = 0; i < nCount; i++)
            {
               if (FLI[i].Flags & LIF_CHECKED)
               {
                 if (liFirst == -1)
                   liFirst = i;
                 liSelected++;
               }
            }

            if (liSelected <= 1)
            {
              int liAction = (Param2 == KEY_ENTER) ? Opt.EnterAction : Opt.ShiftEnterAction;
              int pos = (liFirst == -1) ? static_cast<int>(Info.SendDlgMessage(hDlg,DM_LISTGETCURPOS,LIST_BOX,NULL)) : liFirst;
              liChanged = ExecuteEntry(pos, liAction, (Opt.RunLowPriority!=0));
            }
            else
            {
              int liAction = (Param2 == KEY_ENTER) ? Opt.EnterAction : Opt.ShiftEnterAction;
              bool LowPriority = (Opt.RunLowPriority!=0);

              // Обязательно ожидание - два инсталлятора сразу недопускаются
              if (liAction == Action_Menu)
              {
                if (EntryMenu(0, liAction, LowPriority, liSelected) < 0)
                  return TRUE;
              }
              else if (liAction == Action_Uninstall)
                liAction = Action_UninstallWait;
              else if (liAction == Action_Modify)
                liAction = Action_ModifyWait;
              else if (liAction == Action_Repair)
                liAction = Action_RepairWait;
              
              for (int pos = 0; pos < nCount; pos++)
              {
                if (!(FLI[pos].Flags & LIF_CHECKED))
                  continue;
                struct FarListPos FLP;
                FLP.SelectPos = pos;
                FLP.TopPos = -1;
                Info.SendDlgMessage(hDlg,DM_LISTSETCURPOS,LIST_BOX,reinterpret_cast<LONG_PTR>(&FLP));
                int li = ExecuteEntry(pos, liAction, LowPriority);
                if (li == -1)
                  break; // отмена
                if (li == 1)
                  liChanged = 1;
              }
            }

            if (liChanged == 1)
            {
              Info.SendDlgMessage(hDlg,DMU_UPDATE,1,0);
            }
          }
        }
        return TRUE;

        case KEY_SHIFTINS:
        case KEY_CTRLV:
        {
          TCHAR * bufP = FSF.PasteFromClipboard();
          static TCHAR bufData[MAX_PATH];
          if (bufP)
          {
            StringCchCopy(bufData,ARRAYSIZE(bufData),bufP);
            FSF.DeleteBuffer(bufP);
            unQuote(bufData);
            FSF.LStrlwr(bufData);
            for (int i = lstrlen(bufData); i >= 1; i--)
              for (int j = 0; j < nCount; j++)
                if (strnstri(p[j].Keys[DisplayName],bufData,i))
                {
                  lstrcpyn(Filter,bufData,i+1);
                  Info.SendDlgMessage(hDlg,DMU_UPDATE,0,0);
                  return TRUE;
                }
          }
        }
        return TRUE;

        case KEY_DEL:
        {
          if (lstrlen(Filter) > 0)
          {
            StringCchCopy(Filter,ARRAYSIZE(Filter),_T(""));
            Info.SendDlgMessage(hDlg,DMU_UPDATE,0,0);
          }
        }
        return TRUE;

        case KEY_F3:
        case KEY_F4:
        {
          if (ListSize)
          {
            DisplayEntry(static_cast<int>(Info.SendDlgMessage(hDlg,DM_LISTGETCURPOS,LIST_BOX,NULL)));
            Info.SendDlgMessage(hDlg,DM_REDRAW,NULL,NULL);
          }
        }
        return TRUE;

        case KEY_F2:
        {
          Opt.SortByDate = !Opt.SortByDate;
          Info.SendDlgMessage(hDlg,DMU_UPDATE,1,0);
        }
        return TRUE;

        case KEY_BS:
        {
          if (lstrlen(Filter))
          {
            Filter[lstrlen(Filter)-1] = '\0';
            Info.SendDlgMessage(hDlg,DMU_UPDATE,0,0);
          }
        }
        return TRUE;

        default:
        {
          if (Param2 >= KEY_SPACE && Param2 < KEY_FKEY_BEGIN)
          {
            struct FarListInfo ListInfo;
            Info.SendDlgMessage(hDlg,DM_LISTINFO,LIST_BOX,reinterpret_cast<LONG_PTR>(&ListInfo));
            if ((lstrlen(Filter) < sizeof(Filter)) && ListInfo.ItemsNumber)
            {
              int filterL = lstrlen(Filter);
              Filter[filterL] = FSF.LLower(static_cast<unsigned>(Param2));
              Filter[filterL+1] = '\0';
              Info.SendDlgMessage(hDlg,DMU_UPDATE,0,0);
              return TRUE;
            }
          }
        }
      }
      return FALSE;

    case DN_CTLCOLORDIALOG:
      return Info.AdvControl(Info.ModuleNumber,ACTL_GETCOLOR,(void *)COL_MENUTEXT);

    case DN_CTLCOLORDLGLIST:
      if (Param1 == LIST_BOX)
      {
        FarListColors *Colors = (FarListColors *)Param2;
        int ColorIndex[] = { COL_MENUBOX, COL_MENUBOX, COL_MENUTITLE, COL_MENUTEXT, COL_MENUHIGHLIGHT, COL_MENUBOX, COL_MENUSELECTEDTEXT, COL_MENUSELECTEDHIGHLIGHT, COL_MENUSCROLLBAR, COL_MENUDISABLEDTEXT, COL_MENUARROWS, COL_MENUARROWSSELECTED, COL_MENUARROWSDISABLED };
        int Count = ARRAYSIZE(ColorIndex);
        if (Count > Colors->ColorCount)
          Count = Colors->ColorCount;
        for (int i = 0; i < Count; i++)
          Colors->Colors[i] = static_cast<BYTE>(Info.AdvControl(Info.ModuleNumber, ACTL_GETCOLOR, reinterpret_cast<void *>(ColorIndex[i])));
        return TRUE;
      }
    break;
  }
  return Info.DefDlgProc(hDlg,Msg,Param1,Param2);
}
Example #19
0
/* Bug: if the monster is a priest or shopkeeper, not every one of these
 * options works, since those are special cases.
 */
char *x_monnam(const struct monst *mtmp,
	       int article, /* ARTICLE_NONE, ARTICLE_THE, ARTICLE_A: obvious
	                     * ARTICLE_YOUR: "your" on pets, "the" on everything
			     * else
			     * If the monster would be referred to as "it" or if the monster has a name
			     * _and_ there is no adjective, "invisible", "saddled", etc., override this
			     * and always use no article.
			     */
	       const char *adjective,
	       int suppress, /* SUPPRESS_IT, SUPPRESS_INVISIBLE, SUPPRESS_HALLUCINATION, SUPPRESS_SADDLE.
	                      * EXACT_NAME: combination of all the above
			      */
	       boolean called)
{
	static char buf[BUFSZ];

	const struct permonst *mdat = mtmp->data;
	boolean do_hallu, do_invis, do_it, do_saddle;
	boolean name_at_start, has_adjectives;
	char *bp;

	if (program_state.gameover)
	    suppress |= SUPPRESS_HALLUCINATION;
	if (article == ARTICLE_YOUR && !mtmp->mtame)
	    article = ARTICLE_THE;

	do_hallu = Hallucination && !(suppress & SUPPRESS_HALLUCINATION);
	do_invis = mtmp->minvis && !(suppress & SUPPRESS_INVISIBLE);
	do_it = !canspotmon(mtmp) && 
	    article != ARTICLE_YOUR &&
	    !program_state.gameover &&
	    mtmp != u.usteed &&
	    !(u.uswallow && mtmp == u.ustuck) &&
	    !(suppress & SUPPRESS_IT);
	do_saddle = !(suppress & SUPPRESS_SADDLE);

	buf[0] = 0;

	/* unseen monsters, etc.  Use "it" */
	if (do_it) {
	    strcpy(buf, "it");
	    return buf;
	}

	/* priests and minions: don't even use this function */
	if (mtmp->ispriest || mtmp->isminion) {
	    struct monst *priestmon = newmonst(mtmp->mxtyp, mtmp->mnamelth);
	    char priestnambuf[BUFSZ];
	    char *name;
	    long save_prop = EHalluc_resistance;
	    memcpy(priestmon, mtmp, sizeof(struct monst) + mtmp->mxlth + mtmp->mnamelth);

	    /* when true name is wanted, explicitly block Hallucination */
	    if (!do_hallu) EHalluc_resistance = 1L;
	    if (!do_invis) priestmon->minvis = 0;
	    name = priestname(priestmon, priestnambuf);
	    EHalluc_resistance = save_prop;
	    if (article == ARTICLE_NONE && !strncmp(name, "the ", 4))
		name += 4;
	    strcpy(buf, name);
	    free(priestmon);
	    return buf;
	}

	/* Shopkeepers: use shopkeeper name.  For normal shopkeepers, just
	 * "Asidonhopo"; for unusual ones, "Asidonhopo the invisible
	 * shopkeeper" or "Asidonhopo the blue dragon".  If hallucinating,
	 * none of this applies.
	 */
	if (mtmp->isshk && !do_hallu) {
	    if (adjective && article == ARTICLE_THE) {
		/* pathological case: "the angry Asidonhopo the blue dragon"
		   sounds silly */
		strcpy(buf, "the ");
		strcat(strcat(buf, adjective), " ");
		strcat(buf, shkname(mtmp));
		return buf;
	    }
	    strcat(buf, shkname(mtmp));
	    if (mdat == &mons[PM_SHOPKEEPER] && !do_invis)
		return buf;
	    strcat(buf, " the ");
	    if (do_invis)
		strcat(buf, "invisible ");
	    strcat(buf, mdat->mname);
	    return buf;
	}

	/* Put the adjectives in the buffer */
	if (adjective)
	    strcat(strcat(buf, adjective), " ");
	if (do_invis)
	    strcat(buf, "invisible ");

	if (do_saddle && (mtmp->misc_worn_check & W_SADDLE) &&
	    !Blind && !Hallucination)
	    strcat(buf, "saddled ");

	if (buf[0] != 0)
	    has_adjectives = TRUE;
	else
	    has_adjectives = FALSE;

	/* Put the actual monster name or type into the buffer now */
	/* Be sure to remember whether the buffer starts with a name */
	if (do_hallu) {
	    strcat(buf, rndmonnam());
	    name_at_start = FALSE;
	} else if (mtmp->mnamelth) {
	    char *name = NAME(mtmp);

	    if (mdat == &mons[PM_GHOST]) {
		sprintf(eos(buf), "%s ghost", s_suffix(name));
		name_at_start = TRUE;
	    } else if (called) {
		sprintf(eos(buf), "%s called %s", mdat->mname, name);
		name_at_start = (boolean)type_is_pname(mdat);
	    } else if (is_mplayer(mdat) && (bp = strstri(name, " the ")) != 0) {
		/* <name> the <adjective> <invisible> <saddled> <rank> */
		char pbuf[BUFSZ];

		strcpy(pbuf, name);
		pbuf[bp - name + 5] = '\0'; /* adjectives right after " the " */
		if (has_adjectives)
		    strcat(pbuf, buf);
		strcat(pbuf, bp + 5);	/* append the rest of the name */
		strcpy(buf, pbuf);
		article = ARTICLE_NONE;
		name_at_start = TRUE;
	    } else {
		strcat(buf, name);
		name_at_start = TRUE;
	    }
	} else if (is_mplayer(mdat) && !In_endgame(&u.uz)) {
	    char pbuf[BUFSZ];
	    strcpy(pbuf, rank_of((int)mtmp->m_lev,
				 monsndx(mdat), (boolean)mtmp->female));
	    strcat(buf, lcase(pbuf));
	    name_at_start = FALSE;
	} else {
	    strcat(buf, mdat->mname);
	    name_at_start = (boolean)type_is_pname(mdat);
	}

	if (name_at_start && (article == ARTICLE_YOUR || !has_adjectives)) {
	    if (mdat == &mons[PM_WIZARD_OF_YENDOR])
		article = ARTICLE_THE;
	    else
		article = ARTICLE_NONE;
	} else if ((mdat->geno & G_UNIQ) && article == ARTICLE_A) {
	    article = ARTICLE_THE;
	}

	{
	    char buf2[BUFSZ];

	    switch(article) {
		case ARTICLE_YOUR:
		    strcpy(buf2, "your ");
		    strcat(buf2, buf);
		    strcpy(buf, buf2);
		    return buf;
		case ARTICLE_THE:
		    strcpy(buf2, "the ");
		    strcat(buf2, buf);
		    strcpy(buf, buf2);
		    return buf;
		case ARTICLE_A:
		    return an(buf);
		case ARTICLE_NONE:
		default:
		    return buf;
	    }
	}
}
Example #20
0
bool SearchContext::searchFile(int id, const std::string &filename, RegexList &filespecRegexes, pcre *matchRegex)
{
    bool matchesOneFilespec = false;
    for(RegexList::iterator it = filespecRegexes.begin(); it != filespecRegexes.end(); ++it)
    {
        pcre *regex = *it;
        if(pcre_exec(regex, NULL, filename.c_str(), filename.length(), 0, 0, NULL, 0) >= 0)
        {
            matchesOneFilespec = true;
            break;
        }
    }
    if(!matchesOneFilespec)
        return false;

    std::string contents;
    if(!readEntireFile(filename, contents, params_.maxFileSize))
        return false;

    std::string workBuffer = contents;
    std::string updatedContents;

    bool atLeastOneMatch = false;

    int lineNumber = 1;
    char *p = &workBuffer[0];
    char *line;
    while((line = nextToken(&p, '\n')) != NULL)
    {
        char *originalLine = line;
        std::string replacedLine;
		SearchEntry entry;
        int ovector[100];
        do
        {
            bool matches = false;
            int matchPos;
            int matchLen;

            if(matchRegex)
            {
                int rc;
                if(rc = pcre_exec(matchRegex, 0, line, strlen(line), 0, 0, ovector, sizeof(ovector)) >= 0)
                {
                    matches = true;
                    matchPos = ovector[0];
                    matchLen = ovector[1] - ovector[0];
                }
            }
            else
            {
                char *match;
                if(params_.flags & SF_MATCH_CASE_SENSITIVE)
                    match = strstr(line, params_.match.c_str());
                else
                    match = strstri(line, params_.match.c_str());
                if(match != NULL)
                {
                    matches = true;
                    matchPos = match - line;
                    matchLen = params_.match.length();
                }
            }

            if(params_.flags & SF_REPLACE)
            {
                if(matches)
                {
                    replacedLine.append(line, matchPos);
					entry.highlights_.push_back(Highlight(replacedLine.length(), params_.replace.length()));
                    replacedLine.append(params_.replace);
                    line += matchPos + matchLen;
                }
                else
                {
                    break;
                }
            }
            else
            {
                if(matches)
                {
                    entry.filename_ = filename;
                    entry.match_ = originalLine;
                    entry.line_ = lineNumber;
					entry.highlights_.push_back(Highlight(matchPos + (line - originalLine), matchLen));
					line += matchPos + matchLen;
                }
				else
				{
					break;
				}
            }

            if(matches)
                hits_++;
        }
        while(*line);

        if(!entry.filename_.empty())
        {
            linesWithHits_++;
            atLeastOneMatch = true;
        }

        if(params_.flags & SF_REPLACE)
        {
            if(line && *line)
                replacedLine += line;
            if(replacedLine != originalLine)
            {
                entry.filename_ = filename;
                entry.match_ = replacedLine;
                entry.line_ = lineNumber;
                append(id, entry);
            }
            replacedLine += "\n";
            updatedContents += replacedLine;
        }
		else
		{
			if(!entry.filename_.empty())
				append(id, entry);
		}
		lineNumber++;
    }
    if(atLeastOneMatch)
        filesWithHits_++;
    if(params_.flags & SF_REPLACE)
    {
        if((contents != updatedContents))
        {
			bool overwriteFile = true;
			if(params_.flags & SF_BACKUP)
			{
				std::string backupFilename = filename;
				backupFilename += ".";
				backupFilename += params_.backupExtension;

				if(!writeEntireFile(backupFilename, contents))
				{
					std::string err = "WARNING: Couldn't write backup file (skipping replacement): ";
					err += backupFilename;
					err += "\n";
					poke(id, err.c_str(), HighlightList(), 0, false);

					overwriteFile = false;
				}
			}

			if(overwriteFile)
			{
				if(writeEntireFile(filename, updatedContents))
				{
					return true;
				}
				else
				{
					std::string err = "WARNING: Couldn't write to file: ";
					err += filename;
					err += "\n";
					poke(id, err.c_str(), HighlightList(), 0, false);
				}
			}
        }
        return false;
    }
    return true;
}
Example #21
0
/* make a (new) human out of the player */
static void polyman(const char *fmt, const char *arg)
{
	boolean sticky = sticks(youmonst.data) && u.ustuck && !u.uswallow,
		was_mimicking = (youmonst.m_ap_type == M_AP_OBJECT);
	boolean could_pass_walls = Passes_walls;
	boolean was_blind = !!Blind;

	if (Upolyd) {
		u.acurr = u.macurr;	/* restore old attribs */
		u.amax = u.mamax;
		u.umonnum = u.umonster;
		flags.female = u.mfemale;
	}
	set_uasmon();

	u.mh = u.mhmax = 0;
	u.mtimedone = 0;
	skinback(FALSE);
	u.uundetected = 0;

	if (sticky) uunstick();
	find_ac();
	if (was_mimicking) {
	    if (multi < 0) unmul("");
	    youmonst.m_ap_type = M_AP_NOTHING;
	}

	newsym(u.ux,u.uy);

	pline(fmt, arg);
	/* check whether player foolishly genocided self while poly'd */
	if ((mvitals[urole.malenum].mvflags & G_GENOD) ||
			(urole.femalenum != NON_PM &&
			(mvitals[urole.femalenum].mvflags & G_GENOD)) ||
			(mvitals[urace.malenum].mvflags & G_GENOD) ||
			(urace.femalenum != NON_PM &&
			(mvitals[urace.femalenum].mvflags & G_GENOD))) {
	    /* intervening activity might have clobbered genocide info */
	    killer = delayed_killer;
	    if (!killer || !strstri(killer, "genocid")) {
		killer_format = KILLED_BY;
		killer = "self-genocide";
	    }
	    done(GENOCIDED);
	}

	if (u.twoweap && !could_twoweap(youmonst.data))
	    untwoweapon();

	if (u.utraptype == TT_PIT) {
	    if (could_pass_walls) {	/* player forms cannot pass walls */
		u.utrap = rn1(6,2);
	    }
	}
	if (was_blind && !Blind) {	/* reverting from eyeless */
	    Blinded = 1L;
	    make_blinded(0L, TRUE);	/* remove blindness */
	}

	if (!Levitation && !u.ustuck &&
	   (is_pool(level, u.ux,u.uy) || is_lava(level, u.ux,u.uy)))
		spoteffects(TRUE);

	see_monsters();
}
Example #22
0
static int menu_get_selections(WINDOW *win, nhmenu *menu, int how)
{
    int curletter;
    int count = -1;
    int count_letter = '\0';
    int curpage = 1;
    int num_selected = 0;
    boolean dismiss = FALSE;
    char search_key[BUFSZ];
    nhmenu_item *menu_item_ptr = menu->entries;

    menu_display_page(menu, win, 1);

    while (!dismiss)
    {
        curletter = getch();
        
        if (curletter == '\033')
        {
            curletter = curses_convert_keys(curletter);
        }
        
        if (isdigit(curletter) && (how != PICK_NONE))
        {
            count = curses_get_count(curletter - '0');
            touchwin(win);
            refresh();
            curletter = getch();
            
            if (count > 0)
            {
                count_letter = curletter;
            }
        }
        

        if ((how == PICK_NONE) && (menu->num_pages == 1))
        {
            if (how==PICK_NONE)
            {    
                if (curletter == KEY_ESC)
                {
                    num_selected = -1;
                }
                else
                {
                    num_selected = 0;

                }
                dismiss = TRUE;
                break;
            }                
        }
        
        switch (curletter)
        {
            case KEY_ESC:
            {
                num_selected = -1;
                dismiss = TRUE;
                break;
            }
            case '\n':
            case '\r':
            {
                dismiss = TRUE;
                break;
            }
            case KEY_RIGHT:
            case KEY_NPAGE:
            case MENU_NEXT_PAGE:
            case ' ':
            {
                if (curpage < menu->num_pages)
                {
                    curpage++;
                    menu_display_page(menu, win, curpage);
                }
                else if (curletter == ' ')
                {
                    dismiss = TRUE;
                    break;
                }
                break;
            }
            case KEY_LEFT:
            case KEY_PPAGE:
            case MENU_PREVIOUS_PAGE:
            {
                if (curpage > 1)
                {
                    curpage--;
                    menu_display_page(menu, win, curpage);
                }
                break;
            }
            case KEY_END:
            case MENU_LAST_PAGE:
            {
                if (curpage != menu->num_pages)
                {
                    curpage = menu->num_pages;
                    menu_display_page(menu, win, curpage);
                }
                break;
            }
            case KEY_HOME:
            case MENU_FIRST_PAGE:
            {
                if (curpage != 1)
                {
                    curpage = 1;
                    menu_display_page(menu, win, curpage);
                }
                break;
            }
            case MENU_SEARCH:
            {
                curses_line_input_dialog("Search for:", search_key,
                 BUFSZ);
        		
                refresh();
                touchwin(win);
                wrefresh(win);
                
        		if (strlen(search_key) == 0)
        		{
        		    break;
        		}
        		
                menu_item_ptr = menu->entries;

                while (menu_item_ptr != NULL)
                {
                    if ((menu_item_ptr->identifier.a_void != NULL) &&
                     (strstri(menu_item_ptr->str, search_key)))
                    {
                        if (how == PICK_ONE)
                        {
                            menu_clear_selections(menu);
                            menu_select_deselect(win, menu_item_ptr,
                             SELECT);
                            num_selected = 1;
                            dismiss = TRUE;
                            break;
                        }
                        else
                        {
                            menu_select_deselect(win, menu_item_ptr,
                             INVERT);
                        }
                    }

                    menu_item_ptr = menu_item_ptr->next_item;
                }

                menu_item_ptr = menu->entries;
                break;
            }
            default:
            {
                if (how==PICK_NONE)
                {    
                    num_selected = 0;
                    dismiss = TRUE;
                    break;
                }                
            }
        }
        if (how == PICK_ANY)
        {
            switch (curletter)
                {
                case MENU_SELECT_PAGE:
                {
                    (void) menu_operation(win, menu, SELECT, curpage);
                    break;
                }
                case MENU_SELECT_ALL:
                {
                    curpage = menu_operation(win, menu, SELECT, 0);
                    break;
                }
                case MENU_UNSELECT_PAGE:
                {
                    (void) menu_operation(win, menu, DESELECT, curpage);
                    break;
                }
                case MENU_UNSELECT_ALL:
                {
                    curpage = menu_operation(win, menu, DESELECT, 0);
                    break;
                }
                case MENU_INVERT_PAGE:
                {
                    (void) menu_operation(win, menu, INVERT, curpage);
                    break;
                }
                case MENU_INVERT_ALL:
                {
                    curpage = menu_operation(win, menu, INVERT, 0);
                    break;
                }
            }
        }
        
        menu_item_ptr = menu->entries;
        
        while (menu_item_ptr != NULL)
        {
            if (menu_item_ptr->identifier.a_void != NULL)
            {
                if (((curletter == menu_item_ptr->accelerator) &&
                 ((curpage == menu_item_ptr->page_num) ||
                 (!menu->reuse_accels))) || ((menu_item_ptr->group_accel)
                 && (curletter == menu_item_ptr->group_accel)))
                {
                    if (curpage != menu_item_ptr->page_num)
                    {
                        curpage = menu_item_ptr->page_num;
                        menu_display_page(menu, win, curpage);
                    }

                    if (how == PICK_ONE)
                    {
                        menu_clear_selections(menu);
                        menu_select_deselect(win, menu_item_ptr, SELECT);
                        num_selected = 1;
                        dismiss = TRUE;
                        break;
                    }
                    else
                    {
                        menu_select_deselect(win, menu_item_ptr, INVERT);
                    }
                }
            }
            menu_item_ptr = menu_item_ptr->next_item;
        }
    }
    
    if ((how == PICK_ANY) && (num_selected != -1))
    {
        num_selected = 0;
        menu_item_ptr = menu->entries;
        
        while (menu_item_ptr != NULL)
        {
            if (menu_item_ptr->identifier.a_void != NULL)
            {
                if (menu_item_ptr->selected)
                {
                    num_selected++;
                    
                    if (menu_item_ptr->accelerator == count_letter)
                    {
                        menu_item_ptr->count = count;
                        count = 0;
                        count_letter = '\0';
                    }
                }
            }
            menu_item_ptr = menu_item_ptr->next_item;
        }
    }
    
    return num_selected;
}
Example #23
0
/* (moved from apply.c) */
boolean wield_tool(struct obj *obj,
		   const char *verb)	/* "rub",&c */
{
    const char *what;
    boolean more_than_1;

    if (obj == uwep) return TRUE;   /* nothing to do if already wielding it */

    if (!verb) verb = "wield";
    what = xname(obj);
    more_than_1 = (obj->quan > 1L ||
		   strstri(what, "pair of ") != 0 ||
		   strstri(what, "s of ") != 0);

    if (obj->owornmask & (W_ARMOR|W_RING|W_AMUL|W_TOOL)) {
	char yourbuf[BUFSZ];

	pline("You can't %s %s %s while wearing %s.",
		 verb, shk_your(yourbuf, obj), what,
		 more_than_1 ? "them" : "it");
	return FALSE;
    }
    if (welded(uwep)) {
	if (flags.verbose) {
	    const char *hand = body_part(HAND);

	    if (bimanual(uwep)) hand = makeplural(hand);
	    if (strstri(what, "pair of ") != 0) more_than_1 = FALSE;
	    pline(
	     "Since your weapon is welded to your %s, you cannot %s %s %s.",
		  hand, verb, more_than_1 ? "those" : "that", xname(obj));
	} else {
	    pline("You can't do that.");
	}
	return FALSE;
    }
    if (cantwield(youmonst.data)) {
	pline("You can't hold %s strongly enough.", more_than_1 ? "them" : "it");
	return FALSE;
    }
    /* check shield */
    if (uarms && bimanual(obj)) {
	pline("You cannot %s a two-handed %s while wearing a shield.",
	    verb, (obj->oclass == WEAPON_CLASS) ? "weapon" : "tool");
	return FALSE;
    }
    if (uquiver == obj) setuqwep(NULL);
    if (uswapwep == obj) {
	doswapweapon();
	/* doswapweapon might fail */
	if (uswapwep == obj) return FALSE;
    } else {
	pline("You now wield %s.", doname(obj));
	setuwep(obj);
    }
    if (uwep != obj) return FALSE;	/* rewielded old object after dying */
    /* applying weapon or tool that gets wielded ends two-weapon combat */
    if (u.twoweap)
	untwoweapon();
    if (obj->oclass != WEAPON_CLASS)
	unweapon = TRUE;
    return TRUE;
}
Example #24
0
bool SearchContext::searchFile(int id, const std::string &filename, RegexList &filespecRegexes, pcre *matchRegex)
{
    bool matchesOneFilespec = false;
    for(RegexList::iterator it = filespecRegexes.begin(); it != filespecRegexes.end(); ++it)
    {
        pcre *regex = *it;
        if(pcre_exec(regex, NULL, filename.c_str(), filename.length(), 0, 0, NULL, 0) >= 0)
        {
            matchesOneFilespec = true;
            break;
        }
    }
    if(!matchesOneFilespec)
        return false;

    std::string contents;
    if(!readEntireFile(filename, contents, params_.maxFileSize))
        return false;

    std::string workBuffer = contents;
    std::string updatedContents;

    std::deque<char *> contextLines;

    bool atLeastOneMatch = false;

    int trailingContextLines = 0;
    int lineNumber = 1;
    char *p = &workBuffer[0];
    char *line;
    while((line = nextToken(&p, '\n')) != NULL)
    {
        char *originalLine = line;
        std::string replacedLine;
        SearchEntry entry;
        int ovector[100];

        // Strip newline, but remember exactly what kind it was
        bool hasCarriageReturn = false;
        int lineLen = strlen(line);
        if(lineLen && (line[lineLen - 1] == '\r'))
        {
            line[lineLen - 1] = 0;
            hasCarriageReturn = true;
        }

        // Matching loop (we might find our string a few times on a single line)
        bool lineMatched = false;
        do
        {
            bool matches = false;
            int matchPos;
            int matchLen;

            // The actual match. Either invoke PCRE or do a boring strstr
            if(matchRegex)
            {
                int rc;
                if(rc = pcre_exec(matchRegex, 0, line, strlen(line), 0, 0, ovector, sizeof(ovector)) >= 0)
                {
                    matches = true;
                    matchPos = ovector[0];
                    matchLen = ovector[1] - ovector[0];
                }
            }
            else
            {
                char *match;
                if(params_.flags & SF_MATCH_CASE_SENSITIVE)
                    match = strstr(line, params_.match.c_str());
                else
                    match = strstri(line, params_.match.c_str());
                if(match != NULL)
                {
                    matches = true;
                    matchPos = match - line;
                    matchLen = params_.match.length();
                }
            }

            if(matches)
                lineMatched = true;

            // Handle the match. For replace or find, we:
            // * Add output explaining the match
            // * Advance the line pointer for another match attempt
            // ... or ...
            // * "break", which leaves the matching loop
            if(params_.flags & SF_REPLACE)
            {
                if(matches)
                {
                    std::string temp(line, matchPos);
                    replacedLine.append(temp);
                    replacedLine.append(params_.replace);
                    entry.textBlocks.addBlock(temp, config_.textColor_);
                    entry.textBlocks.addBlock(params_.replace, config_.highlightColor_, true);
                    line += matchPos + matchLen;
                }
                else
                {
                    break;
                }
            }
            else
            {
                if(matches)
                {
                    entry.textBlocks.addHighlightedBlock(originalLine, matchPos + (line - originalLine), matchLen, config_.textColor_, config_.highlightColor_, true);
                    line += matchPos + matchLen;
                }
                else
                {
                    break;
                }
            }

            if(matches)
                hits_++;
        }
        while(*line); // end of matching loop

        // If we're doing a replace, finish the line and append to the final updated contents
        if(params_.flags & SF_REPLACE)
        {
            if(line && *line)
            {
                replacedLine += line;
                entry.textBlocks.addBlock(line, config_.textColor_);
            }
            if(hasCarriageReturn)
            {
                replacedLine += "\r";
            }
            replacedLine += "\n";
            updatedContents += replacedLine;
        }

        bool outputMatch = false;
        if(lineMatched)
        {
            // keep stats
            linesWithHits_++;
            atLeastOneMatch = true;

            // If we matched, consider notifying the user. We'll always say something
            // unless the replaced text doesn't actually change the line.
            outputMatch = ( !(params_.flags & SF_REPLACE) ) || (replacedLine != originalLine);

            if(outputMatch)
            {
                entry.filename_ = filename;
                entry.line_ = lineNumber;

                // output all existing context lines
                if(contextLines.size())
                {
                    SearchEntry contextEntry;
                    contextEntry.filename_ = entry.filename_;
                    contextEntry.contextOnly_ = true;
                    int currLine = entry.line_ - contextLines.size();
                    for(std::deque<char *>::iterator it = contextLines.begin(); it != contextLines.end(); ++it)
                    {
                        TextBlockList textBlocks;
                        textBlocks.addBlock(*it, config_.textColor_);
                        contextEntry.textBlocks.swap(textBlocks);
                        contextEntry.line_ = currLine++;
                        append(id, contextEntry);
                    }

                    contextLines.clear();
                }

                append(id, entry);
            }

            // Remember that we'd like the next few lines, even if they don't match
            trailingContextLines = config_.contextLines_;
        }

        if(!outputMatch)
        {
            // Didn't output a match. Keep track or output the line anyway for contextual reasons.

            if(trailingContextLines > 0)
            {
                // A recent match wants to see this line in the output anyway

                SearchEntry trailingEntry;
                trailingEntry.filename_ = filename;
                trailingEntry.line_ = lineNumber;
                trailingEntry.contextOnly_ = true;
                trailingEntry.textBlocks.addBlock(originalLine, config_.textColor_);
                append(id, trailingEntry);
                trailingContextLines--;
            }
            else
            {
                // didn't output a match, and wasn't output as context. stash it in contextLines

                contextLines.push_back(originalLine);
                if((int)contextLines.size() > config_.contextLines_)
                    contextLines.pop_front();
            }
        }

        lineNumber++;
    } // end of line loop (done reading file)

    if(atLeastOneMatch)
        filesWithHits_++;

    if(params_.flags & SF_REPLACE)
    {
        if((contents != updatedContents))
        {
            bool overwriteFile = true;
            if(params_.flags & SF_BACKUP)
            {
                std::string backupFilename = filename;
                backupFilename += ".";
                backupFilename += params_.backupExtension;

                if(!writeEntireFile(backupFilename, contents))
                {
                    std::string err = "WARNING: Couldn't write backup file (skipping replacement): ";
                    err += backupFilename;
                    err += "\n";
                    sendError(id, err);

                    overwriteFile = false;
                }
            }

            if(overwriteFile)
            {
                if(writeEntireFile(filename, updatedContents))
                {
                    return true;
                }
                else
                {
                    std::string err = "WARNING: Couldn't write to file: ";
                    err += filename;
                    err += "\n";
                    sendError(id, err);
                }
            }
        }
        return false;
    }
    return true;
}
Example #25
0
File: utils.c Project: redxu/sihook
//获取文件类型
//0 无类型默认
//1 *.c *.cpp *.cxx *.cs
//2 *.h *.hpp *.hxx *.inc
//3 *.txt *.text *.doc
//4 *.php *.php3 *.htm *.js
//5 *.pas *.vb *.pb *.vbs
int GetColorIndex(const char* filename)
{
    const char *p = NULL;
    //type 1
    p = strstri(filename,".c");
    if(p != NULL)
        return 1;
    p = strstri(filename,".cpp");
    if(p != NULL)
        return 1;
    p = strstri(filename,".cxx");
    if(p != NULL)
        return 1;
    p = strstri(filename,".cs");
    if(p != NULL)
        return 1;
    //type 2
    p = strstri(filename,".h");
    if(p != NULL)
        return 2;
    p = strstri(filename,".hpp");
    if(p != NULL)
        return 2;
    p = strstri(filename,".hxx");
    if(p != NULL)
        return 2;
    p = strstri(filename,".inc");
    if(p != NULL)
        return 2;
    //type 3
    p = strstri(filename,".txt");
    if(p != NULL)
        return 3;
    p = strstri(filename,".text");
    if(p != NULL)
        return 3;
    p = strstri(filename,".doc");
    if(p != NULL)
        return 3;
    //type 4
    p = strstri(filename,".php");
    if(p != NULL)
        return 4;
    p = strstri(filename,".php3");
    if(p != NULL)
        return 4;
    p = strstri(filename,".htm");
    if(p != NULL)
        return 4;
    p = strstri(filename,".js");
    if(p != NULL)
        return 4;
    //type 5
    p = strstri(filename,".pas");
    if(p != NULL)
        return 5;
    p = strstri(filename,".pb");
    if(p != NULL)
        return 5;
    p = strstri(filename,".vbs");
    if(p != NULL)
        return 5;
    p = strstri(filename,".vb");
    if(p != NULL)
        return 5;

    return 0;
}
Example #26
0
/*
 * Look in the "data" file for more info.  Called if the user typed in the
 * whole name (user_typed_name == TRUE), or we've found a possible match
 * with a character/glyph.
 */
static void checkfile(const char *inp, struct permonst *pm, boolean user_typed_name,
		      boolean without_asking)
{
    dlb *fp;
    char buf[BUFSZ], newstr[BUFSZ];
    char *ep, *dbase_str;
    long txt_offset;
    int chk_skip;
    boolean found_in_file = FALSE, skipping_entry = FALSE;

    fp = dlb_fopen(DATAFILE, "r");
    if (!fp) {
	pline("Cannot open data file!");
	return;
    }

    /* To prevent the need for entries in data.base like *ngel to account
     * for Angel and angel, make the lookup string the same for both
     * user_typed_name and picked name.
     */
    if (pm != NULL && !user_typed_name)
	dbase_str = strcpy(newstr, pm->mname);
    else dbase_str = strcpy(newstr, inp);
    lcase(dbase_str);

    if (!strncmp(dbase_str, "interior of ", 12))
	dbase_str += 12;
    if (!strncmp(dbase_str, "a ", 2))
	dbase_str += 2;
    else if (!strncmp(dbase_str, "an ", 3))
	dbase_str += 3;
    else if (!strncmp(dbase_str, "the ", 4))
	dbase_str += 4;
    if (!strncmp(dbase_str, "tame ", 5))
	dbase_str += 5;
    else if (!strncmp(dbase_str, "peaceful ", 9))
	dbase_str += 9;
    if (!strncmp(dbase_str, "invisible ", 10))
	dbase_str += 10;
    if (!strncmp(dbase_str, "statue of ", 10))
	dbase_str[6] = '\0';
    else if (!strncmp(dbase_str, "figurine of ", 12))
	dbase_str[8] = '\0';

    /* Make sure the name is non-empty. */
    if (*dbase_str) {
	/* adjust the input to remove " [seen" and "named " and convert to lower case */
	char *alt = 0;	/* alternate description */

	if ((ep = strstri(dbase_str, " [seen")) != 0)
	    *ep = '\0';

	if ((ep = strstri(dbase_str, " named ")) != 0)
	    alt = ep + 7;
	else
	    ep = strstri(dbase_str, " called ");
	if (!ep) ep = strstri(dbase_str, ", ");
	if (ep && ep > dbase_str) *ep = '\0';

	/*
	 * If the object is named, then the name is the alternate description;
	 * otherwise, the result of makesingular() applied to the name is. This
	 * isn't strictly optimal, but named objects of interest to the user
	 * will usually be found under their name, rather than under their
	 * object type, so looking for a singular form is pointless.
	 */

	if (!alt)
	    alt = makesingular(dbase_str);
	else
	    if (user_typed_name)
		lcase(alt);

	/* skip first record; read second */
	txt_offset = 0L;
	if (!dlb_fgets(buf, BUFSZ, fp) || !dlb_fgets(buf, BUFSZ, fp)) {
	    impossible("can't read 'data' file");
	    dlb_fclose(fp);
	    return;
	} else if (sscanf(buf, "%8lx\n", &txt_offset) < 1 || txt_offset <= 0)
	    goto bad_data_file;

	/* look for the appropriate entry */
	while (dlb_fgets(buf,BUFSZ,fp)) {
	    if (*buf == '.') break;  /* we passed last entry without success */

	    if (digit(*buf)) {
		/* a number indicates the end of current entry */
		skipping_entry = FALSE;
	    } else if (!skipping_entry) {
		if (!(ep = strchr(buf, '\n'))) goto bad_data_file;
		*ep = 0;
		/* if we match a key that begins with "~", skip this entry */
		chk_skip = (*buf == '~') ? 1 : 0;
		if (pmatch(&buf[chk_skip], dbase_str) ||
			(alt && pmatch(&buf[chk_skip], alt))) {
		    if (chk_skip) {
			skipping_entry = TRUE;
			continue;
		    } else {
			found_in_file = TRUE;
			break;
		    }
		}
	    }
	}
    }

    if (found_in_file) {
	long entry_offset;
	int  entry_count;
	int  i;

	/* skip over other possible matches for the info */
	do {
	    if (!dlb_fgets(buf, BUFSZ, fp))
		goto bad_data_file;
	} while (!digit(*buf));
	
	if (sscanf(buf, "%ld,%d\n", &entry_offset, &entry_count) < 2) {
bad_data_file:	impossible("'data' file in wrong format");
		dlb_fclose(fp);
		return;
	}

	if (user_typed_name || without_asking || yn("More info?") == 'y') {
	    struct menulist menu;

	    if (dlb_fseek(fp, txt_offset + entry_offset, SEEK_SET) < 0) {
		pline("? Seek error on 'data' file!");
		dlb_fclose(fp);
		return;
	    }
	    
	    init_menulist(&menu);
	    for (i = 0; i < entry_count; i++) {
		if (!dlb_fgets(buf, BUFSZ, fp))
		    goto bad_data_file;
		if ((ep = strchr(buf, '\n')) != 0)
		    *ep = 0;
		if (strchr(buf+1, '\t') != 0)
		    tabexpand(buf+1);
		add_menutext(&menu, buf+1);
	    }
	    
	    display_menu(menu.items, menu.icount, NULL, FALSE, NULL);
	    free(menu.items);
	}
    } else if (user_typed_name)
	pline("I don't have any information on those things.");

    dlb_fclose(fp);
}
Example #27
0
/* exclude_cookie is a hack used because we sometimes want to get rumors in a
 * context where messages such as "You swallowed the fortune!" that refer to
 * cookies should not appear.  This has no effect for true rumors since none
 * of them contain such references anyway.
 */
const char *
getrumor(int truth,     /* 1=true, -1=false, 0=either 3=potter (truier than true)*/
         boolean exclude_cookie, int *truth_out, enum rng rng)
{
    dlb *rumors;
    int tidbit, beginning;
    char *endp;
    int ltruth = 0;
    char line[BUFSZ]; /* for fgets */
    const char *rv = "";

    /* If this happens, we couldn't open the RUMORFILE. So synthesize a
       rumor just for the occasion :-) */
    if (true_rumor_size < 0L)
        return "";

    rumors = dlb_fopen(RUMORFILE, "r");

    if (rumors) {
        int count = 0;
        int adjtruth;

        do {
            if (true_rumor_size == 0L) {        /* if this is 1st outrumor() */
                init_rumors(rumors);
                if (true_rumor_size < 0L)       /* init failed */
                    return msgprintf("Error reading \"%.80s\".", RUMORFILE);
            }
            /* 
             *      input:      3    1    0   -1
             *       rn2 \ +1  4=P  2=T  1=T  0=F
             *       adj./ +0  3=P  1=T  0=F -1=F
             */
            switch (adjtruth = truth + rn2_on_rng(2, rng)) {
            case 4:    /* (might let a bogus input arg sneak thru) */
            case 3:
                beginning = potter_rumor_start;
                tidbit = rn2_on_rng(potter_rumor_size, rng);
                break;
            case 1:
                beginning = true_rumor_start;
                tidbit = rn2_on_rng(true_rumor_size, rng);
                break;
            case 0:    /* once here, 0 => false rather than "either" */
            case -1:
                beginning = false_rumor_start;
                tidbit = rn2_on_rng(false_rumor_size, rng);
                break;
            default:
                impossible("strange truth value for rumor");
                if (truth_out)
                    *truth_out = 0;
                return "Oops...";
            }
            dlb_fseek(rumors, beginning + tidbit, SEEK_SET);
            dlb_fgets(line, sizeof line, rumors);
            if (!dlb_fgets(line, sizeof line, rumors) ||
                ((adjtruth == 2 || adjtruth == 1) && dlb_ftell(rumors) > true_rumor_end)) {
                /* reached end of rumors -- go back to beginning */
                dlb_fseek(rumors, beginning, SEEK_SET);
                dlb_fgets(line, sizeof line, rumors);
            }
            else if (!dlb_fgets(line, sizeof line, rumors) ||
                        (adjtruth < 1 && dlb_ftell(rumors) > false_rumor_end)){
                dlb_fseek(rumors, beginning, SEEK_SET);
                dlb_fgets(line, sizeof line, rumors);
            }
            if ((endp = strchr(line, '\n')) != 0)
                *endp = 0;
            char decrypted_line[strlen(line) + 1];
            xcrypt(line, decrypted_line);
            rv = msg_from_string(decrypted_line);
        } while (count++ < 50 && exclude_cookie &&
                 (strstri(rv, "fortune") || strstri(rv, "pity")));
        dlb_fclose(rumors);
        if (count >= 50)
            impossible("Can't find non-cookie rumor?");
        else
            ltruth = (adjtruth > 0) ? 1 : -1;
    } else {
        pline("Can't open rumors file!");
        true_rumor_size = -1;   /* don't try to open it again */
        if (truth_out)
            *truth_out = 0;
    }
    if (truth_out)
        *truth_out = ltruth;
    return rv;
}
Example #28
0
int
dowrite(struct obj *pen, const struct nh_cmd_arg *arg)
{
    struct obj *paper;
    const char *namebuf, *nm, *bp;
    struct obj *new_obj;
    int basecost, actualcost;
    int curseval;
    const char *qbuf;
    int first, last, i;
    boolean by_descr = FALSE, by_name = FALSE;
    const char *typeword;

    if (nohands(youmonst.data)) {
        pline(msgc_cancelled, "You need hands to be able to write!");
        return 0;
    } else if (slippery_fingers(&youmonst)) {
        pline(msgc_cancelled1, "%s from your %s.", Tobjnam(pen, "slip"),
              makeplural(body_part(FINGER)));
        unwield_silently(pen);
        dropx(pen);
        return 1;
    }

    /* get paper to write on */
    paper = getargobj(arg, write_on, "write on");
    if (!paper)
        return 0;

    typeword = (paper->oclass == SPBOOK_CLASS) ? "spellbook" : "scroll";
    if (Blind && !paper->dknown) {
        pline(msgc_cancelled1,
              "You don't know if that %s is blank or not!", typeword);
        return 1;
    }
    paper->dknown = 1;
    if (paper->otyp != SCR_BLANK_PAPER && paper->otyp != SPE_BLANK_PAPER) {
        pline(msgc_cancelled1, "That %s is not blank!", typeword);
        exercise(A_WIS, FALSE);
        return 1;
    }

    /* what to write */
    qbuf = msgprintf("What type of %s do you want to write?", typeword);
    namebuf = getarglin(arg, qbuf);
    namebuf = msgmungspaces(namebuf);   /* remove any excess whitespace */
    if (namebuf[0] == '\033' || !namebuf[0])
        return 1;
    nm = namebuf;
    if (!strncmpi(nm, "scroll ", 7))
        nm += 7;
    else if (!strncmpi(nm, "spellbook ", 10))
        nm += 10;
    if (!strncmpi(nm, "of ", 3))
        nm += 3;

    if ((bp = strstri(nm, " armour")) != 0)
        nm = msgcat_many(msgchop(nm, bp-nm), " armor", bp+7, NULL);

    first = bases[(int)paper->oclass];
    last = bases[(int)paper->oclass + 1] - 1;
    for (i = first; i <= last; i++) {
        /* extra shufflable descr not representing a real object */
        if (!OBJ_NAME(objects[i]))
            continue;

        if (!strcmpi(OBJ_NAME(objects[i]), nm))
            goto found;
        if (!strcmpi(OBJ_DESCR(objects[i]), nm)) {
            by_descr = TRUE;
            goto found;
        }
        if (objects[i].oc_uname &&
            !strcmpi(objects[i].oc_uname, nm)) {
            by_name = TRUE;
            goto found;
        }
    }

    pline(msgc_cancelled1, "There is no such %s!", typeword);
    return 1;
found:

    if (i == SCR_BLANK_PAPER || i == SPE_BLANK_PAPER) {
        pline(msgc_cancelled1, "You can't write that!");
        pline(msgc_cancelled1, "It's obscene!");
        return 1;
    } else if (i == SPE_BOOK_OF_THE_DEAD) {
        pline(msgc_cancelled1, "No mere dungeon adventurer could write that.");
        return 1;
    } else if ((by_descr || by_name) && paper->oclass == SPBOOK_CLASS &&
               !objects[i].oc_name_known) {
        /* can't write unknown spellbooks by description */
        pline(msgc_cancelled1,
              "Unfortunately you don't have enough information to go on.");
        return 1;
    }

    /* KMH, conduct */
    break_conduct(conduct_illiterate);

    new_obj = mksobj(level, i, FALSE, FALSE, rng_main);
    new_obj->bknown = (paper->bknown && pen->bknown);

    /* shk imposes a flat rate per use, not based on actual charges used */
    check_unpaid(pen);

    /* see if there's enough ink */
    basecost = cost(new_obj);
    if (pen->spe < basecost / 2) {
        pline(msgc_failcurse, "Your marker is too dry to write that!");
        obfree(new_obj, NULL);
        return 1;
    }

    /* we're really going to write now, so calculate cost

       no custom RNG used: too much influence from player actions */
    actualcost = rn1(basecost / 2, basecost / 2);
    curseval = bcsign(pen) + bcsign(paper);
    exercise(A_WIS, TRUE);
    /* dry out marker */
    if (pen->spe < actualcost) {
        pen->spe = 0;
        pline(msgc_itemloss, "Your marker dries out!");
        /* scrolls disappear, spellbooks don't */
        if (paper->oclass == SPBOOK_CLASS) {
            pline(msgc_failcurse,
                  "The spellbook is left unfinished and your writing fades.");
            update_inventory(); /* pen charges */
        } else {
            pline(msgc_failcurse, "The scroll is now useless and disappears!");
            useup(paper);
        }
        obfree(new_obj, NULL);
        return 1;
    }
    pen->spe -= actualcost;

    /* can't write if we don't know it - unless we're lucky */
    if (!(objects[new_obj->otyp].oc_name_known) &&
        (rnl(Role_if(PM_WIZARD) ? 3 : 15))) {
        pline(msgc_failrandom, "You %s to write that!",
              by_descr ? "fail" : "don't know how");
        /* scrolls disappear, spellbooks don't */
        if (paper->oclass == SPBOOK_CLASS) {
            pline_implied(msgc_failrandom,
                          "You write in your best handwriting:  "
                          "\"My Diary\", but it quickly fades.");
            update_inventory(); /* pen charges */
        } else {
            const char *written;
            if (by_descr) {
                written = OBJ_DESCR(objects[new_obj->otyp]);
                written = eroded_text(written,
                                      (6 + MAXULEV - youmonst.m_lev) / 6, 0);
            } else
                written = msgprintf("%s was here!", u.uplname);
            pline_implied(msgc_failrandom,
                          "You write \"%s\" and the scroll disappears.",
                          written);
            useup(paper);
        }
        obfree(new_obj, NULL);
        return 1;
    }

    /* useup old scroll / spellbook */
    useup(paper);

    /* success */
    if (new_obj->oclass == SPBOOK_CLASS) {
        /* acknowledge the change in the object's description... */
        pline(msgc_actionok, "The spellbook warps strangely, then turns %s.",
              OBJ_DESCR(objects[new_obj->otyp]));
    }
    new_obj->blessed = (curseval > 0);
    new_obj->cursed = (curseval < 0);
    hold_another_object(new_obj, "Oops!  %s out of your grasp!",
                        The(aobjnam(new_obj, "slip")), NULL);
    return 1;
}
Example #29
0
/* exclude_cookie is a hack used because we sometimes want to get rumors in a
 * context where messages such as "You swallowed the fortune!" that refer to
 * cookies should not appear.  This has no effect for true rumors since none
 * of them contain such references anyway.
 */
char *
getrumor(int truth,     /* 1=true, -1=false, 0=either */
         char *rumor_buf, boolean exclude_cookie, int *truth_out)
{
    dlb *rumors;
    int tidbit, beginning;
    char *endp, line[BUFSZ], xbuf[BUFSZ];
    int ltruth = 0;

    rumor_buf[0] = '\0';
    if (true_rumor_size < 0L)   /* we couldn't open RUMORFILE */
        return rumor_buf;

    rumors = dlb_fopen(RUMORFILE, "r");

    if (rumors) {
        int count = 0;
        int adjtruth;

        do {
            rumor_buf[0] = '\0';
            if (true_rumor_size == 0L) {        /* if this is 1st outrumor() */
                init_rumors(rumors);
                if (true_rumor_size < 0L) {     /* init failed */
                    sprintf(rumor_buf, "Error reading \"%.80s\".", RUMORFILE);
                    return rumor_buf;
                }
            }
            /* 
             *      input:      1    0   -1
             *       rn2 \ +1  2=T  1=T  0=F
             *       adj./ +0  1=T  0=F -1=F
             */
            switch (adjtruth = truth + rn2(2)) {
            case 2:    /* (might let a bogus input arg sneak thru) */
            case 1:
                beginning = true_rumor_start;
                tidbit = mt_random() % true_rumor_size;
                break;
            case 0:    /* once here, 0 => false rather than "either" */
            case -1:
                beginning = false_rumor_start;
                tidbit = mt_random() % false_rumor_size;
                break;
            default:
                impossible("strange truth value for rumor");
                return strcpy(rumor_buf, "Oops...");
            }
            dlb_fseek(rumors, beginning + tidbit, SEEK_SET);
            dlb_fgets(line, sizeof line, rumors);
            if (!dlb_fgets(line, sizeof line, rumors) ||
                (adjtruth > 0 && dlb_ftell(rumors) > true_rumor_end)) {
                /* reached end of rumors -- go back to beginning */
                dlb_fseek(rumors, beginning, SEEK_SET);
                dlb_fgets(line, sizeof line, rumors);
            }
            if ((endp = strchr(line, '\n')) != 0)
                *endp = 0;
            strcat(rumor_buf, xcrypt(line, xbuf));
        } while (count++ < 50 && exclude_cookie &&
                 (strstri(rumor_buf, "fortune") || strstri(rumor_buf, "pity")));
        dlb_fclose(rumors);
        if (count >= 50)
            impossible("Can't find non-cookie rumor?");
        else
            ltruth = (adjtruth > 0) ? 1 : -1;
    } else {
        pline("Can't open rumors file!");
        true_rumor_size = -1;   /* don't try to open it again */
        if (truth_out)
            *truth_out = 0;
    }
    if (truth_out)
        *truth_out = ltruth;
    return rumor_buf;
}
Example #30
0
int name_to_mon(const char *in_str)
{
	/* Be careful.  We must check the entire string in case it was
	 * something such as "ettin zombie corpse".  The calling routine
	 * doesn't know about the "corpse" until the monster name has
	 * already been taken off the front, so we have to be able to
	 * read the name with extraneous stuff such as "corpse" stuck on
	 * the end.
	 * This causes a problem for names which prefix other names such
	 * as "ettin" on "ettin zombie".  In this case we want the _longest_
	 * name which exists.
	 * This also permits plurals created by adding suffixes such as 's'
	 * or 'es'.  Other plurals must still be handled explicitly.
	 */
	int i;
	int mntmp = NON_PM;
	char *s, *str, *term;
	char buf[BUFSZ];
	int len, slen;

	str = strcpy(buf, in_str);

	if (!strncmp(str, "a ", 2)) str += 2;
	else if (!strncmp(str, "an ", 3)) str += 3;

	slen = strlen(str);
	term = str + slen;

	if ((s = strstri(str, "vortices")) != 0)
	    strcpy(s+4, "ex");
	/* be careful with "ies"; "priest", "zombies" */
	else if (slen > 3 && !strcmpi(term-3, "ies") &&
		    (slen < 7 || strcmpi(term-7, "zombies")))
	    strcpy(term-3, "y");
	/* luckily no monster names end in fe or ve with ves plurals */
	else if (slen > 3 && !strcmpi(term-3, "ves"))
	    strcpy(term-3, "f");

	slen = strlen(str); /* length possibly needs recomputing */

    {
	static const struct alt_spl { const char* name; short pm_val; }
	    names[] = {
	    /* Alternate spellings */
		{ "grey dragon",	PM_GRAY_DRAGON },
		{ "baby grey dragon",	PM_BABY_GRAY_DRAGON },
		{ "grey unicorn",	PM_GRAY_UNICORN },
		{ "grey ooze",		PM_GRAY_OOZE },
		{ "gray-elf",		PM_GREY_ELF },
	    /* Hyphenated names */
		{ "ki rin",		PM_KI_RIN },
		{ "uruk hai",		PM_URUK_HAI },
		{ "orc captain",	PM_ORC_CAPTAIN },
		{ "woodland elf",	PM_WOODLAND_ELF },
		{ "green elf",		PM_GREEN_ELF },
		{ "grey elf",		PM_GREY_ELF },
		{ "gray elf",		PM_GREY_ELF },
		{ "elf lord",		PM_ELF_LORD },
		{ "olog hai",		PM_OLOG_HAI },
		{ "arch lich",		PM_ARCH_LICH },
	    /* Some irregular plurals */
		{ "incubi",		PM_INCUBUS },
		{ "succubi",		PM_SUCCUBUS },
		{ "violet fungi",	PM_VIOLET_FUNGUS },
		{ "homunculi",		PM_HOMUNCULUS },
		{ "baluchitheria",	PM_BALUCHITHERIUM },
		{ "lurkers above",	PM_LURKER_ABOVE },
		{ "cavemen",		PM_CAVEMAN },
		{ "cavewomen",		PM_CAVEWOMAN },
		{ "djinn",		PM_DJINNI },
		{ "mumakil",		PM_MUMAK },
		{ "erinyes",		PM_ERINYS },
	    /* falsely caught by -ves check above */
		{ "master of thief",	PM_MASTER_OF_THIEVES },
	    /* end of list */
		{ 0, 0 }
	};
	const struct alt_spl *namep;

	for (namep = names; namep->name; namep++)
	    if (!strncmpi(str, namep->name, (int)strlen(namep->name)))
		return namep->pm_val;
    }

	for (len = 0, i = LOW_PM; i < NUMMONS; i++) {
	    int m_i_len = strlen(mons[i].mname);
	    if (m_i_len > len && !strncmpi(mons[i].mname, str, m_i_len)) {
		if (m_i_len == slen) return i;	/* exact match */
		else if (slen > m_i_len &&
			(str[m_i_len] == ' ' ||
			 !strcmpi(&str[m_i_len], "s") ||
			 !strncmpi(&str[m_i_len], "s ", 2) ||
			 !strcmpi(&str[m_i_len], "'") ||
			 !strncmpi(&str[m_i_len], "' ", 2) ||
			 !strcmpi(&str[m_i_len], "'s") ||
			 !strncmpi(&str[m_i_len], "'s ", 3) ||
			 !strcmpi(&str[m_i_len], "es") ||
			 !strncmpi(&str[m_i_len], "es ", 3))) {
		    mntmp = i;
		    len = m_i_len;
		}
	    }
	}
	if (mntmp == NON_PM) mntmp = title_to_mon(str, NULL, NULL);
	return mntmp;
}