/** * Checks for full set * @return is the set full? */ bool IsFull() { return this->n == lengthof(data); }
int main(int argc, char *argv[]) { static struct option long_options[] = { {"list", no_argument, NULL, 'l'}, {"host", required_argument, NULL, 'h'}, {"port", required_argument, NULL, 'p'}, {"username", required_argument, NULL, 'U'}, {"no-password", no_argument, NULL, 'w'}, {"password", no_argument, NULL, 'W'}, {"dbname", required_argument, NULL, 'd'}, {"echo", no_argument, NULL, 'e'}, {NULL, 0, NULL, 0} }; const char *progname; int optindex; int c; bool listlangs = false; const char *dbname = NULL; char *host = NULL; char *port = NULL; char *username = NULL; enum trivalue prompt_password = TRI_DEFAULT; bool echo = false; char *langname = NULL; char *p; PQExpBufferData sql; PGconn *conn; PGresult *result; progname = get_progname(argv[0]); set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pgscripts")); handle_help_version_opts(argc, argv, "droplang", help); while ((c = getopt_long(argc, argv, "lh:p:U:wWd:e", long_options, &optindex)) != -1) { switch (c) { case 'l': listlangs = true; break; case 'h': host = pg_strdup(optarg); break; case 'p': port = pg_strdup(optarg); break; case 'U': username = pg_strdup(optarg); break; case 'w': prompt_password = TRI_NO; break; case 'W': prompt_password = TRI_YES; break; case 'd': dbname = pg_strdup(optarg); break; case 'e': echo = true; break; default: fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } } /* * We set dbname from positional arguments if it is not already set by * option arguments -d. If not doing listlangs, positional dbname must * follow positional langname. */ if (argc - optind > 0) { if (listlangs) { if (dbname == NULL) dbname = argv[optind++]; } else { langname = argv[optind++]; if (argc - optind > 0 && dbname == NULL) dbname = argv[optind++]; } } if (argc - optind > 0) { fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } if (dbname == NULL) { if (getenv("PGDATABASE")) dbname = getenv("PGDATABASE"); else if (getenv("PGUSER")) dbname = getenv("PGUSER"); else dbname = get_user_name_or_exit(progname); } initPQExpBuffer(&sql); /* * List option */ if (listlangs) { printQueryOpt popt; static const bool translate_columns[] = {false, true}; conn = connectDatabase(dbname, host, port, username, prompt_password, progname, echo, false, false); printfPQExpBuffer(&sql, "SELECT lanname as \"%s\", " "(CASE WHEN lanpltrusted THEN '%s' ELSE '%s' END) as \"%s\" " "FROM pg_catalog.pg_language WHERE lanispl;", gettext_noop("Name"), gettext_noop("yes"), gettext_noop("no"), gettext_noop("Trusted?")); result = executeQuery(conn, sql.data, progname, echo); memset(&popt, 0, sizeof(popt)); popt.topt.format = PRINT_ALIGNED; popt.topt.border = 1; popt.topt.start_table = true; popt.topt.stop_table = true; popt.topt.encoding = PQclientEncoding(conn); popt.title = _("Procedural Languages"); popt.translate_header = true; popt.translate_columns = translate_columns; popt.n_translate_columns = lengthof(translate_columns); printQuery(result, &popt, stdout, false, NULL); PQfinish(conn); exit(0); } if (langname == NULL) { fprintf(stderr, _("%s: missing required argument language name\n"), progname); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } /* lower case language name */ for (p = langname; *p; p++) if (*p >= 'A' && *p <= 'Z') *p += ('a' - 'A'); conn = connectDatabase(dbname, host, port, username, prompt_password, progname, echo, false, false); /* * Make sure the language is installed */ printfPQExpBuffer(&sql, "SELECT oid " "FROM pg_language WHERE lanname = '%s' AND lanispl;", langname); result = executeQuery(conn, sql.data, progname, echo); if (PQntuples(result) == 0) { fprintf(stderr, _("%s: language \"%s\" is not installed in " "database \"%s\"\n"), progname, langname, PQdb(conn)); PQfinish(conn); exit(1); } PQclear(result); /* * Attempt to drop the language. We do not use CASCADE, so that the drop * will fail if there are any functions in the language. */ printfPQExpBuffer(&sql, "DROP EXTENSION \"%s\";", langname); if (echo) printf("%s\n", sql.data); result = PQexec(conn, sql.data); if (PQresultStatus(result) != PGRES_COMMAND_OK) { fprintf(stderr, _("%s: language removal failed: %s"), progname, PQerrorMessage(conn)); PQfinish(conn); exit(1); } PQclear(result); PQfinish(conn); exit(0); }
NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN), NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_TOOLBAR_AIRCRAFT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS), NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN), EndContainer(), NWidget(NWID_HORIZONTAL), NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_AT_AIRPORT), SetFill(0, 1), SetMinimalSize(42, 22), SetDataTip(SPR_IMG_AIRPORT, STR_TOOLBAR_AIRCRAFT_BUILD_AIRPORT_TOOLTIP), NWidget(WWT_PANEL, COLOUR_DARK_GREEN), SetMinimalSize(4, 22), SetFill(1, 1), EndContainer(), NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_AT_DEMOLISH), SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_DYNAMITE, STR_TOOLTIP_DEMOLISH_BUILDINGS_ETC), EndContainer(), }; static WindowDesc _air_toolbar_desc( WDP_ALIGN_TOOLBAR, "toolbar_air", 0, 0, WC_BUILD_TOOLBAR, WC_NONE, WDF_CONSTRUCTION, _nested_air_toolbar_widgets, lengthof(_nested_air_toolbar_widgets), &BuildAirToolbarWindow::hotkeys ); /** * Open the build airport toolbar window * * If the terraform toolbar is linked to the toolbar, that window is also opened. * * @return newly opened airport toolbar, or NULL if the toolbar could not be opened. */ Window *ShowBuildAirToolbar() { if (!Company::IsValidID(_local_company)) return NULL; DeleteToolbarLinkedWindows();
NWidget(NWID_SPACER), SetFill(1, 0), NWidget(WWT_PUSHTXTBTN, COLOUR_ORANGE, WID_SGI_EXIT), SetMinimalSize(128, 12), SetDataTip(STR_INTRO_QUIT, STR_INTRO_TOOLTIP_QUIT), NWidget(NWID_SPACER), SetFill(1, 0), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(0, 8), EndContainer(), }; static WindowDesc _select_game_desc( WDP_CENTER, NULL, 0, 0, WC_SELECT_GAME, WC_NONE, 0, _nested_select_game_widgets, lengthof(_nested_select_game_widgets) ); void ShowSelectGameWindow() { new SelectGameWindow(&_select_game_desc); } static void AskExitGameCallback(Window *w, bool confirmed) { if (confirmed) _exit_game = true; } void AskExitGame() { #if defined(_WIN32)
void FiosGetDrives() { uint disk, disk2, save, total; #ifndef __INNOTEK_LIBC__ _dos_getdrive(&save); // save original drive #else save = _getdrive(); // save original drive char wd[MAX_PATH]; getcwd(wd, MAX_PATH); total = 'z'; #endif /* get an available drive letter */ #ifndef __INNOTEK_LIBC__ for (disk = 1;; disk++) { _dos_setdrive(disk, &total); #else for (disk = 'A';; disk++) { _chdrive(disk); #endif if (disk >= total) break; #ifndef __INNOTEK_LIBC__ _dos_getdrive(&disk2); #else disk2 = _getdrive(); #endif if (disk == disk2) { FiosItem *fios = _fios_items.Append(); fios->type = FIOS_TYPE_DRIVE; fios->mtime = 0; #ifndef __INNOTEK_LIBC__ snprintf(fios->name, lengthof(fios->name), "%c:", 'A' + disk - 1); #else snprintf(fios->name, lengthof(fios->name), "%c:", disk); #endif strecpy(fios->title, fios->name, lastof(fios->title)); } } /* Restore the original drive */ #ifndef __INNOTEK_LIBC__ _dos_setdrive(save, &total); #else chdir(wd); #endif } bool FiosGetDiskFreeSpace(const char *path, uint64 *tot) { #ifndef __INNOTEK_LIBC__ struct diskfree_t free; char drive = path[0] - 'A' + 1; if (tot != NULL && _getdiskfree(drive, &free) == 0) { *tot = free.avail_clusters * free.sectors_per_cluster * free.bytes_per_sector; return true; } return false; #else uint64 free = 0; #ifdef HAS_STATVFS { struct statvfs s; if (statvfs(path, &s) != 0) return false; free = (uint64)s.f_frsize * s.f_bavail; } #endif if (tot != NULL) *tot = free; return true; #endif } bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb) { char filename[MAX_PATH]; snprintf(filename, lengthof(filename), "%s" PATHSEP "%s", path, ent->d_name); return stat(filename, sb) == 0; }
bool CChannelMenu::Create(const CChannelList *pChannelList,int CurChannel,UINT Command, HMENU hmenu,HWND hwnd,unsigned int Flags,int MaxRows) { Destroy(); if (pChannelList==NULL) return false; m_ChannelList=*pChannelList; m_CurChannel=CurChannel; m_FirstCommand=Command; m_LastCommand=Command+m_ChannelList.NumChannels()-1; m_Flags=Flags; m_hwnd=hwnd; m_MenuPainter.Initialize(hwnd); m_MenuPainter.GetItemMargins(&m_Margins); if (m_Margins.cxLeftWidth<2) m_Margins.cxLeftWidth=2; if (m_Margins.cxRightWidth<2) m_Margins.cxRightWidth=2; HDC hdc=::GetDC(hwnd); CreateFont(hdc); HFONT hfontOld=DrawUtil::SelectObject(hdc,m_Font); CEpgProgramList &EpgProgramList=GetAppClass().EpgProgramList; const bool fCurServices=(Flags & FLAG_CURSERVICES)!=0; SYSTEMTIME st; if (!fCurServices) GetBaseTime(&st); m_ChannelNameWidth=0; m_EventNameWidth=0; if (hmenu==NULL) { m_hmenu=::CreatePopupMenu(); } else { m_hmenu=hmenu; m_Flags|=FLAG_SHARED; ClearMenu(hmenu); } MENUITEMINFO mii; mii.cbSize=sizeof(MENUITEMINFO); mii.fMask=MIIM_FTYPE | MIIM_STATE | MIIM_ID | MIIM_DATA; int PrevSpace=-1; for (int i=0,j=0;i<m_ChannelList.NumChannels();i++) { const CChannelInfo *pChInfo=m_ChannelList.GetChannelInfo(i); if (!pChInfo->IsEnabled()) continue; TCHAR szText[256]; RECT rc; if (i==CurChannel) DrawUtil::SelectObject(hdc,m_FontCurrent); StdUtil::snprintf(szText,lengthof(szText),TEXT("%d: %s"), pChInfo->GetChannelNo(),pChInfo->GetName()); /* m_MenuPainter.GetItemTextExtent(hdc,0,szText,&rc, DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX); */ ::SetRectEmpty(&rc); ::DrawText(hdc,szText,-1,&rc,DT_SINGLELINE | DT_NOPREFIX | DT_CALCRECT); if (rc.right>m_ChannelNameWidth) m_ChannelNameWidth=rc.right; mii.wID=m_FirstCommand+i; mii.fType=MFT_OWNERDRAW; if ((MaxRows>0 && j==MaxRows) || ((Flags&FLAG_SPACEBREAK)!=0 && pChInfo->GetSpace()!=PrevSpace)) { mii.fType|=MFT_MENUBREAK; j=0; } mii.fState=MFS_ENABLED; if (i==CurChannel) mii.fState|=MFS_CHECKED; CChannelMenuItem *pItem=new CChannelMenuItem(pChInfo); mii.dwItemData=reinterpret_cast<ULONG_PTR>(pItem); if ((Flags&FLAG_SHOWEVENTINFO)!=0) { const CEventInfoData *pEventInfo= pItem->GetEventInfo(&EpgProgramList,0,fCurServices?NULL:&st); if (pEventInfo!=NULL) { GetEventText(pEventInfo,szText,lengthof(szText)); /* m_MenuPainter.GetItemTextExtent(hdc,0,szText,&rc, DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX); */ ::SetRectEmpty(&rc); ::DrawText(hdc,szText,-1,&rc,DT_SINGLELINE | DT_NOPREFIX | DT_CALCRECT); if (rc.right>m_EventNameWidth) m_EventNameWidth=rc.right; } } ::InsertMenuItem(m_hmenu,i,TRUE,&mii); if (i==CurChannel) DrawUtil::SelectObject(hdc,m_Font); PrevSpace=pChInfo->GetSpace(); j++; } ::SelectObject(hdc,hfontOld); ::ReleaseDC(hwnd,hdc); if ((Flags&FLAG_SHOWTOOLTIP)!=0) { m_Tooltip.Create(hwnd); m_Tooltip.SetMaxWidth(480); m_Tooltip.SetPopDelay(30*1000); m_Tooltip.AddTrackingTip(1,TEXT("")); } if ((Flags & FLAG_SHOWLOGO)!=0) { if (!m_LogoFrameImage.IsCreated()) { m_LogoFrameImage.Load(GetAppClass().GetResourceInstance(), MAKEINTRESOURCE(IDB_LOGOFRAME),LR_CREATEDIBSECTION); } } return true; }
bool CChannelMenu::OnDrawItem(HWND hwnd,WPARAM wParam,LPARAM lParam) { LPDRAWITEMSTRUCT pdis=reinterpret_cast<LPDRAWITEMSTRUCT>(lParam); if (m_hmenu==NULL || hwnd!=m_hwnd || pdis->CtlType!=ODT_MENU || pdis->itemID<m_FirstCommand || pdis->itemID>m_LastCommand) return false; const CChannelMenuItem *pItem=reinterpret_cast<CChannelMenuItem*>(pdis->itemData); const CChannelInfo *pChInfo=pItem->GetChannelInfo(); TCHAR szText[256]; m_MenuPainter.DrawItemBackground(pdis->hDC,pdis->rcItem,pdis->itemState); COLORREF crTextColor=m_MenuPainter.GetTextColor(pdis->itemState); HFONT hfontOld=DrawUtil::SelectObject(pdis->hDC, (pdis->itemState&ODS_CHECKED)==0?m_Font:m_FontCurrent); int OldBkMode=::SetBkMode(pdis->hDC,TRANSPARENT); COLORREF crOldTextColor=::SetTextColor(pdis->hDC,crTextColor); RECT rc; rc.left=pdis->rcItem.left+m_Margins.cxLeftWidth; rc.top=pdis->rcItem.top+m_Margins.cyTopHeight; rc.bottom=pdis->rcItem.bottom-m_Margins.cyBottomHeight; if ((m_Flags&FLAG_SHOWLOGO)!=0) { HBITMAP hbmLogo=GetAppClass().LogoManager.GetAssociatedLogoBitmap( pChInfo->GetNetworkID(),pChInfo->GetServiceID(),CLogoManager::LOGOTYPE_SMALL); if (hbmLogo!=NULL) { DrawUtil::CMemoryDC MemoryDC(pdis->hDC); MemoryDC.SetBitmap(hbmLogo); int y=rc.top+((rc.bottom-rc.top)-m_LogoHeight)/2; BITMAP bm; ::GetObject(hbmLogo,sizeof(bm),&bm); MemoryDC.DrawStretch(pdis->hDC,rc.left+1,y+1,m_LogoWidth-3,m_LogoHeight-3, 0,0,bm.bmWidth,bm.bmHeight); MemoryDC.SetBitmap(m_LogoFrameImage); MemoryDC.DrawAlpha(pdis->hDC,rc.left,y,0,0,m_LogoWidth,m_LogoHeight); } rc.left+=m_LogoWidth+m_MenuLogoMargin; } rc.right=rc.left+m_ChannelNameWidth; StdUtil::snprintf(szText,lengthof(szText),TEXT("%d: %s"), pChInfo->GetChannelNo(),pChInfo->GetName()); ::DrawText(pdis->hDC,szText,-1,&rc, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX); if ((m_Flags&FLAG_SHOWEVENTINFO)!=0) { const CEventInfoData *pEventInfo=pItem->GetEventInfo(0); if (pEventInfo!=NULL) { int Length=GetEventText(pEventInfo,szText,lengthof(szText)); rc.left=rc.right+m_TextHeight; rc.right=pdis->rcItem.right-m_Margins.cxRightWidth; ::DrawText(pdis->hDC,szText,Length,&rc, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX); } } ::SetTextColor(pdis->hDC,crOldTextColor); ::SetBkMode(pdis->hDC,OldBkMode); ::SelectObject(pdis->hDC,hfontOld); return true; }
static os_result os_signalHandlerInit( os_signalHandler _this) { os_result result = os_resultSuccess; os_sigaction action; os_sigset block_all_sigset, old_sigset; int i, r; if (_this == NULL) { result = os_resultFail; } _this->exitRequestCallback = (os_signalHandlerExitRequestCallback)0; _this->exceptionCallback = (os_signalHandlerExceptionCallback)0; if(isSignallingSafe(1)) { /* Initialise the exceptionsMask */ sigemptyset(&exceptionsMask); for(i = 0; i < lengthof(exceptions); i++) { sigaddset(&exceptionsMask, exceptions[i]); } /* Initialise the quitsMask */ sigemptyset(&quitsMask); for(i = 0; i < lengthof(quits); i++) { sigaddset(&quitsMask, quits[i]); } /* create signal handling pipes */ if (result == os_resultSuccess) { r = pipe(_this->pipeIn); if (r<0) { OS_REPORT_1(OS_ERROR, "os_signalHandlerInit", 0, "pipe(_this->pipeIn) failed, result = %d", r); result = os_resultFail; } else { r = fcntl(_this->pipeIn[0], F_SETFD, 1); if (r<0) { OS_REPORT_1(OS_WARNING, "os_signalHandlerInit", 0, "fcntl(_this->pipeIn[0]) failed, result = %d", r); assert(OS_FALSE); } r = fcntl(_this->pipeIn[1], F_SETFD, 1); if (r<0) { OS_REPORT_1(OS_WARNING, "os_signalHandlerInit", 0, "fcntl(_this->pipeIn[1]) failed, result = %d", r); assert(OS_FALSE); } } } if (result == os_resultSuccess) { r = pipe(_this->pipeOut); if (r<0) { OS_REPORT_1(OS_ERROR, "os_signalHandlerInit", 1, "pipe(_this->pipeOut) failed, result = %d", r); result = os_resultFail; } else { r = fcntl(_this->pipeOut[0], F_SETFD, 1); if (r<0) { OS_REPORT_1(OS_WARNING, "os_signalHandlerInit", 0, "fcntl(_this->pipeOut[0]) failed, result = %d", r); assert(OS_FALSE); } r = fcntl(_this->pipeOut[1], F_SETFD, 1); if (r<0) { OS_REPORT_1(OS_WARNING, "os_signalHandlerInit", 0, "fcntl(_this->pipeOut[1]) failed, result = %d", r); assert(OS_FALSE); } } } /* Block all signals */ if (result == os_resultSuccess) { result = os_sigsetFill(&block_all_sigset); if (result != os_resultSuccess) { OS_REPORT_1(OS_ERROR, "os_signalHandlerInit", 0, "os_sigsetFill(&block_all_sigset) failed, result = %d", r); assert(OS_FALSE); } else { result = os_sigThreadSetMask(&block_all_sigset, &old_sigset); if (result != os_resultSuccess) { OS_REPORT_3(OS_ERROR, "os_signalHandlerInit", 0, "os_sigThreadSetMask(0x%x, 0x%x) failed, result = %d", &block_all_sigset, &old_sigset, r); assert(OS_FALSE); } } } /* Setup signal handler thread. */ if (result == os_resultSuccess) { os_threadAttr thrAttr; result = os_threadAttrInit(&thrAttr); if (result != os_resultSuccess) { OS_REPORT_2(OS_ERROR, "os_signalHandlerInit", 0, "pthread_attr_init(0x%x) failed, result = %d", &thrAttr, r); assert(OS_FALSE); } else { thrAttr.stackSize = 4*1024*1024; /* 4 MB */ result = os_threadCreate(&_this->threadId, "signalHandler", &thrAttr, signalHandlerThread, (void*)_this); if (result != os_resultSuccess) { OS_REPORT_4(OS_ERROR, "os_signalHandlerInit", 0, "os_threadCreate(0x%x, 0x%x,0x%x,0) failed, result = %d", &_this->threadId, &thrAttr, signalHandlerThread, result); assert(OS_FALSE); } } } /* Reset signal mask to original value. */ if (result == os_resultSuccess) { result = os_sigThreadSetMask(&old_sigset, NULL); if (result != os_resultSuccess) { OS_REPORT_2(OS_ERROR, "os_signalHandlerInit", 0, "os_sigThreadSetMask(0x%x, NULL) failed, result = %d", &old_sigset, r); result = os_resultFail; assert(OS_FALSE); } } /* install signal handlers */ if (result == os_resultSuccess) { os_sigset mask; /* block all signals during handling of a signal */ result = os_sigsetFill(&mask); if (result != os_resultSuccess) { OS_REPORT_2(OS_ERROR, "os_signalHandlerInit", 0, "os_sigsetFill(0x%x) failed, result = %d", &action.sa_mask, result); } else { action = os_sigactionNew(signalHandler, &mask, SA_SIGINFO); } if (result == os_resultSuccess) { for (i=0; i<lengthof(exceptions); i++) { const int sig = exceptions[i]; r = os_sigsetDel(&action.sa_mask, sig); if (r<0) { OS_REPORT_3(OS_ERROR, "os_signalHandlerInit", 0, "os_sigsetDel(0x%x, %d) failed, result = %d", &action, sig, r); result = os_resultFail; assert(OS_FALSE); } } } if (result == os_resultSuccess) { for (i=0; i<lengthof(exceptions); i++) { const int sig = exceptions[i]; /* For exceptions we always set our own signal handler, since * applications that cause an exception are not in a position * to ignore it. However, we will chain the old handler to our * own. */ r = os_sigactionSet(sig, &action, &old_signalHandler[sig]); if (r < 0) { OS_REPORT_4(OS_ERROR, "os_signalHandlerInit", 0, "os_sigactionSet(%d, 0x%x, 0x%x) failed, result = %d", sig, &action, &old_signalHandler[sig], r); result = os_resultFail; assert(OS_FALSE); } } } if (result == os_resultSuccess) { for (i=0; i<lengthof(quits); i++) { const int sig = quits[i]; /* By passing NULL we only retrieve the currently set handler. If * the signal should be ignored, we don't do anything. Otherwise we * chain the old handler to our own. * man-page of sigaction only states behaviour when new * action is non-NULL, but all known implementations act as * expected. That is: return the currently set signal-hand- * ler (and not the previous, as the man-pages state). * NOTE: Not MT-safe */ r = os_sigactionSet(sig, NULL, &old_signalHandler[sig]); if (r == 0) { if(old_signalHandler[sig].sa_handler != SIG_IGN) { /* We don't know if the oldHandler has been modified in the mean * time, since there is no way to make the signal handler reentrant. * It doesn't make sense to look for modifications now, since a * new modification could be on its way while we are processing * the current modification. * For that reason we will ignore any intermediate modifications * and continue setting our own handler. Processes should therefore * refrain from modifying the signal handler in multiple threads. */ r = os_sigactionSet(sig, &action, NULL); if (r != 0) { OS_REPORT_4(OS_ERROR, "os_signalHandlerInit", 0, "os_sigactionSet(%d, 0x%x, 0x%x) failed, result = %d", sig, &action, &old_signalHandler[sig], r); result = os_resultFail; assert(OS_FALSE); } } else { OS_REPORT_1(OS_INFO, "os_signalHandlerThread", 0, "Not installing a signal handler for the already ignored signal %d.", sig); } } else { OS_REPORT_1(OS_ERROR, "os_signalHandlerInit", 0, "Could not retrieve currently set signal-handler for signal %d", sig); result = os_resultFail; assert(OS_FALSE); } } } } } else { result = os_resultSuccess; } return result; }
void FioCloseAll() { for (int i = 0; i != lengthof(_fio.handles); i++) { FioCloseFile(i); } }
CControlUI* CDialogBuilder::_Parse(CMarkupNode* pRoot, CControlUI* pParent) { CDialogLayoutUI* pStretched = NULL; IContainerUI* pContainer = NULL; CControlUI* pReturn = NULL; for( CMarkupNode node = pRoot->GetChild() ; node.IsValid(); node = node.GetSibling() ) { LPCTSTR pstrClass = node.GetName(); SIZE_T cchLen = _tcslen(pstrClass); CControlUI* pControl = NULL; switch( cchLen ) { case 4: if( _tcscmp(pstrClass, _T("List")) == 0 ) pControl = new CListUI; break; case 6: if( _tcscmp(pstrClass, _T("Canvas")) == 0 ) pControl = new CCanvasUI; else if( _tcscmp(pstrClass, _T("Button")) == 0 ) pControl = new CButtonUI; else if( _tcscmp(pstrClass, _T("Option")) == 0 ) pControl = new COptionUI; break; case 7: if( _tcscmp(pstrClass, _T("Toolbar")) == 0 ) pControl = new CToolbarUI; else if( _tcscmp(pstrClass, _T("TabPage")) == 0 ) pControl = new CTabPageUI; else if( _tcscmp(pstrClass, _T("ActiveX")) == 0 ) pControl = new CActiveXUI; break; case 8: if( _tcscmp(pstrClass, _T("DropDown")) == 0 ) pControl = new CDropDownUI; break; case 9: if( _tcscmp(pstrClass, _T("FadedLine")) == 0 ) pControl = new CFadedLineUI; else if( _tcscmp(pstrClass, _T("TaskPanel")) == 0 ) pControl = new CTaskPanelUI; else if( _tcscmp(pstrClass, _T("Statusbar")) == 0 ) pControl = new CStatusbarUI; else if( _tcscmp(pstrClass, _T("TabFolder")) == 0 ) pControl = new CTabFolderUI; else if( _tcscmp(pstrClass, _T("TextPanel")) == 0 ) pControl = new CTextPanelUI; break; case 10: if( _tcscmp(pstrClass, _T("ListHeader")) == 0 ) pControl = new CListHeaderUI; else if( _tcscmp(pstrClass, _T("ListFooter")) == 0 ) pControl = new CListFooterUI; else if( _tcscmp(pstrClass, _T("TileLayout")) == 0 ) pControl = new CTileLayoutUI; else if( _tcscmp(pstrClass, _T("ToolButton")) == 0 ) pControl = new CToolButtonUI; else if( _tcscmp(pstrClass, _T("ImagePanel")) == 0 ) pControl = new CImagePanelUI; else if( _tcscmp(pstrClass, _T("LabelPanel")) == 0 ) pControl = new CLabelPanelUI; break; case 11: if( _tcscmp(pstrClass, _T("ToolGripper")) == 0 ) pControl = new CToolGripperUI; else if( _tcscmp(pstrClass, _T("WhiteCanvas")) == 0 ) pControl = new CWhiteCanvasUI; else if( _tcscmp(pstrClass, _T("TitleShadow")) == 0 ) pControl = new CTitleShadowUI; break; case 12: if( _tcscmp(pstrClass, _T("WindowCanvas")) == 0 ) pControl = new CWindowCanvasUI; else if( _tcscmp(pstrClass, _T("DialogCanvas")) == 0 ) pControl = new CDialogCanvasUI; else if( _tcscmp(pstrClass, _T("DialogLayout")) == 0 ) pControl = new CDialogLayoutUI; else if( _tcscmp(pstrClass, _T("PaddingPanel")) == 0 ) pControl = new CPaddingPanelUI; else if( _tcscmp(pstrClass, _T("WarningPanel")) == 0 ) pControl = new CWarningPanelUI; break; case 13: if( _tcscmp(pstrClass, _T("SeparatorLine")) == 0 ) pControl = new CSeparatorLineUI; else if( _tcscmp(pstrClass, _T("ControlCanvas")) == 0 ) pControl = new CControlCanvasUI; else if( _tcscmp(pstrClass, _T("MultiLineEdit")) == 0 ) pControl = new CMultiLineEditUI; else if( _tcscmp(pstrClass, _T("ToolSeparator")) == 0 ) pControl = new CToolSeparatorUI; break; case 14: if( _tcscmp(pstrClass, _T("VerticalLayout")) == 0 ) pControl = new CVerticalLayoutUI; else if( _tcscmp(pstrClass, _T("SingleLineEdit")) == 0 ) pControl = new CSingleLineEditUI; else if( _tcscmp(pstrClass, _T("SingleLinePick")) == 0 ) pControl = new CSingleLinePickUI; else if( _tcscmp(pstrClass, _T("NavigatorPanel")) == 0 ) pControl = new CNavigatorPanelUI; else if( _tcscmp(pstrClass, _T("ListHeaderItem")) == 0 ) pControl = new CListHeaderItemUI; else if( _tcscmp(pstrClass, _T("GreyTextHeader")) == 0 ) pControl = new CGreyTextHeaderUI; break; case 15: if( _tcscmp(pstrClass, _T("ListTextElement")) == 0 ) pControl = new CListTextElementUI; else if( _tcscmp(pstrClass, _T("NavigatorButton")) == 0 ) pControl = new CNavigatorButtonUI; else if( _tcscmp(pstrClass, _T("TabFolderCanvas")) == 0 ) pControl = new CTabFolderCanvasUI; break; case 16: if( _tcscmp(pstrClass, _T("ListHeaderShadow")) == 0 ) pControl = new CListHeaderShadowUI; else if( _tcscmp(pstrClass, _T("HorizontalLayout")) == 0 ) pControl = new CHorizontalLayoutUI; else if( _tcscmp(pstrClass, _T("ListLabelElement")) == 0 ) pControl = new CListLabelElementUI; else if( _tcscmp(pstrClass, _T("SearchTitlePanel")) == 0 ) pControl = new CSearchTitlePanelUI; break; case 17: if( _tcscmp(pstrClass, _T("ToolbarTitlePanel")) == 0 ) pControl = new CToolbarTitlePanelUI; else if( _tcscmp(pstrClass, _T("ListExpandElement")) == 0 ) pControl = new CListExpandElementUI; break; } // User-supplied control factory if( pControl == NULL && m_pCallback != NULL ) { pControl = m_pCallback->CreateControl(pstrClass); } ASSERT(pControl); if( pControl == NULL ) return NULL; // Add children if( node.HasChildren() ) { _Parse(&node, pControl); } // Attach to parent if( pParent != NULL ) { if( pContainer == NULL ) pContainer = static_cast<IContainerUI*>(pParent->GetInterface(_T("Container"))); ASSERT(pContainer); if( pContainer == NULL ) return NULL; pContainer->Add(pControl); } // Process attributes if( node.HasAttributes() ) { TCHAR szValue[500] = { 0 }; SIZE_T cchLen = lengthof(szValue) - 1; // Set ordinary attributes int nAttributes = node.GetAttributeCount(); for( int i = 0; i < nAttributes; i++ ) { pControl->SetAttribute(node.GetAttributeName(i), node.GetAttributeValue(i)); } // Very custom attributes if( node.GetAttributeValue(_T("stretch"), szValue, cchLen) ) { if( pStretched == NULL ) pStretched = static_cast<CDialogLayoutUI*>(pParent->GetInterface(_T("DialogLayout"))); ASSERT(pStretched); if( pStretched == NULL ) return NULL; UINT uMode = 0; if( _tcsstr(szValue, _T("move_x")) != NULL ) uMode |= UISTRETCH_MOVE_X; if( _tcsstr(szValue, _T("move_y")) != NULL ) uMode |= UISTRETCH_MOVE_Y; if( _tcsstr(szValue, _T("move_xy")) != NULL ) uMode |= UISTRETCH_MOVE_X | UISTRETCH_MOVE_Y; if( _tcsstr(szValue, _T("size_x")) != NULL ) uMode |= UISTRETCH_SIZE_X; if( _tcsstr(szValue, _T("size_y")) != NULL ) uMode |= UISTRETCH_SIZE_Y; if( _tcsstr(szValue, _T("size_xy")) != NULL ) uMode |= UISTRETCH_SIZE_X | UISTRETCH_SIZE_Y; if( _tcsstr(szValue, _T("group")) != NULL ) uMode |= UISTRETCH_NEWGROUP; if( _tcsstr(szValue, _T("line")) != NULL ) uMode |= UISTRETCH_NEWLINE; pStretched->SetStretchMode(pControl, uMode); } } // Return first item if( pReturn == NULL ) pReturn = pControl; } return pReturn; }
INT_PTR CAboutDialog::DlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam) { static const struct { COLORREF Header1; COLORREF Header2; COLORREF HeaderText; COLORREF HeaderShadow; COLORREF Info1; COLORREF Info2; COLORREF InfoText; } Colors = { RGB(192,213,245),RGB(160,192,240),RGB(0,0,0),RGB(200,214,255),RGB(224,232,255),RGB(240,244,255),RGB(64,64,64) }; switch (uMsg) { case WM_INITDIALOG: { HWND hwndHeader=::GetDlgItem(hDlg,IDC_ABOUT_HEADER); HWND hwndInfo=::GetDlgItem(hDlg,IDC_ABOUT_INFO); HWND hwndLogo=::GetDlgItem(hDlg,IDC_ABOUT_LOGO); m_Font.Create(DrawUtil::FONT_MESSAGE); ::SetWindowText(hwndHeader, ABOUT_VERSION_TEXT #ifdef VERSION_PLATFORM TEXT(" (") VERSION_PLATFORM TEXT(")") #endif ); HDC hdc=::GetDC(hDlg); HFONT hfontOld=DrawUtil::SelectObject(hdc,m_Font); TCHAR szText[MAX_INFO_TEXT]; ::GetWindowText(hwndInfo,szText,lengthof(szText)); RECT rcText={0,0,0,0}; ::DrawText(hdc,szText,-1,&rcText,DT_CALCRECT | DT_NOPREFIX); ::SelectObject(hdc,hfontOld); ::ReleaseDC(hDlg,hdc); RECT rcInfo; ::GetWindowRect(hwndInfo,&rcInfo); ::OffsetRect(&rcText,-rcText.left,-rcText.top); ::OffsetRect(&rcInfo,-rcInfo.left,-rcInfo.top); RECT rcLogo; ::GetWindowRect(hwndLogo,&rcLogo); if (rcInfo.bottom<rcText.bottom || rcInfo.right<rcText.right) { int Width=max(rcInfo.right,rcText.right); int Height=max(rcInfo.bottom,rcText.bottom); ::SetWindowPos(hwndInfo,NULL,0,0,Width,Height, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); RECT rcHeader; ::GetWindowRect(hwndHeader,&rcHeader); ::SetWindowPos(hwndHeader,NULL,0,0,Width,rcHeader.bottom-rcHeader.top, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); RECT rcDialog; ::GetWindowRect(hDlg,&rcDialog); ::SetWindowPos(hDlg,NULL,0,0, (rcDialog.right-rcDialog.left)+(Width-rcInfo.right), (rcDialog.bottom-rcDialog.top)+(Height-rcInfo.bottom), SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); RECT rcClient; ::GetClientRect(hDlg,&rcClient); ::SetWindowPos(hwndLogo,NULL,0,0, rcLogo.right-rcLogo.left,rcClient.bottom, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); } ::SetRect(&rcLogo,rcLogo.right-rcLogo.left,0,0,0); if (m_AeroGlass.ApplyAeroGlass(hDlg,&rcLogo)) { m_GdiPlus.Initialize(); m_LogoImage.LoadFromResource(GetAppClass().GetResourceInstance(), MAKEINTRESOURCE(IDB_LOGO32),TEXT("PNG")); ::ShowWindow(hwndLogo,SW_HIDE); } else { HBITMAP hbm=::LoadBitmap(GetAppClass().GetResourceInstance(), MAKEINTRESOURCE(IDB_LOGO)); ::SendMessage(hwndLogo,STM_SETIMAGE, IMAGE_BITMAP,reinterpret_cast<LPARAM>(hbm)); } AdjustDialogPos(GetParent(hDlg),hDlg); } return TRUE; case WM_CTLCOLORSTATIC: if (reinterpret_cast<HWND>(lParam)==::GetDlgItem(hDlg,IDC_ABOUT_LOGO)) return reinterpret_cast<INT_PTR>(::GetStockObject(WHITE_BRUSH)); if (reinterpret_cast<HWND>(lParam)==::GetDlgItem(hDlg,IDC_ABOUT_HEADER) || reinterpret_cast<HWND>(lParam)==::GetDlgItem(hDlg,IDC_ABOUT_INFO)) return reinterpret_cast<INT_PTR>(::GetStockObject(NULL_BRUSH)); break; case WM_DRAWITEM: { LPDRAWITEMSTRUCT pdis=reinterpret_cast<LPDRAWITEMSTRUCT>(lParam); int OldBkMode=::SetBkMode(pdis->hDC,TRANSPARENT); HFONT hfontOld=DrawUtil::SelectObject(pdis->hDC,m_Font); COLORREF OldTextColor; TCHAR szText[MAX_INFO_TEXT]; if (pdis->CtlID==IDC_ABOUT_HEADER) { OldTextColor=::SetTextColor(pdis->hDC,Colors.HeaderText); ::GetDlgItemText(hDlg,IDC_ABOUT_HEADER,szText,lengthof(szText)); ::DrawText(pdis->hDC,szText,-1,&pdis->rcItem, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX); } else if (pdis->CtlID==IDC_ABOUT_INFO) { OldTextColor=::SetTextColor(pdis->hDC,Colors.InfoText); ::GetDlgItemText(hDlg,IDC_ABOUT_INFO,szText,lengthof(szText)); ::DrawText(pdis->hDC,szText,-1,&pdis->rcItem,DT_CENTER | DT_NOPREFIX); } ::SetTextColor(pdis->hDC,OldTextColor); ::SelectObject(pdis->hDC,hfontOld); ::SetBkMode(pdis->hDC,OldBkMode); } return TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: case IDCANCEL: ::EndDialog(hDlg,LOWORD(wParam)); return TRUE; } break; case WM_PAINT: { PAINTSTRUCT ps; RECT rcClient,rcLogo,rcHeader,rc; ::BeginPaint(hDlg,&ps); GetDlgItemRect(hDlg,IDC_ABOUT_LOGO,&rcLogo); GetDlgItemRect(hDlg,IDC_ABOUT_HEADER,&rcHeader); ::GetClientRect(hDlg,&rcClient); rcClient.left=rcLogo.right; if (m_GdiPlus.IsInitialized()) { CGdiPlus::CCanvas Canvas(ps.hdc); Canvas.Clear(0,0,0,0); m_GdiPlus.DrawImage(&Canvas,&m_LogoImage, (rcLogo.right-m_LogoImage.GetWidth())/2, (rcLogo.bottom-m_LogoImage.GetHeight())/2); rc=rcClient; rc.bottom=rcHeader.bottom; m_GdiPlus.FillGradient(&Canvas,Colors.Header1,Colors.Header2, rc,CGdiPlus::GRADIENT_DIRECTION_VERT); rc.top=rc.bottom; rc.bottom=rc.top+8; m_GdiPlus.FillGradient(&Canvas,Colors.HeaderShadow,Colors.Info1, rc,CGdiPlus::GRADIENT_DIRECTION_VERT); rc.top=rc.bottom; rc.bottom=rcClient.bottom; m_GdiPlus.FillGradient(&Canvas,Colors.Info1,Colors.Info2, rc,CGdiPlus::GRADIENT_DIRECTION_VERT); } else { rc=rcClient; rc.bottom=rcHeader.bottom; DrawUtil::FillGradient(ps.hdc,&rc,Colors.Header1,Colors.Header2, DrawUtil::DIRECTION_VERT); rc.top=rc.bottom; rc.bottom=rc.top+8; DrawUtil::FillGradient(ps.hdc,&rc,Colors.HeaderShadow,Colors.Info1, DrawUtil::DIRECTION_VERT); rc.top=rc.bottom; rc.bottom=rcClient.bottom; DrawUtil::FillGradient(ps.hdc,&rc,Colors.Info1,Colors.Info2, DrawUtil::DIRECTION_VERT); } ::EndPaint(hDlg,&ps); } return TRUE; case WM_DESTROY: { HBITMAP hbm=reinterpret_cast<HBITMAP>(::SendDlgItemMessage(hDlg,IDC_ABOUT_LOGO, STM_SETIMAGE,IMAGE_BITMAP,reinterpret_cast<LPARAM>((HBITMAP)NULL))); if (hbm!=NULL) { ::DeleteObject(hbm); } else { m_LogoImage.Free(); m_GdiPlus.Finalize(); } m_Font.Destroy(); } return TRUE; } return FALSE; }
Datum dbms_pipe_list_pipes(PG_FUNCTION_ARGS) { FuncCallContext *funcctx; TupleDesc tupdesc; AttInMetadata *attinmeta; PipesFctx *fctx; float8 endtime; int cycle = 0; int timeout = 10; if (SRF_IS_FIRSTCALL()) { int i; MemoryContext oldcontext; bool has_lock = false; WATCH_PRE(timeout, endtime, cycle); if (ora_lock_shmem(SHMEMMSGSZ, MAX_PIPES, MAX_EVENTS, MAX_LOCKS, false)) { has_lock = true; break; } WATCH_POST(timeout, endtime, cycle); if (!has_lock) LOCK_ERROR(); funcctx = SRF_FIRSTCALL_INIT(); oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); fctx = palloc(sizeof(PipesFctx)); funcctx->user_fctx = fctx; fctx->pipe_nth = 0; #if PG_VERSION_NUM >= 120000 tupdesc = CreateTemplateTupleDesc(DB_PIPES_COLS); #else tupdesc = CreateTemplateTupleDesc(DB_PIPES_COLS, false); #endif i = 0; TupleDescInitEntry(tupdesc, ++i, "name", VARCHAROID, -1, 0); TupleDescInitEntry(tupdesc, ++i, "items", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, ++i, "size", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, ++i, "limit", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, ++i, "private", BOOLOID, -1, 0); TupleDescInitEntry(tupdesc, ++i, "owner", VARCHAROID, -1, 0); Assert(i == DB_PIPES_COLS); attinmeta = TupleDescGetAttInMetadata(tupdesc); funcctx->attinmeta = attinmeta; MemoryContextSwitchTo(oldcontext); } funcctx = SRF_PERCALL_SETUP(); fctx = (PipesFctx *) funcctx->user_fctx; while (fctx->pipe_nth < MAX_PIPES) { if (pipes[fctx->pipe_nth].is_valid) { Datum result; HeapTuple tuple; char *values[DB_PIPES_COLS]; char items[16]; char size[16]; char limit[16]; /* name */ values[0] = pipes[fctx->pipe_nth].pipe_name; /* items */ snprintf(items, lengthof(items), "%d", pipes[fctx->pipe_nth].count); values[1] = items; /* items */ snprintf(size, lengthof(size), "%d", pipes[fctx->pipe_nth].size); values[2] = size; /* limit */ if (pipes[fctx->pipe_nth].limit != -1) { snprintf(limit, lengthof(limit), "%d", pipes[fctx->pipe_nth].limit); values[3] = limit; } else values[3] = NULL; /* private */ values[4] = (pipes[fctx->pipe_nth].creator ? "true" : "false"); /* owner */ values[5] = pipes[fctx->pipe_nth].creator; tuple = BuildTupleFromCStrings(funcctx->attinmeta, values); result = HeapTupleGetDatum(tuple); fctx->pipe_nth += 1; SRF_RETURN_NEXT(funcctx, result); } fctx->pipe_nth += 1; } LWLockRelease(shmem_lockid); SRF_RETURN_DONE(funcctx); }
/** Names of the filter types as used in console function. e.g. in .ufo files. * @sa inv_shared.h:itemFilterTypes_t */ static char const* const filterTypeNames[MAX_FILTERTYPES] = { "primary", /**< FILTER_S_PRIMARY */ "secondary", /**< FILTER_S_SECONDARY */ "heavy", /**< FILTER_S_HEAVY */ "misc", /**< FILTER_S_MISC */ "armour", /**< FILTER_S_ARMOUR */ "", /**< MAX_SOLDIER_FILTERTYPES */ "craftitem", /**< FILTER_CRAFTITEM */ "ugvitem", /**< FILTER_UGVITEM */ "aircraft", /**< FILTER_AIRCRAFT */ "dummy", /**< FILTER_DUMMY */ "disassembly" /**< FILTER_DISASSEMBLY */ }; CASSERT(lengthof(filterTypeNames) == MAX_FILTERTYPES); /** * @brief Searches for a filter type name (as used in console functions) and returns the matching itemFilterTypes_t enum. * @param[in] filterTypeID Filter type name so search for. @sa filterTypeNames. */ itemFilterTypes_t INV_GetFilterTypeID (const char * filterTypeID) { int i; if (!filterTypeID) return MAX_FILTERTYPES; /* default filter type is primary */ if (filterTypeID[0] == '\0') return FILTER_S_PRIMARY;
int Exiv2::http(dict_t& request,dict_t& response,std::string& errors) { if ( !request.count("verb") ) request["verb" ] = "GET"; if ( !request.count("header") ) request["header" ] = "" ; if ( !request.count("version")) request["version"] = "1.0"; if ( !request.count("port") ) request["port" ] = "" ; std::string file; errors = ""; int result = 0; //////////////////////////////////// // Windows specific code #ifdef WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); #endif const char* servername = request["server" ].c_str(); const char* page = request["page" ].c_str(); const char* verb = request["verb" ].c_str(); const char* header = request["header" ].c_str(); const char* version = request["version"].c_str(); const char* port = request["port" ].c_str(); const char* servername_p = servername; const char* port_p = port ; std::string url = std::string("http://") + request["server"] + request["page"]; // parse and change server if using a proxy const char* PROXI = "HTTP_PROXY"; const char* proxi = "http_proxy"; const char* PROXY = getenv(PROXI); const char* proxy = getenv(proxi); bool bProx = PROXY || proxy; const char* prox = bProx ? (proxy?proxy:PROXY):""; Exiv2::Uri Proxy = Exiv2::Uri::Parse(prox); // find the dictionary of no_proxy servers const char* NO_PROXI = "NO_PROXY"; const char* no_proxi = "no_proxy"; const char* NO_PROXY = getenv(NO_PROXI); const char* no_proxy = getenv(no_proxi); bool bNoProxy = NO_PROXY||no_proxy; std::string no_prox = std::string(bNoProxy?(no_proxy?no_proxy:NO_PROXY):""); Exiv2::dict_t noProxy= stringToDict(no_prox + ",localhost,127.0.0.1"); // if the server is on the no_proxy list ... ignore the proxy! if ( noProxy.count(servername) ) bProx = false; if ( bProx ) { servername_p = Proxy.Host.c_str(); port_p = Proxy.Port.c_str(); page = url.c_str(); std::string p(proxy?proxi:PROXI); // std::cerr << p << '=' << prox << " page = " << page << std::endl; } if ( !port [0] ) port = "80"; if ( !port_p[0] ) port_p = "80"; //////////////////////////////////// // open the socket int sockfd = (int) socket(AF_INET , SOCK_STREAM,IPPROTO_TCP) ; if ( sockfd < 0 ) return error("unable to create socket\n",NULL,NULL,0) ; // connect the socket to the server int server = -1 ; // fill in the address struct sockaddr_in serv_addr ; int serv_len = sizeof(serv_addr); memset((char *)&serv_addr,0,serv_len); serv_addr.sin_addr.s_addr = inet_addr(servername_p); serv_addr.sin_family = AF_INET ; serv_addr.sin_port = htons(atoi(port_p)); // convert unknown servername into IP address // http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzab6/rzab6uafinet.htm if (serv_addr.sin_addr.s_addr == (unsigned long)INADDR_NONE) { struct hostent* host = gethostbyname(servername_p); if ( !host ) return error("no such host",servername_p,NULL,0); memcpy(&serv_addr.sin_addr,host->h_addr,sizeof(serv_addr.sin_addr)); } makeNonBlocking(sockfd) ; //////////////////////////////////// // and connect server = connect(sockfd, (const struct sockaddr *) &serv_addr, serv_len) ; if ( server == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK ) return error(errors,"error - unable to connect to server = %s port = %s wsa_error = %d",servername_p,port_p,WSAGetLastError()); char buffer[32*1024+1]; size_t buff_l= sizeof buffer - 1 ; //////////////////////////////////// // format the request #ifdef MSDEV_2003 int n = sprintf(buffer,httpTemplate,verb,page,version,servername,header) ; #else int n = snprintf(buffer,buff_l,httpTemplate,verb,page,version,servername,header) ; #endif buffer[n] = 0 ; response["requestheaders"]=std::string(buffer,n); //////////////////////////////////// // send the header (we'll have to wait for the connection by the non-blocking socket) while ( sleep_ >= 0 && send(sockfd,buffer,n,0) == SOCKET_ERROR /* && WSAGetLastError() == WSAENOTCONN */ ) { Sleep(snooze) ; sleep_ -= snooze ; } if ( sleep_ < 0 ) return error(errors,"error - timeout connecting to server = %s port = %s wsa_error = %d",servername,port,WSAGetLastError()); int end = 0 ; // write position in buffer bool bSearching = true ; // looking for headers in the response int status= 200 ; // assume happiness //////////////////////////////////// // read and process the response int err ; n=forgive(recv(sockfd,buffer,(int)buff_l,0),err) ; while ( n >= 0 && OK(status) ) { if ( n ) { end += n ; buffer[end] = 0 ; size_t body = 0 ; // start of body if ( bSearching ) { // search for the body for ( size_t b = 0 ; bSearching && b < lengthof(blankLines) ; b++ ) { if ( strstr(buffer,blankLines[b]) ) { bSearching = false ; body = (int) ( strstr(buffer,blankLines[b]) - buffer ) + strlen(blankLines[b]) ; status = atoi(strchr(buffer,' ')) ; } } // parse response headers char* h = buffer; char C = ':' ; char N = '\n'; int i = 0 ; // initial byte in buffer while(buffer[i] == N ) i++; h = strchr(h+i,N)+1; response[""]=std::string(buffer+i).substr(0,h-buffer-2); result = atoi(strchr(buffer,' ')); char* c = strchr(h,C); char* n = strchr(h,N); while ( c && n && c < n && h < buffer+body ) { std::string key(h); std::string value(c+1); key = key.substr(0,c-h); value = value.substr(0,n-c-1); response[key]=value; h = n+1; c = strchr(h,C); n = strchr(h,N); } } // if the bufffer's full and we're still searching - give up! // this handles the possibility that there are no headers if ( bSearching && buff_l-end < 10 ) { bSearching = false ; body = 0 ; } if ( !bSearching && OK(status) ) { flushBuffer(buffer,body,end,file); } } n=forgive(recv(sockfd,buffer+end,(int)(buff_l-end),0),err) ; if ( !n ) { Sleep(snooze) ; sleep_ -= snooze ; if ( sleep_ < 0 ) n = FINISH ; } } if ( n != FINISH || !OK(status) ) { #ifdef MSDEV_2003 sprintf(buffer,"wsa_error = %d,n = %d,sleep_ = %d status = %d" , WSAGetLastError() , n , sleep_ , status ) ; #else snprintf(buffer,sizeof buffer,"wsa_error = %d,n = %d,sleep_ = %d status = %d" , WSAGetLastError() , n , sleep_ , status ) ; #endif error(errors,buffer,NULL,NULL,0) ; } else if ( bSearching && OK(status) ) { if ( end ) { // we finished OK without finding headers, flush the buffer flushBuffer(buffer,0,end,file) ; } else { return error(errors,"error - no response from server = %s port = %s wsa_error = %d",servername,port,WSAGetLastError()); } } //////////////////////////////////// // close sockets closesocket(server) ; closesocket(sockfd) ; response["body"]=file; return result; }
bool CMenuOptions::ReadSettings(CSettings &Settings) { int Value; if (Settings.Read(TEXT("MaxChannelMenuRows"),&Value) && Value>0) m_MaxChannelMenuRows=Value; Settings.Read(TEXT("MaxChannelMenuEventInfo"),&m_MaxChannelMenuEventInfo); int ItemCount; if (Settings.Read(TEXT("ItemCount"),&ItemCount) && ItemCount>0) { const CCommandList *pCommandList=GetAppClass().GetCommandList(); std::vector<MenuItemInfo> ItemList; for (int i=0;i<ItemCount;i++) { TCHAR szName[32],szText[CCommandList::MAX_COMMAND_TEXT]; ::wsprintf(szName,TEXT("Item%d_ID"),i); if (Settings.Read(szName,szText,lengthof(szText))) { MenuItemInfo Item; Item.fVisible=true; ::wsprintf(szName,TEXT("Item%d_State"),i); if (Settings.Read(szName,&Value)) Item.fVisible=(Value&ITEM_STATE_VISIBLE)!=0; if (szText[0]==_T('\0')) { Item.ID=MENU_ID_SEPARATOR; ItemList.push_back(Item); } else { int Command=pCommandList->ParseText(szText); if (Command>0) { int ID=CommandToID(Command); if (ID>=0) { Item.ID=ID; ItemList.push_back(Item); } } #ifdef _DEBUG else { TRACE(TEXT("CMenuOptions::ReadSettings() : Unknown command \"%s\"\n"),szText); } #endif } } } for (int i=0;i<lengthof(m_DefaultMenuItemList);i++) { bool fFound=false; for (size_t j=0;j<ItemList.size();j++) { if (ItemList[j].ID==m_DefaultMenuItemList[i].ID) { fFound=true; break; } } if (!fFound) { MenuItemInfo Item; Item.ID=m_DefaultMenuItemList[i].ID; Item.fVisible=false; ItemList.push_back(Item); } } m_MenuItemList=ItemList; } return true; }
INT_PTR CMenuOptions::DlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: ::SetDlgItemInt(hDlg,IDC_MENUOPTIONS_MAXCHANNELMENUROWS,m_MaxChannelMenuRows,TRUE); DlgUpDown_SetRange(hDlg,IDC_MENUOPTIONS_MAXCHANNELMENUROWS_SPIN,1,100); ::SetDlgItemInt(hDlg,IDC_MENUOPTIONS_MAXCHANNELMENUEVENTINFO,m_MaxChannelMenuEventInfo,TRUE); DlgUpDown_SetRange(hDlg,IDC_MENUOPTIONS_MAXCHANNELMENUEVENTINFO_SPIN,0,100); { HWND hwndList=::GetDlgItem(hDlg,IDC_MENUOPTIONS_ITEMLIST); ListView_SetExtendedListViewStyle(hwndList, LVS_EX_FULLROWSELECT | LVS_EX_CHECKBOXES | LVS_EX_LABELTIP); RECT rc; ::GetClientRect(hwndList,&rc); LVCOLUMN lvc; lvc.mask=LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; lvc.fmt=LVCFMT_LEFT; lvc.cx=rc.right-::GetSystemMetrics(SM_CXVSCROLL); lvc.pszText=TEXT(""); lvc.iSubItem=0; ListView_InsertColumn(hwndList,0,&lvc); m_fChanging=true; LVITEM lvi; TCHAR szText[CCommandList::MAX_COMMAND_NAME]; lvi.mask=LVIF_TEXT | LVIF_PARAM; lvi.iSubItem=0; lvi.pszText=szText; for (int i=0;i<(int)m_MenuItemList.size();i++) { int ID=m_MenuItemList[i].ID; GetItemText(ID,szText,lengthof(szText)); lvi.iItem=i; lvi.lParam=ID; lvi.iItem=ListView_InsertItem(hwndList,&lvi); ListView_SetCheckState(hwndList,lvi.iItem,m_MenuItemList[i].fVisible); } m_fChanging=false; } return TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_MENUOPTIONS_ITEMLIST_UP: case IDC_MENUOPTIONS_ITEMLIST_DOWN: { HWND hwndList=::GetDlgItem(hDlg,IDC_MENUOPTIONS_ITEMLIST); int From=ListView_GetNextItem(hwndList,-1,LVNI_SELECTED),To; if (From>=0) { if (LOWORD(wParam)==IDC_MENUOPTIONS_ITEMLIST_UP) { if (From<1) break; To=From-1; } else { if (From+1>=ListView_GetItemCount(hwndList)) break; To=From+1; } m_fChanging=true; LVITEM lvi; TCHAR szText[CCommandList::MAX_COMMAND_NAME]; lvi.mask=LVIF_STATE | LVIF_TEXT | LVIF_PARAM; lvi.iItem=From; lvi.iSubItem=0; lvi.stateMask=~0U; lvi.pszText=szText; lvi.cchTextMax=lengthof(szText); ListView_GetItem(hwndList,&lvi); BOOL fChecked=ListView_GetCheckState(hwndList,From); ListView_DeleteItem(hwndList,From); lvi.iItem=To; ListView_InsertItem(hwndList,&lvi); ListView_SetCheckState(hwndList,To,fChecked); SetDlgItemState(hDlg); m_fChanging=false; } } return TRUE; case IDC_MENUOPTIONS_ITEMLIST_INSERTSEPARATOR: { HWND hwndList=::GetDlgItem(hDlg,IDC_MENUOPTIONS_ITEMLIST); int Sel=ListView_GetNextItem(hwndList,-1,LVNI_SELECTED); if (Sel>=0) { LVITEM lvi; TCHAR szText[CCommandList::MAX_COMMAND_NAME]; m_fChanging=true; GetItemText(MENU_ID_SEPARATOR,szText,lengthof(szText)); lvi.mask=LVIF_TEXT | LVIF_PARAM; lvi.iItem=Sel; lvi.iSubItem=0; lvi.pszText=szText; lvi.lParam=MENU_ID_SEPARATOR; ListView_InsertItem(hwndList,&lvi); ListView_SetItemState(hwndList,Sel,LVIS_SELECTED | LVIS_FOCUSED,LVIS_SELECTED | LVIS_FOCUSED); ListView_SetCheckState(hwndList,Sel,TRUE); SetDlgItemState(hDlg); m_fChanging=false; } } return TRUE; case IDC_MENUOPTIONS_ITEMLIST_REMOVESEPARATOR: { HWND hwndList=::GetDlgItem(hDlg,IDC_MENUOPTIONS_ITEMLIST); int Sel=ListView_GetNextItem(hwndList,-1,LVNI_SELECTED); if (Sel>=0) { if (GetListViewItemParam(hwndList,Sel)==MENU_ID_SEPARATOR) { m_fChanging=true; ListView_DeleteItem(hwndList,Sel); SetDlgItemState(hDlg); m_fChanging=false; } } } return TRUE; case IDC_MENUOPTIONS_ITEMLIST_DEFAULT: { HWND hwndList=::GetDlgItem(hDlg,IDC_MENUOPTIONS_ITEMLIST); m_fChanging=true; ListView_DeleteAllItems(hwndList); LVITEM lvi; TCHAR szText[CCommandList::MAX_COMMAND_NAME]; lvi.mask=LVIF_TEXT | LVIF_PARAM; lvi.iSubItem=0; lvi.pszText=szText; for (int i=0;i<lengthof(m_DefaultMenuItemList);i++) { int ID=m_DefaultMenuItemList[i].ID; GetItemText(ID,szText,lengthof(szText)); lvi.iItem=i; lvi.lParam=ID; lvi.iItem=ListView_InsertItem(hwndList,&lvi); ListView_SetCheckState(hwndList,lvi.iItem,TRUE); } SetDlgItemState(hDlg); m_fChanging=false; } return TRUE; } return TRUE; case WM_NOTIFY: switch (((LPNMHDR)lParam)->code) { case LVN_ITEMCHANGED: if (!m_fChanging) SetDlgItemState(hDlg); return TRUE; case PSN_APPLY: { int Value; Value=::GetDlgItemInt(hDlg,IDC_MENUOPTIONS_MAXCHANNELMENUROWS,NULL,TRUE); if (Value>0) m_MaxChannelMenuRows=Value; Value=::GetDlgItemInt(hDlg,IDC_MENUOPTIONS_MAXCHANNELMENUEVENTINFO,NULL,TRUE); m_MaxChannelMenuEventInfo=Value; } { HWND hwndList=::GetDlgItem(hDlg,IDC_MENUOPTIONS_ITEMLIST); const int ItemCount=ListView_GetItemCount(hwndList); m_MenuItemList.resize(ItemCount); LVITEM lvi; lvi.mask=LVIF_STATE | LVIF_PARAM; lvi.iSubItem=0; lvi.stateMask=~0U; for (int i=0;i<ItemCount;i++) { lvi.iItem=i; ListView_GetItem(hwndList,&lvi); m_MenuItemList[i].ID=(int)lvi.lParam; m_MenuItemList[i].fVisible=(lvi.state & LVIS_STATEIMAGEMASK)==INDEXTOSTATEIMAGEMASK(2); } } m_fChanged=true; return TRUE; } break; } return FALSE; }
void SwitchToMode(SwitchMode new_mode) { #ifdef ENABLE_NETWORK /* If we are saving something, the network stays in his current state */ if (new_mode != SM_SAVE_GAME) { /* If the network is active, make it not-active */ if (_networking) { if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) { NetworkReboot(); } else { NetworkDisconnect(); } } /* If we are a server, we restart the server */ if (_is_network_server) { /* But not if we are going to the menu */ if (new_mode != SM_MENU) { /* check if we should reload the config */ if (_settings_client.network.reload_cfg) { LoadFromConfig(); MakeNewgameSettingsLive(); ResetGRFConfig(false); } NetworkServerStart(); } else { /* This client no longer wants to be a network-server */ _is_network_server = false; } } } #endif /* ENABLE_NETWORK */ /* Make sure all AI controllers are gone at quiting game */ if (new_mode != SM_SAVE_GAME) AI::KillAll(); switch (new_mode) { case SM_EDITOR: // Switch to scenario editor MakeNewEditorWorld(); break; case SM_RESTARTGAME: // Restart --> 'Random game' with current settings case SM_NEWGAME: // New Game --> 'Random game' #ifdef ENABLE_NETWORK if (_network_server) { snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map"); } #endif /* ENABLE_NETWORK */ MakeNewGame(false, new_mode == SM_NEWGAME); break; case SM_LOAD_GAME: { // Load game, Play Scenario ResetGRFConfig(true); ResetWindowSystem(); if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) { SetDParamStr(0, GetSaveLoadErrorString()); ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR); } else { if (_saveload_mode == SLD_LOAD_SCENARIO) { StartupEngines(); } /* Update the local company for a loaded game. It is either always * company #1 (eg 0) or in the case of a dedicated server a spectator */ SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST); /* Execute the game-start script */ IConsoleCmdExec("exec scripts/game_start.scr 0"); /* Decrease pause counter (was increased from opening load dialog) */ DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE); #ifdef ENABLE_NETWORK if (_network_server) { snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title); } #endif /* ENABLE_NETWORK */ } break; } case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it #ifdef ENABLE_NETWORK if (_network_server) { snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title); } #endif /* ENABLE_NETWORK */ MakeNewGame(true, true); break; case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor SetLocalCompany(OWNER_NONE); GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y); MarkWholeScreenDirty(); break; case SM_LOAD_SCENARIO: { // Load scenario from scenario editor if (SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) { SetLocalCompany(OWNER_NONE); _settings_newgame.game_creation.starting_year = _cur_year; /* Cancel the saveload pausing */ DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE); } else { SetDParamStr(0, GetSaveLoadErrorString()); ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR); } break; } case SM_MENU: // Switch to game intro menu LoadIntroGame(); if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) { ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL); BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name); } break; case SM_SAVE_GAME: // Save game. /* Make network saved games on pause compatible to singleplayer */ if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) { SetDParamStr(0, GetSaveLoadErrorString()); ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR); } else { #ifdef EMSCRIPTEN std::string script("Module['SAVE_GAME']('"); script.append(_file_to_saveload.name) .append("');"); emscripten_run_script_int(script.c_str()); #endif DeleteWindowById(WC_SAVELOAD, 0); } break; case SM_SAVE_HEIGHTMAP: // Save heightmap. MakeHeightmapScreenshot(_file_to_saveload.name); DeleteWindowById(WC_SAVELOAD, 0); break; case SM_GENRANDLAND: // Generate random land within scenario editor SetLocalCompany(OWNER_NONE); GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y); /* XXX: set date */ MarkWholeScreenDirty(); break; default: NOT_REACHED(); } }
/*------------------------------------------------------------------------- * * keywords.c * lexical token lookup for key words in PostgreSQL * * * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/parser/keywords.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "parser/gramparse.h" #define PG_KEYWORD(a,b,c) {a,b,c}, const ScanKeyword ScanKeywords[] = { #include "parser/kwlist.h" }; const int NumScanKeywords = lengthof(ScanKeywords);
os_result os_signalHandlerFinishExitRequest( os_callbackArg arg) { os_result r = os_resultSuccess; int sig = (int)(os_address)arg.sig; os_sigaction * xo; /* This is a request from the application to round up an (asynchronous) * exit-request. */ if (sig < 1 || sig >= OS_NSIG) { OS_REPORT_2(OS_WARNING, "os_signalHandlerFinishExitRequest", 0, "Callback-arg contains invalid signal, value out of range 1-%d: arg = %d", OS_NSIG, sig); r = os_resultInvalid; } else if (sigismember(&quitsMask, sig) == 0) { #if OS_NSIG >= 100 #error "Worst-case allocation assumes max. signal of 99, which apparently is not correct" #endif /* We know which signal-number exist, all take at most 2 digits + ", ", * so allocate worst-case 4 * lengthof(quits) */ char *expected = os_malloc(lengthof(quits) * 4 + 1); if(expected) { int i, pos; assert(lengthof(quits) > 0); pos = sprintf(expected, "%d", quits[0]); for(i = 1; i < lengthof(quits); i++) { pos += sprintf(expected + pos, ", %d", quits[i]); } } OS_REPORT_2(OS_WARNING, "os_signalHandlerFinishExitRequest", 0, "Unexpected Signal, value out of range: signal = %d. Expected one of %s.", sig, expected ? expected : "the asynchronous exit request signals"); os_free(expected); r = os_resultInvalid; } if(r == os_resultSuccess) { /* We need to restore the original signal-handler and than re-raise the * original signal. */ xo = &old_signalHandler[sig]; if(os_sigactionSet(sig, xo, NULL) != 0) { r = os_resultFail; OS_REPORT_1(OS_WARNING, "os_signalHandlerFinishExitRequest", 0, "Resetting original signal handler for signal %d failed, sigaction did not return 0.",sig); abort(); /* We were unable to reset the original handler, which is pretty serious. */ } else { os_sigset current_sigset, old_sigset; /* Determine the current mask, and make sure that the signal to be * raised is not blocked (this code is typically executed in the * signalHandlerThread (if callback is implemented synchronously), * which blocks all signals). */ os_sigThreadSetMask(NULL, ¤t_sigset); os_sigsetDel(¤t_sigset, sig); raise(sig); /* Set mask temporarily, this should raise the pending signal set above. */ os_sigThreadSetMask(¤t_sigset, &old_sigset); /* Reset the mask to the original state. If this is the signal- * HandlerThread this is essential (if sig is handled), otherwise just * the proper thing to do. */ os_sigThreadSetMask(&old_sigset, NULL); } } return r; }
/** * Will return the ottd's index correspondance to * the ttdpatch's id. If the id is bigger than the array, * it is a grf written for ottd, thus returning the same id. * Only called from newgrf.cpp * @param grfcurr_id currency id coming from newgrf * @return the corrected index **/ byte GetNewgrfCurrencyIdConverted(byte grfcurr_id) { return (grfcurr_id >= lengthof(TTDPatch_To_OTTDIndex)) ? grfcurr_id : TTDPatch_To_OTTDIndex[grfcurr_id]; }
/** * Acquire the base paths (personal dir and game data dir), * fill all other paths (save dir, autosave dir etc) and * make the save and scenario directories. * @param exe the path from the current path to the executable */ void DeterminePaths(const char *exe) { DetermineBasePaths(exe); Searchpath sp; FOR_ALL_SEARCHPATHS(sp) { if (sp == SP_WORKING_DIR && !_do_scan_working_directory) continue; DEBUG(misc, 4, "%s added as search path", _searchpaths[sp]); } if (_config_file != NULL) { _personal_dir = strdup(_config_file); char *end = strrchr(_personal_dir, PATHSEPCHAR); if (end == NULL) { _personal_dir[0] = '\0'; } else { end[1] = '\0'; } } else { char personal_dir[MAX_PATH]; FioFindFullPath(personal_dir, lengthof(personal_dir), BASE_DIR, "openttd.cfg"); if (FileExists(personal_dir)) { char *end = strrchr(personal_dir, PATHSEPCHAR); if (end != NULL) end[1] = '\0'; _personal_dir = strdup(personal_dir); _config_file = str_fmt("%sopenttd.cfg", _personal_dir); } else { static const Searchpath new_openttd_cfg_order[] = { SP_PERSONAL_DIR, SP_BINARY_DIR, SP_WORKING_DIR, SP_SHARED_DIR, SP_INSTALLATION_DIR }; for (uint i = 0; i < lengthof(new_openttd_cfg_order); i++) { if (IsValidSearchPath(new_openttd_cfg_order[i])) { _personal_dir = strdup(_searchpaths[new_openttd_cfg_order[i]]); _config_file = str_fmt("%sopenttd.cfg", _personal_dir); break; } } } } DEBUG(misc, 3, "%s found as personal directory", _personal_dir); _highscore_file = str_fmt("%shs.dat", _personal_dir); extern char *_hotkeys_file; _hotkeys_file = str_fmt("%shotkeys.cfg", _personal_dir); /* Make the necessary folders */ #if defined(__PLAYBOOK__) || (!defined(__MORPHOS__) && !defined(__AMIGA__) && defined(WITH_PERSONAL_DIR)) FioCreateDirectory(_personal_dir); #endif static const Subdirectory default_subdirs[] = { SAVE_DIR, AUTOSAVE_DIR, SCENARIO_DIR, HEIGHTMAP_DIR }; for (uint i = 0; i < lengthof(default_subdirs); i++) { char *dir = str_fmt("%s%s", _personal_dir, _subdirs[default_subdirs[i]]); FioCreateDirectory(dir); free(dir); } /* If we have network we make a directory for the autodownloading of content */ _searchpaths[SP_AUTODOWNLOAD_DIR] = str_fmt("%s%s", _personal_dir, "content_download" PATHSEP); #ifdef ENABLE_NETWORK FioCreateDirectory(_searchpaths[SP_AUTODOWNLOAD_DIR]); /* Create the directory for each of the types of content */ const Subdirectory dirs[] = { SCENARIO_DIR, HEIGHTMAP_DIR, DATA_DIR, AI_DIR, AI_LIBRARY_DIR, GM_DIR }; for (uint i = 0; i < lengthof(dirs); i++) { char *tmp = str_fmt("%s%s", _searchpaths[SP_AUTODOWNLOAD_DIR], _subdirs[dirs[i]]); FioCreateDirectory(tmp); free(tmp); } extern char *_log_file; _log_file = str_fmt("%sopenttd.log", _personal_dir); #else /* ENABLE_NETWORK */ /* If we don't have networking, we don't need to make the directory. But * if it exists we keep it, otherwise remove it from the search paths. */ if (!FileExists(_searchpaths[SP_AUTODOWNLOAD_DIR])) { free((void*)_searchpaths[SP_AUTODOWNLOAD_DIR]); _searchpaths[SP_AUTODOWNLOAD_DIR] = NULL; } #endif /* ENABLE_NETWORK */ TarScanner::DoScan(); }
}, {UserMappingRelationId, /* USERMAPPINGUSERSERVER */ UserMappingUserServerIndexId, 2, { Anum_pg_user_mapping_umuser, Anum_pg_user_mapping_umserver, 0, 0 }, 128 } }; static CatCache *SysCache[ lengthof(cacheinfo)]; static int SysCacheSize = lengthof(cacheinfo); static bool CacheInitialized = false; /* * InitCatalogCache - initialize the caches * * Note that no database access is done here; we only allocate memory * and initialize the cache structure. Interrogation of the database * to complete initialization of a cache happens upon first use * of that cache. */ void InitCatalogCache(void) {
/** * Extract the tar with the given filename in the directory * where the tar resides. * @param tar_filename the name of the tar to extract. * @return false on failure. */ bool ExtractTar(const char *tar_filename) { TarList::iterator it = _tar_list.find(tar_filename); /* We don't know the file. */ if (it == _tar_list.end()) return false; const char *dirname = (*it).second.dirname; /* The file doesn't have a sub directory! */ if (dirname == NULL) return false; char filename[MAX_PATH]; strecpy(filename, tar_filename, lastof(filename)); char *p = strrchr(filename, PATHSEPCHAR); /* The file's path does not have a separator? */ if (p == NULL) return false; p++; strecpy(p, dirname, lastof(filename)); DEBUG(misc, 8, "Extracting %s to directory %s", tar_filename, filename); FioCreateDirectory(filename); for (TarFileList::iterator it2 = _tar_filelist.begin(); it2 != _tar_filelist.end(); it2++) { if (strcmp((*it2).second.tar_filename, tar_filename) != 0) continue; strecpy(p, (*it2).first.c_str(), lastof(filename)); DEBUG(misc, 9, " extracting %s", filename); /* First open the file in the .tar. */ size_t to_copy = 0; FILE *in = FioFOpenFileTar(&(*it2).second, &to_copy); if (in == NULL) { DEBUG(misc, 6, "Extracting %s failed; could not open %s", filename, tar_filename); return false; } /* Now open the 'output' file. */ FILE *out = fopen(filename, "wb"); if (out == NULL) { DEBUG(misc, 6, "Extracting %s failed; could not open %s", filename, filename); fclose(in); return false; } /* Now read from the tar and write it into the file. */ char buffer[4096]; size_t read; for (; to_copy != 0; to_copy -= read) { read = fread(buffer, 1, min(to_copy, lengthof(buffer)), in); if (read <= 0 || fwrite(buffer, 1, read, out) != read) break; } /* Close everything up. */ fclose(in); fclose(out); if (to_copy != 0) { DEBUG(misc, 6, "Extracting %s failed; still %i bytes to copy", filename, (int)to_copy); return false; } } DEBUG(misc, 9, " extraction successful"); return true; }
/** * @brief Fully equip one actor. The equipment that is added to the inventory of the given actor * is taken from the equipment script definition. * @param[in] chr The character that will get the weapon. * @param[in] ed The equipment that is added from to the actors inventory * @param[in] maxWeight The max weight this actor is allowed to carry. * @note The code below is a complete implementation * of the scheme sketched at the beginning of equipment_missions.ufo. * Beware: If two weapons in the same category have the same price, * only one will be considered for inventory. */ void InventoryInterface::EquipActorNormal (character_t* const chr, const equipDef_t* ed, int maxWeight) { const teamDef_t* td = chr->teamDef; const int numEquip = lengthof(ed->numItems); int repeat = 0; if (td->weapons) { int missedPrimary = 0; /**< If actor has a primary weapon, this is zero. Otherwise, this is the probability * 100 * that the actor had to get a primary weapon (used to compensate the lack of primary weapon) */ const objDef_t* primaryWeapon = nullptr; /* Primary weapons */ const int maxWeaponIdx = std::min(this->csi->numODs - 1, numEquip - 1); int randNumber = rand() % 100; for (int i = 0; i < maxWeaponIdx; i++) { const objDef_t* obj = INVSH_GetItemByIDX(i); if (ed->numItems[i] && obj->weapon && obj->fireTwoHanded && obj->isPrimary) { randNumber -= ed->numItems[i]; missedPrimary += ed->numItems[i]; if (!primaryWeapon && randNumber < 0) primaryWeapon = obj; } } /* See if a weapon has been selected. */ equipPrimaryWeaponType_t primary = WEAPON_NO_PRIMARY; int hasWeapon = 0; if (primaryWeapon) { hasWeapon += PackAmmoAndWeapon(chr, primaryWeapon, 0, ed, maxWeight); if (hasWeapon) { int ammo; /* Find the first possible ammo to check damage type. */ for (ammo = 0; ammo < this->csi->numODs; ammo++) if (ed->numItems[ammo] && this->csi->ods[ammo].isLoadableInWeapon(primaryWeapon)) break; if (ammo < this->csi->numODs) { if (/* To avoid two particle weapons. */ !(this->csi->ods[ammo].dmgtype == this->csi->damParticle) /* To avoid SMG + Assault Rifle */ && !(this->csi->ods[ammo].dmgtype == this->csi->damNormal)) { primary = WEAPON_OTHER; } else { primary = WEAPON_PARTICLE_OR_NORMAL; } } /* reset missedPrimary: we got a primary weapon */ missedPrimary = 0; } else { Com_DPrintf(DEBUG_SHARED, "INVSH_EquipActor: primary weapon '%s' couldn't be equipped in equipment '%s' (%s).\n", primaryWeapon->id, ed->id, invName); repeat = WEAPONLESS_BONUS > frand(); } } /* Sidearms (secondary weapons with reload). */ do { int randNumber = rand() % 100; const objDef_t* secondaryWeapon = nullptr; for (int i = 0; i < this->csi->numODs; i++) { const objDef_t* obj = INVSH_GetItemByIDX(i); if (ed->numItems[i] && obj->weapon && obj->isReloadable() && !obj->deplete && obj->isSecondary) { randNumber -= ed->numItems[i] / (primary == WEAPON_PARTICLE_OR_NORMAL ? 2 : 1); if (randNumber < 0) { secondaryWeapon = obj; break; } } } if (secondaryWeapon) { hasWeapon += PackAmmoAndWeapon(chr, secondaryWeapon, missedPrimary, ed, maxWeight); } } while (!hasWeapon && repeat--); /* Misc items and secondary weapons without reload. */ if (!hasWeapon) repeat = WEAPONLESS_BONUS > frand(); else repeat = 0; /* Misc object probability can be bigger than 100 -- you're sure to * have one misc if it fits your backpack */ int sum = 0; for (int i = 0; i < this->csi->numODs; i++) { const objDef_t* obj = INVSH_GetItemByIDX(i); if (ed->numItems[i] && ((obj->weapon && obj->isSecondary && (!obj->isReloadable() || obj->deplete)) || obj->isMisc)) { /* if ed->num[i] is greater than 100, the first number is the number of items you'll get: * don't take it into account for probability * Make sure that the probability is at least one if an item can be selected */ sum += ed->numItems[i] ? std::max(ed->numItems[i] % 100, 1) : 0; } } if (sum) { do { int randNumber = rand() % sum; const objDef_t* secondaryWeapon = nullptr; for (int i = 0; i < this->csi->numODs; i++) { const objDef_t* obj = INVSH_GetItemByIDX(i); if (ed->numItems[i] && ((obj->weapon && obj->isSecondary && (!obj->isReloadable() || obj->deplete)) || obj->isMisc)) { randNumber -= ed->numItems[i] ? std::max(ed->numItems[i] % 100, 1) : 0; if (randNumber < 0) { secondaryWeapon = obj; break; } } } if (secondaryWeapon) { int num = ed->numItems[secondaryWeapon->idx] / 100 + (ed->numItems[secondaryWeapon->idx] % 100 >= 100 * frand()); while (num--) { hasWeapon += PackAmmoAndWeapon(chr, secondaryWeapon, 0, ed, maxWeight); } } } while (repeat--); /* Gives more if no serious weapons. */ } /* If no weapon at all, bad guys will always find a blade to wield. */ if (!hasWeapon) { int maxPrice = 0; const objDef_t* blade = nullptr; Com_DPrintf(DEBUG_SHARED, "INVSH_EquipActor: no weapon picked in equipment '%s', defaulting to the most expensive secondary weapon without reload. (%s)\n", ed->id, invName); for (int i = 0; i < this->csi->numODs; i++) { const objDef_t* obj = INVSH_GetItemByIDX(i); if (ed->numItems[i] && obj->weapon && obj->isSecondary && !obj->isReloadable()) { if (obj->price > maxPrice) { maxPrice = obj->price; blade = obj; } } } if (maxPrice) hasWeapon += PackAmmoAndWeapon(chr, blade, 0, ed, maxWeight); } /* If still no weapon, something is broken, or no blades in equipment. */ if (!hasWeapon) Com_DPrintf(DEBUG_SHARED, "INVSH_EquipActor: cannot add any weapon; no secondary weapon without reload detected for equipment '%s' (%s).\n", ed->id, invName); /* Armour; especially for those without primary weapons. */ repeat = (float) missedPrimary > frand() * 100.0; } else { return; } Inventory* const inv = &chr->inv; const int speed = chr->score.skills[ABILITY_SPEED]; if (td->armour) { do { int randNumber = rand() % 100; for (int i = 0; i < this->csi->numODs; i++) { const objDef_t* armour = INVSH_GetItemByIDX(i); if (ed->numItems[i] && armour->isArmour()) { randNumber -= ed->numItems[i]; if (randNumber < 0) { const Item item(armour); int tuNeed = 0; const int weight = GetInventoryState(inv, tuNeed) + item.getWeight(); const int maxTU = GET_TU(speed, GET_ENCUMBRANCE_PENALTY(weight, chr->score.skills[ABILITY_POWER])); if (weight > maxWeight * WEIGHT_FACTOR || tuNeed > maxTU) continue; if (tryAddToInventory(inv, &item, &this->csi->ids[CID_ARMOUR])) { repeat = 0; break; } } } } } while (repeat-- > 0); } else { Com_DPrintf(DEBUG_SHARED, "INVSH_EquipActor: teamdef '%s' may not carry armour (%s)\n", td->name, invName); } { int randNumber = rand() % 10; for (int i = 0; i < this->csi->numODs; i++) { if (ed->numItems[i]) { const objDef_t* miscItem = INVSH_GetItemByIDX(i); if (miscItem->isMisc && !miscItem->weapon) { randNumber -= ed->numItems[i]; if (randNumber < 0) { const bool oneShot = miscItem->oneshot; const Item item(miscItem, oneShot ? miscItem : nullptr, oneShot ? miscItem->ammo : NONE_AMMO); containerIndex_t container; int tuNeed; const fireDef_t* itemFd = item.getSlowestFireDef(); const float weight = GetInventoryState(inv, tuNeed) + item.getWeight(); const int maxTU = GET_TU(speed, GET_ENCUMBRANCE_PENALTY(weight, chr->score.skills[ABILITY_POWER])); if (miscItem->headgear) container = CID_HEADGEAR; else if (miscItem->implant) container = CID_IMPLANT; else container = CID_BACKPACK; if (weight > maxWeight * WEIGHT_FACTOR || tuNeed > maxTU || (itemFd && itemFd->time > maxTU)) continue; tryAddToInventory(inv, &item, &this->csi->ids[container]); } } } } } }
bool CMainMenu::Show(UINT Flags,int x,int y,HWND hwnd,bool fToggle,const std::vector<int> *pItemList) { if (m_hmenu==NULL) return false; if (!m_fPopup || !fToggle || m_PopupMenu>=0) { if (m_fPopup) ::EndMenu(); HMENU hmenuCustom=m_hmenuPopup; if (pItemList!=NULL && !pItemList->empty()) { hmenuCustom=::CreatePopupMenu(); int OrigItemCount=::GetMenuItemCount(m_hmenuPopup); MENUITEMINFO mii; TCHAR szText[256]; mii.cbSize=sizeof(mii); mii.fMask=MIIM_FTYPE | MIIM_STATE | MIIM_ID | MIIM_SUBMENU | MIIM_STRING; mii.dwTypeData=szText; int ItemCount=0; for (auto itr=pItemList->begin();itr!=pItemList->end();++itr) { int ID=*itr; if (ID<0) { if (::AppendMenu(hmenuCustom,MF_SEPARATOR,0,NULL)) ItemCount++; } else if (ID>=CM_COMMAND_FIRST) { for (int j=0;j<OrigItemCount;j++) { mii.cch=lengthof(szText); if (::GetMenuItemInfo(m_hmenuPopup,j,TRUE,&mii) && mii.wID==ID) { if (::InsertMenuItem(hmenuCustom,ItemCount,TRUE,&mii)) ItemCount++; break; } } } else { mii.cch=lengthof(szText); if (::GetMenuItemInfo(m_hmenuPopup,ID,TRUE,&mii) && ::InsertMenuItem(hmenuCustom,ItemCount,TRUE,&mii)) ItemCount++; } } if (ItemCount==0) { ::DestroyMenu(hmenuCustom); hmenuCustom=m_hmenuPopup; } } m_hmenuShow=hmenuCustom; m_fPopup=true; m_PopupMenu=-1; ::TrackPopupMenu(hmenuCustom,Flags,x,y,0,hwnd,NULL); m_fPopup=false; m_hmenuShow=NULL; if (hmenuCustom!=m_hmenuPopup) { for (int i=::GetMenuItemCount(hmenuCustom)-1;i>=0;i--) { if ((::GetMenuState(hmenuCustom,i,MF_BYPOSITION)&MF_POPUP)!=0) ::RemoveMenu(hmenuCustom,i,MF_BYPOSITION); } ::DestroyMenu(hmenuCustom); } } else { ::EndMenu(); } return true; }
void win_open(wstring wpath) { wstring p = wpath; while (iswalpha(*p)) p++; if (*wpath == '\\' || *p == ':' || wcsncmp(W("www."), wpath, 4) == 0) { // Looks like it's a Windows path or URI shell_exec(wpath); } else { // Need to convert POSIX path to Windows first if (support_wsl) { #ifdef debug_wsl printf("open <%ls>\n", wpath); #endif if (wcsncmp(wpath, W("/mnt/"), 5) == 0) { wchar * unwsl = newn(wchar, wcslen(wpath) + 6); wcscpy(unwsl, W("/cygdrive")); wcscat(unwsl, wpath + 4); delete(wpath); wpath = unwsl; } else if (*wpath == '/') { // prepend %LOCALAPPDATA%\lxss[\rootfs] char * appd = getenv("LOCALAPPDATA"); if (appd) { wchar * wappd = cs__mbstowcs(appd); appd = path_win_w_to_posix(wappd); free(wappd); wappd = cs__mbstowcs(appd); free(appd); bool rootfs_mount = true; for (uint i = 0; i < lengthof(lxss_mounts); i++) { if (ispathprefixw(lxss_mounts[i].w, wpath)) { rootfs_mount = false; break; } } wchar * unwsl = newn(wchar, wcslen(wappd) + wcslen(wpath) + 13); wcscpy(unwsl, wappd); free(wappd); wcscat(unwsl, W("/lxss")); if (rootfs_mount) wcscat(unwsl, W("/rootfs")); wcscat(unwsl, wpath); delete(wpath); wpath = unwsl; } } } wstring conv_wpath = child_conv_path(wpath); #ifdef debug_wsl printf("open <%ls> <%ls>\n", wpath, conv_wpath); #endif delete(wpath); if (conv_wpath) shell_exec(conv_wpath); else message_box(0, strerror(errno), null, MB_ICONERROR, null); } }
/* * pgstrom_collect_device_info * * It collects properties of all the OpenCL devices. It shall be called once * by the OpenCL management worker process, prior to any other backends. */ static List * construct_opencl_device_info(int platform_index) { cl_platform_id platforms[32]; cl_device_id devices[MAX_NUM_DEVICES]; cl_uint n_platform; cl_uint n_devices; cl_int i, j, rc; long score_max = -1; List *result = NIL; rc = clGetPlatformIDs(lengthof(platforms), platforms, &n_platform); if (rc != CL_SUCCESS) elog(ERROR, "clGetPlatformIDs failed (%s)", opencl_strerror(rc)); for (i=0; i < n_platform; i++) { pgstrom_platform_info *pl_info; pgstrom_device_info *dev_info; long score = 0; List *temp = NIL; pl_info = collect_opencl_platform_info(platforms[i]); pl_info->pl_index = i; rc = clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_CPU | CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR, lengthof(devices), devices, &n_devices); if (rc != CL_SUCCESS) elog(ERROR, "clGetDeviceIDs failed (%s)", opencl_strerror(rc)); elog(LOG, "PG-Strom: [%d] OpenCL Platform: %s", i, pl_info->pl_name); for (j=0; j < n_devices; j++) { dev_info = collect_opencl_device_info(devices[j]); dev_info->pl_info = pl_info; dev_info->dev_index = j; elog(LOG, "PG-Strom: + device %s (%uMHz x %uunits, %luMB)", dev_info->dev_name, dev_info->dev_max_clock_frequency, dev_info->dev_max_compute_units, dev_info->dev_global_mem_size >> 20); /* rough estimation about computing power */ if ((dev_info->dev_type & CL_DEVICE_TYPE_GPU) != 0) score += 32 * (dev_info->dev_max_compute_units * dev_info->dev_max_clock_frequency); else score += (dev_info->dev_max_compute_units * dev_info->dev_max_clock_frequency); temp = lappend(temp, dev_info); } if (platform_index == i || (platform_index < 0 && score > score_max)) { opencl_platform_id = platforms[i]; opencl_num_devices = n_devices; for (j=0; j < n_devices; j++) opencl_devices[j] = devices[j]; score_max = score; result = temp; } } /* show platform name if auto-selection */ if (platform_index < 0 && result != NIL) { pgstrom_platform_info *pl_info = ((pgstrom_device_info *) linitial(result))->pl_info; elog(LOG, "PG-Strom: auto platform selection: %s", pl_info->pl_name); } if (result != NIL) { /* * Create an OpenCL context */ opencl_context = clCreateContext(NULL, opencl_num_devices, opencl_devices, NULL, NULL, &rc); if (rc != CL_SUCCESS) elog(ERROR, "clCreateContext failed: %s", opencl_strerror(rc)); /* * Create an OpenCL command queue for each device */ for (j=0; j < opencl_num_devices; j++) { opencl_cmdq[j] = clCreateCommandQueue(opencl_context, opencl_devices[j], CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_PROFILING_ENABLE, &rc); if (rc != CL_SUCCESS) elog(ERROR, "clCreateCommandQueue failed: %s", opencl_strerror(rc)); } } return result; }
static float4 calc_rank_cd(float4 *arrdata, TSVector txt, TSQuery query, int method) { DocRepresentation *doc; int len, i, doclen = 0; Extention ext; double Wdoc = 0.0; double invws[lengthof(weights)]; double SumDist = 0.0, PrevExtPos = 0.0, CurExtPos = 0.0; int NExtent = 0; QueryRepresentation qr; for (i = 0; i < lengthof(weights); i++) { invws[i] = ((double) ((arrdata[i] >= 0) ? arrdata[i] : weights[i])); if (invws[i] > 1.0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("weight out of range"))); invws[i] = 1.0 / invws[i]; } qr.query = query; qr.operandexist = (bool *) palloc0(sizeof(bool) * query->size); doc = get_docrep(txt, &qr, &doclen); if (!doc) { pfree(qr.operandexist); return 0.0; } MemSet(&ext, 0, sizeof(Extention)); while (Cover(doc, doclen, &qr, &ext)) { double Cpos = 0.0; double InvSum = 0.0; int nNoise; DocRepresentation *ptr = ext.begin; while (ptr <= ext.end) { InvSum += invws[ptr->wclass]; ptr++; } Cpos = ((double) (ext.end - ext.begin + 1)) / InvSum; /* * if doc are big enough then ext.q may be equal to ext.p due to limit * of posional information. In this case we approximate number of * noise word as half cover's length */ nNoise = (ext.q - ext.p) - (ext.end - ext.begin); if (nNoise < 0) nNoise = (ext.end - ext.begin) / 2; Wdoc += Cpos / ((double) (1 + nNoise)); CurExtPos = ((double) (ext.q + ext.p)) / 2.0; if (NExtent > 0 && CurExtPos > PrevExtPos /* prevent devision by * zero in a case of multiple lexize */ ) SumDist += 1.0 / (CurExtPos - PrevExtPos); PrevExtPos = CurExtPos; NExtent++; } if ((method & RANK_NORM_LOGLENGTH) && txt->size > 0) Wdoc /= log((double) (cnt_length(txt) + 1)); if (method & RANK_NORM_LENGTH) { len = cnt_length(txt); if (len > 0) Wdoc /= (double) len; } if ((method & RANK_NORM_EXTDIST) && NExtent > 0 && SumDist > 0) Wdoc /= ((double) NExtent) / SumDist; if ((method & RANK_NORM_UNIQ) && txt->size > 0) Wdoc /= (double) (txt->size); if ((method & RANK_NORM_LOGUNIQ) && txt->size > 0) Wdoc /= log((double) (txt->size + 1)) / log(2.0); if (method & RANK_NORM_RDIVRPLUS1) Wdoc /= (Wdoc + 1); pfree(doc); pfree(qr.operandexist); return (float4) Wdoc; }
NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_D_LOCATION), SetDataTip(STR_BUTTON_LOCATION, STR_NULL), SetFill(1, 1), SetResize(1, 0), NWidget(NWID_SELECTION, INVALID_COLOUR, WID_D_SHOW_RENAME), // rename button NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_D_RENAME), SetDataTip(STR_BUTTON_RENAME, STR_DEPOT_RENAME_TOOLTIP), SetFill(1, 1), SetResize(1, 0), EndContainer(), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_D_VEHICLE_LIST), SetDataTip(0x0, STR_NULL), SetFill(0, 1), NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_D_STOP_ALL), SetDataTip(SPR_FLAG_VEH_STOPPED, STR_NULL), SetFill(0, 1), NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_D_START_ALL), SetDataTip(SPR_FLAG_VEH_RUNNING, STR_NULL), SetFill(0, 1), NWidget(WWT_RESIZEBOX, COLOUR_GREY), EndContainer(), }; static const WindowDesc _train_depot_desc( WDP_AUTO, 362, 123, WC_VEHICLE_DEPOT, WC_NONE, 0, _nested_train_depot_widgets, lengthof(_nested_train_depot_widgets) ); static const WindowDesc _road_depot_desc( WDP_AUTO, 316, 97, WC_VEHICLE_DEPOT, WC_NONE, 0, _nested_train_depot_widgets, lengthof(_nested_train_depot_widgets) ); static const WindowDesc _ship_depot_desc( WDP_AUTO, 306, 99, WC_VEHICLE_DEPOT, WC_NONE, 0, _nested_train_depot_widgets, lengthof(_nested_train_depot_widgets) );
void R_RemapDeluxeImages( world_t *world ) { int i; if( !tr.deluxemaps[0] ) return; R_InitConverter(); R_StateSetActiveTmuUntracked( GL_TEXTURE0 ); R_StateSetActiveClientTmuUntracked( GL_TEXTURE0 ); glPushAttrib( GL_ALL_ATTRIB_BITS ); glPushClientAttrib( GL_CLIENT_ALL_ATTRIB_BITS ); glEnableClientState( GL_VERTEX_ARRAY ); glEnableClientState( GL_NORMAL_ARRAY ); glEnableVertexAttribArrayARB( 6 ); glEnableVertexAttribArrayARB( 7 ); glClearColor( 0, 0, 0, 0 ); glDisable( GL_DEPTH_TEST ); glDisable( GL_STENCIL_TEST ); glDisable( GL_ALPHA_TEST ); glDisable( GL_BLEND ); glDisable( GL_CULL_FACE ); glDisable( GL_MULTISAMPLE ); glEnable( GL_POLYGON_SMOOTH ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glEnable( GL_VERTEX_PROGRAM_ARB ); glBindProgramARB( GL_VERTEX_PROGRAM_ARB, conv.vp ); glEnable( GL_FRAGMENT_PROGRAM_ARB ); glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, conv.fp ); glEnable( GL_TEXTURE_2D ); for( i = 0; i < tr.numLightmaps; i++ ) { int j, y; unsigned *buf0, *buf1; image_t *img = tr.deluxemaps[i]; glBindTexture( GL_TEXTURE_2D, img->texnum ); glClear( GL_COLOR_BUFFER_BIT ); glViewport( 0, img->uploadHeight, img->uploadWidth, img->uploadHeight ); glDisable( GL_VERTEX_PROGRAM_ARB ); glDisable( GL_FRAGMENT_PROGRAM_ARB ); glBegin( GL_QUADS ); { glTexCoord2f( 0, 0 ); glVertex2f( -1, -1 ); glTexCoord2f( 0, 1 ); glVertex2f( -1, 1 ); glTexCoord2f( 1, 1 ); glVertex2f( 1, 1 ); glTexCoord2f( 1, 0 ); glVertex2f( 1, -1 ); } glEnd(); glEnable( GL_VERTEX_PROGRAM_ARB ); glEnable( GL_FRAGMENT_PROGRAM_ARB ); glViewport( 0, 0, img->uploadWidth, img->uploadHeight ); glProgramLocalParameter4fARB( GL_VERTEX_PROGRAM_ARB, 0, img->uploadWidth, img->uploadHeight, 1.0F / img->uploadWidth, 1.0F / img->uploadHeight ); for( j = 0; j < world->numsurfaces; j++ ) { const msurface_t *srf = world->surfaces + j; const shader_t *shader = srf->shader; const msurface_ex_t *exsrf = srf->redirect; if( !shader->stages[0] || !shader->stages[0]->active ) continue; if( shader->stages[0]->deluxeMap != img ) continue; if( !exsrf ) continue; glVertexPointer( 2, GL_FLOAT, sizeof( drawVert_ex_t ), &exsrf->verts[0].uvL ); glNormalPointer( GL_FLOAT, sizeof( drawVert_ex_t ), &exsrf->verts[0].norm ); glVertexAttribPointerARB( 6, 3, GL_FLOAT, GL_FALSE, sizeof( drawVert_ex_t ), &exsrf->verts[0].tan ); glVertexAttribPointerARB( 7, 3, GL_FLOAT, GL_FALSE, sizeof( drawVert_ex_t ), &exsrf->verts[0].bin ); glDrawElements( exsrf->primType, exsrf->numIndices, GL_UNSIGNED_SHORT, exsrf->indices ); } glFinish(); buf0 = (unsigned*)ri.Hunk_AllocateTempMemory( img->uploadWidth * img->uploadHeight * 4 ); buf1 = (unsigned*)ri.Hunk_AllocateTempMemory( img->uploadWidth * img->uploadHeight * 4 ); //can't just copy to the texture since we //need the custom mipmap generator glReadPixels( 0, 0, img->uploadWidth, img->uploadHeight, GL_RGBA, GL_UNSIGNED_BYTE, buf0 ); #define DELUXEL( buf, x, y ) ((byte*)(buf) + (((y) * img->uploadWidth + (x)) * 4)) Com_Memcpy( buf1, buf0, img->uploadWidth * img->uploadHeight * 4 ); for( j = 0; j < 4; j++ ) { for( y = 0; y < img->uploadHeight; y++ ) { int x; for( x = 0; x < img->uploadWidth; x++ ) { static int neighbors[8][2] = { { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 }, { -1, 0 }, { -1, 1 } }; int i; int sum[3], c; byte *cIn = DELUXEL( buf0, x, y ); byte *cOut = DELUXEL( buf1, x, y ); cOut[3] = cIn[3]; if( cIn[2] ) { //if it has some Z value //then it's already good cOut[0] = cIn[0]; cOut[1] = cIn[1]; cOut[2] = cIn[2]; continue; } c = 0; sum[0] = sum[1] = sum[2] = 0; for( i = 0; i < lengthof( neighbors ); i++ ) { int nx = x + neighbors[i][0]; int ny = y + neighbors[i][1]; if( nx >= 0 && nx < img->uploadWidth && ny >= 0 && ny < img->uploadHeight ) { byte *n = DELUXEL( buf0, nx, ny ); if( !n[2] ) continue; sum[0] += n[0]; sum[1] += n[1]; sum[2] += n[2]; c++; } } if( c ) { cOut[0] = sum[0] / c; cOut[1] = sum[1] / c; cOut[2] = sum[2] / c; } } } Com_Memcpy( buf0, buf1, img->uploadWidth * img->uploadHeight * 4 ); } for( y = 0; y < img->uploadHeight; y++ ) { int x; for( x = 0; x < img->uploadWidth; x++ ) { byte *d = DELUXEL( buf1, x, y ); if( !d[2] ) { d[0] = 0; d[1] = 0; d[2] = 0xFF; } } } //write it out to file { int size; char path[MAX_QPATH]; byte *out_buf; Com_sprintf( path, sizeof( path ), "deluxe/%s/dm_%04d.tga", world->baseName, i ); size = 18 + img->uploadWidth * img->uploadHeight * 3; out_buf = (byte*)ri.Hunk_AllocateTempMemory( size ); Com_Memset( out_buf, 0, 18 ); out_buf[2] = 2; // uncompressed type out_buf[12] = img->uploadWidth & 255; out_buf[13] = img->uploadWidth >> 8; out_buf[14] = img->uploadHeight & 255; out_buf[15] = img->uploadHeight >> 8; out_buf[16] = 24; // pixel size out_buf[17] = 0x20; // reverse row order for( y = 0; y < img->uploadHeight; y++ ) { int x; for( x = 0; x < img->uploadWidth; x++ ) { byte *d = DELUXEL( buf1, x, y ); out_buf[18 + (y * img->uploadWidth + x) * 3 + 0] = d[2]; out_buf[18 + (y * img->uploadWidth + x) * 3 + 1] = d[1]; out_buf[18 + (y * img->uploadWidth + x) * 3 + 2] = d[0]; } } ri.FS_WriteFile( path, out_buf, size ); ri.Hunk_FreeTempMemory( out_buf ); } #undef DELUXEL Upload32( buf1, qfalse, img, ILF_VECTOR_SB3 ); #ifdef _DEBUG glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, img->texnum ); glViewport( img->uploadWidth, 0, img->uploadWidth, img->uploadHeight ); glDisable( GL_VERTEX_PROGRAM_ARB ); glDisable( GL_FRAGMENT_PROGRAM_ARB ); glBegin( GL_QUADS ); { glTexCoord2f( 0, 0 ); glVertex2f( -1, -1 ); glTexCoord2f( 0, 1 ); glVertex2f( -1, 1 ); glTexCoord2f( 1, 1 ); glVertex2f( 1, 1 ); glTexCoord2f( 1, 0 ); glVertex2f( 1, -1 ); } glEnd(); glEnable( GL_VERTEX_PROGRAM_ARB ); glEnable( GL_FRAGMENT_PROGRAM_ARB ); GLimp_EndFrame(); #endif ri.Hunk_FreeTempMemory( buf1 ); ri.Hunk_FreeTempMemory( buf0 ); } glPopClientAttrib(); glPopAttrib(); glDeleteProgramsARB( 1, &conv.vp ); glDeleteProgramsARB( 1, &conv.fp ); }