CFNetDiagnosticRef CFNetDiagnosticCreateBasic( CFAllocatorRef allocator, CFStringRef remoteHost, CFStringRef protocol, CFNumberRef port) { CFMutableDictionaryRef retval = NULL; retval = CFDictionaryCreateMutable(allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if(retval != NULL) { _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticNameKey, CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleNameKey), retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticBundleKey, CFBundleGetIdentifier( CFBundleGetMainBundle() ), retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticRemoteHostKey, remoteHost, retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticProtocolKey, protocol, retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticPortKey, port, retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticMethodKey, CFSTR("CFNetDiagnosticCreateBasic"), retval); } return (CFNetDiagnosticRef)retval; }
/*! * \brief Adds default data dirs * * Priority: * Lower loads first. Current: * -datadir > User's home dir > source tree data > AutoPackage > BaseDir > DEFAULT_DATADIR * * Only -datadir and home dir are allways examined. Others only if data still not found. * * We need ParseCommandLine, before we can add any mods... * * \sa rebuildSearchPath */ static void scanDataDirs( void ) { char tmpstr[PATH_MAX], prefix[PATH_MAX]; char* separator; #if defined(WZ_OS_MAC) // version-independent location for video files registerSearchPath("/Library/Application Support/Warzone 2100/", 1); #endif // Find out which PREFIX we are in... sstrcpy(prefix, PHYSFS_getBaseDir()); separator = strrchr(prefix, *PHYSFS_getDirSeparator()); if (separator) { *separator = '\0'; // Trim ending '/', which getBaseDir always provides separator = strrchr(prefix, *PHYSFS_getDirSeparator()); if (separator) { *separator = '\0'; // Skip the last dir from base dir } } // Commandline supplied datadir if( strlen( datadir ) != 0 ) registerSearchPath( datadir, 1 ); // User's home dir registerSearchPath( PHYSFS_getWriteDir(), 2 ); rebuildSearchPath( mod_multiplay, true ); if( !PHYSFS_exists("gamedesc.lev") ) { // Data in source tree sstrcpy(tmpstr, prefix); sstrcat(tmpstr, "/data/"); registerSearchPath( tmpstr, 3 ); rebuildSearchPath( mod_multiplay, true ); if( !PHYSFS_exists("gamedesc.lev") ) { // Relocation for AutoPackage sstrcpy(tmpstr, prefix); sstrcat(tmpstr, "/share/warzone2100/"); registerSearchPath( tmpstr, 4 ); rebuildSearchPath( mod_multiplay, true ); if( !PHYSFS_exists("gamedesc.lev") ) { // Program dir registerSearchPath( PHYSFS_getBaseDir(), 5 ); rebuildSearchPath( mod_multiplay, true ); if( !PHYSFS_exists("gamedesc.lev") ) { // Guessed fallback default datadir on Unix registerSearchPath( WZ_DATADIR, 6 ); rebuildSearchPath( mod_multiplay, true ); } } } } #ifdef WZ_OS_MAC if( !PHYSFS_exists("gamedesc.lev") ) { CFURLRef resourceURL = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle()); char resourcePath[PATH_MAX]; if( CFURLGetFileSystemRepresentation( resourceURL, true, (UInt8 *) resourcePath, PATH_MAX) ) { chdir( resourcePath ); registerSearchPath( "data", 7 ); rebuildSearchPath( mod_multiplay, true ); } else { debug( LOG_ERROR, "Could not change to resources directory." ); } if( resourceURL != NULL ) { CFRelease( resourceURL ); } } #endif /** Debugging and sanity checks **/ printSearchPath(); if( PHYSFS_exists("gamedesc.lev") ) { debug( LOG_WZ, "gamedesc.lev found at %s", PHYSFS_getRealDir( "gamedesc.lev" ) ); } else { debug( LOG_FATAL, "Could not find game data. Aborting." ); exit(1); } }
void MediaPluginGStreamer010::set_gst_plugin_path() { // Linux sets GST_PLUGIN_PATH in wrapper.sh, not here. #if LL_WINDOWS || LL_DARWIN std::string imp_dir = ""; // Get the current working directory: #if LL_WINDOWS char* raw_dir; raw_dir = _getcwd(NULL,0); if( raw_dir != NULL ) { imp_dir = std::string( raw_dir ); } #elif LL_DARWIN CFBundleRef main_bundle = CFBundleGetMainBundle(); if( main_bundle != NULL ) { CFURLRef bundle_url = CFBundleCopyBundleURL( main_bundle ); if( bundle_url != NULL ) { #ifndef MAXPATHLEN #define MAXPATHLEN 1024 #endif char raw_dir[MAXPATHLEN]; if( CFURLGetFileSystemRepresentation( bundle_url, true, (UInt8 *)raw_dir, MAXPATHLEN) ) { imp_dir = std::string( raw_dir ) + "/Contents/MacOS/"; } CFRelease(bundle_url); } } #endif if( imp_dir == "" ) { WARNMSG("Could not get application directory, not setting GST_PLUGIN_PATH."); return; } DEBUGMSG("Imprudence is installed at %s", imp_dir); // ":" on Mac and 'Nix, ";" on Windows std::string separator = G_SEARCHPATH_SEPARATOR_S; // Grab the current path, if it's set. std::string old_plugin_path = ""; char *old_path = getenv("GST_PLUGIN_PATH"); if(old_path == NULL) { DEBUGMSG("Did not find user-set GST_PLUGIN_PATH."); } else { old_plugin_path = separator + std::string( old_path ); } // Search both Imprudence and Imprudence\lib\gstreamer-plugins. // But we also want to search the path the user has set, if any. std::string plugin_path = "GST_PLUGIN_PATH=" + #if LL_WINDOWS imp_dir + "\\lib\\gstreamer-plugins" + #elif LL_DARWIN imp_dir + separator + imp_dir + "/../Resources/lib/gstreamer-plugins" + #endif old_plugin_path; int put_result; // Place GST_PLUGIN_PATH in the environment settings #if LL_WINDOWS put_result = _putenv( (char*)plugin_path.c_str() ); #elif LL_DARWIN put_result = putenv( (char*)plugin_path.c_str() ); #endif if( put_result == -1 ) { WARNMSG("Setting GST_PLUGIN_PATH failed!"); } else { DEBUGMSG("GST_PLUGIN_PATH set to %s", getenv("GST_PLUGIN_PATH")); } // Don't load system plugins. We only want to use ours, to avoid conflicts. #if LL_WINDOWS put_result = _putenv( "GST_PLUGIN_SYSTEM_PATH=\"\"" ); #elif LL_DARWIN put_result = putenv( "GST_PLUGIN_SYSTEM_PATH=\"\"" ); #endif if( put_result == -1 ) { WARNMSG("Setting GST_PLUGIN_SYSTEM_PATH=\"\" failed!"); } #endif // LL_WINDOWS || LL_DARWIN }
GLchar* getShaderString(const char* shaderName, const char* shaderType) { CFBundleRef mainBundle = CFBundleGetMainBundle(); CFStringRef shaderNameRef = CFStringCreateWithCStringNoCopy(NULL, shaderName, kCFStringEncodingASCII, NULL); CFStringRef shaderTypeRef = CFStringCreateWithCStringNoCopy(NULL, shaderType, kCFStringEncodingASCII, NULL); // Get a reference to the file's URL CFURLRef shaderURL = CFBundleCopyResourceURL(mainBundle, shaderNameRef, shaderTypeRef, NULL); // Convert the URL reference into a string reference CFStringRef shaderPathRef = CFURLCopyFileSystemPath(shaderURL, kCFURLPOSIXPathStyle); // Get the system encoding method CFStringEncoding encodingMethod = CFStringGetSystemEncoding(); // Convert the string reference into a C string const char *shaderPath = CFStringGetCStringPtr(shaderPathRef, encodingMethod); fprintf(stderr, "Shader file loaded from path: %s\n", shaderPath); GLchar* sourceString = NULL; float glLanguageVersion; sscanf((char *)glGetString(GL_SHADING_LANGUAGE_VERSION), "%f", &glLanguageVersion); GLuint version = 100 * glLanguageVersion; // Get the size of the version preprocessor string info so we know // how much memory to allocate for our sourceString const GLsizei versionStringSize = sizeof("#version 123\n"); FILE* curFile = fopen(shaderPath, "r"); // Get the size of the source fseek(curFile, 0, SEEK_END); GLsizei fileSize = ftell (curFile); //fileSize += 1; // for null terminator // Alloc memory for the string GLchar *string = (GLchar *)malloc(fileSize+1); // Read entire file into the string from beginning of the file fseek(curFile, 0, SEEK_SET); fread(string, 1, fileSize, curFile); fclose(curFile); // Insert null terminator string[fileSize] = 0; sourceString = (GLchar *)malloc(fileSize+1 + versionStringSize); // printf("VERSION IS: %d\n", version); // Prepend our vertex shader source string with the supported GLSL version so // the shader will work on ES, Legacy, and OpenGL 3.2 Core Profile contexts sprintf(sourceString, "#version %d\n%s", version, string); return sourceString; }
void AppPathManager::initAppPath() { QApplication::setOrganizationName(V_COMPANY); QApplication::setOrganizationDomain(V_PGE_URL); QApplication::setApplicationName("Playable Character Calibrator"); #ifdef __APPLE__ { CFURLRef appUrlRef; appUrlRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef filePathRef = CFURLGetString(appUrlRef); //const char* filePath = CFStringGetCStringPtr(filePathRef, kCFStringEncodingUTF8); ApplicationPath = QUrl(QString::fromCFString(filePathRef)).toLocalFile(); { int i = ApplicationPath.lastIndexOf(".app"); i = ApplicationPath.lastIndexOf('/', i); ApplicationPath.remove(i, ApplicationPath.size() - i); } //CFRelease(filePathRef); CFRelease(appUrlRef); //! If it's a path randomizer if(ApplicationPath.startsWith("/private/var/")) { QString realAppPath("/Applications/PGE Project"); if(QDir(realAppPath).exists()) { ApplicationPath = realAppPath; } } } #else ApplicationPath = QApplication::applicationDirPath(); #endif ApplicationPath_x = ApplicationPath; if(isPortable()) return; #if defined(__ANDROID__) || defined(__APPLE__) QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); #else QString path = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); #endif if(!path.isEmpty()) { QDir appDir(path+UserDirName); if(!appDir.exists()) if(!appDir.mkpath(path+UserDirName)) goto defaultSettingsPath; m_userPath = appDir.absolutePath(); initSettingsPath(); } else { goto defaultSettingsPath; } return; defaultSettingsPath: m_userPath = ApplicationPath; initSettingsPath(); }
bool XMacSystem::DisplayNotification( const VString& inTitle, const VString& inMessage, EDisplayNotificationOptions inOptions, ENotificationResponse *outResponse) { CFOptionFlags flags = (inOptions & EDN_StyleCritical) ? kCFUserNotificationCautionAlertLevel : kCFUserNotificationPlainAlertLevel; CFStringRef cfIconFileName = (CFStringRef) CFBundleGetValueForInfoDictionaryKey( CFBundleGetMainBundle(), CFSTR("CFBundleIconFile")); CFURLRef cfIconURL = (cfIconFileName == NULL) ? NULL : CFBundleCopyResourceURL( CFBundleGetMainBundle(), cfIconFileName, NULL, NULL); CFMutableDictionaryRef dico = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (cfIconURL != NULL && dico != NULL) CFDictionaryAddValue( dico, kCFUserNotificationIconURLKey, cfIconURL); // kCFUserNotificationAlertHeaderKey is required if (inTitle.IsEmpty()) { PutStringIntoDictionary( inMessage, dico, kCFUserNotificationAlertHeaderKey); } else { PutStringIntoDictionary( inTitle, dico, kCFUserNotificationAlertHeaderKey); PutStringIntoDictionary( inMessage, dico, kCFUserNotificationAlertMessageKey); } ENotificationResponse responseDefault = ERN_None; ENotificationResponse responseAlternate = ERN_None; ENotificationResponse responseOther = ERN_None; switch( inOptions & EDN_LayoutMask) { case EDN_OK_Cancel: if (inOptions & EDN_Default1) { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("OK")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("Cancel")); responseDefault = ERN_OK; responseAlternate = ERN_Cancel; } else { CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("OK")); CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("Cancel")); responseDefault = ERN_Cancel; responseAlternate = ERN_OK; } break; case EDN_Yes_No: if (inOptions & EDN_Default1) { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("Yes")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("No")); responseDefault = ERN_Yes; responseAlternate = ERN_No; } else { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("No")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("Yes")); responseDefault = ERN_No; responseAlternate = ERN_Yes; } break; case EDN_Yes_No_Cancel: if ((inOptions & EDN_DefaultMask) == EDN_Default1) { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("Yes")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("No")); CFDictionaryAddValue( dico, kCFUserNotificationOtherButtonTitleKey, CFSTR("Cancel")); responseDefault = ERN_Yes; responseAlternate = ERN_No; responseOther = ERN_Cancel; } else if ((inOptions & EDN_DefaultMask) == EDN_Default2) { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("No")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("Yes")); CFDictionaryAddValue( dico, kCFUserNotificationOtherButtonTitleKey, CFSTR("Cancel")); responseDefault = ERN_No; responseAlternate = ERN_Yes; responseOther = ERN_Cancel; } else { CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("Cancel")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("No")); CFDictionaryAddValue( dico, kCFUserNotificationOtherButtonTitleKey, CFSTR("Yes")); responseDefault = ERN_Cancel; responseAlternate = ERN_No; responseOther = ERN_Yes; } case EDN_Abort_Retry_Ignore: CFDictionaryAddValue( dico, kCFUserNotificationDefaultButtonTitleKey, CFSTR("Retry")); CFDictionaryAddValue( dico, kCFUserNotificationAlternateButtonTitleKey, CFSTR("Ignore")); CFDictionaryAddValue( dico, kCFUserNotificationOtherButtonTitleKey, CFSTR("Abort")); responseDefault = ERN_Retry; responseAlternate = ERN_Ignore; responseOther = ERN_Abort; break; case EDN_OK: default: responseDefault = ERN_OK; } SInt32 error = 0; CFUserNotificationRef refNotification = CFUserNotificationCreate( kCFAllocatorDefault, 0 /*CFTimeInterval timeout*/, flags, &error, dico); if ( (refNotification != NULL) && (outResponse != NULL) ) { *outResponse = ERN_None; if (error == 0) { CFOptionFlags responseFlags = 0; SInt32 rCode = CFUserNotificationReceiveResponse( refNotification, 0 /*CFTimeInterval timeout*/, &responseFlags); if (testAssert( rCode == 0)) // "0 if the cancel was successful; a non-0 value otherwise." { switch( responseFlags & 0x3) { case kCFUserNotificationDefaultResponse: *outResponse = responseDefault; break; case kCFUserNotificationAlternateResponse: *outResponse = responseAlternate; break; case kCFUserNotificationOtherResponse: *outResponse = responseOther; break; case kCFUserNotificationCancelResponse: *outResponse = ERN_Timeout; break; } } } } if (refNotification != NULL) CFRelease( refNotification); if (cfIconURL != NULL) CFRelease( cfIconURL); if (dico != NULL) CFRelease( dico); return error == 0; }
static std::string sGetProcessPath() { #if EE_PLATFORM == EE_PLATFORM_MACOSX char exe_file[PATH_MAX + 1]; CFBundleRef mainBundle = CFBundleGetMainBundle(); if (mainBundle) { CFURLRef mainURL = CFBundleCopyBundleURL(mainBundle); if (mainURL) { int ok = CFURLGetFileSystemRepresentation ( mainURL, (Boolean) true, (UInt8*)exe_file, PATH_MAX ); if (ok) { return std::string(exe_file) + "/"; } } } return "./"; #elif EE_PLATFORM == EE_PLATFORM_LINUX char exe_file[PATH_MAX + 1]; int size; size = readlink("/proc/self/exe", exe_file, PATH_MAX); if (size < 0) { return "./"; } else { exe_file[size] = '\0'; return std::string(dirname(exe_file)) + "/"; } #elif EE_PLATFORM == EE_PLATFORM_WIN #ifdef UNICODE // Get path to executable: char szDrive[_MAX_DRIVE]; char szDir[_MAX_DIR]; char szFilename[_MAX_DIR]; char szExt[_MAX_DIR]; std::wstring dllName( _MAX_DIR, 0 ); GetModuleFileName(0, &dllName[0], _MAX_PATH); std::string dllstrName( String( dllName ).ToUtf8() ); #ifdef EE_COMPILER_MSVC _splitpath_s( dllstrName.c_str(), szDrive, _MAX_DRIVE, szDir, _MAX_DIR, szFilename, _MAX_DIR, szExt, _MAX_DIR ); #else _splitpath(szDllName, szDrive, szDir, szFilename, szExt); #endif return std::string( szDrive ) + std::string( szDir ); #else // Get path to executable: TCHAR szDllName[_MAX_PATH]; TCHAR szDrive[_MAX_DRIVE]; TCHAR szDir[_MAX_DIR]; TCHAR szFilename[_MAX_DIR]; TCHAR szExt[_MAX_DIR]; GetModuleFileName(0, szDllName, _MAX_PATH); #ifdef EE_COMPILER_MSVC _splitpath_s(szDllName, szDrive, _MAX_DRIVE, szDir, _MAX_DIR, szFilename, _MAX_DIR, szExt, _MAX_DIR ); #else _splitpath(szDllName, szDrive, szDir, szFilename, szExt); #endif return std::string(szDrive) + std::string(szDir); #endif #elif EE_PLATFORM == EE_PLATFORM_BSD int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; char buf[1024]; size_t cb = sizeof(buf); sysctl(mib, 4, buf, &cb, NULL, 0); return FileSystem::FileRemoveFileName( std::string( buf ) ); #elif EE_PLATFORM == EE_PLATFORM_SOLARIS return FileRemoveFileName( std::string( getexecname() ) ); #elif EE_PLATFORM == EE_PLATFORM_HAIKU image_info info; int32 cookie = 0; while ( B_OK == get_next_image_info( 0, &cookie, &info ) ) { if ( info.type == B_APP_IMAGE ) break; } return FileSystem::FileRemoveFileName( std::string( info.name ) ); #elif EE_PLATFORM == EE_PLATFORM_ANDROID if ( NULL != Window::cEngine::instance() && NULL != Window::cEngine::instance()->GetCurrentWindow() ) return Window::cEngine::instance()->GetCurrentWindow()->GetExternalStoragePath(); return "/sdcard/"; #else #warning Sys::GetProcessPath() not implemented on this platform. ( will return "./" ) return "./"; #endif }
void fill_pathname_application_path(char *s, size_t len) { size_t i; #ifdef __APPLE__ CFBundleRef bundle = CFBundleGetMainBundle(); #endif #ifdef _WIN32 DWORD ret; wchar_t ws[PATH_MAX_LENGTH] = {0}; #endif #ifdef __HAIKU__ image_info info; int32_t cookie = 0; #endif (void)i; if (!len) return; #ifdef _WIN32 ret = GetModuleFileName(GetModuleHandle(NULL), s, len - 1); s[ret] = '\0'; #elif defined(__APPLE__) if (bundle) { CFURLRef bundle_url = CFBundleCopyBundleURL(bundle); CFStringRef bundle_path = CFURLCopyPath(bundle_url); CFStringGetCString(bundle_path, s, len, kCFStringEncodingUTF8); CFRelease(bundle_path); CFRelease(bundle_url); retro_assert(strlcat(s, "nobin", len) < len); return; } #elif defined(__HAIKU__) while (get_next_image_info(0, &cookie, &info) == B_OK) { if (info.type == B_APP_IMAGE) { strlcpy(s, info.name, len); return; } } #else { pid_t pid; static const char *exts[] = { "exe", "file", "path/a.out" }; char link_path[255]; link_path[0] = *s = '\0'; pid = getpid(); /* Linux, BSD and Solaris paths. Not standardized. */ for (i = 0; i < ARRAY_SIZE(exts); i++) { ssize_t ret; snprintf(link_path, sizeof(link_path), "/proc/%u/%s", (unsigned)pid, exts[i]); ret = readlink(link_path, s, len - 1); if (ret >= 0) { s[ret] = '\0'; return; } } } RARCH_ERR("Cannot resolve application path! This should not happen.\n"); #endif }
static void _INXIsSpringBoardInit() { CFStringRef thisBundleID = CFBundleGetIdentifier(CFBundleGetMainBundle()); _INXIsSpringBoard = CFEqual(thisBundleID, CFSTR("com.apple.springboard")); }
int main(int argc, char **argv) { nsresult rv; char *lastSlash; char iniPath[MAXPATHLEN]; char greDir[MAXPATHLEN]; bool greFound = false; CFBundleRef appBundle = CFBundleGetMainBundle(); if (!appBundle) return 1; CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(appBundle); if (!resourcesURL) return 1; CFURLRef absResourcesURL = CFURLCopyAbsoluteURL(resourcesURL); CFRelease(resourcesURL); if (!absResourcesURL) return 1; CFURLRef iniFileURL = CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault, absResourcesURL, CFSTR("application.ini"), false); CFRelease(absResourcesURL); if (!iniFileURL) return 1; CFStringRef iniPathStr = CFURLCopyFileSystemPath(iniFileURL, kCFURLPOSIXPathStyle); CFRelease(iniFileURL); if (!iniPathStr) return 1; CFStringGetCString(iniPathStr, iniPath, sizeof(iniPath), kCFStringEncodingUTF8); CFRelease(iniPathStr); printf("iniPath = %s\n", iniPath); //////////////////////////////////////// if (!getExePath(greDir)) { return 1; } /*if (!getFrameworkPath(greDir)) { return 1; }*/ /*if (realpath(tmpPath, greDir)) { greFound = true; }*/ printf("greDir = %s\n", greDir); if (access(greDir, R_OK | X_OK) == 0) greFound = true; if (!greFound) { printf("Could not find the Mozilla runtime.\n"); return 1; } rv = XPCOMGlueStartup(greDir); if (NS_FAILED(rv)) { printf("Couldn't load XPCOM.\n"); return 1; } printf("Glue startup OK.\n"); ///////////////////////////////////////////////////// static const nsDynamicFunctionLoad kXULFuncs[] = { { "XRE_CreateAppData", (NSFuncPtr*) &XRE_CreateAppData }, { "XRE_FreeAppData", (NSFuncPtr*) &XRE_FreeAppData }, { "XRE_main", (NSFuncPtr*) &XRE_main }, { nullptr, nullptr } }; rv = XPCOMGlueLoadXULFunctions(kXULFuncs); if (NS_FAILED(rv)) { printf("Couldn't load XRE functions.\n"); return 1; } NS_LogInit(); int retval; nsXREAppData *pAppData = NULL; { nsCOMPtr<nsIFile> iniFile; // nsIFile *pIniFile; rv = NS_NewNativeLocalFile(nsDependentCString(iniPath), PR_FALSE, getter_AddRefs(iniFile)); //&pIniFile); //NS_ADDREF(pIniFile); if (NS_FAILED(rv)) { printf("Couldn't find application.ini file.\n"); return 1; } rv = XRE_CreateAppData(iniFile, &pAppData); //rv = XRE_CreateAppData(pIniFile, &pAppData); if (NS_FAILED(rv)) { printf("Error: couldn't parse application.ini.\n"); return 1; } } NS_ASSERTION(pAppData->directory, "Failed to get app directory."); { nsAutoString path; pAppData->directory->GetPath(path); nsAutoCString nsstr; ::CopyUTF16toUTF8(path, nsstr); printf("appData.directory=%s\n", nsstr.get()); } if (!pAppData->xreDirectory) { char xreDir[MAXPATHLEN]; if (!getFrameworkPath(xreDir)) return 1; rv = NS_NewNativeLocalFile(nsDependentCString(xreDir), PR_FALSE, &pAppData->xreDirectory); } printf("### ENTERING XRE_MAIN ###\n"); retval = XRE_main(argc, argv, pAppData, 0); printf("### LEAVING XRE_MAIN ###\n"); NS_LogTerm(); return retval; }
int ImportLibSndFileFunctions() { int errcnt=0; #ifdef _WIN32 if (g_hLibSndFile) return 0; g_hLibSndFile=LoadLibraryA("libsndfile-1.dll"); if (!g_hLibSndFile) errcnt++; if (g_hLibSndFile) { //OutputDebugStringA("libsndfile dll loaded! now loading functions..."); *((void **)&ptr_sf_command)=(void*)GetProcAddress(g_hLibSndFile,"sf_command"); if (!ptr_sf_command) errcnt++; *((void **)&ptr_sf_open)=(void*)GetProcAddress(g_hLibSndFile,"sf_open"); if (!ptr_sf_open) errcnt++; *((void **)&ptr_sf_close)=(void*)GetProcAddress(g_hLibSndFile,"sf_close"); if (!ptr_sf_close) errcnt++; *((void **)&ptr_sf_read_float)=(void*)GetProcAddress(g_hLibSndFile,"sf_read_float"); *((void **)&ptr_sf_read_double)=(void*)GetProcAddress(g_hLibSndFile,"sf_read_double"); if (!ptr_sf_read_double) errcnt++; *((void **)&ptr_sf_seek)=(void*)GetProcAddress(g_hLibSndFile,"sf_seek"); if (!ptr_sf_seek) errcnt++; *((void **)&ptr_sf_readf_double)=(void*)GetProcAddress(g_hLibSndFile,"sf_readf_double"); if (!ptr_sf_readf_double) errcnt++; *((void **)&ptr_sf_version_string)=(void*)GetProcAddress(g_hLibSndFile,"sf_version_string"); if (!ptr_sf_version_string) errcnt++; *((void **)&ptr_sf_format_check)=(void*)GetProcAddress(g_hLibSndFile,"sf_format_check"); if (!ptr_sf_format_check) errcnt++; *((void **)&ptr_sf_write_float)=(void*)GetProcAddress(g_hLibSndFile,"sf_write_float"); if (!ptr_sf_write_float) errcnt++; *((void **)&ptr_sf_write_double)=(void*)GetProcAddress(g_hLibSndFile,"sf_write_double"); if (!ptr_sf_write_double) errcnt++; //OutputDebugStringA("libsndfile functions loaded!"); } //else OutputDebugStringA("libsndfile DLL not loaded!"); #elif defined(__APPLE__) static int a; static void *dll; if (!dll&&!a) { a=1; if (!dll) dll=dlopen("libsndfile.1.dylib",RTLD_LAZY); if (!dll) dll=dlopen("/usr/local/lib/libsndfile.1.dylib",RTLD_LAZY); if (!dll) dll=dlopen("/usr/lib/libsndfile.1.dylib",RTLD_LAZY); if (!dll) { CFBundleRef bund=CFBundleGetMainBundle(); if (bund) { CFURLRef url=CFBundleCopyBundleURL(bund); if (url) { char buf[8192]; if (CFURLGetFileSystemRepresentation(url,true,(UInt8*)buf,sizeof(buf)-128)) { char *p=buf; while (*p) p++; while (p>=buf && *p != '/') p--; if (p>=buf) { strcat(buf,"/Contents/Plugins/libsndfile.1.dylib"); if (!dll) dll=dlopen(buf,RTLD_LAZY); if (!dll) { strcpy(p,"/libsndfile.1.dylib"); dll=dlopen(buf,RTLD_LAZY); } if (!dll) { strcpy(p,"/Plugins/libsndfile.1.dylib"); if (!dll) dll=dlopen(buf,RTLD_LAZY); } } } CFRelease(url); } } } if (dll) { *(void **)(&ptr_sf_command) = dlsym(dll, "sf_command"); *(void **)(&ptr_sf_open) = dlsym(dll, "sf_open"); *(void **)(&ptr_sf_close) = dlsym(dll, "sf_close"); *(void **)(&ptr_sf_read_float) = dlsym(dll, "sf_read_float"); *(void **)(&ptr_sf_read_double) = dlsym(dll, "sf_read_double"); *(void **)(&ptr_sf_readf_double) = dlsym(dll, "sf_readf_double"); *(void **)(&ptr_sf_seek) = dlsym(dll, "sf_seek"); *(void **)(&ptr_sf_version_string) = dlsym(dll, "sf_version_string"); *(void **)(&ptr_sf_format_check) = dlsym(dll, "sf_format_check"); *(void **)(&ptr_sf_write_float) = dlsym(dll, "sf_write_float"); *(void **)(&ptr_sf_write_double) = dlsym(dll, "sf_write_double"); } if (!dll) errcnt++; } #endif return errcnt; }
wxStandardPathsCF::wxStandardPathsCF() : m_bundle(CFBundleGetMainBundle()) { CFRetain(m_bundle); }
CFNetDiagnosticRef CFNetDiagnosticCreateWithStreams(CFAllocatorRef allocator, CFReadStreamRef readStream, CFWriteStreamRef writeStream) { //FIXME deal with read and write streams CFMutableDictionaryRef retval; #if 0 CFArrayRef hostnames; CFHostRef host; #endif retval = CFDictionaryCreateMutable(allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if(retval != NULL) { #if 0 host = (CFHostRef)CFReadStreamCopyProperty(readStream, kCFStreamPropertySocketRemoteHost); if(host) { hostnames = CFHostGetAddressing(host, NULL); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticRemoteHostKey, CFArrayGetValueAtIndex(hostnames, 0), retval); CFRelease(host); } #endif _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticNameKey, CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleNameKey), retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticBundleKey, CFBundleGetIdentifier( CFBundleGetMainBundle() ), retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticMethodKey, CFSTR("CFNetDiagnosticCreateWithStreams"), retval); } return (CFNetDiagnosticRef)retval; }
CFNetDiagnosticRef CFNetDiagnosticCreateWithURL(CFAllocatorRef allocator, CFURLRef url) { CFMutableDictionaryRef retval; SInt32 port = 0; retval = CFDictionaryCreateMutable(allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if(retval != NULL && CFURLCanBeDecomposed(url)) { port = CFURLGetPortNumber(url); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticNameKey, CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleNameKey), retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticBundleKey, CFBundleGetIdentifier( CFBundleGetMainBundle() ), retval); _CFNetDiagnosticSetDictionaryKeyAndReleaseIfNotNull(_CFNetDiagnosticRemoteHostKey, CFURLCopyHostName(url), retval); _CFNetDiagnosticSetDictionaryKeyAndReleaseIfNotNull(_CFNetDiagnosticProtocolKey, CFURLCopyScheme(url), retval); _CFNetDiagnosticSetDictionaryKeyAndReleaseIfNotNull(_CFNetDiagnosticPortKey, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &port), retval); _CFNetDiagnosticSetDictionaryKeyIfNotNull(_CFNetDiagnosticMethodKey, CFSTR("CFNetDiagnosticCreateWithURL"), retval); } return (CFNetDiagnosticRef)retval; }
void initializePaths(char* argv0) { #ifdef RUN_IN_PLACE /* Use relative paths if RUN_IN_PLACE */ dstream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl; /* Windows */ #if defined(_WIN32) #include <windows.h> const DWORD buflen = 1000; char buf[buflen]; DWORD len; // Find path of executable and set path_data relative to it len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen); assert(len < buflen); pathRemoveFile(buf, '\\'); pathRemoveFile(buf, '\\'); // Use "./bin/../data" path_data = std::string(buf) + DIR_DELIM + "data"; // Use "./bin/.." path_userdata = std::string(buf); /* Linux */ #elif defined(linux) || defined(__linux) #include <unistd.h> char buf[BUFSIZ]; memset(buf, 0, BUFSIZ); // Get path to executable if (readlink("/proc/self/exe", buf, BUFSIZ-1) < 0) { char* b = posix_guess_path(argv0); if (!b) { strcpy(buf,".."); }else{ strcpy(buf,b); free(b); } }else{ pathRemoveFile(buf, '/'); pathRemoveFile(buf, '/'); } // Use "./bin/../data" path_data = std::string(buf) + "/data"; // Use "./bin/../" path_userdata = std::string(buf); /* OS X */ #elif defined(__APPLE__) || defined(__FreeBSD__) const int info[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; char* path = NULL; size_t size = 0; if (!sysctl(info, 4, NULL, &size, NULL, 0)) { path = (char*)malloc(size); if (path) { if (!sysctl(info, 4, path, &size, NULL, 0)) { pathRemoveFile(path, '/'); pathRemoveFile(path, '/'); }else{ free(path); path = NULL; } } } if (!path) path = posix_guess_path(argv0); if (path) { path_userdata = std::string(path); path_data = std::string(path) + "/data"; free(path); }else{ path_userdata = std::string(".."); path_data = std::string("../data"); } #endif #else // RUN_IN_PLACE /* Use platform-specific paths otherwise */ dstream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl; /* Windows */ #if defined(_WIN32) #include <windows.h> const DWORD buflen = 1000; char buf[buflen]; DWORD len; // Find path of executable and set path_data relative to it len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen); assert(len < buflen); pathRemoveFile(buf, '\\'); // Use "./bin/../data" path_data = std::string(buf) + DIR_DELIM ".." DIR_DELIM "data"; //path_data = std::string(buf) + "/../share/" + PROJECT_NAME; // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>" len = GetEnvironmentVariable("APPDATA", buf, buflen); assert(len < buflen); path_userdata = std::string(buf) + DIR_DELIM + PROJECT_NAME; /* Linux */ #elif defined(linux) #include <unistd.h> char buf[BUFSIZ]; memset(buf, 0, BUFSIZ); // Get path to executable assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1); pathRemoveFile(buf, '/'); pathRemoveFile(buf, '/'); path_data = std::string(buf) + "/share/" + PROJECT_NAME; //path_data = std::string(INSTALL_PREFIX) + "/share/" + PROJECT_NAME; if (!fs::PathExists(path_data)) { dstream<<"WARNING: data path " << path_data << " not found!"; path_data = std::string(buf) + "/data"; dstream<<" Trying " << path_data << std::endl; } path_userdata = std::string(getenv("HOME")) + "/." + PROJECT_NAME; /* OS X */ #elif defined(__APPLE__) #include <unistd.h> // Code based on // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c CFBundleRef main_bundle = CFBundleGetMainBundle(); CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle); char path[PATH_MAX]; if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) { dstream<<"Bundle resource path: "<<path<<std::endl; //chdir(path); path_data = std::string(path) + "/share/" + PROJECT_NAME; } else { // error! dstream<<"WARNING: Could not determine bundle resource path"<<std::endl; } CFRelease(resources_url); path_userdata = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME; #elif defined(__FreeBSD__) path_data = std::string(INSTALL_PREFIX) + "/share/" + PROJECT_NAME; path_userdata = std::string(getenv("HOME")) + "/." + PROJECT_NAME; #endif #endif // RUN_IN_PLACE dstream<<"path_data = "<<path_data<<std::endl; dstream<<"path_userdata = "<<path_userdata<<std::endl; }
App::App() : KUniqueApplication() , m_tray(0) { DEBUG_BLOCK PERF_LOG( "Begin Application ctor" ) // required for last.fm plugin to grab app version setApplicationVersion( AMAROK_VERSION ); qRegisterMetaType<Meta::DataPtr>(); qRegisterMetaType<Meta::DataList>(); qRegisterMetaType<Meta::TrackPtr>(); qRegisterMetaType<Meta::TrackList>(); qRegisterMetaType<Meta::AlbumPtr>(); qRegisterMetaType<Meta::AlbumList>(); qRegisterMetaType<Meta::ArtistPtr>(); qRegisterMetaType<Meta::ArtistList>(); qRegisterMetaType<Meta::GenrePtr>(); qRegisterMetaType<Meta::GenreList>(); qRegisterMetaType<Meta::ComposerPtr>(); qRegisterMetaType<Meta::ComposerList>(); qRegisterMetaType<Meta::YearPtr>(); qRegisterMetaType<Meta::YearList>(); qRegisterMetaType<Meta::LabelPtr>(); qRegisterMetaType<Meta::LabelList>(); qRegisterMetaType<Playlists::PlaylistPtr>(); qRegisterMetaType<Playlists::PlaylistList>(); #ifdef Q_WS_MAC // this is inspired by OpenSceneGraph: osgDB/FilePath.cpp // Start with the Bundle PlugIns directory. // Get the main bundle first. No need to retain or release it since // we are not keeping a reference CFBundleRef myBundle = CFBundleGetMainBundle(); if( myBundle ) { // CFBundleGetMainBundle will return a bundle ref even if // the application isn't part of a bundle, so we need to // check // if the path to the bundle ends in ".app" to see if it is // a // proper application bundle. If it is, the plugins path is // added CFURLRef urlRef = CFBundleCopyBundleURL(myBundle); if(urlRef) { char bundlePath[1024]; if( CFURLGetFileSystemRepresentation( urlRef, true, (UInt8 *)bundlePath, sizeof(bundlePath) ) ) { QByteArray bp( bundlePath ); size_t len = bp.length(); if( len > 4 && bp.right( 4 ) == ".app" ) { bp.append( "/Contents/MacOS" ); QByteArray path = qgetenv( "PATH" ); if( path.length() > 0 ) { path.prepend( ":" ); } path.prepend( bp ); debug() << "setting PATH=" << path; setenv("PATH", path, 1); } } // docs say we are responsible for releasing CFURLRef CFRelease(urlRef); } } setupEventHandler_mac(this); #endif PERF_LOG( "Done App ctor" ) continueInit(); }
UBApplication::UBApplication(const QString &id, int &argc, char **argv) : QtSingleApplication(id, argc, argv), mPreferencesController(NULL) { staticMemoryCleaner = new QObject(0); // deleted in UBApplication destructor setOrganizationName("Sankore"); setOrganizationDomain("sankore.org"); setApplicationName("Open-Sankore"); setApplicationVersion(UBVERSION); #if defined(Q_WS_MAC) && !defined(QT_NO_DEBUG) CFStringRef shortVersion = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), CFSTR("CFBundleShortVersionString")); const char *version = CFStringGetCStringPtr(shortVersion, kCFStringEncodingMacRoman); Q_ASSERT(version); setApplicationVersion(version); #endif QStringList args = arguments(); mIsVerbose = args.contains("-v") || args.contains("-verbose") || args.contains("verbose") || args.contains("-log") || args.contains("log"); UBPlatformUtils::init(); UBResources::resources(); if (!undoStack) { undoStack = new QUndoStack(staticMemoryCleaner); } QTranslator *translator = new QTranslator(this); translator->load(UBPlatformUtils::preferredTranslation()); installTranslator(translator); QString localString; if (!translator->isEmpty()) { localString = UBPlatformUtils::preferredLanguage(); } else { localString = "en_US"; } QLocale::setDefault(QLocale(localString)); qDebug() << "Running application in:" << localString; UBSettings *settings = UBSettings::settings(); connect(settings->appToolBarPositionedAtTop, SIGNAL(changed(QVariant)), this, SLOT(toolBarPositionChanged(QVariant))); connect(settings->appToolBarDisplayText, SIGNAL(changed(QVariant)), this, SLOT(toolBarDisplayTextChanged(QVariant))); updateProtoActionsState(); #ifndef Q_WS_MAC setWindowIcon(QIcon(":/images/uniboard.png")); #endif setStyle(new UBStyle()); // Style is owned and deleted by the application QString css = UBFileSystemUtils::readTextFile(UBPlatformUtils::applicationResourcesDirectory() + "/etc/Uniboard.css"); if (css.length() > 0) setStyleSheet(css); QApplication::setStartDragDistance(8); // default is 4, and is a bit small for tablets installEventFilter(this); }
QMacSettingsPrivate::QMacSettingsPrivate(QSettings::Scope scope, const QString &organization, const QString &application) : QSettingsPrivate(QSettings::NativeFormat, scope, organization, application) { QString javaPackageName; int curPos = 0; int nextDot; // attempt to use the organization parameter QString domainName = comify(organization); // if not found, attempt to use the bundle identifier. if (domainName.isEmpty()) { CFBundleRef main_bundle = CFBundleGetMainBundle(); if (main_bundle != NULL) { CFStringRef main_bundle_identifier = CFBundleGetIdentifier(main_bundle); if (main_bundle_identifier != NULL) { QString bundle_identifier(qtKey(main_bundle_identifier)); // CFBundleGetIdentifier returns identifier separated by slashes rather than periods. QStringList bundle_identifier_components = bundle_identifier.split(QLatin1Char('/')); // pre-reverse them so that when they get reversed again below, they are in the com.company.product format. QStringList bundle_identifier_components_reversed; for (int i=0; i<bundle_identifier_components.size(); ++i) { const QString &bundle_identifier_component = bundle_identifier_components.at(i); bundle_identifier_components_reversed.push_front(bundle_identifier_component); } domainName = bundle_identifier_components_reversed.join(QLatin1Char('.')); } } } // if no bundle identifier yet. use a hard coded string. if (domainName.isEmpty()) { domainName = QLatin1String("unknown-organization.trolltech.com"); } while ((nextDot = domainName.indexOf(QLatin1Char('.'), curPos)) != -1) { javaPackageName.prepend(domainName.midRef(curPos, nextDot - curPos)); javaPackageName.prepend(QLatin1Char('.')); curPos = nextDot + 1; } javaPackageName.prepend(domainName.midRef(curPos)); javaPackageName = javaPackageName.toLower(); if (curPos == 0) javaPackageName.prepend(QLatin1String("com.")); suiteId = javaPackageName; if (scope == QSettings::SystemScope) spec |= F_System; if (application.isEmpty()) { spec |= F_Organization; } else { javaPackageName += QLatin1Char('.'); javaPackageName += application; applicationId = javaPackageName; } numDomains = 0; for (int i = (spec & F_System) ? 1 : 0; i < 2; ++i) { for (int j = (spec & F_Organization) ? 1 : 0; j < 3; ++j) { SearchDomain &domain = domains[numDomains++]; domain.userName = (i == 0) ? kCFPreferencesCurrentUser : kCFPreferencesAnyUser; if (j == 0) domain.applicationOrSuiteId = applicationId; else if (j == 1) domain.applicationOrSuiteId = suiteId; else domain.applicationOrSuiteId = kCFPreferencesAnyApplication; } } hostName = (scope == QSettings::SystemScope) ? kCFPreferencesCurrentHost : kCFPreferencesAnyHost; sync(); }
OSStatus PickMonitor (DisplayIDType *inOutDisplayID, WindowRef parentWindow) { WindowRef theWindow; OSStatus status = noErr; static const ControlID kUserPane = { 'MONI', 1 }; // Fetch the dialog IBNibRef aslNib; CFBundleRef theBundle = CFBundleGetMainBundle(); status = CreateNibReferenceWithCFBundle(theBundle, CFSTR("ASLCore"), &aslNib); status = ::CreateWindowFromNib(aslNib, CFSTR( "Pick Monitor" ), &theWindow ); if (status != noErr) { assert(false); return userCanceledErr; } #if 0 // Put game name in window title. By default the title includes the token <<<kGameName>>>. Str255 windowTitle; GetWTitle(theWindow, windowTitle); FormatPStringWithGameName(windowTitle); SetWTitle(theWindow, windowTitle); #endif // Set up the controls ControlRef monitorPane; GetControlByID( theWindow, &kUserPane, &monitorPane ); assert(monitorPane); SetupPickMonitorPane(monitorPane, *inOutDisplayID); // Create our UPP and install the handler. EventTypeSpec cmdEvent = { kEventClassCommand, kEventCommandProcess }; EventHandlerUPP handler = NewEventHandlerUPP( PickMonitorHandler ); InstallWindowEventHandler( theWindow, handler, 1, &cmdEvent, theWindow, NULL ); // Show the window if (parentWindow) ShowSheetWindow( theWindow, parentWindow ); else ShowWindow( theWindow ); // Now we run modally. We will remain here until the PrefHandler // calls QuitAppModalLoopForWindow if the user clicks OK or // Cancel. RunAppModalLoopForWindow( theWindow ); // OK, we're done. Dispose of our window and our UPP. // We do the UPP last because DisposeWindow can send out // CarbonEvents, and we haven't explicitly removed our // handler. If we disposed the UPP, the Toolbox might try // to call it. That would be bad. TearDownPickMonitorPane(monitorPane); if (parentWindow) HideSheetWindow( theWindow ); DisposeWindow( theWindow ); DisposeEventHandlerUPP( handler ); // Return settings to caller if (sSelectedDevice != 0) { // Read back the controls DMGetDisplayIDByGDevice (sSelectedDevice, &*inOutDisplayID, true); return noErr; } else return userCanceledErr; }
/* ================= main ================= */ int main(int argc, char **argv) { char commandLine[MAX_STRING_CHARS] = { 0 }; Sys_PlatformInit(); // Set the initial time base Sys_Milliseconds(); #ifdef __APPLE__ // This is passed if we are launched by double-clicking if (argc >= 2 && Q_strncmp(argv[1], "-psn", 4) == 0) { argc = 1; } #endif Sys_ParseArgs(argc, argv); #if defined(__APPLE__) && !defined(DEDICATED) // argv[0] would be /Users/seth/etlegacy/etl.app/Contents/MacOS // But on OS X we want to pretend the binary path is the .app's parent // So that way the base folder is right next to the .app allowing { char parentdir[1024]; CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle()); if (!url) { Sys_Dialog(DT_ERROR, "A CFURL for the app bundle could not be found.", "Can't set Sys_SetBinaryPath"); Sys_Exit(1); } CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url); if (!url2 || !CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, 1024)) { Sys_Dialog(DT_ERROR, "CFURLGetFileSystemRepresentation returned an error when finding the app bundle's parent directory.", "Can't set Sys_SetBinaryPath"); Sys_Exit(1); } Sys_SetBinaryPath(parentdir); CFRelease(url); CFRelease(url2); } #else Sys_SetBinaryPath(Sys_Dirname(argv[0])); #endif Sys_SetDefaultInstallPath(DEFAULT_BASEDIR); // Sys_BinaryPath() by default // Concatenate the command line for passing to Com_Init Sys_BuildCommandLine(argc, argv, commandLine, sizeof(commandLine)); Com_Init(commandLine); NET_Init(); Sys_SetUpConsoleAndSignals(); Sys_GameLoop(); return 0; }
std::string System::get_exe_path() { char exe_file[PATH_MAX]; #ifdef __APPLE__ CFBundleRef mainBundle = CFBundleGetMainBundle(); if (mainBundle) { CFURLRef mainURL = CFBundleCopyBundleURL(mainBundle); if (mainURL) { int ok = CFURLGetFileSystemRepresentation ( mainURL, (Boolean) true, (UInt8*)exe_file, PATH_MAX ); if (ok) { return std::string(exe_file) + "/"; } } } throw Exception("get_exe_path failed"); #else #ifndef PROC_EXE_PATH #define PROC_EXE_PATH "/proc/self/exe" #endif int size; struct stat sb; if (lstat(PROC_EXE_PATH, &sb) < 0) { #ifdef EXTERN___PROGNAME char *pathenv, *name, *end; char fname[PATH_MAX]; char cwd[PATH_MAX]; struct stat sba; exe_file[0] = '\0'; if ((pathenv = getenv("PATH")) != nullptr) { for (name = pathenv; name; name = end) { if ((end = strchr(name, ':'))) *end++ = '\0'; snprintf(fname, sizeof(fname), "%s/%s", name, (char *)__progname); if (stat(fname, &sba) == 0) { snprintf(exe_file, sizeof(exe_file), "%s/", name); break; } } } // if getenv failed or path still not found // try current directory as last resort if (!exe_file[0]) { if (getcwd(cwd, sizeof(cwd)) != nullptr) { snprintf(fname, sizeof(fname), "%s/%s", cwd, (char *)__progname); if (stat(fname, &sba) == 0) snprintf(exe_file, sizeof(exe_file), "%s/", cwd); } } if (!exe_file[0]) throw Exception("get_exe_path: could not find path"); else return std::string(exe_file); #else throw Exception("get_exe_path: proc file system not accesible"); #endif } else { size = readlink(PROC_EXE_PATH, exe_file, PATH_MAX); if (size < 0) { throw Exception(strerror(errno)); } else { exe_file[size] = '\0'; return std::string(dirname(exe_file)) + "/"; } } #endif }
bool World::Initialize(unsigned int windowWidth, unsigned int windowHeight, String windowName, bool antiAliasing, bool fullScreen, bool resizable) { if (_initialized) { return false; } _running = true; // General windowing initialization #if !ANGEL_MOBILE glfwInit(); #endif #if defined(__APPLE__) // Set up paths correctly in the .app bundle #if !ANGEL_MOBILE CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle); char path[PATH_MAX]; if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) { //sysLog.Log("Problem setting up working directory!"); } CFRelease(resourcesURL); chdir(path); chdir(".."); #if DEBUG // set paths to the local resources rather than the copied ones String fileName = __FILE__; String dirPath = fileName.substr(0, fileName.size() - String("Angel/Infrastructure/World.cpp").size()); CFURLRef exeURL = CFBundleCopyExecutableURL(mainBundle); char exePath[PATH_MAX]; if (!CFURLGetFileSystemRepresentation(exeURL, TRUE, (UInt8 *)exePath, PATH_MAX)) { //sysLog.Log("Problem setting up working directory!"); } CFRelease(exeURL); chdir(dirPath.c_str()); StringList pathElements = SplitString(exePath, "/"); String exeName = pathElements[pathElements.size()-1]; chdir(exeName.c_str()); #endif #else CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle); char path[PATH_MAX]; if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) { std::cout << "Problem setting up working directory!" << std::endl; } CFRelease(resourcesURL); chdir(path); chdir("Angel"); // the iPhone doesn't like having a "Resources" directory in the root of the .app bundle #endif #endif //Start scripting LuaScriptingModule::Prep(); //Reset values based on preferences antiAliasing = thePrefs.OverrideInt("WindowSettings", "antiAliasing", antiAliasing); fullScreen = thePrefs.OverrideInt("WindowSettings", "antiAliasing", fullScreen); resizable = thePrefs.OverrideInt("WindowSettings", "antiAliasing", resizable); windowHeight = thePrefs.OverrideInt("WindowSettings", "height", windowHeight); windowWidth = thePrefs.OverrideInt("WindowSettings", "width", windowWidth); windowName = thePrefs.OverrideString("WindowSettings", "name", windowName); //Windowing system setup #if !ANGEL_MOBILE if (antiAliasing) { glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); //4x looks pretty good } int windowMode = GLFW_WINDOW; if (fullScreen) { windowMode = GLFW_FULLSCREEN; } if (resizable) { glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_FALSE); } else { glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE); } glfwOpenWindow(windowWidth, windowHeight, 8, 8, 8, 8, 8, 1, windowMode); glfwSetWindowTitle(windowName.c_str()); glfwSetWindowPos(50, 50); glfwSwapInterval(1); //better visual quality, set to zero for max drawing performance glfwSetWindowSizeCallback(Camera::ResizeCallback); glfwSetKeyCallback(keyboardInput); glfwSetCharCallback(charInput); glfwDisable(GLFW_KEY_REPEAT); glfwSetMousePosCallback(MouseMotion); glfwSetMouseButtonCallback(MouseButton); glfwSetMouseWheelCallback(MouseWheel); glfwSetWindowCloseCallback(windowClosed); _prevTime = glfwGetTime(); #else struct timeval tv; gettimeofday(&tv, NULL); _currTime = _startTime = tv.tv_sec + (double) tv.tv_usec / 1000000.0; #endif //OpenGL state setup #if !ANGEL_MOBILE glClearDepth(1.0f); glPolygonMode(GL_FRONT, GL_FILL); #endif glShadeModel(GL_FLAT); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(GL_BACK); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearStencil(0); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); theCamera.ResizeCallback(windowWidth, windowHeight); //Get textures going InitializeTextureLoading(); //Subscribe to camera changes theSwitchboard.SubscribeTo(this, "CameraChange"); //initialize singletons #if !ANGEL_MOBILE theInput; theControllerManager.Setup(); #endif theSound; theSpatialGraph; #if !ANGEL_MOBILE RegisterConsole(new TestConsole()); #else // register fonts, since we don't have the console doing it for us on the phone RegisterFont("Resources/Fonts/Inconsolata.otf", 24, "Console"); RegisterFont("Resources/Fonts/Inconsolata.otf", 18, "ConsoleSmall"); #endif LuaScriptingModule::Initialize(); return _initialized = true; }
void TclpSetVariables( Tcl_Interp *interp) { #ifndef NO_UNAME struct utsname name; #endif int unameOK; Tcl_DString ds; #ifdef HAVE_COREFOUNDATION char tclLibPath[MAXPATHLEN + 1]; #if MAC_OS_X_VERSION_MAX_ALLOWED > 1020 /* * Set msgcat fallback locale to current CFLocale identifier. */ CFLocaleRef localeRef; if (CFLocaleCopyCurrent != NULL && CFLocaleGetIdentifier != NULL && (localeRef = CFLocaleCopyCurrent())) { CFStringRef locale = CFLocaleGetIdentifier(localeRef); if (locale) { char loc[256]; if (CFStringGetCString(locale, loc, 256, kCFStringEncodingUTF8)) { if (!Tcl_CreateNamespace(interp, "::tcl::mac", NULL, NULL)) { Tcl_ResetResult(interp); } Tcl_SetVar(interp, "::tcl::mac::locale", loc, TCL_GLOBAL_ONLY); } } CFRelease(localeRef); } #endif /* MAC_OS_X_VERSION_MAX_ALLOWED > 1020 */ if (MacOSXGetLibraryPath(interp, MAXPATHLEN, tclLibPath) == TCL_OK) { const char *str; CFBundleRef bundleRef; Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); Tcl_SetVar(interp, "tcl_pkgPath", " ", TCL_GLOBAL_ONLY | TCL_APPEND_VALUE); str = TclGetEnv("DYLD_FRAMEWORK_PATH", &ds); if ((str != NULL) && (str[0] != '\0')) { char *p = Tcl_DStringValue(&ds); /* * Convert DYLD_FRAMEWORK_PATH from colon to space separated. */ do { if (*p == ':') { *p = ' '; } } while (*p++); Tcl_SetVar(interp, "tcl_pkgPath", Tcl_DStringValue(&ds), TCL_GLOBAL_ONLY | TCL_APPEND_VALUE); Tcl_SetVar(interp, "tcl_pkgPath", " ", TCL_GLOBAL_ONLY | TCL_APPEND_VALUE); Tcl_DStringFree(&ds); } bundleRef = CFBundleGetMainBundle(); if (bundleRef) { CFURLRef frameworksURL; Tcl_StatBuf statBuf; frameworksURL = CFBundleCopyPrivateFrameworksURL(bundleRef); if (frameworksURL) { if (CFURLGetFileSystemRepresentation(frameworksURL, TRUE, (unsigned char*) tclLibPath, MAXPATHLEN) && ! TclOSstat(tclLibPath, &statBuf) && S_ISDIR(statBuf.st_mode)) { Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY | TCL_APPEND_VALUE); Tcl_SetVar(interp, "tcl_pkgPath", " ", TCL_GLOBAL_ONLY | TCL_APPEND_VALUE); } CFRelease(frameworksURL); } frameworksURL = CFBundleCopySharedFrameworksURL(bundleRef); if (frameworksURL) { if (CFURLGetFileSystemRepresentation(frameworksURL, TRUE, (unsigned char*) tclLibPath, MAXPATHLEN) && ! TclOSstat(tclLibPath, &statBuf) && S_ISDIR(statBuf.st_mode)) { Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY | TCL_APPEND_VALUE); Tcl_SetVar(interp, "tcl_pkgPath", " ", TCL_GLOBAL_ONLY | TCL_APPEND_VALUE); } CFRelease(frameworksURL); } } Tcl_SetVar(interp, "tcl_pkgPath", pkgPath, TCL_GLOBAL_ONLY | TCL_APPEND_VALUE); } else #endif /* HAVE_COREFOUNDATION */ { Tcl_SetVar(interp, "tcl_pkgPath", pkgPath, TCL_GLOBAL_ONLY); } #ifdef DJGPP Tcl_SetVar2(interp, "tcl_platform", "platform", "dos", TCL_GLOBAL_ONLY); #else Tcl_SetVar2(interp, "tcl_platform", "platform", "unix", TCL_GLOBAL_ONLY); #endif unameOK = 0; #ifndef NO_UNAME if (uname(&name) >= 0) { const char *native; unameOK = 1; native = Tcl_ExternalToUtfDString(NULL, name.sysname, -1, &ds); Tcl_SetVar2(interp, "tcl_platform", "os", native, TCL_GLOBAL_ONLY); Tcl_DStringFree(&ds); /* * The following code is a special hack to handle differences in the * way version information is returned by uname. On most systems the * full version number is available in name.release. However, under * AIX the major version number is in name.version and the minor * version number is in name.release. */ if ((strchr(name.release, '.') != NULL) || !isdigit(UCHAR(name.version[0]))) { /* INTL: digit */ Tcl_SetVar2(interp, "tcl_platform", "osVersion", name.release, TCL_GLOBAL_ONLY); } else { #ifdef DJGPP /* * For some obscure reason DJGPP puts major version into * name.release and minor into name.version. As of DJGPP 2.04 this * is documented in djgpp libc.info file. */ Tcl_SetVar2(interp, "tcl_platform", "osVersion", name.release, TCL_GLOBAL_ONLY); Tcl_SetVar2(interp, "tcl_platform", "osVersion", ".", TCL_GLOBAL_ONLY|TCL_APPEND_VALUE); Tcl_SetVar2(interp, "tcl_platform", "osVersion", name.version, TCL_GLOBAL_ONLY|TCL_APPEND_VALUE); #else Tcl_SetVar2(interp, "tcl_platform", "osVersion", name.version, TCL_GLOBAL_ONLY); Tcl_SetVar2(interp, "tcl_platform", "osVersion", ".", TCL_GLOBAL_ONLY|TCL_APPEND_VALUE); Tcl_SetVar2(interp, "tcl_platform", "osVersion", name.release, TCL_GLOBAL_ONLY|TCL_APPEND_VALUE); #endif /* DJGPP */ } Tcl_SetVar2(interp, "tcl_platform", "machine", name.machine, TCL_GLOBAL_ONLY); } #endif /* !NO_UNAME */ if (!unameOK) { Tcl_SetVar2(interp, "tcl_platform", "os", "", TCL_GLOBAL_ONLY); Tcl_SetVar2(interp, "tcl_platform", "osVersion", "", TCL_GLOBAL_ONLY); Tcl_SetVar2(interp, "tcl_platform", "machine", "", TCL_GLOBAL_ONLY); } /* * Copy the username of the real user (according to getuid()) into * tcl_platform(user). */ { struct passwd *pwEnt = TclpGetPwUid(getuid()); const char *user; if (pwEnt == NULL) { user = ""; Tcl_DStringInit(&ds); /* ensure cleanliness */ } else { user = Tcl_ExternalToUtfDString(NULL, pwEnt->pw_name, -1, &ds); } Tcl_SetVar2(interp, "tcl_platform", "user", user, TCL_GLOBAL_ONLY); Tcl_DStringFree(&ds); } /* * Define what the platform PATH separator is. [TIP #315] */ Tcl_SetVar2(interp, "tcl_platform","pathSeparator", ":", TCL_GLOBAL_ONLY); }
void set_menu(void* hwnd, wchar_t const* filename) { CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef pluginURL = CFBundleCopyBuiltInPlugInsURL(mainBundle); CFStringRef fn = CFStringCreateWithWString(kCFAllocatorDefault, filename, kCFStringEncodingUTF8); CFURLRef path = CFURLCreateCopyAppendingPathComponent(NULL, pluginURL, fn, FALSE); CFBundleRef bundle = CFBundleCreate(kCFAllocatorSystemDefault, path); CFRelease(path); CFRelease(fn); CFRelease(pluginURL); if (bundle==NULL) throw filename; FuncLoadMenu func = reinterpret_cast<FuncLoadMenu>(CFBundleGetFunctionPointerForName(bundle, CFSTR("load_menu"))); if (func==NULL) { CFRelease(bundle); throw filename; } #elif _MSC_VER void set_menu(HWND hwnd, wchar_t const* filename) { wstring path = wstring(L"dll\\")+filename; HMODULE handle = LoadLibrary(path.c_str()); FuncLoadMenu func = (FuncLoadMenu)GetProcAddress(handle, "load_menu"); if (func==0) throw path.c_str(); #endif unordered_map<int, wstring> menu; func(menu); #ifdef __APPLE__ HMENU hmenu = get_main_menu(); unsigned int main_menu_id = get_file_menu_pos(hmenu); int mii = NULL; #elif _MSC_VER HMENU hmenu = CreateMenu(); UINT main_menu_id = 0; MENUITEMINFO mii; #else #error Not implemented #endif //////////////////////////////////////////////////////////////////////////////// // FILE #ifdef __APPLE__ HMENU hmenu_file = get_file_menu(hmenu); ++main_menu_id; #else HMENU hmenu_file = create_submenu(mii, hmenu, main_menu_id, menu, IDM_FILE); #endif { #ifndef __APPLE__ unsigned int pos = 0; create_menuitem(mii, hmenu_file, pos, menu, IDM_FILE_CANCEL); create_separator(mii, hmenu_file, pos); create_menuitem(mii, hmenu_file, pos, menu, IDM_FILE_QUIT); #endif } //////////////////////////////////////////////////////////////////////////////// // EDIT HMENU hmenu_edit = create_submenu(mii, hmenu, main_menu_id, menu, IDM_EDIT); { unsigned int pos = 0; HMENU hmenu_edit_select_current = create_submenu(mii, hmenu_edit, pos, menu, IDM_EDIT_MARK_ON_CURRENT_LAYER); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_ALL_NODES_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_ALL_EDGES_ON_CURRENT_LAYER); create_separator(mii, hmenu_edit_select_current, pos); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_NODES_INSIDE_COMMUNITY_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_EDGES_INSIDE_COMMUNITY_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_ELEMENTS_INSIDE_COMMUNITY_ON_CURRENT_LAYER); create_separator(mii, hmenu_edit_select_current, pos); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_NODES_OUTSIDE_COMMUNITY_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_EDGES_OUTSIDE_COMMUNITY_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_ELEMENTS_OUTSIDE_COMMUNITY_ON_CURRENT_LAYER); create_separator(mii, hmenu_edit_select_current, pos); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_NODES_IN_SELECTED_COMMUNITY_CONTINUUMS_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_EDGES_IN_SELECTED_COMMUNITY_CONTINUUMS_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_ELEMENTS_IN_SELECTED_COMMUNITY_CONTINUUMS_ON_CURRENT_LAYER); create_separator(mii, hmenu_edit_select_current, pos); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_MARK_ALL_ELEMENTS_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_select_current, pos, menu, IDM_EDIT_INVERT_MARK_ON_CURRENT_LAYER); } HMENU hmenu_edit_select_all = create_submenu(mii, hmenu_edit, pos, menu, IDM_EDIT_MARK_ON_EACH_LAYER); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_ALL_NODES_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_ALL_EDGES_ON_EACH_LAYER); create_separator(mii, hmenu_edit_select_all, pos); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_NODES_INSIDE_COMMUNITY_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_EDGES_INSIDE_COMMUNITY_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_ELEMENTS_INSIDE_COMMUNITY_ON_EACH_LAYER); create_separator(mii, hmenu_edit_select_all, pos); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_NODES_OUTSIDE_COMMUNITY_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_EDGES_OUTSIDE_COMMUNITY_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_ELEMENTS_OUTSIDE_COMMUNITY_ON_EACH_LAYER); create_separator(mii, hmenu_edit_select_all, pos); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_NODES_IN_SELECTED_COMMUNITY_CONTINUUMS_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_EDGES_IN_SELECTED_COMMUNITY_CONTINUUMS_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_ELEMENTS_IN_SELECTED_COMMUNITY_CONTINUUMS_ON_EACH_LAYER); create_separator(mii, hmenu_edit_select_all, pos); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_MARK_ALL_ELEMENTS_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_select_all, pos, menu, IDM_EDIT_INVERT_MARK_ON_EACH_LAYER); } create_separator(mii, hmenu_edit, pos); HMENU hmenu_edit_hide = create_submenu(mii, hmenu_edit, pos, menu, IDM_EDIT_HIDE_MARKED_ELEMENTS); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_edit_hide, pos, menu, IDM_EDIT_HIDE_MARKED_NODES_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_hide, pos, menu, IDM_EDIT_HIDE_MARKED_EDGES_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_hide, pos, menu, IDM_EDIT_HIDE_MARKED_ELEMENTS_ON_CURRENT_LAYER); create_separator(mii, hmenu_edit_hide, pos); create_menuitem(mii, hmenu_edit_hide, pos, menu, IDM_EDIT_HIDE_MARKED_NODES_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_hide, pos, menu, IDM_EDIT_HIDE_MARKED_EDGES_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_hide, pos, menu, IDM_EDIT_HIDE_MARKED_ELEMENTS_ON_EACH_LAYER); } HMENU hmenu_edit_hide_all = create_submenu(mii, hmenu_edit, pos, menu, IDM_EDIT_HIDE_MARKED_ELEMENTS_ALL); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_edit_hide_all, pos, menu, IDM_EDIT_HIDE_MARKED_NODES_ON_CURRENT_LAYER_ALL); create_menuitem(mii, hmenu_edit_hide_all, pos, menu, IDM_EDIT_HIDE_MARKED_EDGES_ON_CURRENT_LAYER_ALL); create_menuitem(mii, hmenu_edit_hide_all, pos, menu, IDM_EDIT_HIDE_MARKED_ELEMENTS_ON_CURRENT_LAYER_ALL); create_separator(mii, hmenu_edit_hide_all, pos); create_menuitem(mii, hmenu_edit_hide_all, pos, menu, IDM_EDIT_HIDE_MARKED_NODES_ON_EACH_LAYER_ALL); create_menuitem(mii, hmenu_edit_hide_all, pos, menu, IDM_EDIT_HIDE_MARKED_EDGES_ON_EACH_LAYER_ALL); create_menuitem(mii, hmenu_edit_hide_all, pos, menu, IDM_EDIT_HIDE_MARKED_ELEMENTS_ON_EACH_LAYER_ALL); } HMENU hmenu_edit_show = create_submenu(mii, hmenu_edit, pos, menu, IDM_EDIT_SHOW_HIDDEN_ELEMENTS); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_edit_show, pos, menu, IDM_EDIT_SHOW_HIDDEN_NODES_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_show, pos, menu, IDM_EDIT_SHOW_HIDDEN_EDGES_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_show, pos, menu, IDM_EDIT_SHOW_HIDDEN_ELEMENTS_ON_CURRENT_LAYER); create_separator(mii, hmenu_edit_show, pos); create_menuitem(mii, hmenu_edit_show, pos, menu, IDM_EDIT_SHOW_HIDDEN_NODES_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_show, pos, menu, IDM_EDIT_SHOW_HIDDEN_EDGES_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_show, pos, menu, IDM_EDIT_SHOW_HIDDEN_ELEMENTS_ON_EACH_LAYER); } create_separator(mii, hmenu_edit, pos); HMENU hmenu_edit_remove = create_submenu(mii, hmenu_edit, pos, menu, IDM_EDIT_REMOVE_MARKED_ELEMENTS); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_edit_remove, pos, menu, IDM_EDIT_REMOVE_MARKED_NODES_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_remove, pos, menu, IDM_EDIT_REMOVE_MARKED_EDGES_ON_CURRENT_LAYER); create_menuitem(mii, hmenu_edit_remove, pos, menu, IDM_EDIT_REMOVE_MARKED_ELEMENTS_ON_CURRENT_LAYER); create_separator(mii, hmenu_edit_remove, pos); create_menuitem(mii, hmenu_edit_remove, pos, menu, IDM_EDIT_REMOVE_MARKED_NODES_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_remove, pos, menu, IDM_EDIT_REMOVE_MARKED_EDGES_ON_EACH_LAYER); create_menuitem(mii, hmenu_edit_remove, pos, menu, IDM_EDIT_REMOVE_MARKED_ELEMENTS_ON_EACH_LAYER); } HMENU hmenu_edit_remove_all = create_submenu(mii, hmenu_edit, pos, menu, IDM_EDIT_REMOVE_MARKED_ELEMENTS_ALL); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_edit_remove_all, pos, menu, IDM_EDIT_REMOVE_MARKED_NODES_ON_CURRENT_LAYER_ALL); create_menuitem(mii, hmenu_edit_remove_all, pos, menu, IDM_EDIT_REMOVE_MARKED_EDGES_ON_CURRENT_LAYER_ALL); create_menuitem(mii, hmenu_edit_remove_all, pos, menu, IDM_EDIT_REMOVE_MARKED_ELEMENTS_ON_CURRENT_LAYER_ALL); create_separator(mii, hmenu_edit_remove_all, pos); create_menuitem(mii, hmenu_edit_remove_all, pos, menu, IDM_EDIT_REMOVE_MARKED_NODES_ON_EACH_LAYER_ALL); create_menuitem(mii, hmenu_edit_remove_all, pos, menu, IDM_EDIT_REMOVE_MARKED_EDGES_ON_EACH_LAYER_ALL); create_menuitem(mii, hmenu_edit_remove_all, pos, menu, IDM_EDIT_REMOVE_MARKED_ELEMENTS_ON_EACH_LAYER_ALL); } } //////////////////////////////////////////////////////////////////////////////// // VIEW HMENU hmenu_view = create_submenu(mii, hmenu, main_menu_id, menu, IDM_VIEW); { unsigned int pos = 0; create_menuitem(mii, hmenu_view, pos, menu, IDM_VIEW_SHOW_NODE); create_menuitem(mii, hmenu_view, pos, menu, IDM_VIEW_SHOW_EDGE); create_menuitem(mii, hmenu_view, pos, menu, IDM_VIEW_SHOW_COMMUNITY); create_menuitem(mii, hmenu_view, pos, menu, IDM_VIEW_SHOW_COMMUNITY_EDGE); create_separator(mii, hmenu_view, pos); HMENU hmenu_view_node_size = create_submenu(mii, hmenu_view, pos, menu, IDM_VIEW_NODE_SIZE); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_view_node_size, pos, menu, IDM_VIEW_NODE_SIZE_UPDATE); create_menuitem(mii, hmenu_view_node_size, pos, menu, IDM_VIEW_NODE_SIZE_CANCEL); create_separator(mii, hmenu_view_node_size, pos); create_menuitem(mii, hmenu_view_node_size, pos, menu, IDM_VIEW_NODE_SIZE_UNIFORM); create_menuitem(mii, hmenu_view_node_size, pos, menu, IDM_VIEW_NODE_SIZE_WEIGHT); create_menuitem(mii, hmenu_view_node_size, pos, menu, IDM_VIEW_NODE_SIZE_DEGREE_CENTRALITY); create_menuitem(mii, hmenu_view_node_size, pos, menu, IDM_VIEW_NODE_SIZE_CLOSENESS_CENTRALITY); create_menuitem(mii, hmenu_view_node_size, pos, menu, IDM_VIEW_NODE_SIZE_BETWEENNESS_CENTRALITY); create_menuitem(mii, hmenu_view_node_size, pos, menu, IDM_VIEW_NODE_SIZE_PAGERANK); create_menuitem(mii, hmenu_view_node_size, pos, menu, IDM_VIEW_NODE_SIZE_POINT); } HMENU hmenu_view_edge_width = create_submenu(mii, hmenu_view, pos, menu, IDM_VIEW_EDGE_WIDTH); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_view_edge_width, pos, menu, IDM_VIEW_EDGE_WIDTH_UPDATE); create_menuitem(mii, hmenu_view_edge_width, pos, menu, IDM_VIEW_EDGE_WIDTH_CANCEL); create_separator(mii, hmenu_view_edge_width, pos); create_menuitem(mii, hmenu_view_edge_width, pos, menu, IDM_VIEW_EDGE_WIDTH_UNIFORM); create_menuitem(mii, hmenu_view_edge_width, pos, menu, IDM_VIEW_EDGE_WIDTH_WEIGHT); create_menuitem(mii, hmenu_view_edge_width, pos, menu, IDM_VIEW_EDGE_WIDTH_BETWEENNESS_CENTRALITY); } create_separator(mii, hmenu_view, pos); HMENU hmenu_view_node_style = create_submenu(mii, hmenu_view, pos, menu, IDM_VIEW_NODE_STYLE); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_view_node_style, pos, menu, IDM_VIEW_NODE_STYLE_POLYGON); create_menuitem(mii, hmenu_view_node_style, pos, menu, IDM_VIEW_NODE_STYLE_TEXTURE); } HMENU hmenu_view_edge_style = create_submenu(mii, hmenu_view, pos, menu, IDM_VIEW_EDGE_STYLE); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_view_edge_style, pos, menu, IDM_VIEW_EDGE_STYLE_LINE); create_menuitem(mii, hmenu_view_edge_style, pos, menu, IDM_VIEW_EDGE_STYLE_POLYGON); } HMENU hmenu_view_community_style = create_submenu(mii, hmenu_view, pos, menu, IDM_VIEW_COMMUNITY_STYLE); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_view_community_style, pos, menu, IDM_VIEW_COMMUNITY_STYLE_POLYGON_CIRCLE); create_menuitem(mii, hmenu_view_community_style, pos, menu, IDM_VIEW_COMMUNITY_STYLE_TEXTURE); } HMENU hmenu_view_community_edge_style = create_submenu(mii, hmenu_view, pos, menu, IDM_VIEW_COMMUNITY_EDGE_STYLE); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_view_community_edge_style, pos, menu, IDM_VIEW_COMMUNITY_EDGE_STYLE_LINE); create_menuitem(mii, hmenu_view_community_edge_style, pos, menu, IDM_VIEW_COMMUNITY_EDGE_STYLE_POLYGON); } } //////////////////////////////////////////////////////////////////////////////// // STRING HMENU hmenu_string = create_submenu(mii, hmenu, main_menu_id, menu, IDM_STRING); { unsigned int pos = 0; create_menuitem(mii, hmenu_string, pos, menu, IDM_STRING_SHOW_NODE_NAME); create_menuitem(mii, hmenu_string, pos, menu, IDM_STRING_SHOW_EDGE_NAME); create_menuitem(mii, hmenu_string, pos, menu, IDM_STRING_SHOW_COMMUNITY_NAME); create_menuitem(mii, hmenu_string, pos, menu, IDM_STRING_SHOW_COMMUNITY_EDGE_NAME); create_separator(mii, hmenu_string, pos); HMENU hmenu_string_node_name_size = create_submenu(mii, hmenu_string, pos, menu, IDM_STRING_NODE_NAME_SIZE); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_string_node_name_size, pos, menu, IDM_STRING_NODE_NAME_SIZE_VARIABLE); create_separator(mii, hmenu_string_node_name_size, pos); create_menuitem(mii, hmenu_string_node_name_size, pos, menu, IDM_STRING_NODE_NAME_SIZE_0); create_menuitem(mii, hmenu_string_node_name_size, pos, menu, IDM_STRING_NODE_NAME_SIZE_1); create_menuitem(mii, hmenu_string_node_name_size, pos, menu, IDM_STRING_NODE_NAME_SIZE_2); create_menuitem(mii, hmenu_string_node_name_size, pos, menu, IDM_STRING_NODE_NAME_SIZE_3); create_menuitem(mii, hmenu_string_node_name_size, pos, menu, IDM_STRING_NODE_NAME_SIZE_4); } HMENU hmenu_string_edge_name_size = create_submenu(mii, hmenu_string, pos, menu, IDM_STRING_EDGE_NAME_SIZE); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_string_edge_name_size, pos, menu, IDM_STRING_EDGE_NAME_SIZE_VARIABLE); create_separator(mii, hmenu_string_edge_name_size, pos); create_menuitem(mii, hmenu_string_edge_name_size, pos, menu, IDM_STRING_EDGE_NAME_SIZE_0); create_menuitem(mii, hmenu_string_edge_name_size, pos, menu, IDM_STRING_EDGE_NAME_SIZE_1); create_menuitem(mii, hmenu_string_edge_name_size, pos, menu, IDM_STRING_EDGE_NAME_SIZE_2); create_menuitem(mii, hmenu_string_edge_name_size, pos, menu, IDM_STRING_EDGE_NAME_SIZE_3); create_menuitem(mii, hmenu_string_edge_name_size, pos, menu, IDM_STRING_EDGE_NAME_SIZE_4); } HMENU hmenu_string_community_name_size = create_submenu(mii, hmenu_string, pos, menu, IDM_STRING_COMMUNITY_NAME_SIZE); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_string_community_name_size, pos, menu, IDM_STRING_COMMUNITY_NAME_SIZE_VARIABLE); create_separator(mii, hmenu_string_community_name_size, pos); create_menuitem(mii, hmenu_string_community_name_size, pos, menu, IDM_STRING_COMMUNITY_NAME_SIZE_0); create_menuitem(mii, hmenu_string_community_name_size, pos, menu, IDM_STRING_COMMUNITY_NAME_SIZE_1); create_menuitem(mii, hmenu_string_community_name_size, pos, menu, IDM_STRING_COMMUNITY_NAME_SIZE_2); create_menuitem(mii, hmenu_string_community_name_size, pos, menu, IDM_STRING_COMMUNITY_NAME_SIZE_3); create_menuitem(mii, hmenu_string_community_name_size, pos, menu, IDM_STRING_COMMUNITY_NAME_SIZE_4); } HMENU hmenu_string_community_edge_name_size = create_submenu(mii, hmenu_string, pos, menu, IDM_STRING_COMMUNITY_EDGE_NAME_SIZE); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_string_community_edge_name_size, pos, menu, IDM_STRING_COMMUNITY_EDGE_NAME_SIZE_VARIABLE); create_separator(mii, hmenu_string_community_edge_name_size, pos); create_menuitem(mii, hmenu_string_community_edge_name_size, pos, menu, IDM_STRING_COMMUNITY_EDGE_NAME_SIZE_0); create_menuitem(mii, hmenu_string_community_edge_name_size, pos, menu, IDM_STRING_COMMUNITY_EDGE_NAME_SIZE_1); create_menuitem(mii, hmenu_string_community_edge_name_size, pos, menu, IDM_STRING_COMMUNITY_EDGE_NAME_SIZE_2); create_menuitem(mii, hmenu_string_community_edge_name_size, pos, menu, IDM_STRING_COMMUNITY_EDGE_NAME_SIZE_3); create_menuitem(mii, hmenu_string_community_edge_name_size, pos, menu, IDM_STRING_COMMUNITY_EDGE_NAME_SIZE_4); } create_separator(mii, hmenu_string, pos); HMENU hmenu_string_type = create_submenu(mii, hmenu_string, pos, menu, IDM_STRING_FONT_TYPE); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_string_type, pos, menu, IDM_STRING_FONT_TYPE_POLYGON); create_menuitem(mii, hmenu_string_type, pos, menu, IDM_STRING_FONT_TYPE_TEXTURE); } create_separator(mii, hmenu_string, pos); create_menuitem(mii, hmenu_string, pos, menu, IDM_STRING_SHOW_LAYER_NAME); create_menuitem(mii, hmenu_string, pos, menu, IDM_STRING_SHOW_FPS); } //////////////////////////////////////////////////////////////////////////////// // LAYOUT HMENU hmenu_layout = create_submenu(mii, hmenu, main_menu_id, menu, IDM_LAYOUT); { unsigned int pos = 0; create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_UPDATE); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_CANCEL); create_separator(mii, hmenu_layout, pos); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_KAMADA_KAWAI_METHOD); HMENU hmenu_layout_hde = create_submenu(mii, hmenu_layout, pos, menu, IDM_LAYOUT_HIGH_DIMENSIONAL_EMBEDDING); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_layout_hde, pos, menu, IDM_LAYOUT_HIGH_DIMENSIONAL_EMBEDDING_1_2); create_menuitem(mii, hmenu_layout_hde, pos, menu, IDM_LAYOUT_HIGH_DIMENSIONAL_EMBEDDING_1_3); create_menuitem(mii, hmenu_layout_hde, pos, menu, IDM_LAYOUT_HIGH_DIMENSIONAL_EMBEDDING_2_3); } create_separator(mii, hmenu_layout, pos); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_CIRCLE); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_CIRCLE_IN_SIZE_ORDER); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_LATTICE); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_RANDOM); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_CARTOGRAMS); create_separator(mii, hmenu_layout, pos); HMENU hmenu_layout_fde = create_submenu(mii, hmenu_layout, pos, menu, IDM_LAYOUT_FORCE_DIRECTION); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_layout_fde, pos, menu, IDM_LAYOUT_FORCE_DIRECTION_RUN); create_separator(mii, hmenu_layout_fde, pos); create_menuitem(mii, hmenu_layout_fde, pos, menu, IDM_LAYOUT_FORCE_DIRECTION_KAMADA_KAWAI_METHOD); create_menuitem(mii, hmenu_layout_fde, pos, menu, IDM_LAYOUT_FORCE_DIRECTION_KAMADA_KAWAI_METHOD_WITH_COMMUNITY_SEPARATION); create_menuitem(mii, hmenu_layout_fde, pos, menu, IDM_LAYOUT_FORCE_DIRECTION_COMMUNITY_ORIENTED); create_separator(mii, hmenu_layout_fde, pos); create_menuitem(mii, hmenu_layout_fde, pos, menu, IDM_LAYOUT_FORCE_DIRECTION_SPRING_AND_REPULSIVE_FORCE); create_menuitem(mii, hmenu_layout_fde, pos, menu, IDM_LAYOUT_FORCE_DIRECTION_LATTICE_GAS_METHOD); #if 0 create_menuitem(mii, hmenu_layout_fde, pos, menu, IDM_LAYOUT_FORCE_DIRECTION_DESIGNTIDE); #endif } create_separator(mii, hmenu_layout, pos); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_SHOW_LAYOUT_FRAME); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_INITIALIZE_LAYOUT_FRAME); create_separator(mii, hmenu_layout, pos); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_SHOW_GRID); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_SHOW_CENTER); create_separator(mii, hmenu_layout, pos); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_INITIALIZE_EYEPOINT); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_ZOOM_IN); create_menuitem(mii, hmenu_layout, pos, menu, IDM_LAYOUT_ZOOM_OUT); } //////////////////////////////////////////////////////////////////////////////// // COMMUNITY HMENU hmenu_community = create_submenu(mii, hmenu, main_menu_id, menu, IDM_COMMUNITY_DETECTION); { unsigned int pos = 0; create_menuitem(mii, hmenu_community, pos, menu, IDM_COMMUNITY_DETECTION_UPDATE); create_menuitem(mii, hmenu_community, pos, menu, IDM_COMMUNITY_DETECTION_CANCEL); create_separator(mii, hmenu_community, pos); HMENU hmenu_community_connected_components = create_submenu(mii, hmenu_community, pos, menu, IDM_COMMUNITY_DETECTION_CONNECTED_COMPONENTS); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_community_connected_components, pos, menu, IDM_COMMUNITY_DETECTION_WEAKLY_CONNECTED_COMPONENTS); create_menuitem(mii, hmenu_community_connected_components, pos, menu, IDM_COMMUNITY_DETECTION_STRONGLY_CONNECTED_COMPONENTS); } HMENU hmenu_community_modularity_maximization = create_submenu(mii, hmenu_community, pos, menu, IDM_COMMUNITY_DETECTION_MODULARITY_MAXIMIZATION); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_community_modularity_maximization, pos, menu, IDM_COMMUNITY_DETECTION_MODULARITY_MAXIMIZATION_USING_GREEDY_METHOD); create_menuitem(mii, hmenu_community_modularity_maximization, pos, menu, IDM_COMMUNITY_DETECTION_MODULARITY_MAXIMIZATION_USING_TEO_METHOD); create_separator(mii, hmenu_community_modularity_maximization, pos); create_menuitem(mii, hmenu_community_modularity_maximization, pos, menu, IDM_COMMUNITY_DETECTION_USE_WEIGHTED_MODULARITY); } HMENU hmenu_community_clique_percolaion = create_submenu(mii, hmenu_community, pos, menu, IDM_COMMUNITY_DETECTION_CLIQUE_PERCOLATION); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_community_clique_percolaion, pos, menu, IDM_COMMUNITY_DETECTION_CLIQUE_PERCOLATION_3); create_menuitem(mii, hmenu_community_clique_percolaion, pos, menu, IDM_COMMUNITY_DETECTION_CLIQUE_PERCOLATION_4); create_menuitem(mii, hmenu_community_clique_percolaion, pos, menu, IDM_COMMUNITY_DETECTION_CLIQUE_PERCOLATION_5); } HMENU hmenu_community_others = create_submenu(mii, hmenu_community, pos, menu, IDM_COMMUNITY_DETECTION_OTHERS); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_community_others, pos, menu, IDM_COMMUNITY_DETECTION_BETWEENNESS_CENTRALITY_SEPARATION); #if 0 create_menuitem(mii, hmenu_community_others, pos, menu, IDM_COMMUNITY_DETECTION_INFORMATION_FLOW_MAPPING); #endif } create_separator(mii, hmenu_community, pos); create_menuitem(mii, hmenu_community, pos, menu, IDM_COMMUNITY_TRANSITION_DIAGRAM); create_menuitem(mii, hmenu_community, pos, menu, IDM_COMMUNITY_TRANSITION_DIAGRAM_SCOPE_WIDER); create_menuitem(mii, hmenu_community, pos, menu, IDM_COMMUNITY_TRANSITION_DIAGRAM_SCOPE_NARROWER); create_separator(mii, hmenu_community, pos); create_menuitem(mii, hmenu_community, pos, menu, IDM_COMMUNITY_DETECTION_CLEAR); } //////////////////////////////////////////////////////////////////////////////// // TIMELINE HMENU hmenu_timeline = create_submenu(mii, hmenu, main_menu_id, menu, IDM_TIMELINE); { unsigned int pos = 0; create_menuitem(mii, hmenu_timeline, pos, menu, IDM_TIMELINE_NEXT); create_menuitem(mii, hmenu_timeline, pos, menu, IDM_TIMELINE_PREV); create_separator(mii, hmenu_timeline, pos); HMENU hmenu_timeline_auto = create_submenu(mii, hmenu_timeline, pos, menu, IDM_TIMELINE_AUTO_RUN); { #ifdef __APPLE__ unsigned int pos = 0; #endif create_menuitem(mii, hmenu_timeline_auto, pos, menu, IDM_TIMELINE_STOP); create_separator(mii, hmenu_timeline_auto, pos); create_menuitem(mii, hmenu_timeline_auto, pos, menu, IDM_TIMELINE_FORWARD_1); create_menuitem(mii, hmenu_timeline_auto, pos, menu, IDM_TIMELINE_FORWARD_2); create_menuitem(mii, hmenu_timeline_auto, pos, menu, IDM_TIMELINE_FORWARD_3); create_menuitem(mii, hmenu_timeline_auto, pos, menu, IDM_TIMELINE_FORWARD_4); create_separator(mii, hmenu_timeline_auto, pos); create_menuitem(mii, hmenu_timeline_auto, pos, menu, IDM_TIMELINE_BACKWARD_1); create_menuitem(mii, hmenu_timeline_auto, pos, menu, IDM_TIMELINE_BACKWARD_2); create_menuitem(mii, hmenu_timeline_auto, pos, menu, IDM_TIMELINE_BACKWARD_3); create_menuitem(mii, hmenu_timeline_auto, pos, menu, IDM_TIMELINE_BACKWARD_4); } create_separator(mii, hmenu_timeline, pos); create_menuitem(mii, hmenu_timeline, pos, menu, IDM_TIMELINE_SHOW_SLIDER); } #ifdef __APPLE__ CFRelease(bundle); #elif _MSC_VER SetMenu(hwnd, hmenu); FreeLibrary(handle); #else #error Not implemented #endif }
/** * Locate the Premake executable, and push its full path to the Lua stack. * Based on: * http://sourceforge.net/tracker/index.php?func=detail&aid=3351583&group_id=71616&atid=531880 * http://stackoverflow.com/questions/933850/how-to-find-the-location-of-the-executable-in-c * http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe */ int premake_locate(lua_State* L, const char* argv0) { #if !defined(PATH_MAX) #define PATH_MAX (4096) #endif char buffer[PATH_MAX]; const char* path = NULL; #if PLATFORM_WINDOWS DWORD len = GetModuleFileName(NULL, buffer, PATH_MAX); if (len > 0) path = buffer; #endif #if PLATFORM_MACOSX CFURLRef bundleURL = CFBundleCopyExecutableURL(CFBundleGetMainBundle()); CFStringRef pathRef = CFURLCopyFileSystemPath(bundleURL, kCFURLPOSIXPathStyle); if (CFStringGetCString(pathRef, buffer, PATH_MAX - 1, kCFStringEncodingUTF8)) path = buffer; #endif #if PLATFORM_LINUX int len = readlink("/proc/self/exe", buffer, PATH_MAX); if (len > 0) path = buffer; #endif #if PLATFORM_BSD int len = readlink("/proc/curproc/file", buffer, PATH_MAX); if (len < 0) len = readlink("/proc/curproc/exe", buffer, PATH_MAX); if (len > 0) path = buffer; #endif #if PLATFORM_SOLARIS int len = readlink("/proc/self/path/a.out", buffer, PATH_MAX); if (len > 0) path = buffer; #endif /* As a fallback, search the PATH with argv[0] */ if (!path) { lua_pushcfunction(L, os_pathsearch); lua_pushstring(L, argv0); lua_pushstring(L, getenv("PATH")); if (lua_pcall(L, 2, 1, 0) == OKAY && !lua_isnil(L, -1)) { lua_pushstring(L, "/"); lua_pushstring(L, argv0); lua_concat(L, 3); path = lua_tostring(L, -1); } } /* If all else fails, use argv[0] as-is and hope for the best */ if (!path) { /* make it absolute, if needed */ os_getcwd(L); lua_pushstring(L, "/"); lua_pushstring(L, argv0); if (!path_isabsolute(L)) { lua_concat(L, 3); } else { lua_pop(L, 1); } path = lua_tostring(L, -1); } lua_pushstring(L, path); return 1; }
} #endif QSettings mySettings; // For non static builds on mac and win (static builds are not supported) // we need to be sure we can find the qt image // plugins. In mac be sure to look in the // application bundle... #ifdef Q_OS_WIN QCoreApplication::addLibraryPath( QApplication::applicationDirPath() + QDir::separator() + "qtplugins" ); #endif #ifdef Q_OS_MACX //qDebug("Adding qt image plugins to plugin search path..."); CFURLRef myBundleRef = CFBundleCopyBundleURL( CFBundleGetMainBundle() ); CFStringRef myMacPath = CFURLCopyFileSystemPath( myBundleRef, kCFURLPOSIXPathStyle ); const char *mypPathPtr = CFStringGetCStringPtr( myMacPath, CFStringGetSystemEncoding() ); CFRelease( myBundleRef ); CFRelease( myMacPath ); QString myPath( mypPathPtr ); // if we are not in a bundle assume that the app is built // as a non bundle app and that image plugins will be // in system Qt frameworks. If the app is a bundle // lets try to set the qt plugin search path... QFileInfo myInfo( myPath ); if ( myInfo.isBundle() ) { // First clear the plugin search paths so we can be sure // only plugins from the bundle are being used QStringList myPathList;
/** * @brief Adds the directories in the colon separated string to the datadir handler. */ void DataDirLocater::AddDirs(const std::string& in) { size_t prev_colon = 0, colon; #ifndef _WIN32 while ((colon = in.find(':', prev_colon)) != std::string::npos) { #else while ((colon = in.find(';', prev_colon)) != std::string::npos) { #endif datadirs.push_back(in.substr(prev_colon, colon - prev_colon)); #ifdef DEBUG logOutput.Print("Adding %s to directories" , in.substr(prev_colon, colon - prev_colon).c_str()); #endif prev_colon = colon + 1; } #ifdef DEBUG logOutput.Print("Adding %s to directories" , in.substr(prev_colon).c_str()); #endif datadirs.push_back(in.substr(prev_colon)); } /** * @brief Figure out permissions we have for a single data directory d. * @returns whether we have permissions to read the data directory. */ bool DataDirLocater::DeterminePermissions(DataDir* d) { #ifndef _WIN32 if (d->path.c_str()[0] != '/' || d->path.find("..") != std::string::npos) #else if (d->path.find("..") != std::string::npos) #endif throw content_error("specify data directories using absolute paths please"); // Figure out whether we have read/write permissions // First check read access, if we got that check write access too // (no support for write-only directories) // Note: we check for executable bit otherwise we can't browse the directory // Note: we fail to test whether the path actually is a directory // Note: modifying permissions while or after this function runs has undefined behaviour #ifndef _WIN32 if (access(d->path.c_str(), R_OK | X_OK | F_OK) == 0) { // Note: disallow multiple write directories. // There isn't really a use for it as every thing is written to the first one anyway, // and it may give funny effects on errors, e.g. it probably only gives funny things // like network mounted datadir lost connection and suddenly files end up in some // other random writedir you didn't even remember you had added it. if (!writedir && access(d->path.c_str(), W_OK) == 0) { #else if (_access(d->path.c_str(), 4) == 0) { if (!writedir && _access(d->path.c_str(), 2) == 0) { #endif d->writable = true; writedir = &*d; } return true; } else { if (filesystem.CreateDirectory(d->path)) { // it didn't exist before, now it does and we just created it with rw access, // so we just assume we still have read-write acces... if (!writedir) { d->writable = true; writedir = d; } return true; } } return false; } /** * @brief Figure out permissions we have for the data directories. */ void DataDirLocater::DeterminePermissions() { std::vector<DataDir> newDatadirs; std::string previous; // used to filter out consecutive duplicates // (I didn't bother filtering out non-consecutive duplicates because then // there is the question which of the multiple instances to purge.) writedir = NULL; for (std::vector<DataDir>::iterator d = datadirs.begin(); d != datadirs.end(); ++d) { if (d->path != previous && DeterminePermissions(&*d)) { newDatadirs.push_back(*d); previous = d->path; } } datadirs = newDatadirs; } /** * @brief locate spring data directory * * On *nix platforms, attempts to locate * and change to the spring data directory * * In Unixes, the data directory to chdir to is determined by the following, in this * order (first items override lower items): * * - 'SPRING_DATADIR' environment variable. (colon separated list, like PATH) * - 'SpringData=/path/to/data' declaration in '~/.springrc'. (colon separated list) * - "$HOME/.spring" * - In the same order any line in '/etc/spring/datadir', if that file exists. * - 'datadir=/path/to/data' option passed to 'scons configure'. * - 'prefix=/install/path' option passed to scons configure. The datadir is * assumed to be at '$prefix/games/spring' in this case. * - the default datadirs in the default prefix, ie. '/usr/local/games/spring' * (This is set by the build system, ie. SPRING_DATADIR and SPRING_DATADIR_2 * preprocessor definitions.) * * In Windows, its: * - SPRING_DATADIR env-variable * - user configurable (SpringData in registry) * - location of the binary dir (like it has been until 0.76b1) * - the Users 'Documents'-directory (in subdirectory Spring), unless spring is configured to use another * - all users app-data (in subdirectory Spring) * - compiler flags SPRING_DATADIR and SPRING_DATADIR_2 * * All of the above methods support environment variable substitution, eg. * '$HOME/myspringdatadir' will be converted by spring to something like * '/home/username/myspringdatadir'. * * If it fails to chdir to the above specified directory spring will asume the * current working directory is the data directory. */ void DataDirLocater::LocateDataDirs() { // Construct the list of datadirs from various sources. datadirs.clear(); // environment variable char* env = getenv("SPRING_DATADIR"); if (env && *env) AddDirs(SubstEnvVars(env)); // user defined (in spring config handler (Linux: ~/.springrc, Windows: registry)) std::string userDef = configHandler.GetString("SpringData", ""); if (!userDef.empty()) { AddDirs(SubstEnvVars(userDef)); } #ifdef WIN32 TCHAR currentDir[MAX_PATH]; ::GetCurrentDirectory(sizeof(currentDir) - 1, currentDir); std::string curPath = currentDir; AddDirs(std::string(currentDir)); // my documents TCHAR strPath[MAX_PATH]; SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, strPath); std::string cfg = strPath; cfg += "\\Spring"; // e.g. F:\Dokumente und Einstellungen\Karl-Robert\Eigene Dateien\Spring AddDirs(cfg); cfg.clear(); // appdata SHGetFolderPath( NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, strPath); cfg = strPath; cfg += "\\Spring"; // e.g. F:\Dokumente und Einstellungen\All Users\Anwendungsdaten\Spring AddDirs(cfg); #elif defined(__APPLE__) // copied from old MacFileSystemHandler, won't compile here, but would not compile in its old location either // needs fixing for new DataDirLocater-structure // Get the path to the application bundle we are running: char cPath[1024]; CFBundleRef mainBundle = CFBundleGetMainBundle(); if(!mainBundle) throw content_error("Could not determine bundle path"); CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle); if(!mainBundleURL) throw content_error("Could not determine bundle path"); CFStringRef cfStringRef = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle); if(!cfStringRef) throw content_error("Could not determine bundle path"); CFStringGetCString(cfStringRef, cPath, 1024, kCFStringEncodingASCII); CFRelease(mainBundleURL); CFRelease(cfStringRef); std::string path(cPath); datadirs.clear(); writedir = NULL; // Add bundle resources: datadirs.push_back(path + "/Contents/Resources/"); datadirs.rbegin()->readable = true; // Add the directory surrounding the bundle, for users to add mods and maps in: datadirs.push_back(filesystem.GetDirectory(path)); // Use surrounding directory as writedir for now, should propably // change this to something inside the home directory: datadirs.rbegin()->writable = true; datadirs.rbegin()->readable = true; writedir = &*datadirs.rbegin(); #else // home AddDirs(SubstEnvVars("$HOME/.spring")); // settings in /etc FILE* f = ::fopen("/etc/spring/datadir", "r"); if (f) { char buf[1024]; while (fgets(buf, sizeof(buf), f)) { char* newl = strchr(buf, '\n'); if (newl) *newl = 0; char white[3] = {'\t', ' ', 0}; if (strlen(buf) > 0 && strspn(buf, white) != strlen(buf)) // don't count lines of whitespaces / tabulators AddDirs(SubstEnvVars(buf)); } fclose(f); } #endif // compiler flags #ifdef SPRING_DATADIR AddDirs(SubstEnvVars(SPRING_DATADIR)); #endif // should not be needed because you can seperate directories with a ':' in SPRING_DATADIR(1) #ifdef SPRING_DATADIR_2 AddDirs(SubstEnvVars(SPRING_DATADIR_2)); #endif // Figure out permissions of all datadirs DeterminePermissions(); if (!writedir) { // bail out #ifdef WIN32 const std::string errstr = "Not a single writable data directory found!\n\n" "Configure a writable data directory using either:\n" "- the SPRING_DATADIR environment variable,\n" "- a SpringData=C:/path/to/data declaration in spring's registry entry or\n" "- by giving you write access to the installation directory"; #else const std::string errstr = "Not a single writable data directory found!\n\n" "Configure a writable data directory using either:\n" "- the SPRING_DATADIR environment variable,\n" "- a SpringData=/path/to/data declaration in ~/.springrc or\n" "- the configuration file /etc/spring/datadir"; #endif throw content_error(errstr); } // for now, chdir to the datadirectory as a safety measure: // all AIs still just assume it's ok to put their stuff in the current directory after all // Not only safety anymore, it's just easier if other code can safely assume that // writedir == current working directory #ifndef _WIN32 chdir(GetWriteDir()->path.c_str()); #else _chdir(GetWriteDir()->path.c_str()); #endif // Initialize the log. Only after this moment log will be written to file. logOutput.Initialize(); // Logging MAY NOT start before the chdir, otherwise the logfile ends up // in the wrong directory. // Update: now it actually may start before, log has preInitLog. for (std::vector<DataDir>::const_iterator d = datadirs.begin(); d != datadirs.end(); ++d) { if (d->writable) logOutput.Print("Using read-write data directory: %s", d->path.c_str()); else logOutput.Print("Using read-only data directory: %s", d->path.c_str()); } }
bool MyApp::OnInit( void ) { try { SetAppName( APP_NAME ); SetVendorName( APP_VENDOR ); respath = wxFindAppPath( argv[0], wxGetCwd(), _T("FNPATH"), _T("fn") ); #ifdef __WXMSW__ if (respath.Last() != '\\') respath += '\\'; shaderPath = respath + _T("GLSL\\"); iconsPath = respath + _T("icons\\"); int fd; FILE *fp; AllocConsole(); fd = _open_osfhandle( (long)GetStdHandle( STD_OUTPUT_HANDLE ), 0); fp = _fdopen( fd, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); // TODO fix may not work. #elif __WXMAC__ // If we use the above code to get the same on OSX, I get a segfault somewhere // therefore I use the OSX native code here: // OSX only: Try to find the resource path... CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyBundleURL( mainBundle ); CFStringRef str = CFURLCopyFileSystemPath( resourcesURL, kCFURLPOSIXPathStyle ); CFRelease( resourcesURL ); char path[ PATH_MAX ]; CFStringGetCString( str, path, FILENAME_MAX, kCFStringEncodingASCII ); CFRelease( str ); fprintf( stderr, "%s", path ); respath = wxString::FromAscii( path ); respath += _T( "/Contents/Resources/" ); shaderPath = respath + _T( "GLSL/" ); iconsPath = respath + _T( "icons/" ); std::cout << std::endl << iconsPath << std::endl; #else if ( respath.Last() != '/' ) respath += '/'; shaderPath = respath + _T("GLSL/"); iconsPath = respath + _T("icons/"); #endif Logger::getInstance()->print( wxT( "Warning: This version of Fibernavigator is debug compiled." ), LOGLEVEL_DEBUG ); Logger::getInstance()->print( wxT( "For better performance please compile a Release version."), LOGLEVEL_DEBUG ); Logger::getInstance()->print( wxString::Format( wxT( "respath: %s" ), respath.c_str() ), LOGLEVEL_DEBUG ); Logger::getInstance()->print( wxString::Format( wxT( "shader: %s" ), shaderPath.c_str() ), LOGLEVEL_DEBUG ); // Create the main frame window frame = new MainFrame( wxT("Fiber Navigator"), wxPoint( 50, 50 ), wxSize( 800, 600 ) ); SceneManager::getInstance()->setMainFrame( frame ); SceneManager::getInstance()->setTreeCtrl( frame->m_pTreeWidget ); #ifdef __WXMSW__ // Give it an icon (this is ignored in MDI mode: uses resources) frame->SetIcon( wxIcon( _T( "sashtest_icn" ) ) ); #endif frame->SetMinSize( wxSize( 800, 600 ) ); frame->SetSize( wxSize( 1024, 768 ) ); frame->Show( true ); SetTopWindow( frame ); wxString cmd; wxString cmdFileName; wxCmdLineParser cmdParser( desc, argc, argv ); cmdParser.Parse( false ); if ( cmdParser.GetParamCount() > 0 ) { Loader loader = Loader(frame, frame->m_pListCtrl ); for ( size_t i = 0; i < cmdParser.GetParamCount(); ++i ) { cmd = cmdParser.GetParam( i ); wxFileName fName( cmd ); fName.Normalize( wxPATH_NORM_LONG | wxPATH_NORM_DOTS | wxPATH_NORM_TILDE | wxPATH_NORM_ABSOLUTE ); cmdFileName = fName.GetFullPath(); if ( cmdParser.Found(_T("d")) && ( i == 0 ) ) { loader( cmdFileName ); frame->createDistanceMapAndIso(); } else if ( cmdParser.Found( _T( "p" ) ) && ( i == cmdParser.GetParamCount() -1 ) ) { frame->screenshot( wxT( "" ), cmdFileName ); } else { loader( cmdFileName ); } } } if ( cmdParser.Found( _T( "e" ) ) ) { exit( 0 ); } return true; } catch ( ... ) { Logger::getInstance()->print( wxT( "Something went wrong, terribly wrong" ), LOGLEVEL_ERROR ); return false; } Logger::getInstance()->print( wxT( "End on init main" ), LOGLEVEL_DEBUG ); wxFrame *the_frame = new wxFrame(NULL, 1, argv[0]); the_frame->Show(true); return true; }
int main( int argc, char *argv[] ) { #ifdef WIN32 // Windows #ifdef _MSC_VER _set_fmode( _O_BINARY ); #else //MinGW _fmode = _O_BINARY; #endif // _MSC_VER #endif // WIN32 ///////////////////////////////////////////////////////////////// // Command line options 'behaviour' flag setup //////////////////////////////////////////////////////////////// // // Parse the command line arguments, looking to see if the user has asked for any // special behaviours. Any remaining non command arguments will be kept aside to // be passed as a list of layers and / or a project that should be loaded. // int myIterations = 1; QString mySnapshotFileName = ""; QString myLogFileName = ""; QString myPrefixPath = ""; int mySnapshotWidth = 800; int mySnapshotHeight = 600; QString myQuality = ""; // This behaviour will set initial extent of map canvas, but only if // there are no command line arguments. This gives a usable map // extent when qgis starts with no layers loaded. When layers are // loaded, we let the layers define the initial extent. QString myInitialExtent = ""; if ( argc == 1 ) myInitialExtent = "-1,-1,1,1"; // The user can specify a path which will override the default path of custom // user settings (~/.qgis) and it will be used for QSettings INI file QString configpath; #ifndef WIN32 //////////////////////////////////////////////////////////////// // USe the GNU Getopts utility to parse cli arguments // Invokes ctor `GetOpt (int argc, char **argv, char *optstring);' /////////////////////////////////////////////////////////////// int optionChar; while ( 1 ) { static struct option long_options[] = { /* These options set a flag. */ {"help", no_argument, 0, '?'}, /* These options don't set a flag. * We distinguish them by their indices. */ {"iterations", required_argument, 0, 'i'}, {"snapshot", required_argument, 0, 's'}, {"log", required_argument, 0, 'l'}, {"width", required_argument, 0, 'w'}, {"height", required_argument, 0, 'h'}, {"project", required_argument, 0, 'p'}, {"extent", required_argument, 0, 'e'}, {"optionspath", required_argument, 0, 'o'}, {"configpath", required_argument, 0, 'c'}, {"prefix", required_argument, 0, 'r'}, {"quality", required_argument, 0, 'q'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; optionChar = getopt_long( argc, argv, "islwhpeocrq", long_options, &option_index ); /* Detect the end of the options. */ if ( optionChar == -1 ) break; switch ( optionChar ) { case 0: /* If this option set a flag, do nothing else now. */ if ( long_options[option_index].flag != 0 ) break; printf( "option %s", long_options[option_index].name ); if ( optarg ) printf( " with arg %s", optarg ); printf( "\n" ); break; case 'i': myIterations = QString( optarg ).toInt(); break; case 's': mySnapshotFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() ); break; case 'l': myLogFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() ); break; case 'w': mySnapshotWidth = QString( optarg ).toInt(); break; case 'h': mySnapshotHeight = QString( optarg ).toInt(); break; case 'p': myProjectFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() ); break; case 'e': myInitialExtent = optarg; break; case 'o': QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optarg ); break; case 'c': configpath = optarg; break; case 'r': myPrefixPath = optarg; break; case 'q': myQuality = optarg; break; case '?': usage( argv[0] ); return 2; // XXX need standard exit codes break; default: QgsDebugMsg( QString( "%1: getopt returned character code %2" ).arg( argv[0] ).arg( optionChar ) ); return 1; // XXX need standard exit codes } } // Add any remaining args to the file list - we will attempt to load them // as layers in the map view further down.... QgsDebugMsg( QString( "Files specified on command line: %1" ).arg( optind ) ); if ( optind < argc ) { while ( optind < argc ) { #ifdef QGISDEBUG int idx = optind; QgsDebugMsg( QString( "%1: %2" ).arg( idx ).arg( argv[idx] ) ); #endif myFileList.append( QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[optind++] ) ).absoluteFilePath() ) ); } } #else for ( int i = 1; i < argc; i++ ) { QString arg = argv[i]; if ( arg == "--help" || arg == "-?" ) { usage( argv[0] ); return 2; } else if ( i + 1 < argc && ( arg == "--iterations" || arg == "-i" ) ) { myIterations = QString( argv[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) ) { mySnapshotFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--log" || arg == "-l" ) ) { myLogFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) ) { mySnapshotWidth = QString( argv[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) ) { mySnapshotHeight = QString( argv[++i] ).toInt(); } else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) ) { myProjectFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() ); } else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) ) { myInitialExtent = argv[++i]; } else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) ) { QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, argv[++i] ); } else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) ) { configpath = argv[++i]; QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, configpath ); } else if ( i + 1 < argc && ( arg == "--prefix" ) ) { myPrefixPath = argv[++i]; } else if ( i + 1 < argc && ( arg == "--quality" || arg == "-q" ) ) { myQuality = argv[++i]; } else { myFileList.append( QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[i] ) ).absoluteFilePath() ) ); } } #endif //WIN32 ///////////////////////////////////////////////////////////////////// // Now we have the handlers for the different behaviours... //////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Initialise the application and the translation stuff ///////////////////////////////////////////////////////////////////// if ( !configpath.isEmpty() ) { // tell QSettings to use INI format and save the file in custom config path QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, configpath ); } // TODO: Qt: there should be exactly one QCoreApplication object for console app. // but QgsApplication inherits from QApplication (GUI) // it is working, but maybe we should make QgsCoreApplication, which // could also be used by mapserver // Don't use QgsApplication( int, char **, bool GUIenabled, QString) which is new // so that this program may be run with old libraries //QgsApplication myApp( argc, argv, false, configpath ); QCoreApplication myApp( argc, argv ); if ( myPrefixPath.isEmpty() ) { QDir dir( QCoreApplication::applicationDirPath() ); dir.cdUp(); myPrefixPath = dir.absolutePath(); } QgsApplication::setPrefixPath( myPrefixPath, true ); // Set up the QSettings environment must be done after qapp is created QgsApplication::setOrganizationName( "QuantumGIS" ); QgsApplication::setOrganizationDomain( "qgis.org" ); QgsApplication::setApplicationName( "QGIS2" ); QgsProviderRegistry::instance( QgsApplication::pluginPath() ); #ifdef Q_OS_MACX // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH // is not already defined, use the GDAL plugins in the application bundle. QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) ); if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) ) { setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 ); } #endif QSettings mySettings; // For non static builds on mac and win (static builds are not supported) // we need to be sure we can find the qt image // plugins. In mac be sure to look in the // application bundle... #ifdef Q_WS_WIN QCoreApplication::addLibraryPath( QApplication::applicationDirPath() + QDir::separator() + "qtplugins" ); #endif #ifdef Q_OS_MACX //qDebug("Adding qt image plugins to plugin search path..."); CFURLRef myBundleRef = CFBundleCopyBundleURL( CFBundleGetMainBundle() ); CFStringRef myMacPath = CFURLCopyFileSystemPath( myBundleRef, kCFURLPOSIXPathStyle ); const char *mypPathPtr = CFStringGetCStringPtr( myMacPath, CFStringGetSystemEncoding() ); CFRelease( myBundleRef ); CFRelease( myMacPath ); QString myPath( mypPathPtr ); // if we are not in a bundle assume that the app is built // as a non bundle app and that image plugins will be // in system Qt frameworks. If the app is a bundle // lets try to set the qt plugin search path... QFileInfo myInfo( myPath ); if ( myInfo.isBundle() ) { // First clear the plugin search paths so we can be sure // only plugins from the bundle are being used QStringList myPathList; QCoreApplication::setLibraryPaths( myPathList ); // Now set the paths inside the bundle myPath += "/Contents/plugins"; QCoreApplication::addLibraryPath( myPath ); } #endif QgsBench *qbench = new QgsBench( mySnapshotWidth, mySnapshotHeight, myIterations ); ///////////////////////////////////////////////////////////////////// // If no --project was specified, parse the args to look for a // // .qgs file and set myProjectFileName to it. This allows loading // // of a project file by clicking on it in various desktop managers // // where an appropriate mime-type has been set up. // ///////////////////////////////////////////////////////////////////// if ( myProjectFileName.isEmpty() ) { // check for a .qgs for ( int i = 0; i < argc; i++ ) { QString arg = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[i] ) ).absoluteFilePath() ); if ( arg.contains( ".qgs" ) ) { myProjectFileName = arg; break; } } } ///////////////////////////////////////////////////////////////////// // Load a project file if one was specified ///////////////////////////////////////////////////////////////////// if ( ! myProjectFileName.isEmpty() ) { if ( ! qbench->openProject( myProjectFileName ) ) { fprintf( stderr, "Cannot load project\n" ); return 1; } } if ( ! myQuality.isEmpty() ) { QPainter::RenderHints hints; QStringList list = myQuality.split( ',' ); foreach ( QString q, list ) { if ( q == "Antialiasing" ) hints |= QPainter::Antialiasing; else if ( q == "TextAntialiasing" ) hints |= QPainter::TextAntialiasing; else if ( q == "SmoothPixmapTransform" ) hints |= QPainter::SmoothPixmapTransform; else if ( q == "NonCosmeticDefaultPen" ) hints |= QPainter::NonCosmeticDefaultPen; else { fprintf( stderr, "Unknown quality option\n" ); return 1; } } QgsDebugMsg( QString( "hints: %1" ).arg( hints ) ); qbench->setRenderHints( hints ); }
void initializePaths() { #if RUN_IN_PLACE /* Use relative paths if RUN_IN_PLACE */ infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl; /* Windows */ #if defined(_WIN32) const DWORD buflen = 1000; char buf[buflen]; DWORD len; // Find path of executable and set path_share relative to it len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen); assert(len < buflen); pathRemoveFile(buf, '\\'); if(detectMSVCBuildDir(buf)){ infostream<<"MSVC build directory detected"<<std::endl; path_share = std::string(buf) + "\\..\\.."; path_user = std::string(buf) + "\\..\\.."; } else{ path_share = std::string(buf) + "\\.."; path_user = std::string(buf) + "\\.."; } /* Linux */ #elif defined(linux) char buf[BUFSIZ]; memset(buf, 0, BUFSIZ); // Get path to executable assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1); pathRemoveFile(buf, '/'); path_share = std::string(buf) + "/.."; path_user = std::string(buf) + "/.."; /* OS X */ #elif defined(__APPLE__) //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html //TODO: Test this code char buf[BUFSIZ]; uint32_t len = sizeof(buf); assert(_NSGetExecutablePath(buf, &len) != -1); pathRemoveFile(buf, '/'); path_share = std::string(buf) + "/.."; path_user = std::string(buf) + "/.."; /* FreeBSD */ #elif defined(__FreeBSD__) int mib[4]; char buf[BUFSIZ]; size_t len = sizeof(buf); mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1); pathRemoveFile(buf, '/'); path_share = std::string(buf) + "/.."; path_user = std::string(buf) + "/.."; #else //TODO: Get path of executable. This assumes working directory is bin/ dstream<<"WARNING: Relative path not properly supported on this platform" <<std::endl; path_share = std::string(".."); path_user = std::string(".."); #endif #else // RUN_IN_PLACE /* Use platform-specific paths otherwise */ infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl; /* Windows */ #if defined(_WIN32) const DWORD buflen = 1000; char buf[buflen]; DWORD len; // Find path of executable and set path_share relative to it len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen); assert(len < buflen); pathRemoveFile(buf, '\\'); // Use ".\bin\.." path_share = std::string(buf) + "\\.."; // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>" len = GetEnvironmentVariable("APPDATA", buf, buflen); assert(len < buflen); path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME; /* Linux */ #elif defined(linux) // Get path to executable std::string bindir = ""; { char buf[BUFSIZ]; memset(buf, 0, BUFSIZ); assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1); pathRemoveFile(buf, '/'); bindir = buf; } // Find share directory from these. // It is identified by containing the subdirectory "builtin". std::list<std::string> trylist; std::string static_sharedir = STATIC_SHAREDIR; if(static_sharedir != "" && static_sharedir != ".") trylist.push_back(static_sharedir); trylist.push_back(bindir + "/../share/" + PROJECT_NAME); trylist.push_back(bindir + "/.."); for(std::list<std::string>::const_iterator i = trylist.begin(); i != trylist.end(); i++) { const std::string &trypath = *i; if(!fs::PathExists(trypath) || !fs::PathExists(trypath + "/builtin")){ dstream<<"WARNING: system-wide share not found at \"" <<trypath<<"\""<<std::endl; continue; } // Warn if was not the first alternative if(i != trylist.begin()){ dstream<<"WARNING: system-wide share found at \"" <<trypath<<"\""<<std::endl; } path_share = trypath; break; } path_user = std::string(getenv("HOME")) + "/." + PROJECT_NAME; /* OS X */ #elif defined(__APPLE__) // Code based on // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c CFBundleRef main_bundle = CFBundleGetMainBundle(); CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle); char path[PATH_MAX]; if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) { dstream<<"Bundle resource path: "<<path<<std::endl; //chdir(path); path_share = std::string(path) + "/share"; } else { // error! dstream<<"WARNING: Could not determine bundle resource path"<<std::endl; } CFRelease(resources_url); path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME; #elif defined(__FreeBSD__) path_share = STATIC_SHAREDIR; path_user = std::string(getenv("HOME")) + "/." + PROJECT_NAME; #endif #endif // RUN_IN_PLACE }