示例#1
0
int __cdecl
wmain(int argc, PWCHAR argv[])
{
	size_t	i;
    WCHAR	fileName[MAX_PATH];
    WCHAR	driverFullPath[MAX_PATH] = { 0 };
    WCHAR	mounterFullPath[MAX_PATH] = { 0 };
    WCHAR	type;

    //setlocale(LC_ALL, "");

    GetModuleFileName(NULL, fileName, MAX_PATH);
    
    // search the last "\"
    for(i = wcslen(fileName) - 1; i > 0 && fileName[i] != L'\\'; --i)
    {
        ;
    }
    fileName[i] = L'\0';

    wcscpy_s(mounterFullPath, MAX_PATH, fileName);
    wcscat_s(mounterFullPath, MAX_PATH, L"\\mounter.exe");
    fwprintf(stderr, L"mounter path %s\n", mounterFullPath);

    GetSystemDirectory(driverFullPath, MAX_PATH);
    wcscat_s(driverFullPath, MAX_PATH, L"\\drivers\\dokan.sys");

    fwprintf(stderr, L"driver path %s\n", driverFullPath);
    

    if (GetOption(argc, argv, 1) == L'v') {
        fprintf(stderr, "dokanctl : %s %s\n", __DATE__, __TIME__);
        fprintf(stderr, "Dokan version : %d\n", DokanVersion());
        fprintf(stderr, "Dokan driver version : 0x%X\n", DokanDriverVersion());
        return 0;
    
    } else if (GetOption(argc, argv, 1) == L'm') {
        return ShowMountList();

    } else if (GetOption(argc, argv, 1) == L'u' && argc == 3) {
        return Unmount(argv[2], FALSE);

    } else if (GetOption(argc, argv, 1) == L'u' &&
                GetOption(argc, argv, 3) == L'f' && argc == 4) {
        return Unmount(argv[2], TRUE);

    } else if (argc < 3 || wcslen(argv[1]) != 2 || argv[1][0] != L'/' ) {
        return ShowUsage();
    }

    type = towlower(argv[2][0]);

    switch(towlower(argv[1][1])) {
    case L'i':
        if (type ==  L'd') {
            if (DokanServiceInstall(DOKAN_DRIVER_SERVICE,
                                    SERVICE_FILE_SYSTEM_DRIVER,
                                    driverFullPath))
                fprintf(stderr, "driver install ok");
            else
                fprintf(stderr, "driver install failed");

        } else if (type == L's') {
            if (DokanServiceInstall(DOKAN_MOUNTER_SERVICE,
                                    SERVICE_WIN32_OWN_PROCESS,
                                    mounterFullPath))
                fprintf(stderr, "mounter install ok");
            else
                fprintf(stderr, "mounter install failed");
        
        } else if (type == L'a') {
            if (DokanServiceInstall(DOKAN_DRIVER_SERVICE,
                                    SERVICE_FILE_SYSTEM_DRIVER,
                                    driverFullPath))
                fprintf(stderr, "driver install ok");
            else
                fprintf(stderr, "driver install failed");

            if (DokanServiceInstall(DOKAN_MOUNTER_SERVICE,
                                    SERVICE_WIN32_OWN_PROCESS,
                                    mounterFullPath))
                fprintf(stderr, "mounter install ok");
            else
                fprintf(stderr, "mounter install failed");
        } else if (type == L'n') {
            if (DokanNetworkProviderInstall())
                fprintf(stderr, "network provider install ok");
            else
                fprintf(stderr, "network provider install failed");
        }
        break;

    case L'r':
        if (type == L'd') {
            if (DokanServiceDelete(DOKAN_DRIVER_SERVICE))
                fprintf(stderr, "driver remove ok");
            else
                fprintf(stderr, "driver remvoe failed");
        
        } else if (type == L's') {
            if (DokanServiceDelete(DOKAN_MOUNTER_SERVICE))
                fprintf(stderr, "mounter remove ok");
            else
                fprintf(stderr, "mounter remvoe failed");	
        
        } else if (type == L'a') {
            if (DokanServiceDelete(DOKAN_MOUNTER_SERVICE))
                fprintf(stderr, "mounter remove ok");
            else
                fprintf(stderr, "mounter remvoe failed");	

            if (DokanServiceDelete(DOKAN_DRIVER_SERVICE))
                fprintf(stderr, "driver remove ok");
            else
                fprintf(stderr, "driver remvoe failed");
        } else if (type == L'n') {
            if (DokanNetworkProviderUninstall())
                fprintf(stderr, "network provider remove ok");
            else
                fprintf(stderr, "network provider remove failed");
        }
        break;
    case L'd':
        if (L'0' <= type && type <= L'9') {
            ULONG mode = type - L'0';
            if (DokanSetDebugMode(mode)) {
                fprintf(stderr, "set debug mode ok");
            } else {
                fprintf(stderr, "set debug mode failed");
            }
        }
        break;
    default:
        fprintf(stderr, "unknown option");
    }
    

    return 0;
}
示例#2
0
int 
main(int argc, char **argv)
{
  // Look for help
  for (int i = 0; i < argc; i++) {
    if (!strcmp(argv[i], "-help")) {
      ShowUsage();
    }
  }

  // Read input and output mesh filenames
  if (argc < 3)  ShowUsage();
  argv++, argc--; // First argument is program name
  char *input_mesh_name = *argv; argv++, argc--; 
  char *output_mesh_name = *argv; argv++, argc--; 

  // Allocate mesh
  R3Mesh *mesh = new R3Mesh();
  if (!mesh) {
    fprintf(stderr, "Unable to allocate mesh\n");
    exit(-1);
  }

  // Read input mesh
  if (!mesh->Read(input_mesh_name)) {
    fprintf(stderr, "Unable to read mesh from %s\n", input_mesh_name);
    exit(-1);
  }

  // Parse arguments and perform operations 
  while (argc > 0) {
    if (!strcmp(*argv, "-twist")) {
      CheckOption(*argv, argc, 2);
      double angle = atof(argv[1]);
      argv += 2, argc -= 2;
      mesh->Twist(angle);
    }
    else if (!strcmp(*argv, "-taubin")) {
      CheckOption(*argv, argc, 4);
      double lambda = atof(argv[1]);
      double mu = atof(argv[2]);
      double iters = atoi(argv[3]);
      argv += 4, argc -= 4;
      mesh->Taubin(lambda, mu, iters);
    }
    else if (!strcmp(*argv, "-loop")) {
      CheckOption(*argv, argc, 1);
      argv += 1, argc -= 1;
      mesh->Loop();
    }
    else {
      // Unrecognized program argument
      fprintf(stderr, "meshpro: invalid option: %s\n", *argv);
      ShowUsage();
    }
  }

  // Write output mesh
  if (!mesh->Write(output_mesh_name)) {
    fprintf(stderr, "Unable to write mesh to %s\n", output_mesh_name);
    exit(-1);
  }

  // Delete mesh
  delete mesh;

  // Return success
  return EXIT_SUCCESS;
}
示例#3
0
DWORD
ParseArgs(
    int    argc,
    char*  argv[],
    PSTR*  ppszTargetFQDN,
    PSTR*  ppszSiteName,
    PSTR*  ppszPrimaryDomain,
    PDWORD pdwFlags
    )
{
    typedef enum {
            PARSE_MODE_OPEN = 0,
            PARSE_MODE_SITENAME,
            PARSE_MODE_PREFERRED_DOMAIN,
            PARSE_MODE_OPTIONS
        } ParseMode;

    DWORD dwError = 0;
    int iArg = 1;
    PSTR pszArg = NULL;
    ParseMode parseMode = PARSE_MODE_OPEN;
    PSTR pszTargetFQDN = NULL;
    PSTR pszSiteName = NULL;
    PSTR pszPrimaryDomain = NULL;
    DWORD dwFlags = 0;

    do {
        pszArg = argv[iArg++];
        if (IsNullOrEmptyString(pszArg))
        {
            break;
        }
        
        switch (parseMode)
        {
            case PARSE_MODE_OPEN:
        
                if ((strcmp(pszArg, "--help") == 0) ||
                    (strcmp(pszArg, "-h") == 0))
                {
                    ShowUsage();
                    exit(0);
                }
                else
                {
                    dwError = LWNetAllocateString(pszArg, &pszTargetFQDN);
                    BAIL_ON_LWNET_ERROR(dwError);
        
                    parseMode = PARSE_MODE_OPTIONS;
                }
                break;

            case PARSE_MODE_OPTIONS:
                if(strcmp(pszArg, "--site") == 0)
                {
                    parseMode = PARSE_MODE_SITENAME;
                }
                else if(strcmp(pszArg, "--preferred-domain") == 0)
                {
                    parseMode = PARSE_MODE_PREFERRED_DOMAIN;
                }
                else if(strcmp(pszArg, "--force") == 0)
                {
                    dwError = AddFlag(DS_FORCE_REDISCOVERY, &dwFlags);
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                else if(strcmp(pszArg, "--ds-required") == 0)
                {
                    dwError = AddFlag(DS_DIRECTORY_SERVICE_REQUIRED, &dwFlags);
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                else if(strcmp(pszArg, "--gc-required") == 0)
                {
                    dwError = AddFlag(DS_GC_SERVER_REQUIRED, &dwFlags);
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                else if(strcmp(pszArg, "--pdc-required") == 0)
                {
                    dwError = AddFlag(DS_PDC_REQUIRED, &dwFlags);
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                else if(strcmp(pszArg, "--background-only") == 0)
                {
                    dwError = AddFlag(DS_BACKGROUND_ONLY, &dwFlags);
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                else if(strcmp(pszArg, "--kdc-required") == 0)
                {
                    dwError = AddFlag(DS_KDC_REQUIRED, &dwFlags);
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                else if(strcmp(pszArg, "--timeserv-required") == 0)
                {
                    dwError = AddFlag(DS_TIMESERV_REQUIRED, &dwFlags);
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                else if(strcmp(pszArg, "--writeable-required") == 0)
                {
                    dwError = AddFlag(DS_WRITABLE_REQUIRED, &dwFlags);
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                else if(strcmp(pszArg, "--good-timeserv-required") == 0)
                {
                    dwError = AddFlag(DS_GOOD_TIMESERV_REQUIRED, &dwFlags);
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                else if(strcmp(pszArg, "--avoid-self") == 0)
                {
                    dwError = AddFlag(DS_AVOID_SELF, &dwFlags);
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                else 
                {
                    LWNET_LOG_ERROR("Invalid argument: %s", pszArg);
                    dwError = ERROR_INVALID_PARAMETER;
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                break;
            case PARSE_MODE_SITENAME:
                
                if(!IsNullOrEmptyString(pszSiteName))
                {
                    LWNET_LOG_ERROR("Invalid argument: %s", pszArg);
                    dwError = ERROR_INVALID_PARAMETER;
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                
                dwError = LWNetAllocateString(pszArg, &pszSiteName);
                BAIL_ON_LWNET_ERROR(dwError);
                
                parseMode = PARSE_MODE_OPTIONS;
                break;
            case PARSE_MODE_PREFERRED_DOMAIN:
                
                if(!IsNullOrEmptyString(pszPrimaryDomain))
                {
                    LWNET_LOG_ERROR("Invalid argument: %s", pszArg);
                    dwError = ERROR_INVALID_PARAMETER;
                    BAIL_ON_LWNET_ERROR(dwError);
                }
                
                dwError = LWNetAllocateString(pszArg, &pszPrimaryDomain);
                BAIL_ON_LWNET_ERROR(dwError);
                
                parseMode = PARSE_MODE_OPTIONS;
                break;
        }
        
    } while (iArg < argc);

    
    if(IsNullOrEmptyString(pszTargetFQDN))
    {
        ShowUsage();
        exit(0);
    }
    
error:
    if (dwError)
    {
        LWNET_SAFE_FREE_STRING(pszTargetFQDN);
        LWNET_SAFE_FREE_STRING(pszSiteName);
        LWNET_SAFE_FREE_STRING(pszPrimaryDomain);
        dwFlags = 0;
    }

    *ppszTargetFQDN = pszTargetFQDN;
    *ppszSiteName = pszSiteName;
    *ppszPrimaryDomain = pszPrimaryDomain;
    *pdwFlags = dwFlags;

    return dwError;
}
示例#4
0
// program entry point
int main(int argc, char *argv[])
{
    char szErrorMessage[266] = {0};
    char szExeFilename[266]  = {0};
    char szXbeFilename[266]  = {0};
    char szDumpFilename[266] = {0};
    char szXbeTitle[256]     = "Untitled";
    bool bRetail             = true;

    // parse command line
    for(int v=1;v<argc;v++)
    {
        char *szOption    = 0;
        char *szParam     = 0;
        uint  dwParamSize = 0;

        // if this isn't an option, it must be the Exe file
        if(argv[v][0] != '-')
        {
            strncpy(szExeFilename, argv[v], 265);
            continue;
        }

        // locate the colon and seperate option / parameters
        {
            uint dwColon = (uint)-1;

            for(uint c=1;argv[v][c] != 0;c++)
            {
                if(argv[v][c] == ':')
                {
                    dwColon = c;
                    break;
                }
            }

            if(dwColon == (uint)-1)
            {
                strcpy(szErrorMessage, "Command line format error");
                goto cleanup;
            }

            argv[v][dwColon] = '\0';

            szOption = &argv[v][1];
            szParam  = &argv[v][dwColon + 1];

            while(szParam[dwParamSize] != 0)
                dwParamSize++;
        }

        // interpret the current switch
        {
            char szOptionU[266] = {0};
            char szParamU[266] = {0};

            strncpy(szOptionU, szOption, 265);
            strncpy(szParamU, szParam, 265);

            MakeUpper(szOptionU);
            MakeUpper(szParamU);

            if(strcmp(szOptionU, "OUT") == 0)
            {
                strcpy(szXbeFilename, szParam);
            }
            else if(strcmp(szOptionU, "DUMPINFO") == 0)
            {
                strcpy(szDumpFilename, szParam);
            }
            else if(strcmp(szOptionU, "TITLE") == 0)
            {
                if(dwParamSize > 256)
                    printf("WARNING: Title too long, using default title\n");
                else
                    strcpy(szXbeTitle, szParam);
            }
            else if(strcmp(szOptionU, "MODE") == 0)
            {
                if(strcmp(szParamU, "RETAIL") == 0)
                    bRetail = true;
                else if(strcmp(szParamU, "DEBUG") == 0)
                    bRetail = false;
                else
                {
                    strcpy(szErrorMessage, "invalid MODE");
                    goto cleanup;
                }
            }
            else
            {
                char szBuffer[255];
                sprintf(szBuffer, "Unrecognized command : %s", szOption);
                strcpy(szErrorMessage, szBuffer);
                goto cleanup;
            }
        }
    }

    // verify we recieved the required parameters
    if(szExeFilename[0] == '\0')
    {
        ShowUsage();
        return 1;
    }

    // if we don't have an Xbe filename, generate one from szExeFilename
    if(szXbeFilename[0] == '\0')
    {
        strcpy(szXbeFilename, szExeFilename);

        char *szFilename = &szXbeFilename[0];

        // locate last \ or / (if there are any)
        {
            for(int c=0;szXbeFilename[c] != 0;c++)
                if(szXbeFilename[c] == '\\' || szXbeFilename[c] == '/')
                    szFilename = &szXbeFilename[c+1];
        }

        // locate and remove last . (if there are any)
        {
            char szWorkingU[266];

            char *szWorking = szFilename;

            strncpy(szWorkingU, szWorking, 265);

            for(int c=0;szFilename[c] != 0;c++)
                if(szFilename[c] == '.')
                    szWorking = &szFilename[c];

            MakeUpper(szWorking);

            if(strcmp(szWorkingU, ".exe") == 0)
                strcpy(szWorking, ".xbe");
            else
                strcat(szXbeFilename, ".xbe");
        }
    }

    // open and convert Exe file
    {
        Exe *ExeFile = new Exe(szExeFilename);

        if(ExeFile->GetError() != 0)
        {
            strcpy(szErrorMessage, ExeFile->GetError());
            goto cleanup;
        }

        Xbe *XbeFile = new Xbe(ExeFile, szXbeTitle, bRetail);

        if(XbeFile->GetError() != 0)
        {
            strcpy(szErrorMessage, XbeFile->GetError());
            goto cleanup;
        }

        if(szDumpFilename[0] != 0)
        {
            FILE *outfile = fopen(szDumpFilename, "wt");
            XbeFile->DumpInformation(outfile);
            fclose(outfile);

            if(XbeFile->GetError() != 0)
            {
                if(XbeFile->IsFatal())
                {
                    strcpy(szErrorMessage, XbeFile->GetError());
                    goto cleanup;
                }
                else
                {
                    printf("DUMPINFO -> Warning: %s\n", XbeFile->GetError());
                    XbeFile->ClearError();
                }
            }
        }

        XbeFile->Export(szXbeFilename);

        if(XbeFile->GetError() != 0)
        {
            strcpy(szErrorMessage, XbeFile->GetError());
            goto cleanup;
        }
    }

cleanup:

    if(szErrorMessage[0] != 0)
    {
        ShowUsage();
    
        printf("\n");
        printf(" *  Error : %s\n", szErrorMessage);

        return 1;
    }

    return 0;
}
示例#5
0
int main (int argc, char **argv)
{
int ix,tv,found=0, spr, resolution;
int dloop=1, rcc=-1;
char rstr[BUFSIZE]={0}, *rptr=NULL, *aptr=NULL;
time_t tm1,tm2;
#ifndef MARTII
FILE *fh;
#endif

		if(argc<2)
		{
			ShowUsage();
			return 0;
		}

		//init framebuffer before 1st scale2res
		fb = open(FB_DEVICE, O_RDWR);
#if HAVE_SPARK_HARDWARE || HAVE_DUCKBOX_HARDWARE
		if (fb < 0)
			fb = open(FB_DEVICE_FALLBACK, O_RDWR);
#endif
		if(fb == -1)
		{
			perror(__plugin__ " <open framebuffer device>");
			exit(1);
		}
		if(ioctl(fb, FBIOGET_FSCREENINFO, &fix_screeninfo) == -1)
		{
			perror(__plugin__ " <FBIOGET_FSCREENINFO>\n");
			return -1;
		}
		if(ioctl(fb, FBIOGET_VSCREENINFO, &var_screeninfo) == -1)
		{
			perror(__plugin__ " <FBIOGET_VSCREENINFO>\n");
			return -1;
		}
#if defined(HAVE_SPARK_HARDWARE) || defined(HAVE_DUCKBOX_HARDWARE)
		var_screeninfo.xres = DEFAULT_XRES;
		var_screeninfo.yres = DEFAULT_YRES;
#endif

		if(!(lfb = (uint32_t*)mmap(0, fix_screeninfo.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fb, 0)))
		{
			perror(__plugin__ " <mapping of Framebuffer>\n");
			return -1;
		}

		dloop=0;
		for(tv=1; !dloop && tv<argc; tv++)
		{
			aptr=argv[tv];
			if(!strcmp(aptr,"-v") || !strcmp(aptr,"--version"))
			{
				printf("%s Version %.2f\n", __plugin__, M_VERSION);
				return 0;
			}
			if((rptr=strchr(aptr,'='))!=NULL)
			{
				rptr++;
				if(strstr(aptr,"size=")!=NULL)
				{
					if(sscanf(rptr,"%d",&FSIZE_MED)!=1)
					{
						dloop=1;
					}
				}
				else
				{
					if(strstr(aptr,"title=")!=NULL)
					{
						size_t l = strlen(rptr);
						char *t = (char *)alloca(l * 4 + 1);
						memcpy(t, rptr, l + 1);
						TranslateString(t, l * 4);
						title = strdup(t);
						CatchTabs(title);

						if(strcmp(title,"none")==0)
						{
							header=0;
						}
					}
					else
					{
						if(strstr(aptr,"timeout=")!=NULL)
						{
							if(sscanf(rptr,"%d",&timeout)!=1)
							{
								dloop=1;
							}
						}
						else
						{
							if(strstr(aptr,"msg=")!=NULL)
							{
								dloop=Transform_Msg(rptr);
								if(timeout==0)
								{
										if((timeout=Read_Neutrino_Cfg("timing.epg"))<0)
											timeout=300;
								}
								type=1;
							}
							else
							{
								if(strstr(aptr,"popup=")!=NULL)
								{
									dloop=Transform_Msg(rptr);
									if(timeout==0)
									{
										if((timeout=Read_Neutrino_Cfg("timing.infobar"))<0)
											timeout=6;
									}
									type=2;
								}
								else
								{
									if(strstr(aptr,"refresh=")!=NULL)
									{
										if(sscanf(rptr,"%d",&refresh)!=1)
										{
											dloop=1;
										}
									}
									else
									{
										if(strstr(aptr,"select=")!=NULL)
										{
											dloop=GetSelection(rptr);
										}
										else
										{
											if(strstr(aptr,"default=")!=NULL)
											{
												if((sscanf(rptr,"%d",&selection)!=1) || selection<1)
												{
													dloop=1;
												}
											}
											else
											{
												if(strstr(aptr,"order=")!=NULL)
												{
													if(sscanf(rptr,"%d",&bpline)!=1)
													{
														dloop=1;
													}
												}
												else
												{
													if(strstr(aptr,"echo=")!=NULL)
													{
														if(sscanf(rptr,"%d",&echo)!=1)
														{
															dloop=1;
														}
													}
													else
													{
														if(strstr(aptr,"absolute=")!=NULL)
														{
															if(sscanf(rptr,"%d",&absolute)!=1)
															{
																dloop=1;
															}
														}
														else
														{
															if(strstr(aptr,"hide=")!=NULL)
															{
																if(sscanf(rptr,"%d",&mute)!=1)
																{
																	dloop=1;
																}
															}
															else
															{
																if(strstr(aptr,"cyclic=")!=NULL)
																{
																	if(sscanf(rptr,"%d",&cyclic)!=1)
																	{
																		dloop=1;
																	}
																}
																else
																{
																	if(strstr(aptr,"icon=")!=NULL)
																	{
																		icon=rptr;
																		dloop=Transform_Icon(icon)==0;
																	}
																	else
																	{
																		dloop=2;
																	}
																}
															}
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
			switch (dloop)
			{
				case 1:
					printf("%s <param error: %s>\n", __plugin__, aptr);
					return 0;
					break;
				
				case 2:
					printf("%s <unknown command: %s>\n\n", __plugin__, aptr);
					ShowUsage();
					return 0;
					break;
			}
		}

		FSIZE_BIG=(float)FSIZE_MED*1.25;
		FSIZE_SMALL=(FSIZE_MED*4)/5;
		TABULATOR=2*FSIZE_MED;
		size=FSIZE_MED;
		
		/*
		if(!echo)
		{
			printf("\nMsgBox Version %.2f\n", M_VERSION);
		}
		*/
		if(!buttons)
		{
			butmsg[0]=strdup("OK");
			buttons=1;
		}
		if(!absolute)
		{
			for(tv=0; tv<buttons; tv++)
			{
				rbutt[tv]=tv+1;
			}
		}
		if(selection)
		{	
			for(tv=0; tv<buttons && !found; tv++)		
			{
				if(rbutt[tv]==selection)
				{
					selection=tv+1;
					found=1;
				}
			}
			if(!found)
			{
				printf("%s <param error: default=%d>\n", __plugin__, selection);
				return 0;
			}
		}
		else
		{
			for(tv=0; tv<buttons && !selection; tv++)
			{
				if(strlen(butmsg[tv]))
				{
					selection=tv+1;
				}
			}
		}
		if(!icon)
		{
			icon=strdup("info");
		}
		if(!title)
		{
			title=strdup("Information");
		}
		if((line_buffer=calloc(BUFSIZE+1, sizeof(char)))==NULL)
		{
			printf(NOMEM);
			return -1;
		}
	
		spr=Read_Neutrino_Cfg("screen_preset")+1;
		resolution=Read_Neutrino_Cfg("osd_resolution");

		if (resolution == -1)
			sprintf(line_buffer,"screen_StartX_%s", spres[spr]);
		else
			sprintf(line_buffer,"screen_StartX_%s_%d", spres[spr], resolution);
		if((sx=Read_Neutrino_Cfg(line_buffer))<0)
			sx=scale2res(100);

		if (resolution == -1)
			sprintf(line_buffer,"screen_EndX_%s", spres[spr]);
		else
			sprintf(line_buffer,"screen_EndX_%s_%d", spres[spr], resolution);
		if((ex=Read_Neutrino_Cfg(line_buffer))<0)
			ex=scale2res(1180);

		if (resolution == -1)
			sprintf(line_buffer,"screen_StartY_%s", spres[spr]);
		else
			sprintf(line_buffer,"screen_StartY_%s_%d", spres[spr], resolution);
		if((sy=Read_Neutrino_Cfg(line_buffer))<0)
			sy=scale2res(100);

		if (resolution == -1)
			sprintf(line_buffer,"screen_EndY_%s", spres[spr]);
		else
			sprintf(line_buffer,"screen_EndY_%s_%d", spres[spr], resolution);
		if((ey=Read_Neutrino_Cfg(line_buffer))<0)
			ey=scale2res(620);

		for(ix=CMCST; ix<=CMH; ix++)
		{
			sprintf(rstr,"menu_%s_alpha",menucoltxt[ix]);
			if((tv=Read_Neutrino_Cfg(rstr))>=0)
				tr[ix]=255-(float)tv*2.55;

			sprintf(rstr,"menu_%s_blue",menucoltxt[ix]);
			if((tv=Read_Neutrino_Cfg(rstr))>=0)
				bl[ix]=(float)tv*2.55;

			sprintf(rstr,"menu_%s_green",menucoltxt[ix]);
			if((tv=Read_Neutrino_Cfg(rstr))>=0)
				gn[ix]=(float)tv*2.55;

			sprintf(rstr,"menu_%s_red",menucoltxt[ix]);
			if((tv=Read_Neutrino_Cfg(rstr))>=0)
				rd[ix]=(float)tv*2.55;
		}

		int	cix=CMC;
		for(ix=COL_MENUCONTENT_PLUS_0; ix<=COL_MENUCONTENT_PLUS_3; ix++)
		{
			rd[ix]=rd[cix]+25;
			gn[ix]=gn[cix]+25;
			bl[ix]=bl[cix]+25;
			tr[ix]=tr[cix];
			cix=ix;
		}

		sprintf(rstr,"infobar_alpha");
		if((tv=Read_Neutrino_Cfg(rstr))>=0)
			tr[COL_SHADOW_PLUS_0]=255-(float)tv*2.55;

		sprintf(rstr,"infobar_blue");
		if((tv=Read_Neutrino_Cfg(rstr))>=0)
			bl[COL_SHADOW_PLUS_0]=(float)tv*2.55*0.4;

		sprintf(rstr,"infobar_green");
		if((tv=Read_Neutrino_Cfg(rstr))>=0)
			gn[COL_SHADOW_PLUS_0]=(float)tv*2.55*0.4;

		sprintf(rstr,"infobar_red");
		if((tv=Read_Neutrino_Cfg(rstr))>=0)
			rd[COL_SHADOW_PLUS_0]=(float)tv*2.55*0.4;

		for (ix = 0; ix <= COL_SHADOW_PLUS_0; ix++)
			bgra[ix] = (tr[ix] << 24) | (rd[ix] << 16) | (gn[ix] << 8) | bl[ix];

		if(Read_Neutrino_Cfg("rounded_corners")>0)
		{
			radius = scale2res(11);
			radius_small = scale2res(5);
		}
		else
			radius = radius_small = 0;

		InitRC();
		
		if((trstr=malloc(BUFSIZE))==NULL)
		{
			printf(NOMEM);
			return -1;
		}
		
	//init fontlibrary

		if((error = FT_Init_FreeType(&library)))
		{
			printf("%s <FT_Init_FreeType failed with Errorcode 0x%.2X>", __plugin__, error);
			munmap(lfb, fix_screeninfo.smem_len);
			return -1;
		}

		if((error = FTC_Manager_New(library, 1, 2, 0, &MyFaceRequester, NULL, &manager)))
		{
			printf("%s <FTC_Manager_New failed with Errorcode 0x%.2X>\n", __plugin__, error);
			FT_Done_FreeType(library);
			munmap(lfb, fix_screeninfo.smem_len);
			return -1;
		}

		if((error = FTC_SBitCache_New(manager, &cache)))
		{
			printf("%s <FTC_SBitCache_New failed with Errorcode 0x%.2X>\n", __plugin__, error);
			FTC_Manager_Done(manager);
			FT_Done_FreeType(library);
			munmap(lfb, fix_screeninfo.smem_len);
			return -1;
		}

		Read_Neutrino_Cfg("font_file=");
		if((error = FTC_Manager_LookupFace(manager, FONT, &face)))
		{
			if((error = FTC_Manager_LookupFace(manager, FONT2, &face)))
			{
				printf("%s <FTC_Manager_LookupFace failed with Errorcode 0x%.2X>\n", __plugin__, error);
				FTC_Manager_Done(manager);
				FT_Done_FreeType(library);
				munmap(lfb, fix_screeninfo.smem_len);
				return 2;
			}
			else
				desc.face_id = FONT2;
		}
		else
			desc.face_id = FONT;
		
		use_kerning = FT_HAS_KERNING(face);

		desc.flags = FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT;

		//init backbuffer
#if HAVE_SPARK_HARDWARE || HAVE_DUCKBOX_HARDWARE
		lbb = lfb + 1920 * 1080;
		fix_screeninfo.line_length = DEFAULT_XRES * sizeof(uint32_t);
		stride = DEFAULT_XRES;
#else
		stride = fix_screeninfo.line_length/sizeof(uint32_t);
		if(stride == 7680 && var_screeninfo.xres == 1280) {
			var_screeninfo.yres = 1080;
		}
		if(!(lbb = malloc(var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t))))
		{
			perror(__plugin__ " <allocating of Backbuffer>\n");
			FTC_Manager_Done(manager);
			FT_Done_FreeType(library);
			munmap(lfb, fix_screeninfo.smem_len);
			return -1;
		}
#endif
		if(!(obb = malloc(var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t))))
		{
			perror(__plugin__ " <allocating of Backbuffer>\n");
			FTC_Manager_Done(manager);
			FT_Done_FreeType(library);
			free(lbb);
			munmap(lfb, fix_screeninfo.smem_len);
			return -1;
		}
		if(!(hbb = malloc(var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t))))
		{
			perror(__plugin__ " <allocating of Backbuffer>\n");
			FTC_Manager_Done(manager);
			FT_Done_FreeType(library);
			free(lbb);
			free(obb);
			munmap(lfb, fix_screeninfo.smem_len);
			return -1;
		}
		if(!(ibb = malloc(var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t))))
		{
			perror(__plugin__ " <allocating of Backbuffer>\n");
			FTC_Manager_Done(manager);
			FT_Done_FreeType(library);
			free(lbb);
			free(obb);
			free(hbb);
			munmap(lfb, fix_screeninfo.smem_len);
			return -1;
		}

		if(refresh & 1)
		{
			memcpy(ibb, lbb, var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t));
		}
		else
		{
			memset(ibb, TRANSP, var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t));
		}
		if(mute==2)
		{
			memcpy(hbb, lbb, var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t));
		}
		else
		{
			memset(hbb, TRANSP, var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t));
		}
		if(refresh & 2)
		{
			memcpy(obb, lbb, var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t));
		}
		else
		{
			memset(obb, TRANSP, var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t));
		}

		startx = sx;
		starty = sy;


	/* scale to resolution */
	FSIZE_BIG = scale2res(FSIZE_BIG);
	FSIZE_MED = scale2res(FSIZE_MED);
	FSIZE_SMALL = scale2res(FSIZE_SMALL);

	TABULATOR = scale2res(TABULATOR);

	OFFSET_MED = scale2res(OFFSET_MED);
	OFFSET_SMALL = scale2res(OFFSET_SMALL);
	OFFSET_MIN = scale2res(OFFSET_MIN);

	size = scale2res(size);

	/* Set up signal handlers. */
	signal(SIGINT, quit_signal);
	signal(SIGTERM, quit_signal);
	signal(SIGQUIT, quit_signal);
	signal(SIGSEGV, quit_signal);

	put_instance(instance=get_instance()+1);

  	show_txt(0);	
	
	time(&tm1);
	tm2=tm1;
	
	//main loop
	while((rcc!=KEY_EXIT) && (rcc!=KEY_HOME) && (rcc!=KEY_OK) && ((timeout==-1)||((tm2-tm1)<timeout)))
	{
		rcc=GetRCCode(1000);
		if(rcc!=-1)
		{
			time(&tm1);
		}
		else
		{
			if(cyclic)
				show_txt(0);
#if 0
			if(++cupd>100)
			{
				if(cyclic)
				{
					show_txt(0);
					cupd=0;
				}
			}
			usleep(10000L);
#endif
		}
		if(mute && rcc==KEY_MUTE)
		{
			hide^=1;
			show_txt(0);
#if HAVE_SPARK_HARDWARE || HAVE_DUCKBOX_HARDWARE
			ClearRC();
#else

			while(GetRCCode(300)!=-1);
			if(hide)
			{
				if((fh=fopen(HDF_FILE,"w"))!=NULL)
				{
					fprintf(fh,"hidden");
					fclose(fh);
				}
			}
			else
			{
				remove(HDF_FILE);
			}
#endif
		}
		if((!hide) && (rcc!=KEY_EXIT) && (rcc!=KEY_HOME) && (rcc!=KEY_OK))
		{
			switch(rcc)
			{
				case KEY_LEFT:
					if(!hide && (--selection<1))
					{
						selection=buttons;
					}
					show_txt(1);
				break;
				
				case KEY_RIGHT:
					if(!hide && (++selection>buttons))
					{
						selection=1;
					}
					show_txt(1);
				break;
				
				case KEY_UP:
					if(!hide && ((selection-=bpline)<1))
					{
						selection=1;
					}
					show_txt(1);
				break;
				
				case KEY_DOWN:
					if(!hide && ((selection+=bpline)>buttons))
					{
						selection=buttons;
					}
					show_txt(1);
				break;

				default:
					flash^=1;
				break;
			}
		}
		time(&tm2);
		if(hide)
		{
			rcc=-1;
		}
	}
	if((type!=1) || (rcc!=KEY_OK))
	{
		selection=0;
	}
	
	
	//cleanup
#if HAVE_SPARK_HARDWARE || HAVE_DUCKBOX_HARDWARE
	memcpy(lbb, obb, var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t));
	blit();
#else
	memcpy(lfb, obb, var_screeninfo.xres*var_screeninfo.yres*sizeof(uint32_t));
#endif
	munmap(lfb, fix_screeninfo.smem_len);
	close(fb);
#if !defined(HAVE_SPARK_HARDWARE) && !defined(HAVE_DUCKBOX_HARDWARE)
	free(lbb);
#endif

	put_instance(get_instance()-1);

	if(echo && selection>0)
	{
		printf("%s\n",butmsg[selection-1]);
	}

	for(tv=0; tv<buttons; tv++)
	{
		free(butmsg[tv]);
	}
	free(trstr);
	free(line_buffer);
	free(title);

	FTC_Manager_Done(manager);
	FT_Done_FreeType(library);

	free(obb);
	free(hbb);
	free(ibb);

	CloseRC();

	remove("/tmp/msgbox.tmp");

	if(selection)
	{
		return rbutt[selection-1];
	}
	return 0;
}
示例#6
0
static
DWORD
ParseArgs(
    int    argc,
    char*  argv[],
    LsaLogLevel* pLogLevel
)
{
    typedef enum {
        PARSE_MODE_OPEN = 0
    } ParseMode;

    DWORD dwError = 0;
    int iArg = 1;
    PSTR pszArg = NULL;
    ParseMode parseMode = PARSE_MODE_OPEN;
    LsaLogLevel logLevel = LSA_LOG_LEVEL_ERROR;
    BOOLEAN bLogLevelSpecified = FALSE;

    do {
        pszArg = argv[iArg++];
        if (pszArg == NULL || *pszArg == '\0')
        {
            break;
        }

        switch (parseMode)
        {
        case PARSE_MODE_OPEN:

            if ((strcmp(pszArg, "--help") == 0) ||
                    (strcmp(pszArg, "-h") == 0))
            {
                ShowUsage();
                exit(0);
            }
            else
            {
                if (!strcasecmp(pszArg, "error"))
                {
                    logLevel = LSA_LOG_LEVEL_ERROR;
                    bLogLevelSpecified = TRUE;
                }
                else if (!strcasecmp(pszArg, "warning"))
                {
                    logLevel = LSA_LOG_LEVEL_WARNING;
                    bLogLevelSpecified = TRUE;
                }
                else if (!strcasecmp(pszArg, "info"))
                {
                    logLevel = LSA_LOG_LEVEL_INFO;
                    bLogLevelSpecified = TRUE;
                }
                else if (!strcasecmp(pszArg, "verbose"))
                {
                    logLevel = LSA_LOG_LEVEL_VERBOSE;
                    bLogLevelSpecified = TRUE;
                }
                else if (!strcasecmp(pszArg, "debug"))
                {
                    logLevel = LSA_LOG_LEVEL_DEBUG;
                    bLogLevelSpecified = TRUE;
                }
                else if (!strcasecmp(pszArg, "trace"))
                {
                    logLevel = LSA_LOG_LEVEL_TRACE;
                    bLogLevelSpecified = TRUE;
                }
                else
                {
                    ShowUsage();
                    exit(1);
                }
            }
            break;
        }

    } while (iArg < argc);

    if (!bLogLevelSpecified)
    {
        ShowUsage();
        exit(1);
    }

    *pLogLevel = logLevel;

    return dwError;
}
static
DWORD
ParseArgs(
    int    argc,
    char*  argv[],
    PLSA_TRACE_INFO* ppTraceFlagArrayToSet,
    PDWORD           pdwNumFlagsToSet,
    PDWORD           pdwTraceFlag
    )
{
    typedef enum {
        PARSE_MODE_OPEN = 0,
        PARSE_MODE_SET,
        PARSE_MODE_GET
    } ParseMode;

    DWORD dwError = 0;
    int iArg = 1;
    PSTR pszArg = NULL;
    ParseMode parseMode = PARSE_MODE_OPEN;
    DWORD dwTraceFlag = 0;
    PLSA_TRACE_INFO pTraceFlagArray = NULL;
    DWORD dwNumFlags = 0;

    do {
        pszArg = argv[iArg++];
        if (pszArg == NULL || *pszArg == '\0')
        {
            break;
        }

        switch (parseMode)
        {
            case PARSE_MODE_OPEN:

                if ((strcmp(pszArg, "--help") == 0) ||
                    (strcmp(pszArg, "-h") == 0))
                {
                    ShowUsage();
                    exit(0);
                }
                else if (!strcasecmp(pszArg, "--get"))
                {
                    parseMode = PARSE_MODE_GET;
                }
                else if (!strcasecmp(pszArg, "--set"))
                {
                    parseMode = PARSE_MODE_SET;
                }
                else
                {
                   ShowUsage();
                   exit(1);
                }
                break;



           case PARSE_MODE_SET:

                LW_SAFE_FREE_MEMORY(pTraceFlagArray);
                dwNumFlags = 0;

                dwError = ParseTraceFlagArray(
                              pszArg,
                              &pTraceFlagArray,
                              &dwNumFlags);
                BAIL_ON_LSA_ERROR(dwError);

                parseMode = PARSE_MODE_OPEN;

                break;

           case PARSE_MODE_GET:

                dwTraceFlag = 0;

                dwError = ParseTraceFlag(
                              pszArg,
                              &dwTraceFlag);
                BAIL_ON_LSA_ERROR(dwError);

                parseMode = PARSE_MODE_OPEN;

                break;
        }

    } while (iArg < argc);

    *ppTraceFlagArrayToSet = pTraceFlagArray;
    *pdwNumFlagsToSet = dwNumFlags;
    *pdwTraceFlag = dwTraceFlag;

cleanup:

    return dwError;

error:

    *ppTraceFlagArrayToSet = NULL;
    *pdwNumFlagsToSet = 0;
    *pdwTraceFlag = 0;

    LW_SAFE_FREE_MEMORY(pTraceFlagArray);

    goto cleanup;
}
示例#8
0
int main( int argc , char* argv[] )
{
	int paramNum = sizeof(params)/sizeof(cmdLineReadable*);
	cmdLineParse( argc-1 , &argv[1] , paramNum , params , 0 );

#if FOR_RELEASE
	if( !In.set || !Trim.set )
	{
		ShowUsage( argv[0] );
		return EXIT_FAILURE;
	}
#else // !FOR_RELEASE
	if( !In.set )
	{
		ShowUsage( argv[0] );
		return EXIT_FAILURE;
	}
#endif // FOR_RELEASE
	float min , max;
	std::vector< PlyValueVertex< float > > vertices;
	std::vector< std::vector< int > > polygons;

	int ft , commentNum = paramNum+2;
	char** comments;
	bool readFlags[ PlyValueVertex< float >::Components ];
	PlyReadPolygons( In.value , vertices , polygons , PlyValueVertex< float >::Properties , PlyValueVertex< float >::Components , ft , &comments , &commentNum , readFlags );
	if( !readFlags[3] ){ fprintf( stderr , "[ERROR] vertices do not have value flag\n" ) ; return EXIT_FAILURE; }
#if 0
	if( Trim.set ) for( int i=0 ; i<Smooth.value ; i++ ) SmoothValues( vertices , polygons , Trim.value-0.5f , Trim.value+0.5f );
	else           for( int i=0 ; i<Smooth.value ; i++ ) SmoothValues( vertices , polygons );
#else
	for( int i=0 ; i<Smooth.value ; i++ ) SmoothValues( vertices , polygons );
#endif 
	min = max = vertices[0].value;
	for( size_t i=0 ; i<vertices.size() ; i++ ) min = std::min< float >( min , vertices[i].value ) , max = std::max< float >( max , vertices[i].value );
	printf( "Value Range: [%f,%f]\n" , min , max );


	if( Trim.set )
	{
		hash_map< long long , int > vertexTable;
		std::vector< std::vector< int > > ltPolygons , gtPolygons;
		std::vector< bool > ltFlags , gtFlags;

		for( int i=0 ; i<paramNum+2 ; i++ ) comments[i+commentNum]=new char[1024];
		sprintf( comments[commentNum++] , "Running Surface Trimmer (V5)" );
		if(              In.set ) sprintf(comments[commentNum++],"\t--%s %s" , In.name , In.value );
		if(             Out.set ) sprintf(comments[commentNum++],"\t--%s %s" , Out.name , Out.value );
		if(            Trim.set ) sprintf(comments[commentNum++],"\t--%s %f" , Trim.name , Trim.value );
		if(          Smooth.set ) sprintf(comments[commentNum++],"\t--%s %d" , Smooth.name , Smooth.value );
		if( IslandAreaRatio.set ) sprintf(comments[commentNum++],"\t--%s %f" , IslandAreaRatio.name , IslandAreaRatio.value );
		if(     PolygonMesh.set ) sprintf(comments[commentNum++],"\t--%s" , PolygonMesh.name );

		double t=Time();
		for( size_t i=0 ; i<polygons.size() ; i++ ) SplitPolygon( polygons[i] , vertices , &ltPolygons , &gtPolygons , &ltFlags , &gtFlags , vertexTable , Trim.value );
		if( IslandAreaRatio.value>0 )
		{
			std::vector< std::vector< int > > _ltPolygons , _gtPolygons;
			std::vector< std::vector< int > > ltComponents , gtComponents;
			SetConnectedComponents( ltPolygons , ltComponents );
			SetConnectedComponents( gtPolygons , gtComponents );
			std::vector< double > ltAreas( ltComponents.size() , 0. ) , gtAreas( gtComponents.size() , 0. );
			std::vector< bool > ltComponentFlags( ltComponents.size() , false ) , gtComponentFlags( gtComponents.size() , false );
			double area = 0.;
			for( size_t i=0 ; i<ltComponents.size() ; i++ )
			{
				for( size_t j=0 ; j<ltComponents[i].size() ; j++ )
				{
					ltAreas[i] += PolygonArea( vertices , ltPolygons[ ltComponents[i][j] ] );
					ltComponentFlags[i] = ( ltComponentFlags[i] || ltFlags[ ltComponents[i][j] ] );
				}
				area += ltAreas[i];
			}
			for( size_t i=0 ; i<gtComponents.size() ; i++ )
			{
				for( size_t j=0 ; j<gtComponents[i].size() ; j++ )
				{
					gtAreas[i] += PolygonArea( vertices , gtPolygons[ gtComponents[i][j] ] );
					gtComponentFlags[i] = ( gtComponentFlags[i] || gtFlags[ gtComponents[i][j] ] );
				}
				area += gtAreas[i];
			}
			for( size_t i=0 ; i<ltComponents.size() ; i++ )
			{
				if( ltAreas[i]<area*IslandAreaRatio.value && ltComponentFlags[i] ) for( size_t j=0 ; j<ltComponents[i].size() ; j++ ) _gtPolygons.push_back( ltPolygons[ ltComponents[i][j] ] );
				else                                                               for( size_t j=0 ; j<ltComponents[i].size() ; j++ ) _ltPolygons.push_back( ltPolygons[ ltComponents[i][j] ] );
			}
			for( size_t i=0 ; i<gtComponents.size() ; i++ )
			{
				if( gtAreas[i]<area*IslandAreaRatio.value && gtComponentFlags[i] ) for( size_t j=0 ; j<gtComponents[i].size() ; j++ ) _ltPolygons.push_back( gtPolygons[ gtComponents[i][j] ] );
				else                                                               for( size_t j=0 ; j<gtComponents[i].size() ; j++ ) _gtPolygons.push_back( gtPolygons[ gtComponents[i][j] ] );
			}
			ltPolygons = _ltPolygons , gtPolygons = _gtPolygons;
		}
		if( !PolygonMesh.set )
		{
			{
				std::vector< std::vector< int > > polys = ltPolygons;
				Triangulate( vertices , ltPolygons , polys ) , ltPolygons = polys;
			}
			{
				std::vector< std::vector< int > > polys = gtPolygons;
				Triangulate( vertices , gtPolygons , polys ) , gtPolygons = polys;
			}
		}

		RemoveHangingVertices( vertices , gtPolygons );
		sprintf( comments[commentNum++] , "#Trimmed In: %9.1f (s)" , Time()-t );
		if( Out.set ) PlyWritePolygons( Out.value , vertices , gtPolygons , PlyValueVertex< float >::Properties , PlyValueVertex< float >::Components , ft , comments , commentNum );
	}
	else
	{
		if( ColorRange.set ) min = ColorRange.values[0] , max = ColorRange.values[1];
		std::vector< PlyColorVertex< float > > outVertices;
		ColorVertices( vertices , outVertices , min , max );
		if( Out.set ) PlyWritePolygons( Out.value , outVertices , polygons , PlyColorVertex< float >::Properties , PlyColorVertex< float >::Components , ft , comments , commentNum );
	}

	return EXIT_SUCCESS;
}
示例#9
0
/**
 * The main loop for the SDL.
 */
int main(int argc, char *argv[])
{
  // this is a hackish check for the --help arguemnts
  // these are normally processed by the config parser, but SDL_Init
  // must be run before the config parser: so if even SDL_Init fails,
  // these six lines will still print the help output
	if(argc > 1)
	{
		if(!strcmp(argv[1], "--help") || !strcmp(argv[1],"-h"))
		{
            ShowUsage(argv[0]);
			return 0;
		}
	}

	int error, frameskip;

	FCEUD_Message("Starting " FCEU_NAME_AND_VERSION "...\n");

#ifdef WIN32
	/* Taken from win32 sdl_main.c */
	SDL_SetModuleHandle(GetModuleHandle(NULL));
#endif

	/* SDL_INIT_VIDEO Needed for (joystick config) event processing? */
	if(SDL_Init(SDL_INIT_VIDEO)) {
		printf("Could not initialize SDL: %s.\n", SDL_GetError());
		return(-1);
	}

#ifdef OPENGL
	SDL_GL_LoadLibrary(0);
#endif

	// Initialize the configuration system
	g_config = InitConfig();
		
	if(!g_config) {
		SDL_Quit();
		return -1;
	}

	// initialize the infrastructure
	error = FCEUI_Initialize();
	if(error != 1) {
		ShowUsage(argv[0]);
		SDL_Quit();
		return -1;
	}
	
	// check for --help or -h and display usage; also check for --nogui
	for(int i=0; i<argc;i++)
	{
		if(strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
		{
			ShowUsage(argv[0]);
			SDL_Quit();
			return 0;
		}
#ifdef _GTK
		else if(strcmp(argv[i], "--nogui") == 0)
		{
			noGui = 1;
			argv[i] = "";
		}
#endif
	}
	int romIndex = g_config->parse(argc, argv);

	// This is here so that a default fceux.cfg will be created on first
	// run, even without a valid ROM to play.
	// Unless, of course, there's actually --no-config given
	// mbg 8/23/2008 - this is also here so that the inputcfg routines can have 
    // a chance to dump the new inputcfg to the fceux.cfg  in case you didnt 
    // specify a rom  filename
	g_config->getOption("SDL.NoConfig", &noconfig);
	if (!noconfig)
		g_config->save();
	
	std::string s;

	g_config->getOption("SDL.InputCfg", &s);
	if(s.size() != 0)
	{
	InitVideo(GameInfo);
	InputCfg(s);
	}
	// set the FAMICOM PAD 2 Mic thing 
	{
	int t;
	g_config->getOption("SDL.Input.FamicomPad2.EnableMic", &t);
		if(t)
			replaceP2StartWithMicrophone = t;
	}

    // update the input devices
	UpdateInput(g_config);

	// check for a .fcm file to convert to .fm2
	g_config->getOption ("SDL.FCMConvert", &s);
	g_config->setOption ("SDL.FCMConvert", "");
	if (!s.empty())
	{
		int okcount = 0;
		std::string infname = s.c_str();
		// produce output filename
		std::string outname;
		size_t dot = infname.find_last_of (".");
		if (dot == std::string::npos)
			outname = infname + ".fm2";
		else
			outname = infname.substr(0,dot) + ".fm2";
	  
		MovieData md;
		EFCM_CONVERTRESULT result = convert_fcm (md, infname);

		if (result == FCM_CONVERTRESULT_SUCCESS) {
			okcount++;
        // *outf = new EMUFILE;
		EMUFILE_FILE* outf = FCEUD_UTF8_fstream (outname, "wb");
		md.dump (outf,false);
		delete outf;
		FCEUD_Message ("Your file has been converted to FM2.\n");
	}
	else {
		FCEUD_Message ("Something went wrong while converting your file...\n");
	}
	  
	DriverKill();
	  SDL_Quit();
	  return 0;
	}

	// If x/y res set to 0, store current display res in SDL.LastX/YRes
	int yres, xres;
	g_config->getOption("SDL.XResolution", &xres);
	g_config->getOption("SDL.YResolution", &yres);
#if SDL_VERSION_ATLEAST(2, 0, 0)
	// TODO _ SDL 2.0
#else
	const SDL_VideoInfo* vid_info = SDL_GetVideoInfo();
	if(xres == 0) 
    {
        if(vid_info != NULL)
        {
			g_config->setOption("SDL.LastXRes", vid_info->current_w);
        }
        else
        {
			g_config->setOption("SDL.LastXRes", 512);
        }
    }
	else
	{
		g_config->setOption("SDL.LastXRes", xres);
	}	
    if(yres == 0)
    {
        if(vid_info != NULL)
        {
			g_config->setOption("SDL.LastYRes", vid_info->current_h);
        }
        else
        {
			g_config->setOption("SDL.LastYRes", 448);
        }
    } 
	else
	{
		g_config->setOption("SDL.LastYRes", yres);
	}
#endif
	
	int autoResume;
	g_config->getOption("SDL.AutoResume", &autoResume);
	if(autoResume)
	{
		AutoResumePlay = true;
	}
	else
	{
		AutoResumePlay = false;
	}
	// check to see if recording HUD to AVI is enabled
	int rh;
	g_config->getOption("SDL.RecordHUD", &rh);
	if( rh == 0)
		FCEUI_SetAviEnableHUDrecording(true);
	else
		FCEUI_SetAviEnableHUDrecording(false);

	// check to see if movie messages are disabled
	int mm;
	g_config->getOption("SDL.MovieMsg", &mm);
	if( mm == 0)
		FCEUI_SetAviDisableMovieMessages(true);
	else
		FCEUI_SetAviDisableMovieMessages(false);
	
	
	// check for a .fm2 file to rip the subtitles
	g_config->getOption("SDL.RipSubs", &s);
	g_config->setOption("SDL.RipSubs", "");
	if (!s.empty())
	{
		MovieData md;
		std::string infname;
		infname = s.c_str();
		FCEUFILE *fp = FCEU_fopen(s.c_str(), 0, "rb", 0);
		
		// load the movie and and subtitles
		extern bool LoadFM2(MovieData&, EMUFILE*, int, bool);
		LoadFM2(md, fp->stream, INT_MAX, false);
		LoadSubtitles(md); // fill subtitleFrames and subtitleMessages
		delete fp;
		
		// produce .srt file's name and open it for writing
		std::string outname;
		size_t dot = infname.find_last_of (".");
		if (dot == std::string::npos)
			outname = infname + ".srt";
		else
			outname = infname.substr(0,dot) + ".srt";
		FILE *srtfile;
		srtfile = fopen(outname.c_str(), "w");
		
		if (srtfile != NULL)
		{
			extern std::vector<int> subtitleFrames;
			extern std::vector<std::string> subtitleMessages;
			float fps = (md.palFlag == 0 ? 60.0988 : 50.0069); // NTSC vs PAL
			float subduration = 3; // seconds for the subtitles to be displayed
			for (int i = 0; i < subtitleFrames.size(); i++)
			{
				fprintf(srtfile, "%i\n", i+1); // starts with 1, not 0
				double seconds, ms, endseconds, endms;
				seconds = subtitleFrames[i]/fps;
				if (i+1 < subtitleFrames.size()) // there's another subtitle coming after this one
				{
					if (subtitleFrames[i+1]-subtitleFrames[i] < subduration*fps) // avoid two subtitles at the same time
					{
						endseconds = (subtitleFrames[i+1]-1)/fps; // frame x: subtitle1; frame x+1 subtitle2
					} else {
						endseconds = seconds+subduration;
							}
				} else {
					endseconds = seconds+subduration;
				}
				ms = modf(seconds, &seconds);
				endms = modf(endseconds, &endseconds);
				// this is just beyond ugly, don't show it to your kids
				fprintf(srtfile,
				"%02.0f:%02d:%02d,%03d --> %02.0f:%02d:%02d,%03d\n", // hh:mm:ss,ms --> hh:mm:ss,ms
				floor(seconds/3600),	(int)floor(seconds/60   ) % 60, (int)floor(seconds)	% 60, (int)(ms*1000),
				floor(endseconds/3600), (int)floor(endseconds/60) % 60, (int)floor(endseconds) % 60, (int)(endms*1000));
				fprintf(srtfile, "%s\n\n", subtitleMessages[i].c_str()); // new line for every subtitle
			}
		fclose(srtfile);
		printf("%d subtitles have been ripped.\n", (int)subtitleFrames.size());
		} else {
		FCEUD_Message("Couldn't create output srt file...\n");
		}
	  
		DriverKill();
		SDL_Quit();
		return 0;
	}
   

	// if we're not compiling w/ the gui, exit if a rom isn't specified
#ifndef _GTK
	if(romIndex <= 0) {
		
		ShowUsage(argv[0]);
		FCEUD_Message("\nError parsing command line arguments\n");
		SDL_Quit();
		return -1;
	}
#endif
	

	// update the emu core
	UpdateEMUCore(g_config);

	
	#ifdef CREATE_AVI
	g_config->getOption("SDL.VideoLog", &s);
	g_config->setOption("SDL.VideoLog", "");
	if(!s.empty())
	{
		NESVideoSetVideoCmd(s.c_str());
		LoggingEnabled = 1;
		g_config->getOption("SDL.MuteCapture", &mutecapture);
	} else {
		mutecapture = 0;
	}
	#endif

	{
		int id;
		g_config->getOption("SDL.InputDisplay", &id);
		extern int input_display;
		input_display = id;
		// not exactly an id as an true/false switch; still better than creating another int for that
		g_config->getOption("SDL.SubtitleDisplay", &id); 
		extern int movieSubtitles;
		movieSubtitles = id;
	}
	
	// load the hotkeys from the config life
	setHotKeys();

#ifdef _GTK
	if(noGui == 0)
	{
		gtk_init(&argc, &argv);
		InitGTKSubsystem(argc, argv);
		while(gtk_events_pending())
			gtk_main_iteration_do(FALSE);
	}
#endif

  if(romIndex >= 0)
	{
		// load the specified game
		error = LoadGame(argv[romIndex]);
		if(error != 1) {
			DriverKill();
			SDL_Quit();
			return -1;
		}
		g_config->setOption("SDL.LastOpenFile", argv[romIndex]);
		g_config->save();

	}
	
	// movie playback
	g_config->getOption("SDL.Movie", &s);
	g_config->setOption("SDL.Movie", "");
	if (s != "")
	{
		if(s.find(".fm2") != std::string::npos || s.find(".fm3") != std::string::npos)
		{
			static int pauseframe;
			g_config->getOption("SDL.PauseFrame", &pauseframe);
			g_config->setOption("SDL.PauseFrame", 0);
			FCEUI_printf("Playing back movie located at %s\n", s.c_str());
			FCEUI_LoadMovie(s.c_str(), false, pauseframe ? pauseframe : false);
		}
		else
		{
		  FCEUI_printf("Sorry, I don't know how to play back %s\n", s.c_str());
		}
	}
	
    int periodic_saves;
    int save_state;
    g_config->getOption("SDL.PeriodicSaves", &periodic_saves);
    g_config->getOption("SDL.AutoSaveState", &save_state);
    if(periodic_saves && save_state < 10 && save_state >= 0){
        FCEUI_SelectState(save_state, 0);
    } else {
        periodic_saves = 0;
    }
	
#ifdef _S9XLUA_H
	// load lua script if option passed
	g_config->getOption("SDL.LuaScript", &s);
	g_config->setOption("SDL.LuaScript", "");
	if (s != "")
	{
		FCEU_LoadLuaCode(s.c_str());
	}
#endif
	
	{
		int id;
		g_config->getOption("SDL.NewPPU", &id);
		if (id)
			newppu = 1;
	}

	g_config->getOption("SDL.Frameskip", &frameskip);
	// loop playing the game
#ifdef _GTK
	if(noGui == 0)
	{
		while(1)
		{
			if(GameInfo)
				DoFun(frameskip, periodic_saves);
			else
				SDL_Delay(1);
			while(gtk_events_pending())
			gtk_main_iteration_do(FALSE);
		}
	}
	else
	{
		while(GameInfo)
			DoFun(frameskip, periodic_saves);
	}
#else
	while(GameInfo)
	{
		DoFun(frameskip, periodic_saves);
	}
#endif
	CloseGame();

	// exit the infrastructure
	FCEUI_Kill();
	SDL_Quit();
	return 0;
}
/*---------------------------------------------------------------------------*\
 * NAME: HandleDefaultLaunchOption                                           *
 * --------------------------------------------------------------------------*
 * DESCRIPTION: 
\*---------------------------------------------------------------------------*/
void HandleDefaultLaunchOption (
    int cArgs,
    TCHAR **pptszArgv
    )
{
    DWORD dwReturnValue = ERROR_SUCCESS;
    DWORD dwAccessMask = COM_RIGHTS_EXECUTE;

    if (cArgs < 3) ShowUsage (_T("Invalid number of arguments."));

    if (_tcsicmp (pptszArgv [2], _T("LIST")) == 0)
    {
        _tprintf (_T("Default launch permission list:\n\n"));
        dwReturnValue = ListDefaultLaunchACL();

        if (dwReturnValue != ERROR_SUCCESS)
        {
            Error (_T("ERROR: Cannot list default launch ACL."), dwReturnValue);
        }

        return;
    }

    if (cArgs < 4) ShowUsage (_T("Invalid number of arguments."));

    if (_tcsicmp (pptszArgv [2], _T("SET")) == 0)
    {
        if (cArgs < 5) ShowUsage (_T("Invalid number of arguments."));

        if(cArgs == 6) 
        {
            SetAccessMaskFromCommandLine(pptszArgv[5], &dwAccessMask, SDTYPE_DEFAULT_LAUNCH);
        }
        else if(!IsLegacySecurityModel())
        {
            _tprintf (_T("WARNING: Default access flags designated on a system with an enhanced security model.\n"));
        }

        if (_tcsicmp (pptszArgv [4], _T("PERMIT")) == 0)
        {
            dwReturnValue = ChangeDefaultLaunchAndActivateACL (pptszArgv [3], TRUE, TRUE, dwAccessMask); 
        }
        else if (_tcsicmp (pptszArgv [4], _T("DENY")) == 0)
        {
            dwReturnValue = ChangeDefaultLaunchAndActivateACL (pptszArgv [3], TRUE, FALSE, dwAccessMask); 
        }
        else
        {
            ShowUsage (_T("You can only set a user's permissions to \"permit\" or \"deny\".\n\n"));
        }

        if (dwReturnValue != ERROR_SUCCESS)
        {
            Error (_T("ERROR: Cannot add user to default launch ACL."), dwReturnValue);
        }

    } 
    else if (_tcsicmp (pptszArgv [2], _T("REMOVE")) == 0)
    {
        dwReturnValue = ChangeDefaultLaunchAndActivateACL (pptszArgv[3], FALSE, FALSE, dwAccessMask);

        if (dwReturnValue != ERROR_SUCCESS)
        {
            Error (_T("ERROR: Cannot remove user from default launch ACL."), dwReturnValue);
        }
    } 
    else
    {
        ShowUsage (_T("You can only \"set\" or \"remove\" a user."));
    }

     _tprintf (_T("Successfully set the Default Launch ACL.\n"));

    ListDefaultLaunchACL();
}
void HandleApplicationLaunchAndActivateOption (
    int cArgs,
    TCHAR **pptszArgv
    )
{
    DWORD dwReturnValue                 = ERROR_SUCCESS;
    HKEY  hkeyRegistry                  = NULL;
    TCHAR tszAppID [SIZE_NAME_BUFFER]   = {0};
    TCHAR tszKeyName [SIZE_NAME_BUFFER] = {0};

    DWORD dwAccessMask = COM_RIGHTS_EXECUTE;
    
    if (cArgs < 4) ShowUsage (_T("Invalid number of arguments."));

    if (_tcsicmp (pptszArgv[3], _T("LIST")) == 0)
    {
        if (cArgs < 4) ShowUsage (_T("Invalid number of arguments.\n"));

        _tprintf (_T("Launch permission list for AppID %s:\n\n"), pptszArgv[2]);
        ListAppIDLaunchACL (pptszArgv[2]);
        return;
    }

    if (_tcsicmp (pptszArgv[3], _T("DEFAULT")) == 0)
    {


        _stprintf_s (tszAppID, RTL_NUMBER_OF(tszAppID), pptszArgv [2][0] == '{' ? _T("%s") : _T("{%s}"), pptszArgv [2]);
        _stprintf_s (tszKeyName, RTL_NUMBER_OF(tszKeyName), _T("APPID\\%s"), tszAppID);


        dwReturnValue = RegOpenKeyEx (HKEY_CLASSES_ROOT, tszKeyName, 0, KEY_ALL_ACCESS, &hkeyRegistry);
        if (dwReturnValue != ERROR_SUCCESS && dwReturnValue != ERROR_FILE_NOT_FOUND)
        {
            Error (_T("ERROR: Cannot open AppID registry key."), dwReturnValue);
        }

        dwReturnValue = RegDeleteValue (hkeyRegistry, _T("LaunchPermission"));
        if (dwReturnValue != ERROR_SUCCESS && dwReturnValue != ERROR_FILE_NOT_FOUND)
        {
            Error (_T("ERROR: Cannot delete LaunchPermission value."), dwReturnValue);
        }

        if(hkeyRegistry) RegCloseKey (hkeyRegistry);

        _tprintf (_T("Successfully set the Application Launch to the machine default.\n"));

        return;
    }

    if (cArgs < 5) ShowUsage (_T("Invalid number of arguments."));

    if (_tcsicmp (pptszArgv [3], _T("SET")) == 0)
    {
        if (cArgs < 6) ShowUsage (_T("Invalid number of arguments."));

        if(cArgs == 7) 
        {
            SetAccessMaskFromCommandLine(pptszArgv[6], &dwAccessMask, SDTYPE_APPLICATION_LAUNCH);
        }
        else if(!IsLegacySecurityModel())
        {
            _tprintf (_T("WARNING: Default access flags designated on a system with an enhanced security model.\n"));
        }

        if (_tcsicmp (pptszArgv [5], _T("PERMIT")) == 0)
        {
            dwReturnValue = ChangeAppIDLaunchAndActivateACL (pptszArgv[2], pptszArgv [4], TRUE, TRUE, dwAccessMask);
        }
        else if (_tcsicmp (pptszArgv [5], _T("DENY")) == 0)
        {
            dwReturnValue = ChangeAppIDLaunchAndActivateACL (pptszArgv[2], pptszArgv [4], TRUE, FALSE, dwAccessMask);
        }
        else
        {
            ShowUsage (_T("You can only set a user's permissions to \"permit\" or \"deny\".\n\n"));
        }

        if (dwReturnValue != ERROR_SUCCESS)
            Error (_T("ERROR: Cannot add user to application launch ACL."), dwReturnValue);
    } 
    else if (_tcsicmp (pptszArgv [3], _T("REMOVE")) == 0)
    {
        dwReturnValue = ChangeAppIDLaunchAndActivateACL (pptszArgv[2], pptszArgv[4], FALSE, FALSE, dwAccessMask);

        if (dwReturnValue != ERROR_SUCCESS)
        {
            Error (_T("ERROR: Cannot remove user from application launch ACL."), dwReturnValue);
        }
    } 
    else
    {
        ShowUsage (_T("You can only \"set\" or \"remove\" a user."));
    }

     _tprintf (_T("Successfully set the Application Launch ACL.\n"));

    ListAppIDLaunchACL(pptszArgv[2]);
}
/*---------------------------------------------------------------------------*\
 * NAME: HandleDefaultLaunchOption                                           *
 * --------------------------------------------------------------------------*
 * DESCRIPTION: 
\*---------------------------------------------------------------------------*/
void SetAccessMaskFromCommandLine (
    LPTSTR ptszArg,
    DWORD *pdwAccessMask,
    DWORD dwSDType
    )
{
    LPTSTR ptszToken = NULL;
    LPTSTR ptszContext = NULL;

    *pdwAccessMask = 0;

    ptszToken = _tcstok_s(ptszArg, _T(":"), &ptszContext);

    if(!ptszToken || _tcsicmp (ptszToken, _T("LEVEL")) != 0)
    {
        ShowUsage(_T("Invalid LEVEL argument"));
    }

    ptszToken = _tcstok_s(NULL, _T(","), &ptszContext);

    if(!ptszToken)
    {
        ShowUsage(_T("Invalid LEVEL argument"));
    }

    if(dwSDType & SDTYPE_ACCESS) do
    {

        if(_tcsicmp (ptszToken, _T("L")) == 0)
        {
            *pdwAccessMask |= COM_RIGHTS_EXECUTE_LOCAL | COM_RIGHTS_EXECUTE;
        }
        else if(_tcsicmp (ptszToken, _T("R")) == 0)
        {
            *pdwAccessMask |= COM_RIGHTS_EXECUTE_REMOTE | COM_RIGHTS_EXECUTE;
        }
        else
        {
            ShowUsage(_T("Invalid LEVEL argument"));
        }

    }while(ptszToken = _tcstok_s(NULL, _T(","), &ptszContext));
    else do
    {

        if(_tcsicmp (ptszToken, _T("LL")) == 0)
        {
            *pdwAccessMask |= COM_RIGHTS_EXECUTE_LOCAL | COM_RIGHTS_EXECUTE;
        }
        else if(_tcsicmp (ptszToken, _T("LA")) == 0)
        {
            *pdwAccessMask |= COM_RIGHTS_ACTIVATE_LOCAL | COM_RIGHTS_EXECUTE;
        }
        else if(_tcsicmp (ptszToken, _T("RL")) == 0)
        {
            *pdwAccessMask |= COM_RIGHTS_EXECUTE_REMOTE | COM_RIGHTS_EXECUTE;
        }
        else if(_tcsicmp (ptszToken, _T("RA")) == 0)
        {
            *pdwAccessMask |= COM_RIGHTS_ACTIVATE_REMOTE | COM_RIGHTS_EXECUTE;
        }
        else if(_tcsicmp (ptszToken, _T("L")) == 0)
        {
            *pdwAccessMask |= COM_RIGHTS_ACTIVATE_LOCAL | COM_RIGHTS_EXECUTE_LOCAL | COM_RIGHTS_EXECUTE;
        }
        else if(_tcsicmp (ptszToken, _T("R")) == 0)
        {
            *pdwAccessMask |= COM_RIGHTS_ACTIVATE_REMOTE | COM_RIGHTS_EXECUTE_REMOTE | COM_RIGHTS_EXECUTE;
        }
        else
        {
            ShowUsage(_T("Invalid LEVEL argument"));
        }

    }while(ptszToken = _tcstok_s(NULL, _T(","), &ptszContext));
    
}
示例#13
0
void parse(int argc, char *argv[], int Noption, Option *theOptions)
{
  const char routineName[] = "parse";
  register int n, nopt;

  char **options, **values;
  bool_t recognized;
  int    Narg = argc - 1, Nset;

  /* --- Break down the command line in option/value pairs -- ------- */

  options = (char **) malloc(Narg * sizeof(char *));
  values  = (char **) malloc(Narg * sizeof(char *));

  Nset = 0;
  for (n = 1;  n <= Narg;  n++) {
    if (argv[n][0] == '-') {
      options[Nset] = argv[n] + 1;
      if (n < Narg  &&  argv[n+1][0] != '-') {
	n++;
	values[Nset] = argv[n];
      } else
	values[Nset] = NULL;
      Nset++;
    }
  }
  /* --- If called with -help show options and exit -- -------------- */

  for (n = 0;  n < Nset;  n++) {
    if (CHECK_OPTION(options[n], "help",
		     theOptions[0].minlength)) {
      ShowUsage(argv[0], Noption, theOptions);
    }
  }
  /* --- Match the command line options with internal options -- ---- */
  
  for (n = 0;  n < Nset;  n++) {
    recognized = FALSE;
    for (nopt = 1;  nopt < Noption;  nopt++) {
      if (CHECK_OPTION(options[n], theOptions[nopt].name,
		       theOptions[nopt].minlength)) {
        recognized = TRUE;

        /* --- If a value was specified it is copied to the appropriate
               tag of the Option structure --          -------------- */

	if (values[n] != NULL)
	  strcpy(theOptions[nopt].value, values[n]);
	else {
	  if (theOptions[nopt].value_required) {
          /* --- An error results if value is not given when required */

	    sprintf(messageStr, "Option %s requires value",
		    theOptions[nopt].name);
	    Error(ERROR_LEVEL_2, routineName, messageStr);
	  } else
	    /* --- Options that require no value are assumed to be
                   boolean and are set to TRUE --      -------------- */

	    strcpy(theOptions[nopt].value, "TRUE");
	}
      }
    }

    if (!recognized) {
      sprintf(messageStr, "Unknown command line option %s", options[n]);
      Error(WARNING, routineName, messageStr);
    }
  }
  /* --- Finally, set the internal options with either the 
         command line specified values or their defaults -- --------- */
  
  for (nopt = 1;  nopt < Noption;  nopt++) {
    if (theOptions[nopt].pointer != NULL) 
      (*theOptions[nopt].setValue)(theOptions[nopt].value,
				   theOptions[nopt].pointer);
  }

  free(options);  free(values);
}
示例#14
0
int __cdecl wmain(int argc, PWCHAR argv[]) {
  size_t i;
  WCHAR fileName[MAX_PATH];
  WCHAR driverFullPath[MAX_PATH] = {0};
  WCHAR type;
  PVOID wow64OldValue;

  DokanUseStdErr(TRUE); // Set dokan library debug output

  Wow64DisableWow64FsRedirection(&wow64OldValue); // Disable system32 direct
  // setlocale(LC_ALL, "");

  GetModuleFileName(NULL, fileName, MAX_PATH);

  // search the last "\"
  for (i = wcslen(fileName) - 1; i > 0 && fileName[i] != L'\\'; --i) {
    ;
  }
  fileName[i] = L'\0';

  ExpandEnvironmentStringsW(DOKAN_DRIVER_FULL_PATH, driverFullPath, MAX_PATH);

  fwprintf(stderr, L"Driver path: '%s'\n", driverFullPath);

  if (GetOption(argc, argv, 1) == L'v') {
    fprintf(stderr, "dokanctl : %s %s\n", __DATE__, __TIME__);
    fprintf(stderr, "Dokan version : %d\n", DokanVersion());
    fprintf(stderr, "Dokan driver version : 0x%lx\n", DokanDriverVersion());
    return EXIT_SUCCESS;

  } else if (GetOption(argc, argv, 1) == L'u' && argc == 3) {
    return Unmount(argv[2], FALSE);

  } else if (GetOption(argc, argv, 1) == L'u' &&
             GetOption(argc, argv, 3) == L'f' && argc == 4) {
    return Unmount(argv[2], TRUE);

  } else if (argc < 3 || wcslen(argv[1]) != 2 || argv[1][0] != L'/') {
    return ShowUsage();
  }

  type = towlower(argv[2][0]);

  switch (towlower(argv[1][1])) {
  case L'i':
    if (type == L'd') {

      return InstallDriver(driverFullPath);

    } else if (type == L'n') {
      if (DokanNetworkProviderInstall())
        fprintf(stderr, "network provider install ok\n");
      else
        fprintf(stderr, "network provider install failed\n");
    }
    break;

  case L'r':
    if (type == L'd') {

      return DeleteDokanService(DOKAN_DRIVER_SERVICE);

    } else if (type == L'n') {
      if (DokanNetworkProviderUninstall())
        fprintf(stderr, "network provider remove ok\n");
      else
        fprintf(stderr, "network provider remove failed\n");
    }
    break;
  case L'd':
    if (L'0' <= type && type <= L'9') {
      ULONG mode = type - L'0';
      if (DokanSetDebugMode(mode)) {
        fprintf(stderr, "set debug mode ok\n");
      } else {
        fprintf(stderr, "set debug mode failed\n");
      }
    }
    break;
  default:
    fprintf(stderr, "unknown option\n");
  }

  return EXIT_SUCCESS;
}
示例#15
0
ULONG _cdecl wmain(ULONG argc, PWCHAR argv[])
{
    if (argc < 3)
    {
        ShowUsage();
        return 1;
    }

    // parse the command line and execute the benchmark
    BenchmarkType type;
    switch (argv[1][0])
    {
    case 'r': type = ReadBenchmark; break;
    case 'w': type = WriteBenchmark; break;
    default:
        wprintf(L"Unrecognized benchmark type %s\n", argv[1]);
        return 1;
    }

    LPCWSTR wszPortName = argv[2];
    SIZE_T cbRequestSize = DEFAULT_REQUEST_SIZE;
    DWORD dwConcurrency = 0;
    DWORD dwIterations = DEFAULT_NUM_OF_ITERATIONS;

    for (ULONG i = 3; i < argc; i += 2)
    {
        LPCWSTR wszArg = argv[i];
        if (i + 1 >= argc)
        {
            wprintf(L"Missing option value after %s\n", wszArg);
            return 1;
        }

        if ((wszArg[0] == '-' || wszArg[0] == '/') && wszArg[1] != 0 && wszArg[2] == 0)
        {
            BOOL bSuccess = FALSE;
            switch (wszArg[1])
            {
            case 's': bSuccess = ParseUInt<SIZE_T>(argv[i + 1], &cbRequestSize); break;
            case 'c': bSuccess = ParseUInt<DWORD>(argv[i + 1], &dwConcurrency); break;
            case 't': bSuccess = ParseUInt<DWORD>(argv[i + 1], &dwIterations); break;
            default:
                wprintf(L"Unrecognized option %s\n", wszArg);
                return 1;
            }
            if (!bSuccess)
            {
                wprintf(L"Unrecognized number argument %s\n", argv[i + 1]);
                return 1;
            }
        }
        else
        {
            wprintf(L"Unrecognized option %s\n", wszArg);
            return 1;
        }
    }

    RunBenchmark(wszPortName, type, cbRequestSize, dwConcurrency, dwIterations);
    return 0;
}
示例#16
0
int
main(int argc, char* argv[])
{
    setlocale(LC_ALL, "");

    const char* lexicon_file = NULL;
    const char* result_file = NULL;
    const char* log_file = NULL;
    const char* slm_file = NULL;
    int build_endian = get_host_endian();
    int opt;
    while ((opt = getopt(argc, argv, "i:o:l:s:e:")) != -1) {
        switch (opt) {
        case 'i':
            lexicon_file = optarg;
            break;
        case 'o':
            result_file = optarg;
        case 'l':
            log_file = optarg;
            break;
        case 's':
            slm_file = optarg;
            break;
        case 'e':
            build_endian = parse_endian(optarg);
            break;
        }
    }
    if (!lexicon_file || !result_file || !log_file || !slm_file ||
        build_endian == -1) {
        ShowUsage(argv[0]);
    }

    printf("Opening language model..."); fflush(stdout);
    CUnigramSorter srt;
    if (!srt.open(slm_file)) {
        printf("error!\n");
        return -1;
    }
    printf("done!\n"); fflush(stdout);

    CPinyinTrieMaker maker;

    maker.constructFromLexicon(lexicon_file);

    printf("Writing out..."); fflush(stdout);
    maker.write(result_file, &srt, get_host_endian() != build_endian);
    printf("done!\n"); fflush(stdout);

    srt.close();

    if (get_host_endian() != build_endian) {
        printf("host endian is different from build endian. "
               "log_file will not be written.\n");
        fflush(stdout);
        return 0;
    }

    printf("Printing the lexicon out to log_file..."); fflush(stdout);
    CPinyinTrie t;
    t.load(result_file);

    FILE *fp = fopen(log_file, "w");
    t.print(fp);
    fclose(fp);

    printf("done!\n");

    return 0;
}
示例#17
0
int Execute(int argc,char* argv[])
{
	int i;
	cmdLineString In,Out;
	cmdLineReadable Binary,Verbose,NoResetSamples,NoClipTree,Confidence,Manifold,PolygonMesh;
	cmdLineInt Depth(8),SolverDivide(8),IsoDivide(8),Refine(3);
	cmdLineInt KernelDepth;
	cmdLineFloat SamplesPerNode(1.0f),Scale(1.1f);
	char* paramNames[]=
	{
		"in","depth","out","refine","noResetSamples","noClipTree",
		"binary","solverDivide","isoDivide","scale","verbose",
		"kernelDepth","samplesPerNode","confidence","manifold","polygonMesh"
	};
	cmdLineReadable* params[]=
	{
		&In,&Depth,&Out,&Refine,&NoResetSamples,&NoClipTree,
		&Binary,&SolverDivide,&IsoDivide,&Scale,&Verbose,
		&KernelDepth,&SamplesPerNode,&Confidence,&Manifold,&PolygonMesh
	};
	int paramNum=sizeof(paramNames)/sizeof(char*);
	int commentNum=0;
	char **comments;

	comments=new char*[paramNum+7];
	for(i=0;i<paramNum+7;i++){comments[i]=new char[1024];}

	const char* Rev = "Rev: V2 ";
	const char* Date = "Date: 2006-11-09 (Thur, 09 Nov 2006) ";

	cmdLineParse(argc-1,&argv[1],paramNames,paramNum,params,0);

	if(Verbose.set){echoStdout=1;}

	DumpOutput2(comments[commentNum++],"Running Multi-Grid Octree Surface Reconstructor (degree %d). Version 3\n", Degree);
	if(In.set)				{DumpOutput2(comments[commentNum++],"\t--in %s\n",In.value);}
	if(Out.set)				{DumpOutput2(comments[commentNum++],"\t--out %s\n",Out.value);}
	if(Binary.set)			{DumpOutput2(comments[commentNum++],"\t--binary\n");}
	if(Depth.set)			{DumpOutput2(comments[commentNum++],"\t--depth %d\n",Depth.value);}
	if(SolverDivide.set)	{DumpOutput2(comments[commentNum++],"\t--solverDivide %d\n",SolverDivide.value);}
	if(IsoDivide.set)		{DumpOutput2(comments[commentNum++],"\t--isoDivide %d\n",IsoDivide.value);}
	if(Refine.set)			{DumpOutput2(comments[commentNum++],"\t--refine %d\n",Refine.value);}
	if(Scale.set)			{DumpOutput2(comments[commentNum++],"\t--scale %f\n",Scale.value);}
	if(KernelDepth.set)		{DumpOutput2(comments[commentNum++],"\t--kernelDepth %d\n",KernelDepth.value);}
	if(SamplesPerNode.set)	{DumpOutput2(comments[commentNum++],"\t--samplesPerNode %f\n",SamplesPerNode.value);}
	if(NoResetSamples.set)	{DumpOutput2(comments[commentNum++],"\t--noResetSamples\n");}
	if(NoClipTree.set)		{DumpOutput2(comments[commentNum++],"\t--noClipTree\n");}
	if(Confidence.set)		{DumpOutput2(comments[commentNum++],"\t--confidence\n");}
	if(Manifold.set)		{DumpOutput2(comments[commentNum++],"\t--manifold\n");}
	if(PolygonMesh.set)		{DumpOutput2(comments[commentNum++],"\t--polygonMesh\n");}

	double t;
	double tt=Time();
	Point3D<float> center;
	Real scale=1.0;
	Real isoValue=0;
	//////////////////////////////////
	// Fix courtesy of David Gallup //
	TreeNodeData::UseIndex = 1;     //
	//////////////////////////////////
	Octree<Degree> tree;
	PPolynomial<Degree> ReconstructionFunction=PPolynomial<Degree>::GaussianApproximation();

	center.coords[0]=center.coords[1]=center.coords[2]=0;
	if(!In.set || !Out.set)
	{
		ShowUsage(argv[0]);
		return 0;
	}
	
	TreeOctNode::SetAllocator(MEMORY_ALLOCATOR_BLOCK_SIZE);

	t=Time();
	int kernelDepth=Depth.value-2;
	if(KernelDepth.set){kernelDepth=KernelDepth.value;}

	tree.setFunctionData(ReconstructionFunction,Depth.value,0,Real(1.0)/(1<<Depth.value));
	DumpOutput("Function Data Set In: %lg\n",Time()-t);
	DumpOutput("Memory Usage: %.3f MB\n",float(MemoryInfo::Usage())/(1<<20));
	if(kernelDepth>Depth.value){
		fprintf(stderr,"KernelDepth can't be greater than Depth: %d <= %d\n",kernelDepth,Depth.value);
		return EXIT_FAILURE;
	}


	t=Time();
#if 1
	tree.setTree(In.value,Depth.value,Binary.set,kernelDepth,Real(SamplesPerNode.value),Scale.value,center,scale,!NoResetSamples.set,Confidence.set);
#else
if(Confidence.set){
	tree.setTree(In.value,Depth.value,Binary.set,kernelDepth,Real(SamplesPerNode.value),Scale.value,center,scale,!NoResetSamples.set,0,1);
}
else{
	tree.setTree(In.value,Depth.value,Binary.set,kernelDepth,Real(SamplesPerNode.value),Scale.value,center,scale,!NoResetSamples.set,0,0);
}
#endif
	DumpOutput2(comments[commentNum++],"#             Tree set in: %9.1f (s), %9.1f (MB)\n",Time()-t,tree.maxMemoryUsage);
	DumpOutput("Leaves/Nodes: %d/%d\n",tree.tree.leaves(),tree.tree.nodes());
	DumpOutput("   Tree Size: %.3f MB\n",float(sizeof(TreeOctNode)*tree.tree.nodes())/(1<<20));
	DumpOutput("Memory Usage: %.3f MB\n",float(MemoryInfo::Usage())/(1<<20));

	if(!NoClipTree.set){
		t=Time();
		tree.ClipTree();
		DumpOutput("Tree Clipped In: %lg\n",Time()-t);
		DumpOutput("Leaves/Nodes: %d/%d\n",tree.tree.leaves(),tree.tree.nodes());
		DumpOutput("   Tree Size: %.3f MB\n",float(sizeof(TreeOctNode)*tree.tree.nodes())/(1<<20));
	}

	t=Time();
	tree.finalize1(Refine.value);
	DumpOutput("Finalized 1 In: %lg\n",Time()-t);
	DumpOutput("Leaves/Nodes: %d/%d\n",tree.tree.leaves(),tree.tree.nodes());
	DumpOutput("Memory Usage: %.3f MB\n",float(MemoryInfo::Usage())/(1<<20));

	t=Time();
	tree.maxMemoryUsage=0;
	tree.SetLaplacianWeights();
	DumpOutput2(comments[commentNum++],"#Laplacian Weights Set In: %9.1f (s), %9.1f (MB)\n",Time()-t,tree.maxMemoryUsage);
	DumpOutput("Memory Usage: %.3f MB\n",float(MemoryInfo::Usage())/(1<<20));

	t=Time();
	tree.finalize2(Refine.value);
	DumpOutput("Finalized 2 In: %lg\n",Time()-t);
	DumpOutput("Leaves/Nodes: %d/%d\n",tree.tree.leaves(),tree.tree.nodes());
	DumpOutput("Memory Usage: %.3f MB\n",float(MemoryInfo::Usage())/(1<<20));

	tree.maxMemoryUsage=0;
	t=Time();
	tree.LaplacianMatrixIteration(SolverDivide.value);
	DumpOutput2(comments[commentNum++],"# Linear System Solved In: %9.1f (s), %9.1f (MB)\n",Time()-t,tree.maxMemoryUsage);
	DumpOutput("Memory Usage: %.3f MB\n",float(MemoryInfo::Usage())/(1<<20));

	CoredVectorMeshData mesh;
	tree.maxMemoryUsage=0;
	t=Time();
	isoValue=tree.GetIsoValue();
	DumpOutput("Got average in: %f\n",Time()-t);
	DumpOutput("Iso-Value: %e\n",isoValue);
	DumpOutput("Memory Usage: %.3f MB\n",float(tree.MemoryUsage()));

	t=Time();
	if(IsoDivide.value) tree.GetMCIsoTriangles( isoValue , IsoDivide.value , &mesh , 0 , 1 , Manifold.set , PolygonMesh.set );
	else                tree.GetMCIsoTriangles( isoValue ,                   &mesh , 0 , 1 , Manifold.set , PolygonMesh.set );
	if( PolygonMesh.set ) DumpOutput2(comments[commentNum++],"#         Got Polygons in: %9.1f (s), %9.1f (MB)\n",Time()-t,tree.maxMemoryUsage);
	else                  DumpOutput2(comments[commentNum++],"#        Got Triangles in: %9.1f (s), %9.1f (MB)\n",Time()-t,tree.maxMemoryUsage);
	DumpOutput2(comments[commentNum++],"#              Total Time: %9.1f (s)\n",Time()-tt);
	PlyWritePolygons(Out.value,&mesh,PLY_BINARY_NATIVE,center,scale,comments,commentNum);

	return 1;
}
示例#18
0
void VNCOptions::SetFromCommandLine(LPTSTR szCmdLine) {
	// We assume no quoting here.
	// Copy the command line - we don't know what might happen to the original
	int cmdlinelen = _tcslen(szCmdLine);
	if (cmdlinelen == 0) return;
	
	TCHAR *cmd = new TCHAR[cmdlinelen + 1];
	_tcscpy(cmd, szCmdLine);
	
	// Count the number of spaces
	// This may be more than the number of arguments, but that doesn't matter.
	int nspaces = 0;
	TCHAR *p = cmd;
	TCHAR *pos = cmd;
	while ( ( pos = _tcschr(p, ' ') ) != NULL ) {
		nspaces ++;
		p = pos + 1;
	}
	
	// Create the array to hold pointers to each bit of string
	TCHAR **args = new LPTSTR[nspaces + 1];
	
	// replace spaces with nulls and
	// create an array of TCHAR*'s which points to start of each bit.
	pos = cmd;
	int i = 0;
	args[i] = cmd;
	bool inquote=false;
	for (pos = cmd; *pos != 0; pos++) {
		// Arguments are normally separated by spaces, unless there's quoting
		if ((*pos == ' ') && !inquote) {
			*pos = '\0';
			p = pos + 1;
			args[++i] = p;
		}
		if (*pos == '"') {  
			if (!inquote) {      // Are we starting a quoted argument?
				args[i] = ++pos; // It starts just after the quote
			} else {
				*pos = '\0';     // Finish a quoted argument?
			}
			inquote = !inquote;
		}
	}
	i++;

	bool hostGiven = false, portGiven = false;
	// take in order.
	for (int j = 0; j < i; j++) {
		if ( SwitchMatch(args[j], _T("help")) ||
			SwitchMatch(args[j], _T("?")) ||
			SwitchMatch(args[j], _T("h"))) {
			ShowUsage();
			PostQuitMessage(1);
		} else if ( SwitchMatch(args[j], _T("listen"))) {
			m_listening = true;
		} else if ( SwitchMatch(args[j], _T("restricted"))) {
			m_restricted = true;
		} else if ( SwitchMatch(args[j], _T("viewonly"))) {
			m_ViewOnly = true;
		} else if ( SwitchMatch(args[j], _T("fullscreen"))) {
			m_FullScreen = true;
		} else if ( SwitchMatch(args[j], _T("8bit"))) {
			m_Use8Bit = true;
		} else if ( SwitchMatch(args[j], _T("shared"))) {
			m_Shared = true;
		} else if ( SwitchMatch(args[j], _T("swapmouse"))) {
			m_SwapMouse = true;
		} else if ( SwitchMatch(args[j], _T("nocursor"))) {
			m_localCursor = NOCURSOR;
		} else if ( SwitchMatch(args[j], _T("dotcursor"))) {
			m_localCursor = DOTCURSOR;
		} else if ( SwitchMatch(args[j], _T("normalcursor"))) {
			m_localCursor = NORMALCURSOR;
		} else if ( SwitchMatch(args[j], _T("belldeiconify") )) {
			m_DeiconifyOnBell = true;
		} else if ( SwitchMatch(args[j], _T("emulate3") )) {
			m_Emul3Buttons = true;
		} else if ( SwitchMatch(args[j], _T("noemulate3") )) {
			m_Emul3Buttons = false;
		} else if ( SwitchMatch(args[j], _T("scale") )) {
			if (++j == i) {
				ArgError(_T("No scaling factor specified"));
				continue;
			}
			int numscales = _stscanf(args[j], _T("%d/%d"), &m_scale_num, &m_scale_den);
			if (numscales < 1) {
				ArgError(_T("Invalid scaling specified"));
				continue;
			}
			if (numscales == 1) 
				m_scale_den = 1; // needed if you're overriding a previous setting

		} else if ( SwitchMatch(args[j], _T("emulate3timeout") )) {
			if (++j == i) {
				ArgError(_T("No timeout specified"));
				continue;
			}
			if (_stscanf(args[j], _T("%d"), &m_Emul3Timeout) != 1) {
				ArgError(_T("Invalid timeout specified"));
				continue;
			}
			
		} else if ( SwitchMatch(args[j], _T("emulate3fuzz") )) {
			if (++j == i) {
				ArgError(_T("No fuzz specified"));
				continue;
			}
			if (_stscanf(args[j], _T("%d"), &m_Emul3Fuzz) != 1) {
				ArgError(_T("Invalid fuzz specified"));
				continue;
			}
			
		} else if ( SwitchMatch(args[j], _T("disableclipboard") )) {
			m_DisableClipboard = true;
		}
#ifdef UNDER_CE
		// Manual setting of palm vs hpc aspect ratio for dialog boxes.
		else if ( SwitchMatch(args[j], _T("hpc") )) {
			m_palmpc = false;
		} else if ( SwitchMatch(args[j], _T("palm") )) {
			m_palmpc = true;
		} else if ( SwitchMatch(args[j], _T("slow") )) {
			m_slowgdi = true;
		} 
#endif
		else if ( SwitchMatch(args[j], _T("delay") )) {
			if (++j == i) {
				ArgError(_T("No delay specified"));
				continue;
			}
			if (_stscanf(args[j], _T("%d"), &m_delay) != 1) {
				ArgError(_T("Invalid delay specified"));
				continue;
			}
			
		} else if ( SwitchMatch(args[j], _T("loglevel") )) {
			if (++j == i) {
				ArgError(_T("No loglevel specified"));
				continue;
			}
			if (_stscanf(args[j], _T("%d"), &m_logLevel) != 1) {
				ArgError(_T("Invalid loglevel specified"));
				continue;
			}
			
		} else if ( SwitchMatch(args[j], _T("console") )) {
			m_logToConsole = true;
		} else if ( SwitchMatch(args[j], _T("logfile") )) {
			if (++j == i) {
				ArgError(_T("No logfile specified"));
				continue;
			}
			if (_stscanf(args[j], _T("%s"), &m_logFilename) != 1) {
				ArgError(_T("Invalid logfile specified"));
				continue;
			} else {
				m_logToFile = true;
			}
		} else if ( SwitchMatch(args[j], _T("config") )) {
			if (++j == i) {
				ArgError(_T("No config file specified"));
				continue;
			}
			// The GetPrivateProfile* stuff seems not to like some relative paths
			_fullpath(m_configFilename, args[j], _MAX_PATH);
			if (_access(m_configFilename, 04)) {
				ArgError(_T("Can't open specified config file for reading."));
				PostQuitMessage(1);
				continue;
			} else {
				Load(m_configFilename);
				m_configSpecified = true;
			}
		} else if ( SwitchMatch(args[j], _T("register") )) {
			Register();
			PostQuitMessage(0);
		} else {
			TCHAR phost[256];
			if (!ParseDisplay(args[j], phost, 255, &m_port)) {
				ShowUsage(_T("Invalid VNC server specified."));
				PostQuitMessage(1);
			} else {
				_tcscpy(m_host, phost);
				m_connectionSpecified = true;
			}
		}
	}       
	
	if (m_scale_num != 1 || m_scale_den != 1) 			
		m_scaling = true;

	// reduce scaling factors by greatest common denominator
	if (m_scaling) {
		FixScaling();
	}
	// tidy up
	delete [] cmd;
	delete [] args;
}
示例#19
0
文件: input.c 项目: UkCvs/ukcvs
int main (int argc, char **argv)
{
int tv,cols=25,debounce=25,tmo=0;
char ttl[]="Input";
int dloop=1,keys=0,frame=1,mask=0,bhelp=0;
char *title=NULL, *format=NULL, *defstr=NULL, *aptr, *rptr; 
unsigned int alpha;

		if(argc==1)
		{
			ShowUsage();
			return 0;
		}

		dloop=0;
		for(tv=1; !dloop && tv<argc; tv++)
		{
			aptr=argv[tv];
			if((rptr=strchr(aptr,'='))!=NULL)
			{
				rptr++;
				if(strstr(aptr,"l=")!=NULL)
				{
					format=rptr;
					dloop=Transform_Msg(format)==0;
				}
				else
				{
					if(strstr(aptr,"t=")!=NULL)
					{
						title=rptr;
						dloop=Transform_Msg(title)==0;
					}
					else
					{
						if(strstr(aptr,"d=")!=NULL)
						{
							defstr=rptr;
							dloop=Transform_Msg(defstr)==0;
						}
						else
						{
							if(strstr(aptr,"m=")!=NULL)
							{
								if(sscanf(rptr,"%d",&mask)!=1)
								{
									dloop=1;
								}
							}
							else
							{
								if(strstr(aptr,"f=")!=NULL)
								{
									if(sscanf(rptr,"%d",&frame)!=1)
									{
										dloop=1;
									}
								}
								else
								{
									if(strstr(aptr,"k=")!=NULL)
									{
										if(sscanf(rptr,"%d",&keys)!=1)
										{
											dloop=1;
										}
									}
									else
									{
										if(strstr(aptr,"h=")!=NULL)
										{
											if(sscanf(rptr,"%d",&bhelp)!=1)
											{
												dloop=1;
											}
										}
										else
										{
											if(strstr(aptr,"c=")!=NULL)
											{
												if(sscanf(rptr,"%d",&cols)!=1)
												{
													dloop=1;
												}
											}
											else
											{
												if(strstr(aptr,"o=")!=NULL)
												{
													if(sscanf(rptr,"%d",&tmo)!=1)
													{
														dloop=1;
													}
												}
												else
												{
													dloop=2;
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
			switch (dloop)
			{
				case 1:
					printf("input <param error: %s>\n",aptr);
					return 0;
					break;
				
				case 2:
					printf("input <unknown command: %s>\n\n",aptr);
					ShowUsage();
					return 0;
					break;
			}
		}
		if(!format)
		{
			printf("input <missing format string>\n");
			return 0;
    	}
		if(!title)
		{
			title=ttl;
		}

		if((buffer=calloc(BUFSIZE+1, sizeof(char)))==NULL)
		{
			printf(NOMEM);
			return 0;
		}

		if(((sx=Read_Neutrino_Cfg("screen_StartX"))<0)&&((sx=Read_Neutrino_Cfg("/enigma/plugins/needoffsets/left"))<0))
			sx=80;
		
		if(((ex=Read_Neutrino_Cfg("screen_EndX"))<0)&&((ex=Read_Neutrino_Cfg("/enigma/plugins/needoffsets/right"))<0))
			ex=620;

		if(((sy=Read_Neutrino_Cfg("screen_StartY"))<0)&&((sy=Read_Neutrino_Cfg("/enigma/plugins/needoffsets/top"))<0))
			sy=80;

		if(((ey=Read_Neutrino_Cfg("screen_EndY"))<0)&&((ey=Read_Neutrino_Cfg("/enigma/plugins/needoffsets/bottom"))<0))
			ey=505;

		if(Read_Neutrino_Cfg("rounded_corners")>0)
			radius=9;
		else
			radius=0;

		fb = open(FB_DEVICE, O_RDWR);
#ifdef HAVE_DBOX_HARDWARE
		ioctl(fb, AVIA_GT_GV_GET_BLEV, &alpha);
#endif
		InitRC();

	//init framebuffer

		if(ioctl(fb, FBIOGET_FSCREENINFO, &fix_screeninfo) == -1)
		{
			printf("input <FBIOGET_FSCREENINFO failed>\n");
			return 0;
		}
		if(ioctl(fb, FBIOGET_VSCREENINFO, &var_screeninfo) == -1)
		{
			printf("input <FBIOGET_VSCREENINFO failed>\n");
			return 0;
		}
		
		if(!(lfb = (unsigned char*)mmap(0, fix_screeninfo.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fb, 0)))
		{
			printf("input <mapping of Framebuffer failed>\n");
			return 0;
		}
		
	//init fontlibrary

		if((error = FT_Init_FreeType(&library)))
		{
			printf("input <FT_Init_FreeType failed with Errorcode 0x%.2X>", error);
			munmap(lfb, fix_screeninfo.smem_len);
			return 0;
		}

		if((error = FTC_Manager_New(library, 1, 2, 0, &MyFaceRequester, NULL, &manager)))
		{
			printf("input <FTC_Manager_New failed with Errorcode 0x%.2X>\n", error);
			FT_Done_FreeType(library);
			munmap(lfb, fix_screeninfo.smem_len);
			return 0;
		}

		if((error = FTC_SBitCache_New(manager, &cache)))
		{
			printf("input <FTC_SBitCache_New failed with Errorcode 0x%.2X>\n", error);
			FTC_Manager_Done(manager);
			FT_Done_FreeType(library);
			munmap(lfb, fix_screeninfo.smem_len);
			return 0;
		}

		if((error = FTC_Manager_Lookup_Face(manager, FONT, &face)))
		{
			printf("input <FTC_Manager_Lookup_Face failed with Errorcode 0x%.2X>\n", error);
			FTC_Manager_Done(manager);
			FT_Done_FreeType(library);
			munmap(lfb, fix_screeninfo.smem_len);
			return 0;
		}

		use_kerning = FT_HAS_KERNING(face);
#ifdef FT_NEW_CACHE_API
	desc.face_id = (char*)FONT;
#else
		desc.font.face_id = FONT;
#endif
#if FREETYPE_MAJOR == 2 && FREETYPE_MINOR == 0
		desc.image_type = ftc_image_mono;
#else
		desc.flags = FT_LOAD_MONOCHROME;
#endif

	//init backbuffer

		if(!(lbb = malloc(var_screeninfo.xres*var_screeninfo.yres)))
		{
			printf("input <allocating of Backbuffer failed>\n");
			FTC_Manager_Done(manager);
			FT_Done_FreeType(library);
			munmap(lfb, fix_screeninfo.smem_len);
			return 0;
		}

		if(!(obb = malloc(var_screeninfo.xres*var_screeninfo.yres)))
		{
			printf("input <allocating of Backbuffer failed>\n");
			FTC_Manager_Done(manager);
			FT_Done_FreeType(library);
			free(lbb);
			munmap(lfb, fix_screeninfo.smem_len);
			return 0;
		}

		memcpy(lbb, lfb, var_screeninfo.xres*var_screeninfo.yres);
		memcpy(obb, lfb, var_screeninfo.xres*var_screeninfo.yres);

		startx = sx /*+ (((ex-sx) - 620)/2)*/;
		starty = sy /* + (((ey-sy) - 505)/2)*/;



	signal(SIGINT, quit_signal);
	signal(SIGTERM, quit_signal);
	signal(SIGQUIT, quit_signal);

	//main loop
	put_instance(instance=get_instance()+1);
	printf("%s\n",inputd(format, title, defstr, keys, frame, mask, bhelp, cols, tmo, debounce));
	put_instance(get_instance()-1);

	memcpy(lfb, obb, var_screeninfo.xres*var_screeninfo.yres);

	free(buffer);

	FTC_Manager_Done(manager);
	FT_Done_FreeType(library);

	free(lbb);
	free(obb);
#ifdef HAVE_DBOX_HARDWARE
	ioctl(fb, AVIA_GT_GV_SET_BLEV, alpha);
#endif
	munmap(lfb, fix_screeninfo.smem_len);

	close(fb);
	CloseRC();

	return 1;
}
int
main(
    int argc,
    char *argv[]
    )
{
    enum
    {
        UNSET,
        SHOW_HELP,
        CHECK_VERSION,
        INSTALL,
        UNINSTALL
    } mode = UNSET;
    PCSTR pSmbdPath = NULL;
    PSTR pFoundSmbdPath = NULL;
    DWORD error = 0;
    DWORD argIndex = 0;
    LW_RTL_LOG_LEVEL logLevel = LW_RTL_LOG_LEVEL_ERROR;
    PCSTR pErrorSymbol = NULL;

    for (argIndex = 1; argIndex < argc; argIndex++)
    {
        if (!strcmp(argv[argIndex], "--check-version"))
        {
            if (mode == UNSET)
            {
                mode = CHECK_VERSION;
            }
            else
            {
                mode = SHOW_HELP;
            }
        }
        else if (!strcmp(argv[argIndex], "--install"))
        {
            if (mode == UNSET)
            {
                mode = INSTALL;
            }
            else
            {
                mode = SHOW_HELP;
            }
        }
        else if (!strcmp(argv[argIndex], "--uninstall"))
        {
            if (mode == UNSET)
            {
                mode = UNINSTALL;
            }
            else
            {
                mode = SHOW_HELP;
            }
        }
        else if (!strcmp(argv[argIndex], "--loglevel"))
        {
            argIndex++;
            if (argIndex >= argc)
            {
                error = ERROR_INVALID_PARAMETER;
                BAIL_ON_LSA_ERROR(error);
            }
            if (!strcmp(argv[argIndex], "error"))
            {
                logLevel = LW_RTL_LOG_LEVEL_ERROR;
            }
            else if (!strcmp(argv[argIndex], "warning"))
            {
                logLevel = LW_RTL_LOG_LEVEL_WARNING;
            }
            else if (!strcmp(argv[argIndex], "info"))
            {
                logLevel = LW_RTL_LOG_LEVEL_INFO;
            }
            else if (!strcmp(argv[argIndex], "verbose"))
            {
                logLevel = LW_RTL_LOG_LEVEL_VERBOSE;
            }
            else if (!strcmp(argv[argIndex], "debug"))
            {
                logLevel = LW_RTL_LOG_LEVEL_DEBUG;
            }
            else
            {
                error = ERROR_INVALID_PARAMETER;
                BAIL_ON_LSA_ERROR(error);
            }
        }
        else if (argIndex == argc - 1)
        {
            pSmbdPath = argv[2];
        }
        else
        {
            mode = SHOW_HELP;
        }
    }

    if (mode == UNSET || mode == SHOW_HELP)
    {
        ShowUsage(argv[0]);
        goto cleanup;
    }

    LwRtlLogSetCallback(LogCallback, NULL);
    LwRtlLogSetLevel(logLevel);

    if (pSmbdPath == NULL)
    {
        error = FindFileInPath(
                        "smbd",
                        "/usr/sbin",
                        &pFoundSmbdPath);
        BAIL_ON_LSA_ERROR(error);
        pSmbdPath = pFoundSmbdPath;
    }

    error = CheckSambaVersion(pSmbdPath);
    BAIL_ON_LSA_ERROR(error);

    if (mode == CHECK_VERSION)
    {
        fprintf(stderr, "Samba version supported\n");
    }
    else if (mode == INSTALL)
    {
        error = InstallWbclient(pSmbdPath);
        BAIL_ON_LSA_ERROR(error);

        error = InstallLwiCompat(pSmbdPath);
        BAIL_ON_LSA_ERROR(error);

        error = SynchronizePassword(
                    pSmbdPath);
        BAIL_ON_LSA_ERROR(error);

        fprintf(stderr, "Install successful\n");
    }
    else if (mode == UNINSTALL)
    {
        error = UninstallWbclient(pSmbdPath);
        BAIL_ON_LSA_ERROR(error);

        error = UninstallLwiCompat(pSmbdPath);
        BAIL_ON_LSA_ERROR(error);

        error = DeletePassword(
                    pSmbdPath);
        BAIL_ON_LSA_ERROR(error);

        fprintf(stderr, "Uninstall successful\n");
    }
    else
    {
        fprintf(stderr, "Uninstall mode not implemented\n");
        error = ERROR_INVALID_PARAMETER;
        BAIL_ON_LSA_ERROR(error);
    }

cleanup:
    LW_SAFE_FREE_STRING(pFoundSmbdPath);

    if (error)
    {
        pErrorSymbol = LwWin32ErrorToName(error);
        if (pErrorSymbol != NULL)
        {
            fprintf(stderr, "Error: %s\n", pErrorSymbol);
        }
        else
        {
            fprintf(stderr, "Unknown error\n");
        }
    }
    return error;
}
DWORD
ParseArgs(
    int    argc,
    char*  argv[],
    PSTR*  ppszGroupId,
    PLSA_FIND_FLAGS pFindFlags,
    PDWORD pdwInfoLevel,
    PBOOLEAN pbCountOnly
    )
{
    DWORD dwError = 0;
    int iArg = 1;
    PSTR pszArg = NULL;
    PSTR pszGroupId = NULL;
    LSA_FIND_FLAGS FindFlags = 0;
    DWORD dwInfoLevel = 0;
    BOOLEAN bCountOnly = FALSE;

    for (iArg = 1; iArg < argc; iArg++)
    {
        pszArg = argv[iArg];
        if (!strcmp(pszArg, "--help") ||
            !strcmp(pszArg, "-h"))
        {
            ShowUsage();
            exit(0);
        }
        else if (!strcmp(pszArg, "--count"))
        {
            bCountOnly = TRUE;
        }
        else if (!strcmp(pszArg, "--level"))
        {
            PCSTR pszValue;
            if (iArg + 1 >= argc)
            {
                fprintf(stderr, "Missing argument for %s option.\n", pszArg);
                ShowUsage();
                exit(1);
            }
            pszValue = argv[++iArg];
            if (!IsUnsignedInteger(pszValue))
            {
                fprintf(stderr, "Please enter an info level which is an unsigned integer.\n");
                ShowUsage();
                exit(1);
            }
            dwInfoLevel = atoi(pszValue);
        }
        else if (!strcmp(pszArg, "--flags"))
        {
            PCSTR pszValue;
            if (iArg + 1 >= argc)
            {
                fprintf(stderr, "Missing argument for %s option.\n", pszArg);
                ShowUsage();
                exit(1);
            }
            pszValue = argv[++iArg];
            if (!IsUnsignedInteger(pszValue))
            {
                fprintf(stderr, "Please enter a flags value which is an unsigned integer.\n");
                ShowUsage();
                exit(1);
            }
            FindFlags = atoi(pszValue);
        }
        else if (pszArg[0] == '-')
        {
            fprintf(stderr, "Invalid option '%s'.\n", pszArg);
            ShowUsage();
            exit(1);
        }
        else
        {
            break;
        }
    }

    if ((argc - iArg) < 1)
    {
        fprintf(stderr, "Missing required group name argument.\n");
        ShowUsage();
        exit(1);
    }
    dwError = LwAllocateString(argv[iArg++], &pszGroupId);
    BAIL_ON_LSA_ERROR(dwError);

    if ((argc - iArg) > 0)
    {
        fprintf(stderr, "Too many arguments.\n");
        ShowUsage();
        exit(1);
    }

    if (LW_IS_NULL_OR_EMPTY_STR(pszGroupId))
    {
        fprintf(stderr, "Please specify a non-empty group name to query for.\n");
        ShowUsage();
        exit(1);
    }

    *ppszGroupId = pszGroupId;
    *pFindFlags = FindFlags;
    *pdwInfoLevel = dwInfoLevel;
    *pbCountOnly = bCountOnly;

cleanup:

    return dwError;

error:

    *ppszGroupId = NULL;
    *pFindFlags = 0;
    *pdwInfoLevel = 0;
    *pbCountOnly = FALSE;

    LW_SAFE_FREE_STRING(pszGroupId);

    goto cleanup;
}
static
VOID
ParseArgs(
    IN int argc,
    IN char* argv[],
    OUT PCSTR* ppszUserName,
    OUT PDWORD pdwId,
    OUT PBOOLEAN pbShowSid
    )
{
    DWORD dwError = 0;
    int iArg = 0;
    PSTR pszArg = NULL;
    BOOLEAN bIsId = FALSE;
    PSTR pszUserName = NULL;
    DWORD dwId = 0;
    BOOLEAN bShowSid = FALSE;

    if (argc < 2)
    {
        ShowUsage();
        exit(1);
    }

    // First, get any options.
    for (iArg = 1; iArg < argc; iArg++)
    {
        pszArg = argv[iArg];

        if (!strcmp(pszArg, "--help") || !strcmp(pszArg, "-h"))
        {
            ShowUsage();
            exit(0);
        }
        else if (!strcmp(pszArg, "--uid") || !strcmp(pszArg, "-u"))
        {
            PCSTR pszUid = NULL;

            bIsId = TRUE;

            if ((iArg + 1) >= argc)
            {
                fprintf(stderr, "Missing argument for %s option.\n", pszArg);
                ShowUsage();
                exit(1);
            }

            pszUid = argv[iArg + 1];
            iArg++;

            if (!IsAllDigits(pszUid))
            {
                fprintf(stderr, "Non-numeric argument for %s option.\n", pszArg);
                ShowUsage();
                exit(1);
            }

            dwError = StringToId(pszUid, &dwId);
            if (dwError)
            {
                fprintf(stderr, "Invalid range for %s option.\n", pszArg);
                ShowUsage();
                exit(1);
            }

            // There can be no options following this one.
            iArg++;
            break;
        }
        else if (!strcmp(pszArg, "--show-sid"))
        {
            bShowSid = TRUE;
        }
        else
        {
            break;
        }
    }

    // Now get positional arguments.
    if ((argc - iArg) >= 1)
    {
        pszUserName = argv[iArg++];
        if (LW_IS_NULL_OR_EMPTY_STR(pszUserName))
        {
           fprintf(stderr, "Please specify a non-empty user name to query for.\n");
           ShowUsage();
           exit(1);
        }
    }

    // Now verify arguments.
    if (argc > iArg)
    {
        fprintf(stderr, "Too many arguments.\n");
        ShowUsage();
        exit(1);
    }

    if (bIsId && pszUserName)
    {
        fprintf(stderr, "Please specify either a uid or user name.\n");
        ShowUsage();
        exit(1);
    }

    *ppszUserName = pszUserName;
    *pdwId = dwId;
    *pbShowSid = bShowSid;
}
示例#23
0
文件: nbtree.c 项目: 50wu/gpdb
/*
 *	btbuild() -- build a new btree index.
 */
Datum
btbuild(PG_FUNCTION_ARGS)
{
	MIRROREDLOCK_BUFMGR_VERIFY_NO_LOCK_LEAK_DECLARE;

	Relation	heap = (Relation) PG_GETARG_POINTER(0);
	Relation	index = (Relation) PG_GETARG_POINTER(1);
	IndexInfo  *indexInfo = (IndexInfo *) PG_GETARG_POINTER(2);
	IndexBuildResult *result;
	double		reltuples;
	BTBuildState buildstate;

	MIRROREDLOCK_BUFMGR_VERIFY_NO_LOCK_LEAK_ENTER;

	buildstate.isUnique = indexInfo->ii_Unique;
	buildstate.haveDead = false;
	buildstate.heapRel = heap;
	buildstate.spool = NULL;
	buildstate.spool2 = NULL;
	buildstate.indtuples = 0;

#ifdef BTREE_BUILD_STATS
	if (log_btree_build_stats)
		ResetUsage();
#endif   /* BTREE_BUILD_STATS */

	/*
	 * We expect to be called exactly once for any index relation. If that's
	 * not the case, big trouble's what we have.
	 */
	if (RelationGetNumberOfBlocks(index) != 0)
		elog(ERROR, "index \"%s\" already contains data",
			 RelationGetRelationName(index));

	buildstate.spool = _bt_spoolinit(index, indexInfo->ii_Unique, false);

	/*
	 * If building a unique index, put dead tuples in a second spool to keep
	 * them out of the uniqueness check.
	 */
	if (indexInfo->ii_Unique)
		buildstate.spool2 = _bt_spoolinit(index, false, true);

	/* do the heap scan */
	reltuples = IndexBuildScan(heap, index, indexInfo, false,
								   btbuildCallback, (void *) &buildstate);

	/* okay, all heap tuples are indexed */
	if (buildstate.spool2 && !buildstate.haveDead)
	{
		/* spool2 turns out to be unnecessary */
		_bt_spooldestroy(buildstate.spool2);
		buildstate.spool2 = NULL;
	}

	/*
	 * Finish the build by (1) completing the sort of the spool file, (2)
	 * inserting the sorted tuples into btree pages and (3) building the upper
	 * levels.
	 */
	_bt_leafbuild(buildstate.spool, buildstate.spool2);
	_bt_spooldestroy(buildstate.spool);

	if (buildstate.spool2)
		_bt_spooldestroy(buildstate.spool2);

#ifdef BTREE_BUILD_STATS
	if (log_btree_build_stats)
	{
		ShowUsage("BTREE BUILD STATS");
		ResetUsage();
	}
#endif   /* BTREE_BUILD_STATS */

	/*
	 * If we are reindexing a pre-existing index, it is critical to send out a
	 * relcache invalidation SI message to ensure all backends re-read the
	 * index metapage.	We expect that the caller will ensure that happens
	 * (typically as a side effect of updating index stats, but it must happen
	 * even if the stats don't change!)
	 */

	/*
	 * Return statistics
	 */
	result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));

	result->heap_tuples = reltuples;
	result->index_tuples = buildstate.indtuples;

	MIRROREDLOCK_BUFMGR_VERIFY_NO_LOCK_LEAK_EXIT;

	PG_RETURN_POINTER(result);
}
int Execute( int argc , char* argv[] )
{
	int i;
	int paramNum = sizeof(params)/sizeof(cmdLineReadable*);
	int commentNum=0;
	char **comments;

	comments = new char*[paramNum+7];
	for( i=0 ; i<paramNum+7 ; i++ ) comments[i] = new char[1024];

	if( Verbose.set ) echoStdout=1;

	XForm4x4< Real > xForm , iXForm;
	if( XForm.set )
	{
		FILE* fp = fopen( XForm.value , "r" );
		if( !fp )
		{
			fprintf( stderr , "[WARNING] Could not read x-form from: %s\n" , XForm.value );
			xForm = XForm4x4< Real >::Identity();
		}
		else
		{
			for( int i=0 ; i<4 ; i++ ) for( int j=0 ; j<4 ; j++ ) fscanf( fp , " %f " , &xForm( i , j ) );
			fclose( fp );
		}
	}
	else xForm = XForm4x4< Real >::Identity();
	iXForm = xForm.inverse();

	DumpOutput2( comments[commentNum++] , "Running Screened Poisson Reconstruction (Version 5.5)\n" , Degree );
	char str[1024];
	for( int i=0 ; i<paramNum ; i++ )
		if( params[i]->set )
		{
			params[i]->writeValue( str );
			if( strlen( str ) ) DumpOutput2( comments[commentNum++] , "\t--%s %s\n" , params[i]->name , str );
			else                DumpOutput2( comments[commentNum++] , "\t--%s\n" , params[i]->name );
		}

	double t;
	double tt=Time();
	Real isoValue = 0;

	POctree< Degree , OutputDensity > tree;
	tree.threads = Threads.value;
	if( !In.set )
	{
		ShowUsage(argv[0]);
		return 0;
	}
	if( !MaxSolveDepth.set ) MaxSolveDepth.value = Depth.value;
	if( SolverDivide.value<MinDepth.value )
	{
		fprintf( stderr , "[WARNING] %s must be at least as large as %s: %d>=%d\n" , SolverDivide.name , MinDepth.name , SolverDivide.value , MinDepth.value );
		SolverDivide.value = MinDepth.value;
	}
	if( IsoDivide.value<MinDepth.value )
	{
		fprintf( stderr , "[WARNING] %s must be at least as large as %s: %d>=%d\n" , IsoDivide.name , MinDepth.name , IsoDivide.value , IsoDivide.value );
		IsoDivide.value = MinDepth.value;
	}
	
	OctNode< TreeNodeData< OutputDensity > , Real >::SetAllocator( MEMORY_ALLOCATOR_BLOCK_SIZE );

	t=Time();
	int kernelDepth = KernelDepth.set ?  KernelDepth.value : Depth.value-2;

	tree.setBSplineData( Depth.value , BoundaryType.value );
	if( kernelDepth>Depth.value )
	{
		fprintf( stderr,"[ERROR] %s can't be greater than %s: %d <= %d\n" , KernelDepth.name , Depth.name , KernelDepth.value , Depth.value );
		return EXIT_FAILURE;
	}

	double maxMemoryUsage;
	t=Time() , tree.maxMemoryUsage=0;
	int pointCount = tree.setTree( In.value , Depth.value , MinDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , PointWeight.value , AdaptiveExponent.value , xForm );
	tree.ClipTree();
	tree.finalize( IsoDivide.value );

	DumpOutput2( comments[commentNum++] , "#             Tree set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
	DumpOutput( "Input Points: %d\n" , pointCount );
	DumpOutput( "Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() );
	DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );

	maxMemoryUsage = tree.maxMemoryUsage;
	t=Time() , tree.maxMemoryUsage=0;
	tree.SetLaplacianConstraints();
	DumpOutput2( comments[commentNum++] , "#      Constraints set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
	DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage())/(1<<20) );
	maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );

	t=Time() , tree.maxMemoryUsage=0;
	tree.LaplacianMatrixIteration( SolverDivide.value, ShowResidual.set , MinIters.value , SolverAccuracy.value , MaxSolveDepth.value , FixedIters.value );
	DumpOutput2( comments[commentNum++] , "# Linear system solved in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
	DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );
	maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );

	CoredFileMeshData< Vertex > mesh;

	if( Verbose.set ) tree.maxMemoryUsage=0;
	t=Time();
	isoValue = tree.GetIsoValue();
	DumpOutput( "Got average in: %f\n" , Time()-t );
	DumpOutput( "Iso-Value: %e\n" , isoValue );

	if( VoxelGrid.set )
	{
		double t = Time();
		FILE* fp = fopen( VoxelGrid.value , "wb" );
		if( !fp ) fprintf( stderr , "Failed to open voxel file for writing: %s\n" , VoxelGrid.value );
		else
		{
			int res;
			Pointer( Real ) values = tree.GetSolutionGrid( res , isoValue , VoxelDepth.value );
			fwrite( &res , sizeof(int) , 1 , fp );
			if( sizeof(Real)==sizeof(float) ) fwrite( values , sizeof(float) , res*res*res , fp );
			else
			{
				float *fValues = new float[res*res*res];
				for( int i=0 ; i<res*res*res ; i++ ) fValues[i] = float( values[i] );
				fwrite( fValues , sizeof(float) , res*res*res , fp );
				delete[] fValues;
			}
			fclose( fp );
			DeletePointer( values );
		}
		DumpOutput( "Got voxel grid in: %f\n" , Time()-t );
	}

	if( Out.set )
	{
		t = Time() , tree.maxMemoryUsage = 0;
		tree.GetMCIsoTriangles( isoValue , IsoDivide.value , &mesh , 0 , 1 , !NonManifold.set , PolygonMesh.set );
		if( PolygonMesh.set ) DumpOutput2( comments[commentNum++] , "#         Got polygons in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
		else                  DumpOutput2( comments[commentNum++] , "#        Got triangles in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
		maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
		DumpOutput2( comments[commentNum++],"#             Total Solve: %9.1f (s), %9.1f (MB)\n" , Time()-tt , maxMemoryUsage );

		if( NoComments.set )
		{
			if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII         , NULL , 0 , iXForm );
			else            PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , NULL , 0 , iXForm );
		}
		else
		{
			if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII         , comments , commentNum , iXForm );
			else            PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , comments , commentNum , iXForm );
		}
	}

	return 1;
}
示例#25
0
static
DWORD
ParseArgs(
    int    argc,
    char*  argv[],
    PDWORD pdwInfoLevel,
    PDWORD pdwBatchSize,
    PBOOLEAN pbCheckGroupMembersOnline
    )
{
    typedef enum {
            PARSE_MODE_OPEN = 0,
            PARSE_MODE_LEVEL,
            PARSE_MODE_BATCHSIZE
        } ParseMode;

    DWORD dwError = 0;
    int iArg = 1;
    PSTR pszArg = NULL;
    ParseMode parseMode = PARSE_MODE_OPEN;
    DWORD dwInfoLevel = 0;
    DWORD dwBatchSize = 10;
    BOOLEAN bCheckGroupMembersOnline = FALSE;

    do {
        pszArg = argv[iArg++];
        if (pszArg == NULL || *pszArg == '\0')
        {
            break;
        }

        switch (parseMode)
        {
            case PARSE_MODE_OPEN:

                if ((strcmp(pszArg, "--help") == 0) ||
                    (strcmp(pszArg, "-h") == 0))
                {
                    ShowUsage();
                    exit(0);
                }
                else if (!strcmp(pszArg, "--level")) {
                    parseMode = PARSE_MODE_LEVEL;
                }
                else if (!strcmp(pszArg, "--batchsize")) {
                    parseMode = PARSE_MODE_BATCHSIZE;
                }
                else if (!strcmp(pszArg, "--check-group-members-online") ||
                        !strcmp(pszArg, "-c"))
               {
                   bCheckGroupMembersOnline = TRUE;
               }
                else
                {
                    ShowUsage();
                    exit(0);
                }
                break;

            case PARSE_MODE_LEVEL:

                if (!IsUnsignedInteger(pszArg))
                {
                    fprintf(stderr, "Please use an info level which is an unsigned integer.\n");
                    ShowUsage();
                    exit(1);
                }

                dwInfoLevel = atoi(pszArg);
                if (dwInfoLevel > 1) {
                    ShowUsage();
                    exit(1);
                }

                parseMode = PARSE_MODE_OPEN;

                break;

            case PARSE_MODE_BATCHSIZE:

                if (!IsUnsignedInteger(pszArg))
                {
                    fprintf(stderr, "Please use a batchsize which is an unsigned integer.\n");
                    ShowUsage();
                    exit(1);
                }

                dwBatchSize = atoi(pszArg);
                if ((dwBatchSize == 0) ||
                    (dwBatchSize > 1000)) {
                    ShowUsage();
                    exit(1);
                }
                parseMode = PARSE_MODE_OPEN;

                break;
        }

    } while (iArg < argc);

    if (parseMode != PARSE_MODE_OPEN)
    {
        ShowUsage();
        exit(1);
    }

    *pdwInfoLevel = dwInfoLevel;
    *pdwBatchSize = dwBatchSize;
    *pbCheckGroupMembersOnline = bCheckGroupMembersOnline;

    return dwError;
}
示例#26
0
文件: mew.c 项目: redtower/rc
/******************************************************************
 *                     main                                       *
 ******************************************************************/
int WINAPI WinMain( HINSTANCE hInstance,
		    HINSTANCE hPrevInstance,
		    LPSTR     lpCmdLine,
		    int       nCmdShow )
{
  BOOL fLogTime = FALSE;
  BOOL fCompile = TRUE;
  BOOL fInstall = TRUE;
  BOOL fSetup   = FALSE;
  BOOL fQuiet   = FALSE;
  char szPBuf[256];
  char szEPBuf[256];
  char szJPBuf[256];
  char seps[] = " \t";
  char *token;
  char     *pt;
  HMODULE  hModule;

  hInst = hInstance;
  memset( szMeadowVersion, 0, sizeof(szMeadowVersion) );

  token = strtok( lpCmdLine, seps );
  while ( token ){
    if ( ! strcmp(token,"-cd") ||
	 ! strcmp(token,"-nc") )
      fCompile = FALSE;		/* install only (not compile) */
    if ( ! strcmp(token,"-ni") )
      fInstall = FALSE;		/* compile only (not install) */
    if ( ! strcmp(token,"-s") )
      fSetup = TRUE;		/* setup mode */
    if ( ! strcmp(token,"-q") )
      fQuiet = TRUE;		/* quiet mode */
    if ( ! strcmp(token,"-h") ){
      ShowUsage();
      return 0;
    }      
    token = strtok( NULL, seps );
  } /* while ( token ){ */

  /* Setup log module
   * After this, OutputLog function could be used.
   */
  SetupLog( LOGFILE_NAME, TRUE, TRUE, fLogTime, TRUE, 0, fQuiet );

  /* Startup Log Message */
  sprintf(szPBuf,"Mew installer for Win32  Version %s",MEWINST_VERSION);
  OutputLog(szPBuf);
  sprintf(szPBuf,"          Copyright (C) %s  Shuichi Kitaguchi",
	  COPYRIGHT_YEARS);
  OutputLog(szPBuf);
  OutputLog("");

  /* Startup window */
  if (!fQuiet && !DialogBoxParam(hInst,
				 MAKEINTRESOURCE(IDD_TITLE),
				 0, TitleDlgProc, 0)){
      OutputLog("Installation is canceled or title window is failed to create.");
      return -1;
  }
  
  /* Ini file name */
  hModule = GetModuleHandle(NULL);
  GetModuleFileName(hModule,szCurrentPath,sizeof(szCurrentPath));
  if ( (pt = strrchr(szCurrentPath,'\\')) )
    *pt = (char)0;
  sprintf(szIniFile,"%s\\%s",szCurrentPath,MEWINST_DEFAULT);


#if 0  
  /* parent process's console? xxx */
  AllocConsole();
  hConsole = CreateConsoleScreenBuffer( GENERIC_READ|GENERIC_WRITE,
					0,
					NULL,
					CONSOLE_TEXTMODE_BUFFER,
					NULL );
  if ( hConsole == INVALID_HANDLE_VALUE ) goto Error;
  if ( ! SetStdHandle( STD_OUTPUT_HANDLE, hConsole ) ){
    OutputLog("SetStdhandle fails.");
    goto Error;
  }
  if ( ! SetConsoleActiveScreenBuffer( hConsole ) ){
    OutputLog("SetConsoleActiveScreenBuffer fails.");
    goto Error;
  }
#endif

  if ( ! GetEnvironments() ) goto Error;
  if ( ! ReadEnvironments() ) goto Error;
  PrintEnvironments();

  if ( ! CheckFile(MEWINST_DEFAULT) ){
    sprintf(szEPBuf,"[%s] is not found!",MEWINST_DEFAULT);
    sprintf(szJPBuf,"[%s] が見付かりません!",MEWINST_DEFAULT);
    BilErrorMessageBox( szEPBuf, szJPBuf );
    goto Error;
  }
  /*
  if ( ! CheckFile("mew.dot.emacs") ){
    BilErrorMessageBox( "Archive Extraction Error!\nCheck your archiver program(support long filename?).",
			"アーカイブの解凍に失敗しています\n解凍プログラムがロングファイルネームをサポートしているか、確認して下さい");
    goto Error;
  }
  */
  /* selecting Emacs type */
  if ( CheckFile( szIniFile ) ){
    GetPrivateProfileString("Make","EMACS","Default",
			    szPBuf,sizeof(szPBuf),
			    szIniFile);
    if ( !strcmp( szPBuf, "Default" ) && !fQuiet ){
      if ( ! SelectEmacsen() ){
	BilErrorMessageBox( "Any Emacsen cannot found!\nHas Emacs been installed correctly?",
			    "Emacs が見付かりませんでした\nEmacs を正しくインストールしましたか?" );
	goto Error;
      }
    }
  } /* if ( CheckFile( szIniFile ) ) */
  
  if ( langId == LANGID_JAPANESE ){
    OutputLog(">>INI ファイルを読み込んでいます...");
  } else {
    OutputLog(">>Read INI File...");
  }
  if ( ! ReadIniFile() ) goto Error;

  if ( langId == LANGID_JAPANESE )
    strcpy(szPBuf,">>>Emacs は [");
  else
    strcpy(szPBuf,">>>Emacs is [");
  switch ( bEmacsType ){
  case EMACS_MEADOW:
    strcat(szPBuf,"Meadow ");
    strcat(szPBuf,szMeadowVersion);
    break;
  case EMACS_EMACS:
    strcat(szPBuf,"Emacs");
    break;
  case EMACS_XEMACS:
    strcat(szPBuf,"XEmacs");
    break;
  default:
    strcat(szPBuf,"unknown");
    break;
  }
  if ( langId == LANGID_JAPANESE )
    strcat(szPBuf,"] です");
  else
    strcat(szPBuf,"]");
  OutputLog(szPBuf);

#if 0				/* XXX: */
  if ( fSetup ){
    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>設定を生成しています...");
    } else {
      OutputLog(">>Creating configuration...");
    }
    if ( ! SetupMew() ) goto Error;
    BilInfoMessageBox( "Add configuration to your ~/.emacs file.\nPlease check it.",
		       "~/.emacs ファイルに設定を追加しました\n確認して下さい");
    return ( 0 );
  }
#endif
  
  if ( fCompile ){
    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>ソースをコンパイルしています...");
    } else {
      OutputLog(">>Compiling sources...");
    }
    if ( ! CompileSources() ) goto Error;
    
    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>実行ファイルを作成しています...");
    } else {
      OutputLog(">>Making Executables...");
    }
  } /* if ( fCompile ){ */
  
  if ( fInstall ){
    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>el/elc/実行 ファイルをインストールしています...");
    } else {
      OutputLog(">>Installing el/elc/executable Files...");
    }
    if ( ! InstallMew() ) goto Error;
    
    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>画像ファイルをインストールしています...");
    } else {
      OutputLog(">>Installing Image files...");
    }
    if ( ! InstallImage() ) goto Error;

    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>Info ファイルをインストールしています...");
    } else {
      OutputLog(">>Installing Info files...");
    }
    if ( ! InstallInfo() ) goto Error;
  } /* if ( fInstall ){ */

#if 0				/* XXX: */
  if ( fInstall && !fQuiet ){
      if ( BilMessageBox( NULL,
			  "Do you want to setup your ~/.emacs?",
			  "~/.emacs の設定を行ないますか?",
			  "Question", MB_YESNO ) == IDYES ){
	  if ( ! SetupMew() ) goto Error;
	  BilInfoMessageBox( "Add configuration to your ~/.emacs file.\nPlease check it.",
			     "~/.emacs ファイルに設定を追加しました\n確認して下さい");
      }
  }
#endif

  if ( fInstall )
    BilInfoMessageBox( "Mew installation complete",
		       "Mew のインストールが終了しました" );

  if ( langId == LANGID_JAPANESE ){
    OutputLog(">>Mew のインストールが終了しました");
  } else {
    OutputLog(">>Mew installation complete.");
  }

  return ( 0 );

 Error:
  BilErrorMessageBox( "Mew installation is NOT complete!\nCheck mew.log file",
		      "Mew のインストールが正常に終了しませんでした。mew.logファイルをチェックしてください" );

  return ( -1 );
}
示例#27
0
int 
main(int argc, char **argv)
{
  // Look for help
  for (int i = 0; i < argc; i++) {
    if (!strcmp(argv[i], "-help")) {
      ShowUsage();
    }
  }

  // Read input and output filenames
  if (argc < 3)  ShowUsage();
  argv++, argc--; // First argument is program name
  char *input_scene_name = *argv; argv++, argc--; 
  char *output_image_name = *argv; argv++, argc--; 

  // Initialize arguments to default values
  int width = 256;
  int height = 256;
  int max_depth = 0;
  int num_distributed_rays_per_intersection = 0;
  int num_primary_rays_per_pixel = 1;

  // Parse arguments 
  while (argc > 0) {
    if (!strcmp(*argv, "-width")) {
      CheckOption(*argv, argc, 2);
      width = atoi(argv[1]);
      argv += 2, argc -= 2;
    }
    else if (!strcmp(*argv, "-height")) {
      CheckOption(*argv, argc, 2);
      height = atoi(argv[1]);
      argv += 2, argc -= 2;
    }
    else if (!strcmp(*argv, "-max_depth")) {
      CheckOption(*argv, argc, 2);
      max_depth = atoi(argv[1]);
      argv += 2, argc -= 2;
    }
    else if (!strcmp(*argv, "-antialias")) {
      CheckOption(*argv, argc, 2);
      num_primary_rays_per_pixel = atoi(argv[1]);
      argv += 2, argc -= 2;
    }
    else if (!strcmp(*argv, "-distribute")) {
      CheckOption(*argv, argc, 2);
      num_distributed_rays_per_intersection = atoi(argv[1]);
      argv += 2, argc -= 2;
    }
    else {
      // Unrecognized program argument
      fprintf(stderr,  "meshpro: invalid option: %s\n", *argv);
      ShowUsage();
    }
  }

  // Read scene
  R3Scene *scene = ReadScene(input_scene_name, width, height);
  if (!scene) {
    fprintf(stderr, "Unable to read scene from %s\n", input_scene_name);
    exit(-1);
  }

  // Render image
  R2Image *image = RenderImage(scene, width, height, max_depth, 
    num_primary_rays_per_pixel, num_distributed_rays_per_intersection);
  if (!image) {
    fprintf(stderr, "Did not render image from scene\n");
    exit(-1);
  }

  // Transfer the image to sRGB color space: for Windows + Linux and Mac OS X
  // 10.6+ (for earlier MAC OS X it will look slightly too bright, but not as
  // much as it would be too dark otherwise. This function also clamps the 
  // image values; however, it does not scale the brightness and also does not
  // perform any more complicated tone mapping
  image->TosRGB();

  // Write output image
  if (!image->Write(output_image_name)) {
    fprintf(stderr, "Did not write image to %s\n", output_image_name);
    exit(-1);
  }

  // Delete everything
  delete scene;
  delete image;

  // Return success
  return EXIT_SUCCESS;
}
示例#28
0
/*
 *	btbuild() -- build a new btree index.
 */
Datum
btbuild(PG_FUNCTION_ARGS)
{
	Relation	heap = (Relation) PG_GETARG_POINTER(0);
	Relation	index = (Relation) PG_GETARG_POINTER(1);
	IndexInfo  *indexInfo = (IndexInfo *) PG_GETARG_POINTER(2);
	IndexBuildResult *result;
	double		reltuples;
	BTBuildState buildstate;

	buildstate.isUnique = indexInfo->ii_Unique;
	buildstate.haveDead = false;
	buildstate.heapRel = heap;
	buildstate.spool = NULL;
	buildstate.spool2 = NULL;
	buildstate.indtuples = 0;

#ifdef BTREE_BUILD_STATS
	if (log_btree_build_stats)
		ResetUsage();
#endif   /* BTREE_BUILD_STATS */

	/*
	 * We expect to be called exactly once for any index relation. If that's
	 * not the case, big trouble's what we have.
	 */
	if (RelationGetNumberOfBlocks(index) != 0)
		elog(ERROR, "index \"%s\" already contains data",
			 RelationGetRelationName(index));

	buildstate.spool = _bt_spoolinit(heap, index, indexInfo->ii_Unique, false);

	/*
	 * If building a unique index, put dead tuples in a second spool to keep
	 * them out of the uniqueness check.
	 */
	if (indexInfo->ii_Unique)
		buildstate.spool2 = _bt_spoolinit(heap, index, false, true);

	/* do the heap scan */
	reltuples = IndexBuildHeapScan(heap, index, indexInfo, true,
								   btbuildCallback, (void *) &buildstate);

	/* okay, all heap tuples are indexed */
	if (buildstate.spool2 && !buildstate.haveDead)
	{
		/* spool2 turns out to be unnecessary */
		_bt_spooldestroy(buildstate.spool2);
		buildstate.spool2 = NULL;
	}

	/*
	 * Finish the build by (1) completing the sort of the spool file, (2)
	 * inserting the sorted tuples into btree pages and (3) building the upper
	 * levels.
	 */
	_bt_leafbuild(buildstate.spool, buildstate.spool2);
	_bt_spooldestroy(buildstate.spool);
	if (buildstate.spool2)
		_bt_spooldestroy(buildstate.spool2);

#ifdef BTREE_BUILD_STATS
	if (log_btree_build_stats)
	{
		ShowUsage("BTREE BUILD STATS");
		ResetUsage();
	}
#endif   /* BTREE_BUILD_STATS */

	/*
	 * Return statistics
	 */
	result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));

	result->heap_tuples = reltuples;
	result->index_tuples = buildstate.indtuples;

	PG_RETURN_POINTER(result);
}
示例#29
0
void
HandleALOption (
    int argc,
    TCHAR **argv
    )
{
    DWORD returnValue = 0;
    HKEY  registryKey;
    TCHAR appid [256];
    TCHAR keyName [256];

    if (argc < 4)
        ShowUsage (TEXT("Invalid number of arguments."));

    if (_tcscmp (_tcsupr (argv[3]), TEXT("LIST")) == 0)
    {
        if (argc < 4)
            ShowUsage (TEXT("Invalid number of arguments.\n"));

        _tprintf (TEXT("Launch permission list for AppID %s:\n\n"), argv[2]);
        ListAppIDLaunchACL (argv[2]);
        return;
    }
    if (_tcscmp (_tcsupr (argv[3]), TEXT("ZAP_LIST")) == 0)
    {
        if (argc < 4)
            ShowUsage (TEXT("Invalid number of arguments.\n"));

        _tprintf (TEXT("Zapping launch permissions for AppID %s:\n\n"), argv[2]);
        ZapAppIDLaunchACL (argv[2]);
        return;
    }

    if (_tcscmp (_tcsupr (argv[3]), TEXT("DEFAULT")) == 0)
    {
        if (argv [2][0] == '{')
            wsprintf (appid, TEXT("%s"), argv [2]); else
            wsprintf (appid, TEXT("{%s}"), argv [2]);

        wsprintf (keyName, TEXT("APPID\\%s"), appid);

        returnValue = RegOpenKeyEx (HKEY_CLASSES_ROOT, keyName, 0, KEY_ALL_ACCESS, &registryKey);
        if (returnValue != ERROR_SUCCESS && returnValue != ERROR_FILE_NOT_FOUND)
            Error (TEXT("ERROR: Cannot open AppID registry key."), returnValue);

        returnValue = RegDeleteValue (registryKey, TEXT("LaunchPermission"));
        if (returnValue != ERROR_SUCCESS && returnValue != ERROR_FILE_NOT_FOUND)
            Error (TEXT("ERROR: Cannot delete LaunchPermission value."), returnValue);

        RegCloseKey (registryKey);
        return;
    }

    if (argc < 5)
        ShowUsage (TEXT("Invalid number of arguments."));

    if (_tcscmp (_tcsupr (argv [3]), TEXT("SET")) == 0)
    {
        if (argc < 6)
            ShowUsage (TEXT("Invalid number of arguments."));

        if (_tcscmp (_tcsupr (argv [5]), TEXT("PERMIT")) == 0)
            returnValue = ChangeAppIDLaunchACL (argv[2], argv [4], true, true); else

        if (_tcscmp (_tcsupr (argv [5]), TEXT("DENY")) == 0)
            returnValue = ChangeAppIDLaunchACL (argv[2], argv [4], true, false); else
        {
            ShowUsage (TEXT("You can only set a user's permissions to \"permit\" or \"deny\".\n\n"));
        }

        if (returnValue != ERROR_SUCCESS)
            Error (TEXT("ERROR: Cannot add user to application launch ACL."), returnValue);
    } else
    if (_tcscmp (_tcsupr (argv [3]), TEXT("REMOVE")) == 0)
    {
        returnValue = ChangeAppIDLaunchACL (argv[2], argv[4], false, false);

        if (returnValue != ERROR_SUCCESS)
            Error (TEXT("ERROR: Cannot remove user from application launch ACL."), returnValue);
    } else
        ShowUsage (TEXT("You can only \"set\" or \"remove\" a user."));
}
示例#30
0
int __cdecl wmain(int argc, PWCHAR argv[]) {
  size_t i;
  WCHAR fileName[MAX_PATH];
  WCHAR driverFullPath[MAX_PATH] = {0};
  PVOID wow64OldValue;
  BOOL isAdmin;

  isAdmin = IsUserAnAdmin();

  DokanUseStdErr(TRUE); // Set dokan library debug output

  Wow64DisableWow64FsRedirection(&wow64OldValue); // Disable system32 direct
  // setlocale(LC_ALL, "");

  GetModuleFileName(NULL, fileName, MAX_PATH);

  // search the last "\"
  for (i = wcslen(fileName) - 1; i > 0 && fileName[i] != L'\\'; --i) {
    ;
  }
  fileName[i] = L'\0';

  ExpandEnvironmentStringsW(DOKAN_DRIVER_FULL_PATH, driverFullPath, MAX_PATH);

  fwprintf(stdout, L"Driver path: '%s'\n", driverFullPath);

  WCHAR option = GetOption(argc, argv, 1);
  if (option == L'\0') {
    return ShowUsage();
  }

  if (!isAdmin &&
      (option == L'i' || option == L'r' || option == L'd' || option == L'u')) {
    fprintf(stderr, "Admin rights required to process this operation\n");
    return EXIT_FAILURE;
  }

  switch (option) {
  // Admin rights required
  case L'i': {
    WCHAR type = towlower(argv[2][0]);
    if (type == L'd') {
      return InstallDriver(driverFullPath);
    } else if (type == L'n') {
      if (DokanNetworkProviderInstall())
        fprintf(stdout, "network provider install ok\n");
      else
        fprintf(stderr, "network provider install failed\n");
    } else {
      goto DEFAULT;
    }
  } break;

  case L'r': {
    WCHAR type = towlower(argv[2][0]);
    if (type == L'd') {
      return DeleteDokanService(DOKAN_DRIVER_SERVICE);
    } else if (type == L'n') {
      if (DokanNetworkProviderUninstall())
        fprintf(stdout, "network provider remove ok\n");
      else
        fprintf(stderr, "network provider remove failed\n");
    } else {
      goto DEFAULT;
    }
  } break;

  case L'd': {
    WCHAR type = towlower(argv[2][0]);
    if (L'0' > type || type > L'9')
      goto DEFAULT;

    ULONG mode = type - L'0';
    if (DokanSetDebugMode(mode)) {
      fprintf(stdout, "set debug mode ok\n");
    } else {
      fprintf(stderr, "set debug mode failed\n");
    }
  } break;

  case L'u': {
    if (argc < 3) {
      goto DEFAULT;
    }
    return Unmount(argv[2]);
  } break;

  // No admin rights required
  case L'l': {
    ULONG nbRead = 0;
    PDOKAN_CONTROL dokanControl =
        malloc(DOKAN_MAX_INSTANCES * sizeof(*dokanControl));
    if (dokanControl == NULL) {
      fprintf(stderr, "Failed to allocate dokanControl\n");
      return EXIT_FAILURE;
    }

    ZeroMemory(dokanControl, DOKAN_MAX_INSTANCES * sizeof(*dokanControl));
    if (DokanGetMountPointList(dokanControl, DOKAN_MAX_INSTANCES, FALSE,
                               &nbRead)) {
      fwprintf(stdout, L"  Mount points: %d\n", nbRead);
      for (unsigned int p = 0; p < nbRead; ++p) {
        fwprintf(stdout, L"  %d# MountPoint: %s - UNC: %s - DeviceName: %s\n",
                 p, dokanControl[p].MountPoint, dokanControl[p].UNCName,
                 dokanControl[p].DeviceName);
      }
    } else {
      fwprintf(stderr, L"  Cannot retrieve mount point list.\n");
    }
    free(dokanControl);
  } break;

  case L'v': {
    fprintf(stdout, "dokanctl : %s %s\n", __DATE__, __TIME__);
    fprintf(stdout, "Dokan version : %d\n", DokanVersion());
    fprintf(stdout, "Dokan driver version : 0x%lx\n", DokanDriverVersion());
  } break;

  DEFAULT:
  default:
    fprintf(stderr, "Unknown option - Use /? to show usage\n");
  }

  return EXIT_SUCCESS;
}