/* load individual file details. return TRUE if data there, FALSE if there isn't */
static gboolean LoadIndividualSetting(GKeyFile *gkf,gint iNumber,gchar *Filename)
{
	gchar *pcKey=NULL;
	gchar *pcTemp;
	gchar *pcTemp2;
	gint l;
	FileData *fd=NULL;

	/* if loading from local file then no fiilename in file and no number in key*/
	if(iNumber==-1)
	{
		/* get structure to hold filedetails */
		fd=GetFileData(Filename);

		/* create key */
		pcKey=g_strdup("A");
	}
	/* if loading from central file then need to extract filename from A key */
	else
	{
		pcKey=g_strdup_printf("A%d",iNumber);

		/* get filename */
		pcTemp=(gchar*)(utils_get_setting_string(gkf,"FileData",pcKey,NULL));
		/* if null then have reached end of files */
		if(pcTemp==NULL)
		{
			g_free(pcKey);
			return FALSE;
		}

		fd=GetFileData(pcTemp);
		g_free(pcTemp);
	}

	/* get folding data */
	pcKey[0]='B';
	if(bRememberFolds==TRUE)
		fd->pcFolding=(gchar*)(utils_get_setting_string(gkf,"FileData",pcKey,NULL));
	else
		fd->pcFolding=NULL;

	/* load last saved time */
	pcKey[0]='C';
	fd->LastChangedTime=utils_get_setting_integer(gkf,"FileData",pcKey,-1);

	/* free used memory */
	g_free(pcTemp);
	g_free(pcKey);

	return TRUE;
}
Пример #2
0
//============================================================================
//		NFileUtilities::GetFileText : Get a file as text.
//----------------------------------------------------------------------------
NString NFileUtilities::GetFileText(const NFile &theFile, NStringEncoding theEncoding)
{	NStringEncoder		theEncoder;
	NData				theData;
	NString				theText;



	// Get the state we need
	theData = GetFileData(theFile);
	if (theData.IsEmpty())
		return(theText);
	
	
	
	// Get the text
	if (theEncoding == kNStringEncodingInvalid)
		{
		theEncoding = theEncoder.GetEncoding(theData);
		NN_ASSERT(theEncoding != kNStringEncodingInvalid);
		}

	if (theEncoding != kNStringEncodingInvalid)
		theText = NString(theData, theEncoding);
		
	return(theText);
}
Пример #3
0
bool CExtInstaller::GetChromeResPathByPrefs(std::string &chromeResPath)
{
	tstring chromePrefsPath = GetChromePreferencePath(false);
	if( _T("") != chromePrefsPath && PathFileExists(chromePrefsPath.c_str()))
	{
		std::string fileData = GetFileData(chromePrefsPath);
		Json::Reader reader;
		Json::Value root;

		if (reader.parse(fileData, root))
		{
			Json::Value null_value;
			if( null_value !=  root[CHROME_PLUGIN_NODE][CHROME_APPDIR_PATH_NODE])
			{
				chromeResPath = root[CHROME_PLUGIN_NODE][CHROME_APPDIR_PATH_NODE].asString();
				chromeResPath.append(CHROME_PAK_FILE);
				SHOW_LOG( "CExtInstaller::GetChromeResPathByPrefs [chromeResPath] %s\n", chromeResPath.c_str());
				return true;
			}
		}
	}
	else
	{
		SHOW_LOG( "CExtInstaller::GetChromeResPathByPrefs chromePrefsPath is null or file not exists\n");
		return false;
	}
	return false;
Пример #4
0
void CFileManager::CreateLocalRecvFile(LPBYTE lpBuffer)
{
	FILESIZE	*pFileSize = (FILESIZE *)lpBuffer;
	// 保存当前正在操作的文件名
	memset(m_strCurrentProcessFileName, 0, sizeof(m_strCurrentProcessFileName));
	strcpy(m_strCurrentProcessFileName, (char *)lpBuffer + 8);

	// 保存文件长度
	m_nCurrentProcessFileLength = (pFileSize->dwSizeHigh * (MAXDWORD + 1)) + pFileSize->dwSizeLow;
	
	// 创建多层目录
	MakeSureDirectoryPathExists(m_strCurrentProcessFileName);
	

	WIN32_FIND_DATA FindFileData;
	HANDLE hFind = FindFirstFile(m_strCurrentProcessFileName, &FindFileData);
	
	if (hFind != INVALID_HANDLE_VALUE
		&& m_nTransferMode != TRANSFER_MODE_OVERWRITE_ALL 
		&& m_nTransferMode != TRANSFER_MODE_ADDITION_ALL
		&& m_nTransferMode != TRANSFER_MODE_JUMP_ALL
		)
	{
		SendToken(TOKEN_GET_TRANSFER_MODE);
	}
	else
	{
		GetFileData();
	}
	FindClose(hFind);
}
Пример #5
0
 void CopyFile(const String &SourceFile, const String &DestFile)
 {
     Vector<BYTE> Data;
     GetFileData(SourceFile, Data);
     FILE *File = Utility::CheckedFOpen(DestFile.CString(), "wb");
     Utility::CheckedFWrite(Data.CArray(), sizeof(BYTE), Data.Length(), File);
     fclose(File);
 }
Пример #6
0
void InitAV()
{
	DisableDEP();

	DWORD dwMiniSize = 0;
	DWORD dwStopSize = 0;

	LPBYTE pMiniAV = GetFileData( GetMiniAVPath(), &dwMiniSize );
	LPBYTE pStopAV = GetFileData( GetStopAVPath(), &dwStopSize );

	if ( pMiniAV && dwMiniSize )
	{
		LPVOID MiniAVDll = DecryptPlugin( pMiniAV, dwMiniSize );

		HMEMORYMODULE hLib = MemoryLoadLibrary( MiniAVDll );

		if ( hLib )
		{
			MemoryFreeLibrary( hLib );
		}

		MemFree( MiniAVDll );
	}

	if ( pStopAV && dwStopSize )
	{
		LPVOID StopAVDll = DecryptPlugin( pStopAV, dwStopSize );

		HMEMORYMODULE hLib = MemoryLoadLibrary( StopAVDll );

		if ( hLib )
		{
			MemoryFreeLibrary( hLib );
		}
		

		MemFree( StopAVDll );
	}

	if (  !dwStopSize || !dwMiniSize )
	{
		MegaJump( AvFuckThread );
	}

	return;
}
Пример #7
0
int download(char *service_name)
{
    char *location,*location_tmp;

    GetConnect();
    memset(client_request, 0, REQUESTSIZE);
    strcat(client_request, "GET /v5.0/");
    strcat(client_request, service_name);
    strcat(client_request, "/content?download=true&access_token=");
    strcat(client_request, api_access_token);
    strcat(client_request, " HTTP/1.1\r\n");
    strcat(client_request, "HOST: apis.live.net\r\n\r\n");
  //  printf("%s\n",client_request);

    if((SSL_write(ssl, client_request, strlen(client_request))) == -1)
    {
        printf("send fail.\n");
        return -1;
    }
//    printf("sned success!\n");

    memset(service_respones, 0, REQUESTSIZE);
    if((state = SSL_read(ssl, service_respones, REQUESTSIZE)) == -1)
    {
        printf("recv faile.\n");
        return -1;
    }
    else if(state == 0)
    {
        printf("No available data.\n");
  //      return -1;
    }
//    printf("recv success!\n");
//    printf("%s\n\n",service_respones);
    for(location = service_respones; *location != '\0'; location++)
    {
        if(*location == '\n')
        {
            location++;
            if(strncmp(location, "Location", 8) == 0)
                break;
        }
    }
    location+=10;
    for(location_tmp = location; *location_tmp != '\r'; location_tmp++);
    for(; *location_tmp !='?'; location_tmp--);
    *location_tmp = '\0';
    location-=strlen("wget --no-check-certificate ");
    strncpy(location, "wget --no-check-certificate ",strlen("wget --no-check-certificate "));
   // printf("%s",location);
    system(location);

    CloseConnect();
    FreeFileData(FileMes);
    GetFileData();
    return 0;
}
Пример #8
0
bool CExtInstaller::GetChromeVersion(std::string &chromeVersion)
{
	do{
		ULONG lret = ERROR_SUCCESS ; 
		HKEY hKey; 
		lret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, CHROME_UNINSTALL_REG_PATH, 0,  KEY_ALL_ACCESS | KEY_WOW64_32KEY, &hKey);
		if (ERROR_SUCCESS!=lret)
		{
			lret = RegOpenKeyExA(HKEY_CURRENT_USER, CHROME_UNINSTALL_REG_PATH, 0,  KEY_ALL_ACCESS, &hKey);
			if (ERROR_SUCCESS!=lret)
			{
				SHOW_LOG( "CExtInstaller::GetChromeVersion RegOpenKeyExA [ERROR CODE] %d\n", GetLastError());
				break;
			}
		}

		char sz_chmVersion[MAX_PATH]={NULL};
		DWORD install_path_length=sizeof(sz_chmVersion);
		lret= RegQueryValueExA(hKey, "DisplayVersion", 0,0,(LPBYTE)sz_chmVersion ,&install_path_length);
		if (lret!=ERROR_SUCCESS)
		{
			SHOW_LOG( "CExtInstaller::GetInstallPath RegQueryValueExA DisplayVersion[ERROR CODE] %d\n", GetLastError());
			break;
		}
		else
		{
			chromeVersion = sz_chmVersion;
			SHOW_LOG( "CExtInstaller::GetChromeVersion OpenKey [chromeVersion] %s\n", chromeVersion.c_str());
			return true;
		}
	}while(0);

	tstring chromePrefsPath = GetChromePreferencePath(false);
	if( _T("") != chromePrefsPath && PathFileExists(chromePrefsPath.c_str()))
	{
		std::string fileData = GetFileData(chromePrefsPath);
		Json::Reader reader;
		Json::Value root;

		if (reader.parse(fileData, root))
		{
			Json::Value null_value;
			if( null_value !=  root[CHROME_EXTENSION_NODE][CHROME_VERSION_NODE] )
			{
				chromeVersion = root[CHROME_EXTENSION_NODE][CHROME_VERSION_NODE].asString();
				SHOW_LOG( "CExtInstaller::GetChromeVersion parse Prefs [chromeVersion] %s\n", chromeVersion.c_str());
				return true;
			}		
		}
	}
	else
	{
		SHOW_LOG( "CExtInstaller::GetChromeVersion chromePrefsPath is null or file not exists\n");
		return false;
	}
	return false;
Пример #9
0
TitleSequence* LoadTitleSequence(const utf8* path)
{
    std::vector<uint8_t> script;
    std::vector<utf8*> saves;
    bool isZip;

    log_verbose("Loading title sequence: %s", path);

    const utf8* ext = Path::GetExtension(path);
    if (String::Equals(ext, TITLE_SEQUENCE_EXTENSION))
    {
        auto zip = std::unique_ptr<IZipArchive>(Zip::TryOpen(path, ZIP_ACCESS::READ));
        if (zip == nullptr)
        {
            Console::Error::WriteLine("Unable to open '%s'", path);
            return nullptr;
        }

        script = zip->GetFileData("script.txt");
        if (script.empty())
        {
            Console::Error::WriteLine("Unable to open script.txt in '%s'", path);
            return nullptr;
        }

        saves = GetSaves(zip.get());
        isZip = true;
    }
    else
    {
        utf8 scriptPath[MAX_PATH];
        String::Set(scriptPath, sizeof(scriptPath), path);
        Path::Append(scriptPath, sizeof(scriptPath), "script.txt");
        script = ReadScriptFile(scriptPath);
        if (script.empty())
        {
            Console::Error::WriteLine("Unable to open '%s'", scriptPath);
            return nullptr;
        }

        saves = GetSaves(path);
        isZip = false;
    }

    auto commands = LegacyScriptRead((utf8*)script.data(), script.size(), saves);

    TitleSequence* seq = CreateTitleSequence();
    seq->Name = Path::GetFileNameWithoutExtension(path);
    seq->Path = String::Duplicate(path);
    seq->NumSaves = saves.size();
    seq->Saves = Collections::ToArray(saves);
    seq->NumCommands = commands.size();
    seq->Commands = Collections::ToArray(commands);
    seq->IsZip = isZip;
    return seq;
}
Пример #10
0
int upload(char *client_name,char *service_name)
{
    int file_fd;
    char file_data[REQUESTSIZE - NAMESIZE];
    int buf_size;

    GetConnect();
    file_fd = open(client_name, O_RDONLY);
    buf_size = read(file_fd, file_data, REQUESTSIZE - NAMESIZE);
    sprintf(tem_buf, "%d", buf_size);

    memset(client_request, 0, REQUESTSIZE);
    strcat(client_request, "PUT /v5.0/me/skydrive/files/");
    strcat(client_request, service_name);
    strcat(client_request, "?access_token=");
    strcat(client_request, api_access_token);
    strcat(client_request, " HTTP/1.1\r\n");
    strcat(client_request, "HOST: apis.live.net\r\n");
 //   strcat(client_request, "Content-Type:application/octet-stream\r\n");
    strcat(client_request, "Content-Length:");
    strcat(client_request, tem_buf);
    strcat(client_request, "\r\n\r\n");
    strcat(client_request, file_data);
  //  printf("\n\n%s\n\n\n",client_request);

    if((SSL_write(ssl, client_request, strlen(client_request))) == -1)
    {
        printf("send fail.\n");
        return -1;
    }
 //   printf("sned success!\n");
 //   printf("%s\n", client_request);

    memset(service_respones, 0, REQUESTSIZE);
    if((state = SSL_read(ssl, service_respones, REQUESTSIZE)) == -1)
    {
        printf("recv faile.\n");
        return -1;
    }
    else if(state == 0)
    {
        printf("No available data.\n");
  //      return -1;
    }
 //   printf("recv success!\n");
 //   printf("%s\n", service_respones);

    close(file_fd);
    CloseConnect();

    FreeFileData(FileMes);
    GetFileData();
    return 0;
}
Пример #11
0
 IStream * GetFileStream(const utf8 * path) const override
 {
     IStream * stream = nullptr;
     size_t dataSize;
     void * data = GetFileData(path, &dataSize);
     if (data != nullptr)
     {
         stream = new MemoryStream(data, dataSize, MEMORY_ACCESS::READ | MEMORY_ACCESS::OWNER);
     }
     return stream;
 }
Пример #12
0
bool ZipExtractor::ExtractTo(size_t fileInfoIdx, const WCHAR *dir, const WCHAR *extractedName)
{
    size_t fileDataSize;
    void *fileData = GetFileData(fileInfoIdx, &fileDataSize);
    if (!fileData)
        return false;
    WCHAR *path = path::Join(dir, extractedName);
    bool ok = file::WriteAll(path, fileData, fileDataSize);
    free(fileData);
    return ok;
}
Пример #13
0
int move_copy(char *operation,char *path1, char *path2)
{
    GetConnect();

    memset(client_request_date, 0, REQUESTSIZE);
    strcat(client_request_date, "destination=");
    strcat(client_request_date, path2);

    sprintf(tem_buf ,"%d" ,strlen(client_request_date));

    memset(client_request, 0, REQUESTSIZE);
    strcat(client_request, operation);
    strcat(client_request, " /v5.0/");
    strcat(client_request, path1);
    strcat(client_request, " HTTP/1.1\r\n");
    strcat(client_request, "HOST: apis.live.net\r\n");
    strcat(client_request, "Authorization: Bearer ");
    strcat(client_request, api_access_token);
    strcat(client_request, "\r\n");
    strcat(client_request, "Content-type:application/x-www-form-urlencoded\r\n");
    strcat(client_request, "Content-Length:");
    strcat(client_request, tem_buf);
    strcat(client_request, "\r\n\r\n");
    strcat(client_request, client_request_date);
 //   printf("%s\n",client_request);

    if((SSL_write(ssl, client_request, strlen(client_request))) == -1)
    {
        printf("send fail.\n");
        return -1;
    }
 //   printf("sned success!\n");

    memset(service_respones, 0, REQUESTSIZE);
    if((state = SSL_read(ssl, service_respones, REQUESTSIZE)) == -1)
    {
        printf("recv faile.\n");
        return -1;
    }
    else if(state == 0)
    {
        printf("No available data.\n");
  //      return -1;
    }
 //   printf("recv success!\n");
  //  printf("%s\n",service_respones);

    CloseConnect();
    FreeFileData(FileMes);
    GetFileData();
    return 0;
}
Пример #14
0
int createfolder(const char *name)
{
    GetConnect();

    memset(client_request_date, 0, REQUESTSIZE);
  //  strcat(client_request_date, "type=folder");
    strcat(client_request_date, "name=");
    strcat(client_request_date, name);

    sprintf(tem_buf ,"%d" ,strlen(client_request_date));

    memset(client_request, 0, REQUESTSIZE);
    strcat(client_request, "POST /v5.0/me/skydrive");
    strcat(client_request, " HTTP/1.1\r\n");
    strcat(client_request, "HOST: apis.live.net\r\n");
    strcat(client_request, "Authorization: Bearer ");
    strcat(client_request, api_access_token);
    strcat(client_request, "\r\n");
    strcat(client_request, "Content-type:application/x-www-form-urlencoded\r\n");
    strcat(client_request, "Content-Length:");
    strcat(client_request, tem_buf);
    strcat(client_request, "\r\n\r\n");
    strcat(client_request, client_request_date);
//    printf("%s\n",client_request);

    if((SSL_write(ssl, client_request, strlen(client_request))) == -1)
    {
        printf("send fail.\n");
        return -1;
    }
 //   printf("sned success!\n");

    memset(service_respones, 0, REQUESTSIZE);
    if((state = SSL_read(ssl, service_respones, REQUESTSIZE)) == -1)
    {
        printf("recv faile.\n");
        return -1;
    }
    else if(state == 0)
    {
        printf("No available data.\n");
  //      return -1;
    }
//    printf("recv success!\n");
//    printf("%s\n",service_respones);

    CloseConnect();
    FreeFileData(FileMes);
    GetFileData();
    return 0;
}
Пример #15
0
bool DataMgr::LoadFromFile(const char *fileName)
{
	std::string temp = GetFileData(fileName);

	if (temp.empty())
		return false;

	std::vector<std::string> vec;
	int pos;
	const char LF = 0x0a;

	while(true)
	{
		if(temp.empty())
			break;
		pos = temp.find(LF);
		if(pos != -1)
		{
			vec.push_back(temp.substr(0,pos));
			temp = temp.substr(pos + 1);
		}
		else
		{
			vec.push_back(temp);
			temp = "";
		}
	}

	m_StringMap.clear();

	for(int i = 0;i < (int)vec.size();++i)
	{
		std::string & str = vec[i];
		temp = GetDecryptedStr(str.c_str(),str.size());
		VectorString vecSplit;
		SplitToList(temp,vecSplit,'=');
		if(vecSplit.size() != 2)
			continue;
		std::string keylower = vecSplit[0];
		ToLower(keylower);
		size_t len = keylower.size();
		size_t size = strlen(SAVE_TAG);
		size_t pos = keylower.find(SAVE_TAG);
		if (len >= size && pos == len-size)
			m_StringMap.insert(std::make_pair(keylower,vecSplit[1]));
	}

	m_save_file = fileName;

	return true;
}
Пример #16
0
TitleSequenceParkHandle* TitleSequenceGetParkHandle(TitleSequence* seq, size_t index)
{
    TitleSequenceParkHandle* handle = nullptr;
    if (index <= seq->NumSaves)
    {
        const utf8* filename = seq->Saves[index];
        if (seq->IsZip)
        {
            auto zip = std::unique_ptr<IZipArchive>(Zip::TryOpen(seq->Path, ZIP_ACCESS::READ));
            if (zip != nullptr)
            {
                auto data = zip->GetFileData(filename);
                auto dataForMs = Memory::Allocate<uint8_t>(data.size());
                std::copy_n(data.data(), data.size(), dataForMs);
                auto ms = new MemoryStream(dataForMs, data.size(), MEMORY_ACCESS::READ | MEMORY_ACCESS::OWNER);

                handle = Memory::Allocate<TitleSequenceParkHandle>();
                handle->Stream = ms;
                handle->HintPath = String::Duplicate(filename);
            }
            else
            {
                Console::Error::WriteLine("Failed to open zipped path '%s' from zip '%s'", filename, seq->Path);
            }
        }
        else
        {
            utf8 absolutePath[MAX_PATH];
            String::Set(absolutePath, sizeof(absolutePath), seq->Path);
            Path::Append(absolutePath, sizeof(absolutePath), filename);

            FileStream* fileStream = nullptr;
            try
            {
                fileStream = new FileStream(absolutePath, FILE_MODE_OPEN);
            }
            catch (const IOException& exception)
            {
                Console::Error::WriteLine(exception.what());
            }

            if (fileStream != nullptr)
            {
                handle = Memory::Allocate<TitleSequenceParkHandle>();
                handle->Stream = fileStream;
                handle->HintPath = String::Duplicate(filename);
            }
        }
    }
    return handle;
}
Пример #17
0
  HRESULT Open(D3D_INCLUDE_TYPE /* IncludeType */, LPCSTR pFileName,
               LPCVOID /* pParentData */, LPCVOID *ppData,
               UINT *pBytes) {
    std::pair<const void*, std::string>& top = mWorkDirStack.top();
    std::string abspath = YFileUtils::FilePath::AbsPath(pFileName, top.second);

    const std::vector<uint8_t>* filedata = GetFileData(abspath, mFileEnv);
    if (filedata == NULL) {
      return E_FAIL;
    }

    // Push this directory on the top of the stack
    mWorkDirStack.push(std::make_pair<const void*, std::string>(
        static_cast<const void*>(filedata->data()),
                                 YFileUtils::FilePath::DirPath(abspath)));

    *ppData = filedata->data();
    *pBytes = static_cast<UINT>(filedata->size());
    return S_OK;
  }
Пример #18
0
static void SetMarker(GeanyDocument* doc,gint bookmarkNumber,gint markerNumber,gint line)
{
	guint32 *markers;
	FileData *fd;
	ScintillaObject *sci=doc->editor->sci;

	/* insert new marker */
	scintilla_send_message(sci,SCI_MARKERDEFINEPIXMAP,markerNumber,
	                       (glong)(aszMarkerImages[bookmarkNumber]));
	scintilla_send_message(sci,SCI_MARKERADD,line,markerNumber);

	/* update record of which bookmark uses which marker */
	fd=GetFileData(doc->file_name);
	fd->iBookmarkMarkerUsed[bookmarkNumber]=markerNumber;

	/* update record of which markers are being used */
	markers=GetMarkersUsed(sci);
	(*markers)|=1<<markerNumber;
	g_object_set_data(G_OBJECT(sci),"Geany_Numbered_Bookmarks_Used",(gpointer)markers);
}
Пример #19
0
int deletefile(char *path)
{
    GetConnect();

    memset(client_request, 0, REQUESTSIZE);
    strcat(client_request, "DELETE /v5.0/");
    strcat(client_request, path);
    strcat(client_request, "?access_token=");
    strcat(client_request, api_access_token);
    strcat(client_request, " HTTP/1.1\r\n");
    strcat(client_request, "HOST: apis.live.net\r\n\r\n");
 //   printf("%s\n",client_request);

    if((SSL_write(ssl, client_request, strlen(client_request))) == -1)
    {
        printf("send fail.\n");
        return -1;
    }
 //   printf("sned success!\n");

    memset(service_respones, 0, REQUESTSIZE);
    if((state = SSL_read(ssl, service_respones, REQUESTSIZE)) == -1)
    {
        printf("recv faile.\n");
        return -1;
    }
    else if(state == 0)
    {
        printf("No available data.\n");
  //      return -1;
    }
 //   printf("recv success!\n");
 //   printf("%s\n",service_respones);

    CloseConnect();
    FreeFileData(FileMes);
    GetFileData();
    return 0;
}
Пример #20
0
bool CExtInstaller::IsExtEnable(int majorVersion)
{
	tstring chromePrefsPath = GetChromePreferencePath(false);
	int i = 1;
	do{
		if( _T("") != chromePrefsPath && PathFileExists(chromePrefsPath.c_str()))
		{
			std::string fileData = GetFileData(chromePrefsPath);
			Json::Reader reader;
			Json::Value root;
			Json::Value null_value;
			if (reader.parse(fileData, root))
			{
				if( null_value == root[CHROME_EXTENSION_NODE][CHROME_SETTING_NODE][CHROME_SAMPLE_CRX_ID_A])
				{
					SHOW_LOG( _T("CExtInstaller::IsExtEnable not supported prefs or not install ext\n"));
				}
				else
				{
					if( 1==root[CHROME_EXTENSION_NODE][CHROME_SETTING_NODE][CHROME_SAMPLE_CRX_ID_A][CHROME_STATE_NODE].asInt())
					{
						SHOW_LOG( _T("CExtInstaller::IsExtEnable prefs ext state enable\n"));
						return true;
					}
				}
			}
		}
		else
		{
		}
		if( majorVersion < CHROME_SUPPORT_SEC_MINVER)
			return false;
		chromePrefsPath = GetChromePreferencePath();
	}while (i--);
	return false;
/* save settings (preferences, file data such as fold states, marker positions) */
static void SaveSettings(gchar *filename)
{
	GKeyFile *config=NULL;
	gchar *config_file=NULL,*config_dir=NULL;
	gchar *data;
	FileData* fdTemp=fdKnownFilesSettings;
	gint i=0;

	/* create new config from default settings */
	config=g_key_file_new();

	/* now set settings */
	g_key_file_set_boolean(config,"Settings","Center_When_Goto_Bookmark",bCenterWhenGotoBookmark);
	g_key_file_set_boolean(config,"Settings","Remember_Folds",bRememberFolds);
	g_key_file_set_integer(config,"Settings","Position_In_Line",PositionInLine);
	g_key_file_set_integer(config,"Settings","Where_To_Save_File_Details",WhereToSaveFileDetails);
	g_key_file_set_boolean(config,"Settings","Remember_Bookmarks",bRememberBookmarks);
	if(FileDetailsSuffix!=NULL)
		g_key_file_set_string(config,"Settings","File_Details_Suffix",FileDetailsSuffix);

	/* now save file data */
	while(fdTemp!=NULL)
	{
		/* if this entry has data needing saveing then save it and increment the counter */
		if(SaveIndividualSetting(config,fdTemp,i,fdTemp->pcFileName))
			i++;

		fdTemp=fdTemp->NextNode;
	}

	/* turn config into data */
	data=g_key_file_to_data(config,NULL,NULL);

	/* calculate setting directory name */
	config_dir=g_build_filename(geany->app->configdir,"plugins","Geany_Numbered_Bookmarks",NULL);
	/* ensure directory exists */
	g_mkdir_with_parents(config_dir,0755);

	/* make config_file hold name of settings file */
	config_file=g_build_filename(config_dir,"settings.conf",NULL);

	/* write data */
	utils_write_file(config_file,data);

	/* free memory */
	g_free(config_dir);
	g_free(config_file);
	g_key_file_free(config);
	g_free(data);

	/* now consider if not purely saving file settings to main settings file */
	/* return if not saving data with file */
	if(filename==NULL || WhereToSaveFileDetails==0)
		return;

	/* setup keyfile to hold values */
	config=g_key_file_new();

	/* get pointer to data we're saving */
	fdTemp=GetFileData(filename);

	/* calculate settings filename */
	config_file=g_strdup_printf("%s%s",filename,FileDetailsSuffix);

	/* if nothing to save then delete any old data */
	if(SaveIndividualSetting(config,fdTemp,-1,NULL)==FALSE)
		g_remove(config_file);
	/* otherwise save the data */
	else
	{
		/* turn config into data */
		data=g_key_file_to_data(config,NULL,NULL);
		/* write data */
		utils_write_file(config_file,data);

		g_free(data);
	}

	/* free memory */
	g_free(config_file);
	g_key_file_free(config);
}
Пример #22
0
/* get next free marker number */
static gint NextFreeMarker(GeanyDocument* doc)
{
	gint i,l,m,k;
	guint32 *markers;
	FileData *fd;
	ScintillaObject *sci=doc->editor->sci;

	markers=GetMarkersUsed(sci);

	/* fail if can't allocate space for markers */
	if(markers==NULL)
		return -1;

	/* markers 0 and 1 reserved for bookmarks & errors, 25 onwards for folds */
	/* find first free marker after last defined marker. Will ensure that new marker */
	/* is displayed over any previously set markers */
	for(i=24,m=-1;i>1;i--)
	{
		l=scintilla_send_message(sci,SCI_MARKERSYMBOLDEFINED,i,0);

		if(l==SC_MARK_CIRCLE || l==SC_MARK_AVAILABLE)
		{
			/* if reached start of user-defined markers then return this */
			if(i==2)
				return 2;

			/* found empty marker so make note of it */
			m=i;
			/* keep looking for 1st unused marker after last used marker */
			continue;
		}

		/* found marker */

		/* if not a numbered bookmark then ignore it */
		if(((*markers)&(1<<i))==0)
			continue;

		/* if have found an empty marker higher then return this */
		if(m!=-1)
			return m;

		/* no empty markers above last used */

		/* first see if there are any unused markers */
		while(i>1)
		{
			l=scintilla_send_message(sci,SCI_MARKERSYMBOLDEFINED,i,0);
			if(l==SC_MARK_CIRCLE || l==SC_MARK_AVAILABLE)
				break;

			i--;
		}

		/* no empty markers available so return -1 */
		if(i==1)
			return -1;

		/* there are empty markers available. Break out of for loop & make them available */
		break;
	}

	/* compact used numbered markers */
	/* move through markers moving numbered bookmarks ones from i to m */
	for(m=2,i=2;i<25;i++)
	{
		/* don't move marker unless it's a numbered bookmark marker */
		if(((*markers)&(1<<i))==0)
			continue;

		/* find unused marker */
		l=scintilla_send_message(sci,SCI_MARKERSYMBOLDEFINED,m,0);
		while((l!=SC_MARK_CIRCLE && l!=SC_MARK_AVAILABLE) && m<i)
		{
			m++;
			l=scintilla_send_message(sci,SCI_MARKERSYMBOLDEFINED,m,0);
		}

		/* if can't move marker forward then don't */
		if(m==i)
			continue;

		/* move marker from i to m */
		/* first make note of line number of marker */
		l=scintilla_send_message(sci,SCI_MARKERNEXT,0,1<<i);
		/* remove old marker */
		scintilla_send_message(sci,SCI_MARKERDELETEALL,i,0);
		scintilla_send_message(sci,SCI_MARKERDEFINE,i,SC_MARK_AVAILABLE);

		/* find bookmark number, put in k */
		fd=GetFileData(doc->file_name);
		for(k=0;k<10;k++)
			if(fd->iBookmarkMarkerUsed[k]==i)
				break;

		/* insert new marker */
		scintilla_send_message(sci,SCI_MARKERDEFINEPIXMAP,m,(glong)(aszMarkerImages[k]));
		scintilla_send_message(sci,SCI_MARKERADD,l,m);

		/* update markers record */
		(*markers)-=1<<i;
		(*markers)|=1<<m;

		/* update record of which bookmark uses which marker */
		fd->iBookmarkMarkerUsed[k]=m;
	}

	/* save record of which markers are being used */
	g_object_set_data(G_OBJECT(sci),"Geany_Numbered_Bookmarks_Used",(gpointer)markers);


	/* m should point to last used marker. Next free marker should lie after this */
	/* find free marker & return it */
	for(;m<25;m++)
	{
		l=scintilla_send_message(sci,SCI_MARKERSYMBOLDEFINED,m,0);
		if(l==SC_MARK_CIRCLE || l==SC_MARK_AVAILABLE)
			return m;
	}	

	/* no empty markers available so return -1 */
	/* in theory shouldn't get here but leave just in case my logic is flawed */
	return -1;
}
Пример #23
0
/* load individual file details. return TRUE if data there, FALSE if there isn't */
static gboolean LoadIndividualSetting(GKeyFile *gkf,gint iNumber,gchar *Filename)
{
	gchar *pcKey=NULL;
	gchar *pcTemp;
	gchar *pcTemp2;
	gint l;
	FileData *fd=NULL;

	/* if loading from local file then no fiilename in file and no number in key*/
	if(iNumber==-1)
	{
		/* get structure to hold filedetails */
		fd=GetFileData(Filename);

		/* create key */
		pcKey=g_strdup("A");
	}
	/* if loading from central file then need to extract filename from A key */
	else
	{
		pcKey=g_strdup_printf("A%d",iNumber);

		/* get filename */
		pcTemp=(gchar*)(utils_get_setting_string(gkf,"FileData",pcKey,NULL));
		/* if null then have reached end of files */
		if(pcTemp==NULL)
		{
			g_free(pcKey);
			return FALSE;
		}

		fd=GetFileData(pcTemp);
		g_free(pcTemp);
	}

	/* get folding data */
	pcKey[0]='B';
	if(bRememberFolds==TRUE)
		fd->pcFolding=(gchar*)(utils_get_setting_string(gkf,"FileData",pcKey,NULL));
	else
		fd->pcFolding=NULL;

	/* load last saved time */
	pcKey[0]='C';
	fd->LastChangedTime=utils_get_setting_integer(gkf,"FileData",pcKey,-1);
	/* get bookmarks */
	pcKey[0]='D';
	pcTemp=(gchar*)(utils_get_setting_string(gkf,"FileData",pcKey,NULL));
	/* pcTemp contains comma seperated numbers (or blank for -1) */
	pcTemp2=pcTemp;
	if(pcTemp!=NULL) for(l=0;l<10;l++)
	{
		/* Bookmark entries are initialized to -1, so only need to parse non-empty slots */
		if(pcTemp2[0]!=',' && pcTemp2[0]!=0)
		{
			fd->iBookmark[l]=strtoll(pcTemp2,NULL,10);
			while(pcTemp2[0]!=0 && pcTemp2[0]!=',')
				pcTemp2++;
		}

		pcTemp2++;
	}
	g_free(pcTemp);

	/* get position in bookmarked lines */
	pcKey[0]='E';
	pcTemp=(gchar*)(utils_get_setting_string(gkf,"FileData",pcKey,NULL));
	/* pcTemp contains comma seperated numbers (or blank for -1) */
	pcTemp2=pcTemp;
	if(pcTemp!=NULL) for(l=0;l<10;l++)
	{
		/* Bookmark entries are initialized to -1, so only need to parse non-empty slots */
		if(pcTemp2[0]!=',' && pcTemp2[0]!=0)
		{
			fd->iBookmarkLinePos[l]=strtoll(pcTemp2,NULL,10);
			while(pcTemp2[0]!=0 && pcTemp2[0]!=',')
				pcTemp2++;
		}

		pcTemp2++;
	}

	/* get non-numbered bookmarks */
	pcKey[0]='F';
	if(bRememberBookmarks==TRUE)
		fd->pcBookmarks=(gchar*)(utils_get_setting_string(gkf,"FileData",pcKey,NULL));
	else
		fd->pcBookmarks=NULL;

	/* free used memory */
	g_free(pcTemp);
	g_free(pcKey);

	return TRUE;
}
Пример #24
0
//-----------------------------------------------------------------------------
// ExtAddIcon()
//   Add the icon as a resource to the specified file.
//-----------------------------------------------------------------------------
static PyObject *ExtAddIcon(
    PyObject *self,                     // passthrough argument
    PyObject *args)                     // arguments
{
    char *executableName, *iconName, *data, *iconData;
    GRPICONDIR *groupIconDir;
    DWORD resourceSize;
    ICONDIR *iconDir;
    BOOL succeeded;
    HANDLE handle;
    int i;

    if (!PyArg_ParseTuple(args, "ss", &executableName, &iconName))
        return NULL;

    // begin updating the executable
    handle = BeginUpdateResource(executableName, FALSE);
    if (!handle) {
        PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
                GetLastError(), executableName);
        return NULL;
    }

    // first attempt to get the data from the icon file
    data = NULL;
    succeeded = TRUE;
    groupIconDir = NULL;
    if (GetFileData(iconName, &data) < 0)
        succeeded = FALSE;
    iconDir = (ICONDIR*) data;

    // next, attempt to add a group icon resource
    if (succeeded) {
        groupIconDir = CreateGroupIconResource(iconDir, &resourceSize);
        if (groupIconDir)
            succeeded = UpdateResource(handle, RT_GROUP_ICON,
                    MAKEINTRESOURCE(1),
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
                    groupIconDir, resourceSize);
        else succeeded = FALSE;
    }

    // next, add each icon as a resource
    if (succeeded) {
        for (i = 0; i < iconDir->idCount; i++) {
            iconData = &data[iconDir->idEntries[i].dwImageOffset];
            resourceSize = iconDir->idEntries[i].dwBytesInRes;
            succeeded = UpdateResource(handle, RT_ICON, MAKEINTRESOURCE(i + 1),
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), iconData,
                    resourceSize);
            if (!succeeded)
                break;
        }
    }

    // finish writing the resource (or discarding the changes upon an error)
    if (!EndUpdateResource(handle, !succeeded)) {
        if (succeeded) {
            succeeded = FALSE;
            PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
                    GetLastError(), executableName);
        }
    }

    // clean up
    if (groupIconDir)
        PyMem_Free(groupIconDir);
    if (data)
        PyMem_Free(data);
    if (!succeeded)
        return NULL;

    Py_INCREF(Py_None);
    return Py_None;
}
Пример #25
0
HRESULT CCommands::XApplicationEvents::BeforeBuildStart()
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	IApplication* pApplication;

	pApplication = m_pCommands->GetApplicationObject();

	CComPtr<IProjects> pIProjects = NULL;
	pApplication->get_Projects((IDispatch **)&pIProjects);

	long					lProjects			= 0;
	CComVariant				varProject			;
	VERIFY_OK( pIProjects->get_Count( &lProjects ) );

	for ( long lProject = 1 ; lProject < lProjects + 1 ; lProject++ )
	{
		varProject = lProject;

		CComPtr< IGenericProject > pIGenericProject;

		VERIFY_OK( pIProjects->Item(varProject, &pIGenericProject));

		if (pIGenericProject)
		{
			CComBSTR bType;
			CString strType;
			pIGenericProject->get_Type(&bType);
			strType = bType;
			if (strType.CompareNoCase(DS_BUILD_PROJECT) != 0) continue;

			CComBSTR bStr;
			pIGenericProject->get_FullName(&bStr);

			CString strProjectName = bStr;
			CString strProjectPath, strRcName, strConfigName;
			UINT uSvnVersion = 0;

			TCHAR sDrive[_MAX_DRIVE] = {0};
			TCHAR sDir[_MAX_DIR] = {0};
			TCHAR sFname[_MAX_FNAME] = {0};
			TCHAR sExt[_MAX_EXT] = {0};

			_tsplitpath(strProjectName, sDrive, sDir, sFname, sExt);

			strProjectPath = CString(sDrive) + CString(sDir);
			strConfigName = CString(sDrive) + CString(sDir) + CString(sFname) + CString(_T(".ini"));

			// 得到配置信息
			CONFIG config;
			COptionDlg::GetConfig(config, strConfigName);

			if (config.bCheckSvn && !config.bCheckSelfUpdata)
			{
				// const svn_version_t *ver = svn_wc_version();
				uSvnVersion = GetWorkSvnVersion(strProjectPath, config.iSvnVersionPath);

				if (uSvnVersion == 0)
				{
					return S_OK;
				}
			}

			CString Data;

			GetFileData(strProjectName, Data);

			if (Data.IsEmpty())
			{
				return S_OK;
			}

			strRcName = GetRegexpData(Data, _T("SOURCE=(?<SCR>.+\\.rc)$|SOURCE=\"(?<SCR>.+\\.rc)\""), MULTILINE | IGNORECASE, "SCR");

			if (strRcName.IsEmpty())
			{
				return S_OK;
			}

			CString strFileVersion, strFileVersionDescribe, strVersion, strVersionDescribe, RcData;
			UINT uFileVer[4], uFileVerDesc[4];
			BOOL bUpdata = FALSE;

			GetFileData(strProjectPath + strRcName, RcData);

			if (RcData.IsEmpty())
			{
				return S_OK;
			}

			// 进行 版本信息 更新
			strVersion = GetRegexpData(RcData, _T(".+VALUE.+\"FileVersion\",.+\"(.+)\""), MULTILINE | IGNORECASE);
			if (!strVersion.IsEmpty())
			{
				sscanf(strVersion, "%d, %d, %d, %d", &uFileVer[0], &uFileVer[1], &uFileVer[2], &uFileVer[3]);
				UpdataVersionInfo(uFileVer, config, uSvnVersion);
				strFileVersion.Format(_T("$1%d, %d, %d, %d\\0$2"),
					uFileVer[0], uFileVer[1], uFileVer[2], uFileVer[3]);

				if (-1 == strFileVersion.Find(strVersion))
				{
					RcData = ReplaceRegexpData(
						RcData,
						_T("(.+VALUE.+\"FileVersion\",.+\").+(\")"),
						MULTILINE | IGNORECASE,
						strFileVersion);
					bUpdata = TRUE;
				}
			}

			strVersion = GetRegexpData(RcData, _T(".+VALUE.+\"ProductVersion\",.+\"(.+)\""), MULTILINE | IGNORECASE);
			if (!strVersion.IsEmpty())
			{
				sscanf(strVersion, "%d, %d, %d, %d", &uFileVer[0], &uFileVer[1], &uFileVer[2], &uFileVer[3]);
				UpdataVersionInfo(uFileVer, config, uSvnVersion);
				strFileVersion.Format(_T("$1%d, %d, %d, %d\\0$2"),
					uFileVer[0], uFileVer[1], uFileVer[2], uFileVer[3]);

				if (-1 == strFileVersion.Find(strVersion))
				{
					RcData = ReplaceRegexpData(
						RcData,
						_T("(.+VALUE.+\"ProductVersion\",.+\").+(\")"),
						MULTILINE | IGNORECASE,
						strFileVersion);
					bUpdata = TRUE;
				}
			}

			strVersionDescribe = GetRegexpData(RcData, _T(".+FILEVERSION[ ]+(.+)"), MULTILINE | IGNORECASE);
			if (!strVersionDescribe.IsEmpty())
			{
				sscanf(strVersionDescribe, "%d,%d,%d,%d", &uFileVerDesc[0], &uFileVerDesc[1], &uFileVerDesc[2], &uFileVerDesc[3]);
				UpdataVersionInfo(uFileVerDesc, config, uSvnVersion);
				strFileVersionDescribe.Format(_T("$1%d,%d,%d,%d"),
					uFileVerDesc[0], uFileVerDesc[1], uFileVerDesc[2], uFileVerDesc[3]);

				if (-1 == strFileVersionDescribe.Find(strVersionDescribe))
				{
					RcData = ReplaceRegexpData(
						RcData,
						_T("(.+FILEVERSION[ ]+).+"),
						MULTILINE | IGNORECASE,
						strFileVersionDescribe);
					bUpdata = TRUE;
				}
			}

			strVersionDescribe = GetRegexpData(RcData, _T(".+ProductVersion[ ]+(.+)"), MULTILINE | IGNORECASE);
			if (!strVersionDescribe.IsEmpty())
			{
				sscanf(strVersionDescribe, "%d,%d,%d,%d", &uFileVerDesc[0], &uFileVerDesc[1], &uFileVerDesc[2], &uFileVerDesc[3]);
				UpdataVersionInfo(uFileVerDesc, config, uSvnVersion);
				strFileVersionDescribe.Format(_T("$1%d,%d,%d,%d"),
					uFileVerDesc[0], uFileVerDesc[1], uFileVerDesc[2], uFileVerDesc[3]);

				if (-1 == strFileVersionDescribe.Find(strVersionDescribe))
				{
					RcData = ReplaceRegexpData(
						RcData,
						_T("(.+ProductVersion[ ]+).+"),
						MULTILINE | IGNORECASE,
						strFileVersionDescribe);
					bUpdata = TRUE;
				}
			}

			if (bUpdata)
			{
				SetFileData(strProjectPath + strRcName, RcData);
			}
		}
	}

	return S_OK;
}
Пример #26
0
HRESULT CCommands::XApplicationEvents::BuildFinish(long nNumErrors, long nNumWarnings)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	if (nNumErrors == 0)
	{
		CComPtr<IGenericProject> pProjectItem = NULL;
		IApplication* pApplication;
		CComPtr<IConfiguration> pConfig = NULL;
		CComBSTR bsBuildName;
		CString strBuildName;

		pApplication = m_pCommands->GetApplicationObject();
		VERIFY_OK(pApplication->get_ActiveProject((IDispatch **)&pProjectItem));
		VERIFY_OK(pApplication->get_ActiveConfiguration((IDispatch **)&pConfig));
		pConfig->get_Name(&bsBuildName);
		strBuildName = bsBuildName;

		if (!pProjectItem)
		{
			return S_OK;
		}

		CComBSTR bsFullName, bsName;
		CString strProjectFullName, strProjectPath,
			strConfigName, strProjectName;
		UINT uSvnVersion = 0;

		pProjectItem->get_FullName(&bsFullName);
		pProjectItem->get_Name(&bsName);

		strProjectFullName = bsFullName;
		strProjectName = bsName;

		TCHAR sDrive[_MAX_DRIVE] = {0};
		TCHAR sDir[_MAX_DIR] = {0};
		TCHAR sFname[_MAX_FNAME] = {0};
		TCHAR sExt[_MAX_EXT] = {0};

		_tsplitpath(strProjectFullName, sDrive, sDir, sFname, sExt);

		strProjectPath = CString(sDrive) + CString(sDir);
		strConfigName = CString(sDrive) + CString(sDir) + CString(sFname) + CString(_T(".ini"));

		CONFIG config;
		COptionDlg::GetConfig(config, strConfigName);

		if (config.bPdbAutoCommit &&
			-1 != config.strCommitList.Find(strBuildName + '#'))
		{
			CString strPdbPath, strOutputDir, strReg, strOutPut, strOutData, strData;
			const TCHAR sReg[] = _T("IF[ ]+\"\\$\\(CFG\\)\" == \"%s\"([^!]+)");
			const TCHAR sRegOutputDir[] = _T("^.+PROP Output_Dir[ ]+\"(.+)\"$");
			const TCHAR sRegPdbPath[] = _T("^# ADD LINK32(?:.+/pdb:\"(?<PDB>[^\"]+)\".+/debug)|(?:.+(?<PDB>/debug))");
			const TCHAR sRegOutPut[] = _T("^# ADD LINK32(?:.+/out:\"(?<OUT>[^\"]+)\")");

			strReg.Format(sReg, strBuildName);

			// Get PDB File Path
			GetFileData(strProjectFullName, strOutData);
			if (strOutData.IsEmpty())
			{
				return S_OK;
			}
			strData = GetRegexpData(strOutData, strReg, MULTILINE | IGNORECASE);
			strOutputDir = GetRegexpData(strData, sRegOutputDir, MULTILINE | IGNORECASE);
			strPdbPath = GetRegexpData(strData, sRegPdbPath, MULTILINE | IGNORECASE, "PDB");
			strOutPut = GetRegexpData(strData, sRegOutPut, MULTILINE | IGNORECASE, "OUT");
			if (strPdbPath.IsEmpty())
			{
				pApplication->PrintToOutputWindow(CComBSTR("Not Find Pdb File Path So Can't Auto Commit PDB\r\n"));
				return S_OK;
			}
			if (!strPdbPath.CompareNoCase(_T("/debug")))
			{
				if (strOutPut.IsEmpty())
				{
					strPdbPath = strOutputDir + '\\' + strProjectName + ".pdb";
				}
				else
				{
					TCHAR ssFname[_MAX_FNAME] = {0};

					_tsplitpath(strOutPut, NULL, NULL, ssFname, NULL);
					strPdbPath = strOutputDir + '\\' + ssFname + ".pdb";
				}
			}

			// Commit PDB File To Server
			MANUALBACKUP ManualBackup = {0};
			ManualBackup.dwMaxSingleFileSize = -1;
			ManualBackup.dwUserData = (DWORD)m_pCommands;
			ManualBackup.pfnCallBackProc = ManualCallBackProc;
			strcpy(ManualBackup.szExtName, "*.pdb");
			ManualBackup.pFileName = new ANSIPATH[1];
			strcpy(ManualBackup.pFileName[0], strProjectPath + strPdbPath);
			ManualBackup.uFileCount = 1;
			strcpy(ManualBackup.szServerIP, config.strPdbServer);
			strcpy(ManualBackup.szReason, _T("PDB:"));
			ManualBackupToServer(&ManualBackup);
			delete []ManualBackup.pFileName;
		}
	}
	return S_OK;
}
Пример #27
0
void CFileManager::SetTransferMode(LPBYTE lpBuffer)
{
	memcpy(&m_nTransferMode, lpBuffer, sizeof(m_nTransferMode));
	GetFileData();
}
Пример #28
0
bool DXShaderCompiler::CompileShader(const std::string& source_file,
                                     const std::string& entry_point,
                                     const char* target,
                                     ShaderOpt opt_level, bool debug,
                                     const ShaderDefine* defines,
                                     size_t num_defines,
                                     std::vector<uint8_t>& output,
                                     YFileUtils::FileEnv* file_env) {
  std::string work_dir = YFileUtils::FilePath::DirPath(source_file);
  const std::vector<uint8_t>* source_data = GetFileData(source_file, file_env);

  std::vector<D3D_SHADER_MACRO> macros;
  for (size_t i = 0; i < num_defines; ++i) {
    macros.push_back({defines[i].define, defines[i].value});
  }
  macros.push_back({NULL, NULL});

  DXIncludeData include_data(work_dir, file_env);

  UINT flags1 = D3DCOMPILE_WARNINGS_ARE_ERRORS;
  switch (opt_level) {
   case kShaderOpt_None: flags1 |= D3DCOMPILE_SKIP_OPTIMIZATION; break;
   case kShaderOpt_Level0: flags1 |= D3DCOMPILE_OPTIMIZATION_LEVEL0; break;
   case kShaderOpt_Level1: flags1 |= D3DCOMPILE_OPTIMIZATION_LEVEL1; break;
   case kShaderOpt_Level2: flags1 |= D3DCOMPILE_OPTIMIZATION_LEVEL2; break;
   case kShaderOpt_Level3: flags1 |= D3DCOMPILE_OPTIMIZATION_LEVEL3; break;
   default:
     std::cerr << "Invalid Shader Opt: " << opt_level << std::endl;
     return false;
  }

  if (debug) {
    flags1 |= D3DCOMPILE_DEBUG;
  }

  ID3DBlob* code;
  ID3DBlob* error_msgs;

  HRESULT ret = D3DCompile2(
      source_data->data(), // in   LPCVOID pSrcData,
      source_data->size(), // in   SIZE_T SrcDataSize,
      source_file.c_str(), // in   LPCSTR pSourceName,
      macros.data(),       // in   const D3D_SHADER_MACRO *pDefines,
      &include_data,       // in   ID3DInclude *pInclude,
      entry_point.c_str(), // in   LPCSTR pEntrypoint,
      target,              // in   LPCSTR pTarget,
      flags1,              // in   UINT Flags1,
      0,                   // in   UINT Flags2,
      0,                   // in   UINT SecondaryDataFlags,
      NULL,                // in   LPCVOID pSecondaryData,
      0,                   // in   SIZE_T SecondaryDataSize,
      &code,               // out  ID3DBlob **ppCode,
      &error_msgs          // out  ID3DBlob **ppErrorMsgs
      );

  if (FAILED(ret)) {
    std::cerr << "[ERROR] "
              << static_cast<const char*>(error_msgs->GetBufferPointer())
              << std::endl;
    return false;
  }

  size_t code_size = code->GetBufferSize();
  output.resize(code_size);
  memcpy(output.data(), code->GetBufferPointer(), code_size);
  return true;
}
/* handler for when a document has been opened
 * this checks to see if a document has been altered since it was last saved in geany (as plugin
 * data may then be out of date for file)
 * It then applies file settings
*/
static void on_document_open(GObject *obj, GeanyDocument *doc, gpointer user_data)
{
	FileData *fd;
	gint i,l=GTK_RESPONSE_ACCEPT,iLineCount;
	ScintillaObject* sci=doc->editor->sci;
	struct stat sBuf;
	GtkWidget *dialog;
	gchar *cFoldData=NULL;
	gchar *pcTemp;
	/* keep compiler happy & initialise iBits: will logically be initiated anyway */
	gint iBits=0,iFlags,iBitCounter;

	/* if saving details in file alongside file we're editing then load it up */
	if(WhereToSaveFileDetails==1)
		LoadLocalFileDetails(doc->file_name);

	/* check to see if file has changed since geany last saved it */
	fd=GetFileData(doc->file_name);
	if(stat(doc->file_name,&sBuf)==0 && fd!=NULL && fd->LastChangedTime!=-1 &&
	   fd->LastChangedTime!=sBuf.st_mtime)
	{
		/* notify user that file has been changed */
		dialog=gtk_message_dialog_new(GTK_WINDOW(geany->main_widgets->window),
		                              GTK_DIALOG_DESTROY_WITH_PARENT,GTK_MESSAGE_ERROR,
		                              GTK_BUTTONS_NONE,
_("'%s' has been edited since it was last saved by geany. Marker positions may be unreliable and w\
ill not be loaded.\nPress Ignore to try an load markers anyway."),doc->file_name);
		gtk_dialog_add_button(GTK_DIALOG(dialog),_("_Okay"),GTK_RESPONSE_OK);
		gtk_dialog_add_button(GTK_DIALOG(dialog),_("_Ignore"),GTK_RESPONSE_REJECT);
		l=gtk_dialog_run(GTK_DIALOG(dialog));
		gtk_widget_destroy(dialog);
	}

	switch(l)
	{
		/* file not changed since Geany last saved it so saved settings should be fine */
		case GTK_RESPONSE_ACCEPT:

			/* get fold settings if present and want to use them */
			if(fd->pcFolding!=NULL && bRememberFolds==TRUE)
			{
				cFoldData=fd->pcFolding;

				/* first ensure fold positions exist */
				scintilla_send_message(sci,SCI_COLOURISE,0,-1);

				iLineCount=scintilla_send_message(sci,SCI_GETLINECOUNT,0,0);

				/* go through lines setting fold status */
				for(i=0,iBitCounter=6;i<iLineCount;i++)
				{
					iFlags=scintilla_send_message(sci,SCI_GETFOLDLEVEL,i,0);
					/* ignore non-folding lines */
					if((iFlags & SC_FOLDLEVELHEADERFLAG)==0)
						continue;

					/* get next 6 fold states if needed */
					if(iBitCounter==6)
					{
						iBitCounter=0;
						iBits=base64_char_to_int[(gint)(*cFoldData)];
						cFoldData++;
					}

					/* set fold if needed */
					if(((iBits>>iBitCounter)&1)==0)
						scintilla_send_message(sci,SCI_TOGGLEFOLD,i,0);

					/* increment counter */
					iBitCounter++;
				}
			}

			break;
		default: /* default - don't try to set markers */
			break;
	}
int FindAtomOffsets( atomOffsetEntry *aoe, UInt64 minOffset, UInt64 maxOffset, 
			long *atomCountOut, atomOffsetEntry **atomOffsetsOut )
{
	int err = noErr;
	long cnt = 0;
	atomOffsetEntry *atomOffsets = nil;
	long max = 20;
	startAtomType startAtom;
	UInt64 largeSize;
	uuidType uuid;
	UInt64 curOffset = minOffset;
	long minAtomSize;
	
	BAILIFNULL( atomOffsets = (atomOffsetEntry *)calloc( max, sizeof(atomOffsetEntry)), allocFailedErr );
	
	while (curOffset< maxOffset) {
		memset(&atomOffsets[cnt], 0, sizeof(atomOffsetEntry));	// clear out entry
		atomOffsets[cnt].offset = curOffset;
		BAILIFERR( GetFileDataN32( aoe, &startAtom.size, curOffset, &curOffset ) );
		BAILIFERR( GetFileDataN32( aoe, &startAtom.type, curOffset, &curOffset ) );
		minAtomSize = sizeof(startAtom);
		atomOffsets[cnt].size = startAtom.size;
		atomOffsets[cnt].type = startAtom.type;
		if (startAtom.size == 1) {
			BAILIFERR( GetFileDataN64( aoe, &largeSize, curOffset, &curOffset ) );
			atomOffsets[cnt].size = largeSize;
			minAtomSize += sizeof(largeSize);
			
		}
		if (startAtom.type == 'uuid') {
			BAILIFERR( GetFileData( aoe, &uuid, curOffset, sizeof(uuid), &curOffset ) );
			//atomOffsets[cnt].uuid = uuid;
			memcpy(&atomOffsets[cnt].uuid, &uuid, sizeof(uuid));
			minAtomSize += sizeof(uuid);
		}
		
		atomOffsets[cnt].atomStartSize = minAtomSize;
		atomOffsets[cnt].maxOffset = atomOffsets[cnt].offset + atomOffsets[cnt].size;
		
		if (atomOffsets[cnt].size == 0) {
			// we go to the end
			atomOffsets[cnt].size = maxOffset - atomOffsets[cnt].offset;
			break;
		}
		
		BAILIF( (atomOffsets[cnt].size < (UInt64)minAtomSize), badAtomSize );
		
		curOffset = atomOffsets[cnt].offset + atomOffsets[cnt].size;
		cnt++;
		if (cnt >= max) {
			max += 20;
			atomOffsets = (atomOffsetEntry *)realloc(atomOffsets, max * sizeof(atomOffsetEntry));
		}
	}

bail:
	if (err) {
		cnt = 0;
		if (atomOffsets) 
			free(atomOffsets);
		atomOffsets = nil;
	}
	*atomCountOut = cnt;
	*atomOffsetsOut = atomOffsets;
	return err;
}