bool Buffer::checkFileState() { //returns true if the status has been changed (it can change into DOC_REGULAR too). false otherwise struct _stat buf; if (_currentStatus == DOC_UNNAMED) //unsaved document cannot change by environment return false; bool isWow64Off = false; NppParameters *pNppParam = NppParameters::getInstance(); if (!PathFileExists(_fullPathName.c_str())) { pNppParam->safeWow64EnableWow64FsRedirection(FALSE); isWow64Off = true; } bool isOK = false; if (_currentStatus != DOC_DELETED && !PathFileExists(_fullPathName.c_str())) //document has been deleted { _currentStatus = DOC_DELETED; _isFileReadOnly = false; _isDirty = true; //dirty sicne no match with filesystem _timeStamp = 0; doNotify(BufferChangeStatus | BufferChangeReadonly | BufferChangeTimestamp); isOK = true; } else if (_currentStatus == DOC_DELETED && PathFileExists(_fullPathName.c_str())) { //document has returned from its grave if (!generic_stat(_fullPathName.c_str(), &buf)) { _isFileReadOnly = (bool)(!(buf.st_mode & _S_IWRITE)); _currentStatus = DOC_MODIFIED; _timeStamp = buf.st_mtime; doNotify(BufferChangeStatus | BufferChangeReadonly | BufferChangeTimestamp); isOK = true; } } else if (!generic_stat(_fullPathName.c_str(), &buf)) { int mask = 0; //status always 'changes', even if from modified to modified bool isFileReadOnly = (bool)(!(buf.st_mode & _S_IWRITE)); if (isFileReadOnly != _isFileReadOnly) { _isFileReadOnly = isFileReadOnly; mask |= BufferChangeReadonly; } if (_timeStamp != buf.st_mtime) { _timeStamp = buf.st_mtime; mask |= BufferChangeTimestamp; _currentStatus = DOC_MODIFIED; mask |= BufferChangeStatus; //status always 'changes', even if from modified to modified } if (mask != 0) { doNotify(mask); isOK = true; } isOK = false; } if (isWow64Off) { pNppParam->safeWow64EnableWow64FsRedirection(TRUE); isWow64Off = false; } return isOK; }
void COpenDlg::OnOK() { UpdateData(TRUE); bool bUDiffOnClipboard = false; if (OpenClipboard()) { UINT enumFormat = 0; do { if (enumFormat == m_cFormat) { bUDiffOnClipboard = true; } } while((enumFormat = EnumClipboardFormats(enumFormat))!=0); CloseClipboard(); } if (GetDlgItem(IDC_BASEFILEEDIT)->IsWindowEnabled()) { m_sUnifiedDiffFile.Empty(); m_sPatchDirectory.Empty(); } else { m_sBaseFile.Empty(); m_sYourFile.Empty(); m_sTheirFile.Empty(); } UpdateData(FALSE); CString sFile; if (!m_sUnifiedDiffFile.IsEmpty()) if (!PathFileExists(m_sUnifiedDiffFile)) sFile = m_sUnifiedDiffFile; if (!m_sPatchDirectory.IsEmpty()) if (!PathFileExists(m_sPatchDirectory)) sFile = m_sPatchDirectory; if (!m_sBaseFile.IsEmpty()) if (!PathFileExists(m_sBaseFile)) sFile = m_sBaseFile; if (!m_sYourFile.IsEmpty()) if (!PathFileExists(m_sYourFile)) sFile = m_sYourFile; if (!m_sTheirFile.IsEmpty()) if (!PathFileExists(m_sTheirFile)) sFile = m_sTheirFile; if (bUDiffOnClipboard && m_bFromClipboard) { if (OpenClipboard()) { HGLOBAL hglb = GetClipboardData(m_cFormat); LPCSTR lpstr = (LPCSTR)GlobalLock(hglb); DWORD len = GetTempPath(0, NULL); TCHAR * path = new TCHAR[len+1]; TCHAR * tempF = new TCHAR[len+100]; GetTempPath (len+1, path); GetTempFileName (path, TEXT("tsm"), 0, tempF); CString sTempFile = CString(tempF); delete [] path; delete [] tempF; FILE * outFile; size_t patchlen = strlen(lpstr); _tfopen_s(&outFile, sTempFile, _T("wb")); if(outFile) { size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile); if (size < patchlen) bUDiffOnClipboard = false; else { m_sUnifiedDiffFile = sTempFile; UpdateData(FALSE); sFile.Empty(); } fclose(outFile); } GlobalUnlock(hglb); CloseClipboard(); } } if (!sFile.IsEmpty()) { CString sErr; sErr.Format(IDS_ERR_PATCH_INVALIDPATCHFILE, (LPCTSTR)sFile); MessageBox(sErr, NULL, MB_ICONERROR); return; } CDialog::OnOK(); }
BOOL CExportDlg::OnInitDialog() { CResizableStandAloneDialog::OnInitDialog(); CAppUtils::MarkWindowAsUnpinnable(m_hWnd); ExtendFrameIntoClientArea(IDC_REVISIONGROUP); m_aeroControls.SubclassOkCancelHelp(this); m_sExportDirOrig = m_strExportDirectory; m_bAutoCreateTargetName = !(PathIsDirectoryEmpty(m_sExportDirOrig) || !PathFileExists(m_sExportDirOrig)); AdjustControlSize(IDC_NOEXTERNALS); AdjustControlSize(IDC_IGNOREKEYWORDS); AdjustControlSize(IDC_REVISION_HEAD); AdjustControlSize(IDC_REVISION_N); AddAnchor(IDC_REPOGROUP, TOP_LEFT, TOP_RIGHT); AddAnchor(IDC_REPOLABEL, TOP_LEFT); AddAnchor(IDC_URLCOMBO, TOP_LEFT, TOP_RIGHT); AddAnchor(IDC_BROWSE, TOP_RIGHT); AddAnchor(IDC_EXPORT_CHECKOUTDIR, TOP_LEFT); AddAnchor(IDC_CHECKOUTDIRECTORY, TOP_LEFT, TOP_RIGHT); AddAnchor(IDC_CHECKOUTDIRECTORY_BROWSE, TOP_RIGHT); AddAnchor(IDC_DEPTH, TOP_LEFT, TOP_RIGHT); AddAnchor(IDC_NOEXTERNALS, TOP_LEFT); AddAnchor(IDC_IGNOREKEYWORDS, TOP_LEFT); AddAnchor(IDC_EOLLABEL, TOP_LEFT); AddAnchor(IDC_EOLCOMBO, TOP_LEFT); AddAnchor(IDC_REVISIONGROUP, TOP_LEFT, BOTTOM_RIGHT); AddAnchor(IDC_REVISION_HEAD, TOP_LEFT); AddAnchor(IDC_REVISION_N, TOP_LEFT); AddAnchor(IDC_REVISION_NUM, TOP_LEFT); AddAnchor(IDC_SHOW_LOG, TOP_LEFT); AddAnchor(IDOK, BOTTOM_RIGHT); AddAnchor(IDCANCEL, BOTTOM_RIGHT); AddAnchor(IDHELP, BOTTOM_RIGHT); // save the provided url since the url combo // will change that below CString origurl = m_URL; m_URLCombo.SetURLHistory(true, true); m_URLCombo.LoadHistory(L"Software\\TortoiseSVN\\History\\repoURLS", L"url"); m_URLCombo.SetCurSel(0); m_depthCombo.AddString(CString(MAKEINTRESOURCE(IDS_SVN_DEPTH_INFINITE))); m_depthCombo.AddString(CString(MAKEINTRESOURCE(IDS_SVN_DEPTH_IMMEDIATE))); m_depthCombo.AddString(CString(MAKEINTRESOURCE(IDS_SVN_DEPTH_FILES))); m_depthCombo.AddString(CString(MAKEINTRESOURCE(IDS_SVN_DEPTH_EMPTY))); m_depthCombo.SetCurSel(0); // set radio buttons according to the revision SetRevision(Revision); m_editRevision.SetWindowText(L""); if (!origurl.IsEmpty()) m_URLCombo.SetWindowText(origurl); else { // if there is an url on the clipboard, use that url as the default. CAppUtils::AddClipboardUrlToWindow(m_URLCombo.GetSafeHwnd()); } GetDlgItem(IDC_BROWSE)->EnableWindow(!m_URLCombo.GetString().IsEmpty()); m_tooltips.AddTool(IDC_CHECKOUTDIRECTORY, IDS_CHECKOUT_TT_DIR); m_tooltips.AddTool(IDC_EOLCOMBO, IDS_EXPORT_TT_EOL); SHAutoComplete(GetDlgItem(IDC_CHECKOUTDIRECTORY)->m_hWnd, SHACF_FILESYSTEM); // fill the combobox with the choices of eol styles m_eolCombo.AddString(L"default"); m_eolCombo.AddString(L"CRLF"); m_eolCombo.AddString(L"LF"); m_eolCombo.AddString(L"CR"); m_eolCombo.SelectString(0, L"default"); if (!Revision.IsHead()) { // if the revision is not HEAD, change the radio button and // fill in the revision in the edit box CString temp; temp.Format(L"%ld", (LONG)Revision); m_editRevision.SetWindowText(temp); CheckRadioButton(IDC_REVISION_HEAD, IDC_REVISION_N, IDC_REVISION_N); } DialogEnableWindow(IDOK, !m_strExportDirectory.IsEmpty()); if ((m_pParentWnd==NULL)&&(GetExplorerHWND())) CenterWindow(CWnd::FromHandle(GetExplorerHWND())); EnableSaveRestore(L"ExportDlg"); return TRUE; }
bool GetFileCRC32(const TCHAR* pszFileName, unsigned& uCrc32) { bool bRetCode = false; HANDLE hFileMap = NULL; HANDLE hFile = INVALID_HANDLE_VALUE; void* pView = NULL; DWORD dwFileSize = 0; if(NULL == pszFileName) goto Exit0; uCrc32 = 0; //Check file exist if(!PathFileExists(pszFileName)) goto Exit0; //Create file hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if(INVALID_HANDLE_VALUE == hFile) goto Exit0; //Get size of file dwFileSize = GetFileSize(hFile, NULL); if(INVALID_FILE_SIZE == dwFileSize) goto Exit0; //Create file mapping hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, dwFileSize, NULL ); if(NULL == hFileMap) goto Exit0; pView = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, dwFileSize ); if(NULL == pView) goto Exit0; //Compute the CRC32 value of file uCrc32 = CRC32(uCrc32, pView, dwFileSize); bRetCode = true; Exit0: if(NULL != pView) { UnmapViewOfFile(pView); pView = NULL; } if(NULL != hFileMap) { CloseHandle(hFileMap); hFileMap = NULL; } if(hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } return bRetCode; }
BOOL CPOFile::SaveFile(LPCTSTR szPath, LPCTSTR lpszHeaderFile) { //since stream classes still expect the filepath in char and not wchar_t //we need to convert the filepath to multibyte char filepath[MAX_PATH + 1] = { 0 }; int nEntries = 0; SecureZeroMemory(filepath, sizeof(filepath)); WideCharToMultiByte(CP_ACP, NULL, szPath, -1, filepath, _countof(filepath)-1, NULL, NULL); std::wofstream File; File.imbue(std::locale(std::locale(), new utf8_conversion())); File.open(filepath, std::ios_base::binary); if ((lpszHeaderFile)&&(lpszHeaderFile[0])&&(PathFileExists(lpszHeaderFile))) { // read the header file and save it to the top of the pot file std::wifstream inFile; inFile.imbue(std::locale(std::locale(), new utf8_conversion())); inFile.open(lpszHeaderFile, std::ios_base::binary); wchar_t ch; while(inFile && inFile.get(ch)) File.put(ch); inFile.close(); } else { File << L"# SOME DESCRIPTIVE TITLE.\n"; File << L"# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n"; File << L"# This file is distributed under the same license as the PACKAGE package.\n"; File << L"# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.\n"; File << L"#\n"; File << L"#, fuzzy\n"; File << L"msgid \"\"\n"; File << L"msgstr \"\"\n"; File << L"\"Project-Id-Version: PACKAGE VERSION\\n\"\n"; File << L"\"Report-Msgid-Bugs-To: \\n\"\n"; File << L"\"POT-Creation-Date: 1900-01-01 00:00+0000\\n\"\n"; File << L"\"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n\"\n"; File << L"\"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n\"\n"; File << L"\"Language-Team: LANGUAGE <*****@*****.**>\\n\"\n"; File << L"\"MIME-Version: 1.0\\n\"\n"; File << L"\"Content-Type: text/plain; charset=UTF-8\\n\"\n"; File << L"\"Content-Transfer-Encoding: 8bit\\n\"\n\n"; } File << L"\n"; File << L"# msgid/msgstr fields for Accelerator keys\n"; File << L"# Format is: \"ID:xxxxxx:VACS+X\" where:\n"; File << L"# ID:xxxxx = the menu ID corresponding to the accelerator\n"; File << L"# V = Virtual key (or blank if not used) - nearly always set!\n"; File << L"# A = Alt key (or blank if not used)\n"; File << L"# C = Ctrl key (or blank if not used)\n"; File << L"# S = Shift key (or blank if not used)\n"; File << L"# X = upper case character\n"; File << L"# e.g. \"V CS+Q\" == Ctrl + Shift + 'Q'\n"; File << L"\n"; File << L"# ONLY Accelerator Keys with corresponding alphanumeric characters can be\n"; File << L"# updated i.e. function keys (F2), special keys (Delete, HoMe) etc. will not.\n"; File << L"\n"; File << L"# ONLY change the msgstr field. Do NOT change any other.\n"; File << L"# If you do not want to change an Accelerator Key, copy msgid to msgstr\n"; File << L"\n"; for (std::map<std::wstring, RESOURCEENTRY>::iterator I = this->begin(); I != this->end(); ++I) { std::wstring s = I->first; s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<wint_t, int>(iswspace)))); if (s.empty()) continue; RESOURCEENTRY entry = I->second; for (std::vector<std::wstring>::iterator II = entry.automaticcomments.begin(); II != entry.automaticcomments.end(); ++II) { File << II->c_str() << L"\n"; } for (std::vector<std::wstring>::iterator II = entry.translatorcomments.begin(); II != entry.translatorcomments.end(); ++II) { File << II->c_str() << L"\n"; } if (!I->second.resourceIDs.empty()) { File << L"#. Resource IDs: ("; std::set<INT_PTR>::const_iterator II = I->second.resourceIDs.begin(); File << (*II); ++II; while (II != I->second.resourceIDs.end()) { File << L", "; File << (*II); ++II; }; File << L")\n"; } if (I->second.flag.length() > 0) File << (I->second.flag.c_str()) << L"\n"; File << (L"msgid \"") << (I->first.c_str()) << L"\"\n"; File << (L"msgstr \"") << (I->second.msgstr.c_str()) << L"\"\n\n"; nEntries++; } File.close(); if (!m_bQuiet) _ftprintf(stdout, L"File %s saved, containing %d entries\n", szPath, nEntries); return TRUE; }
CStatusCacheEntry CCachedDirectory::GetStatusFromCache(const CTGitPath& path, bool bRecursive) { if(path.IsDirectory()) { // We don't have directory status in our cache // Ask the directory if it knows its own status CCachedDirectory * dirEntry = CGitStatusCache::Instance().GetDirectoryCacheEntry(path); if( dirEntry) { if (dirEntry->IsOwnStatusValid()) return dirEntry->GetOwnStatus(bRecursive); else { /* cache have outof date, need crawl again*/ /*AutoLocker lock(dirEntry->m_critSec); ChildDirStatus::const_iterator it; for(it = dirEntry->m_childDirectories.begin(); it != dirEntry->m_childDirectories.end(); ++it) { CGitStatusCache::Instance().AddFolderForCrawling(it->first); }*/ CGitStatusCache::Instance().AddFolderForCrawling(path); /*Return old status during crawling*/ return dirEntry->GetOwnStatus(bRecursive); } } else { CGitStatusCache::Instance().AddFolderForCrawling(path); } return CStatusCacheEntry(); } else { //All file ignored if under ignore directory if (m_ownStatus.GetEffectiveStatus() == git_wc_status_ignored) return CStatusCacheEntry(git_wc_status_ignored); if (m_ownStatus.GetEffectiveStatus() == git_wc_status_unversioned) return CStatusCacheEntry(git_wc_status_unversioned); // Look up a file in our own cache AutoLocker lock(m_critSec); CString strCacheKey = GetCacheKey(path); CacheEntryMap::iterator itMap = m_entryCache.find(strCacheKey); if(itMap != m_entryCache.end()) { // We've hit the cache - check for timeout if(!itMap->second.HasExpired((long)GetTickCount())) { if(itMap->second.DoesFileTimeMatch(path.GetLastWriteTime())) { if ((itMap->second.GetEffectiveStatus()!=git_wc_status_missing)||(!PathFileExists(path.GetWinPath()))) { // Note: the filetime matches after a modified has been committed too. // So in that case, we would return a wrong status (e.g. 'modified' instead // of 'normal') here. return itMap->second; } } } } CGitStatusCache::Instance().AddFolderForCrawling(path.GetContainingDirectory()); return CStatusCacheEntry(); } }
CBrowseFolder::retVal CBrowseFolder::Show(HWND parent, CString& path, const CString& sDefaultPath /* = CString() */) { retVal ret = OK; //assume OK m_sDefaultPath = sDefaultPath; if (m_sDefaultPath.IsEmpty() && !path.IsEmpty()) { while (!PathFileExists(path) && !path.IsEmpty()) { CString p = path.Left(path.ReverseFind(L'\\')); if ((p.GetLength() == 2) && (p[1] == L':')) { p += L"\\"; if (p.Compare(path) == 0) p.Empty(); } if (p.GetLength() < 2) p.Empty(); path = p; } // if the result path already contains a path, use that as the default path m_sDefaultPath = path; } HRESULT hr; // Create a new common open file dialog IFileOpenDialog* pfd = NULL; hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd)); if (SUCCEEDED(hr)) { // Set the dialog as a folder picker DWORD dwOptions; if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions))) { hr = pfd->SetOptions(dwOptions | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); } // Set a title if (SUCCEEDED(hr)) { TCHAR * nl = _tcschr(m_title, '\n'); if (nl) *nl = 0; pfd->SetTitle(m_title); } // set the default folder if (SUCCEEDED(hr)) { typedef HRESULT(WINAPI *SHCIFPN)(PCWSTR pszPath, IBindCtx * pbc, REFIID riid, void ** ppv); SHCIFPN pSHCIFPN = hLib.GetProcAddress<SHCIFPN>("SHCreateItemFromParsingName"); if (pSHCIFPN) { IShellItem *psiDefault = 0; hr = pSHCIFPN(m_sDefaultPath, NULL, IID_PPV_ARGS(&psiDefault)); if (SUCCEEDED(hr)) { hr = pfd->SetFolder(psiDefault); psiDefault->Release(); } } } // Show the open file dialog if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(parent))) { // Get the selection from the user IShellItem* psiResult = NULL; hr = pfd->GetResult(&psiResult); if (SUCCEEDED(hr)) { PWSTR pszPath = NULL; hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath); if (SUCCEEDED(hr)) { path = pszPath; CoTaskMemFree(pszPath); } psiResult->Release(); } else ret = CANCEL; } else ret = CANCEL; pfd->Release(); } else { BROWSEINFO browseInfo = {}; browseInfo.hwndOwner = parent; browseInfo.pidlRoot = m_root; browseInfo.pszDisplayName = m_displayName; browseInfo.lpszTitle = m_title; browseInfo.ulFlags = m_style; browseInfo.lParam = reinterpret_cast<LPARAM>(this); PCIDLIST_ABSOLUTE itemIDList = SHBrowseForFolder(&browseInfo); //is the dialog canceled? if (!itemIDList) ret = CANCEL; if (ret != CANCEL) { if (!SHGetPathFromIDList(itemIDList, path.GetBuffer(MAX_PATH))) // MAX_PATH ok. Explorer can't handle paths longer than MAX_PATH. ret = NOPATH; path.ReleaseBuffer(); CoTaskMemFree((LPVOID)itemIDList); } } return ret; }
bool CTGitPath::HasStashDir() const { CString topdir; if(!GitAdminDir::HasAdminDir(GetWinPathString(),&topdir)) { return false; } CString dotGitPath; GitAdminDir::GetAdminDirPath(topdir, dotGitPath); if (!!PathFileExists(dotGitPath + _T("refs\\stash"))) return true; CAutoFile hfile = CreateFile(dotGitPath + _T("packed-refs"), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (!hfile) return false; DWORD filesize = ::GetFileSize(hfile, nullptr); if (filesize == 0) return false; DWORD size = 0; auto buff = std::make_unique<char[]>(filesize + 1); ReadFile(hfile, buff.get(), filesize, &size, nullptr); buff.get()[filesize] = '\0'; if (size != filesize) return false; for (DWORD i = 0; i < filesize;) { if (buff[i] == '#' || buff[i] == '^') { while (buff[i] != '\n') { ++i; if (i == filesize) break; } ++i; } if (i >= filesize) break; while (buff[i] != ' ') { ++i; if (i == filesize) break; } ++i; if (i >= filesize) break; if (i <= filesize - 10 && (buff[i + 10] == '\n' || buff[i + 10] == '\0') && !strncmp("refs/stash", buff.get() + i, 10)) return true; while (buff[i] != '\n') { ++i; if (i == filesize) break; } while (buff[i] == '\n') { ++i; if (i == filesize) break; } } return false; }
BOOL CSmtShell::IsInCtr() { m_FathAddFlag = FALSE; m_CouldAdd = TRUE; if(IsFatherAdd()){ m_FathAddFlag = TRUE; for(int i = 0; i < m_NumFiles; i++){ string StatusStr; string StatusCmd = "svn status "; StatusCmd += "\""; StatusCmd += m_szFile[i]; StatusCmd += "\""; StatusStr += ExeCmd((char *)StatusCmd.c_str()); if(0 == StatusStr.find("A ")){ m_InCtrNo[m_InCtrCount] = i; m_InCtrCount++; m_CouldAdd = FALSE; } } return FALSE; } char FilePath[255]; memset(FilePath, 0, sizeof(FilePath)); sprintf(FilePath, "%s\\SmtRec.dat", m_EnvPath); FILE *fp = fopen(FilePath, "r"); if(NULL == fp){ return FALSE; } fseek(fp, 0, SEEK_END); long fileLength = ftell(fp); int CycleTimes = (int)fileLength/255 - 1; fseek(fp, 255, SEEK_SET); m_RecFileLen = fileLength; char RecPath[255]; char TmpPath[255]; m_InCtrCount = 0; memset(m_InCtrNo, 0, sizeof(m_InCtrNo)); BOOL TFlag = FALSE; for(int i = 0; i < m_NumFiles; i++){ int PathLen = strlen(m_szFile[i]); int k = 0; for(k = 0; k < CycleTimes; k++){ memset(RecPath, 0, sizeof(RecPath)); memset(TmpPath, 0, sizeof(TmpPath)); fread(RecPath, 1, sizeof(RecPath), fp); sprintf(TmpPath, "%s%s", m_EnvPath, RecPath); if((PathLen == strlen(TmpPath)) && (!memcmp(m_szFile[i], TmpPath, PathLen))){ break; } } if(k < CycleTimes){ m_InCtrNo[m_InCtrCount] = i; m_InCtrCount++; TFlag = TRUE; /*if(!m_AddFlag){ if(FILE_ATTRIBUTE_DIRECTORY != GetFileAttributes(m_szFile[i])){ string StatusStr; string StatusCmd = "svn status "; StatusCmd += "\""; StatusCmd += m_szFile[i]; StatusCmd += "\""; StatusStr += ExeCmd((char *)StatusCmd.c_str()); if(StatusStr.npos != StatusStr.find("A ")){ m_AddFlag = TRUE; } } }*/ } else{ string StatusStr; string StatusCmd = "svn status "; StatusCmd += "\""; StatusCmd += m_szFile[i]; StatusCmd += "\""; StatusStr += ExeCmd((char *)StatusCmd.c_str()); if(0 == StatusStr.find("A ")){ m_InCtrNo[m_InCtrCount] = i; m_InCtrCount++; TFlag = TRUE; m_AddFlag = TRUE; } } fseek(fp, 255, SEEK_SET); } fclose(fp); if(TFlag){ return TRUE; } for(int i = 0; i < m_NumFiles; i++){ if((!strcmp(m_EnvPath, m_szFile[i])) && m_RecFileLen > 255){ return TRUE; } } if(1 == m_NumFiles){ if(!strcmp(m_EnvPath, m_szFile[0])){ char SvnPath[255]; memset(SvnPath, 0, sizeof(SvnPath)); sprintf(SvnPath, "%s\\.svn", m_EnvPath); if(PathFileExists(SvnPath)){ return TRUE; } } } return FALSE; }
int CDAO::IsDBFileExist() { int bIsExist = PathFileExists(GetInstallFilePath("BussinessLog.accdb")); return bIsExist; }
int Title::Execute() { if (!bSequenceChangeng){ //上下の項目選択 //上 if (CheckStateKey(KEY_INPUT_UP) == 1 || (CheckStateKey(KEY_INPUT_UP) > 15 && CheckStateKey(KEY_INPUT_UP) % 10 == 0)){ //移動先がLoadなら if (Selecting == TIT_EXIT){ //セーブファイルが有れば if (PathFileExists("savedata.sav")){ Selecting = (Selecting + 2) % 3; } //なければ飛ばす else Selecting = TIT_START; } else Selecting = (Selecting + 2) % 3; return MAIN_SEQ_CONTINUE; } if (CheckStateKey(KEY_INPUT_DOWN) == 1 || (CheckStateKey(KEY_INPUT_DOWN) > 15 && CheckStateKey(KEY_INPUT_DOWN) % 10 == 0)){ //移動先がLoadなら if (Selecting == TIT_START){ //セーブファイルが有れば if (PathFileExists("savedata.sav")){ Selecting = (Selecting + 1) % 3; } //なければ飛ばす else Selecting = TIT_EXIT; } else Selecting = (Selecting + 1) % 3; return MAIN_SEQ_CONTINUE; } //決定キー if (CheckStateKey(KEY_INPUT_Z) == 1){ bSequenceChangeng = true; return MAIN_SEQ_CONTINUE; } } else { ++ChangeCounter; if (ChangeCounter == ChangeFrame){ switch (Selecting){ case TIT_START: return MAIN_SEQ_PROLOGUE; break; case TIT_LOAD: return MAIN_SEQ_GAMEMAIN; break; //終了 case TIT_EXIT: return MAIN_SEQ_EXIT; break; default: MessageBox(NULL, "不正なシーケンスが返されました。", "error", MB_OK); break; } } } MainCounter++; return MAIN_SEQ_CONTINUE; }
// Uploads the PNG file to Gyazo BOOL uploadFile(HWND hwnd, LPCTSTR fileName, BOOL isPng) { const int nSize = 256; LPCTSTR DEFAULT_UPLOAD_SERVER = _T("upload.gyazo.com"); LPCTSTR DEFAULT_UPLOAD_PATH = _T("/upload.cgi"); LPCTSTR DEFAULT_UPLOAD_TOKEN = _T(""); //LPCTSTR DEFAULT_USER_AGENT = _T("User-Agent: Gyazowin/1.0\r\n"); const int DEFAULT_UPLOAD_SERVER_PORT = INTERNET_DEFAULT_HTTP_PORT; TCHAR upload_server[nSize]; TCHAR upload_path[nSize]; TCHAR upload_token[nSize]; //TCHAR ua[nSize]; lstrcpy(upload_server, DEFAULT_UPLOAD_SERVER); lstrcpy(upload_path, DEFAULT_UPLOAD_PATH); lstrcpy(upload_token, DEFAULT_UPLOAD_TOKEN); //lstrcpy(ua, DEFAULT_USER_AGENT); int upload_server_port = DEFAULT_UPLOAD_SERVER_PORT; TCHAR runtime_path[MAX_PATH+1]; TCHAR runtime_dirname[MAX_PATH+1]; TCHAR config_file[MAX_PATH+1]; if (0 != ::GetModuleFileName(NULL, runtime_path, MAX_PATH)) { TCHAR tmp[MAX_PATH+1]; _tsplitpath_s(runtime_path, tmp, runtime_dirname, tmp, tmp); } lstrcpy(config_file, runtime_dirname); lstrcat(config_file, _T("\\gyazo.ini")); if (PathFileExists(config_file)) { LPCTSTR SECTION_NAME = _T("gyazo"); GetPrivateProfileString(SECTION_NAME, _T("server"), DEFAULT_UPLOAD_SERVER, upload_server, sizeof(upload_server), config_file); GetPrivateProfileString(SECTION_NAME, _T("path"), DEFAULT_UPLOAD_PATH, upload_path, sizeof(upload_path), config_file); GetPrivateProfileString(SECTION_NAME, _T("token"), DEFAULT_UPLOAD_TOKEN, upload_token, sizeof(upload_token), config_file); //GetPrivateProfileString(SECTION_NAME, _T("user_agent"), DEFAULT_USER_AGENT, ua, sizeof(ua), config_file); upload_server_port = GetPrivateProfileInt(SECTION_NAME, _T("port"), DEFAULT_UPLOAD_SERVER_PORT, config_file); } const char* sBoundary = "----BOUNDARYBOUNDARY----"; // boundary const char sCrLf[] = { 0xd, 0xa, 0x0 }; // 改行(CR+LF) TCHAR szHeader[200]; StringCchPrintf(szHeader, 200, TEXT("Auth-Token: %s\r\nContent-type: multipart/form-data; boundary=----BOUNDARYBOUNDARY----"), upload_token); std::ostringstream buf; // 送信メッセージ wchar_t fname[_MAX_FNAME]; wchar_t ext[_MAX_EXT]; _wsplitpath(fileName, NULL, NULL, fname, ext ); std::string data = (isPng) ? "imagedata" : "data"; LPCTSTR file = (isPng) ? _T("gyazo") : wcsncat(fname, ext, _MAX_FNAME); size_t size = wcstombs(NULL, file, 0); char* CharStr = new char[size + 1]; wcstombs(CharStr, file, size + 1); // -- "imagedata" part buf << "--"; buf << sBoundary; buf << sCrLf; buf << "content-disposition: form-data; name=\""; buf << data; buf << "\"; filename=\""; buf << CharStr; buf << "\""; buf << sCrLf; //buf << "Content-type: image/png"; // 一応 //buf << sCrLf; buf << sCrLf; // 本文: PNG ファイルを読み込む std::ifstream png; png.open(fileName, std::ios::binary); if (png.fail()) { MessageBox(hwnd, _T("PNG open failed"), szTitle, MB_ICONERROR | MB_OK); png.close(); return FALSE; } buf << png.rdbuf(); // read all & append to buffer png.close(); // 最後 buf << sCrLf; buf << "--"; buf << sBoundary; buf << "--"; buf << sCrLf; // メッセージ完成 std::string oMsg(buf.str()); // WinInet を準備 (proxy は 規定の設定を利用) HINTERNET hSession = InternetOpen(_T("Gyazowin/1.0"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(NULL == hSession) { LastErrorMessageBox(hwnd, _T("Cannot configure wininet.")); return FALSE; } // 接続先 HINTERNET hConnection = InternetConnect(hSession, upload_server, upload_server_port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL); if(NULL == hConnection) { LastErrorMessageBox(hwnd, _T("Cannot initiate connection.")); InternetCloseHandle(hSession); return FALSE; } // 要求先の設定 HINTERNET hRequest = HttpOpenRequest(hConnection, _T("POST"), upload_path, NULL, NULL, NULL, INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, NULL); if(NULL == hRequest) { LastErrorMessageBox(hwnd, _T("Cannot compose post request.")); InternetCloseHandle(hConnection); InternetCloseHandle(hSession); return FALSE; } // 要求を送信 BOOL bSuccess = FALSE; if (HttpSendRequest(hRequest, szHeader, lstrlen(szHeader), (LPVOID)oMsg.c_str(), (DWORD) oMsg.length())) { // 要求は成功 DWORD resLen = 8; TCHAR resCode[8]; // status code を取得 if(!HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE, resCode, &resLen, 0)) { LastErrorMessageBox(hwnd, _T("Cannot get status code.")); InternetCloseHandle(hRequest); InternetCloseHandle(hConnection); InternetCloseHandle(hSession); return FALSE; } // 結果 (URL) を読取る DWORD len; char resbuf[1024]; std::string result; // そんなに長いことはないけどまあ一応 while (InternetReadFile(hRequest, (LPVOID)resbuf, 1024, &len) && len != 0) { result.append(resbuf, len); } // 取得結果は NULL terminate されていないので result += '\0'; if( _ttoi(resCode) != 200 ) { // upload 失敗 (status error) TCHAR errorBuf[200]; StringCchPrintf(errorBuf, 200, TEXT("Cannot upload the image. Error %s "),resCode); std::wstring stemp = std::wstring(result.begin(), result.end()); StringCchCat(errorBuf, 200, (LPTSTR)stemp.c_str()); MessageBox(hwnd, errorBuf, szTitle, MB_ICONERROR | MB_OK); } else { // upload succeeded // クリップボードに URL をコピー setClipBoardText(result.c_str()); // URL を起動 execUrl(result.c_str()); bSuccess = TRUE; } } else { // アップロード失敗... LastErrorMessageBox(hwnd, _T("Cannot connect to the server.")); } // ハンドルクローズ InternetCloseHandle(hRequest); InternetCloseHandle(hConnection); InternetCloseHandle(hSession); return bSuccess; }
void CDialogResultNodeOri::OnBnClickedButtonNodeorihangquery() { CLineComputeView* pView = (CLineComputeView*)((CMainFrame *)AfxGetMainWnd())->GetActiveView(); int span = m_resultSpan.GetCurSel() + 1; int hang = m_spanLeftRight.GetCurSel(); float x=0, y=0, z=0, x0=0, y0=0, z0=0; int spanRight; CString fileName1, fileName2, fileName3, strTmp, line; CStdioFile file; switch (pView->m_data->m_windType) { case 0:default: fileName1 = fileName2 = fileName3 = _T("jf"); break; case 1: fileName1 = fileName2 = fileName3 = _T("zf"); break; case 2: fileName1 = fileName2 = fileName3 = _T("mdf"); break; } /*提取挂点张力*/ fileName1 += _T("_span"); strTmp.Format(_T("%d"), span); fileName1 += strTmp; strTmp = 0==hang? _T("_l_"): _T("_r_"); fileName1 += strTmp; fileName1 += _T("hang_force.dat"); CString path1 = pView->m_data->m_workspace + _T("\\result\\") + fileName1; if(!PathFileExists(path1)) { MessageBox(_T("结果文件") + path1 + _T("不存在!"), MsgCaption); return ; } file.Open(path1, CStdioFile::modeRead); while(file.ReadString(strTmp)) { if(strTmp.GetLength()>0) line = strTmp; } file.Close(); //挂点力须乘以导线分裂数 float hangForce = abs(_ttof(line.Mid(15, 15).TrimLeft()))*pView->m_data->m_dxSplitNum; strTmp.Format(_T("%.5f"), hangForce); m_nodeForce.SetWindowText(strTmp); /*提取挂点不平衡张力及挂点坐标*/ if((pView->m_data->m_dxSpanNum==span&&1==hang) || (1==span&&0==hang)){ //第一跨左挂点或最后一跨右挂点 m_nodeUnbalancedForce.SetWindowText(_T("该挂点无不平衡张力")); if(1==span&&0==hang) { x0 = y0 = 0; } if(pView->m_data->m_dxSpanNum==span&&1==hang) { for(int k=0; k<pView->m_data->m_dxSpanNum; k++) { x0 += pView->m_data->m_dxDjgc[k].dj; y0 += pView->m_data->m_dxDjgc[k].gc; } } } else { fileName2 += _T("_span"); fileName3 += _T("_span"); if(0 == hang) //左挂点 { strTmp.Format(_T("%d_%d_"), span-1, span); spanRight = span-1; } else //右挂点 { strTmp.Format(_T("%d_%d_"), span, span+1); spanRight = span; } fileName2 += strTmp + _T("unbalanced_force.dat"); fileName3 += strTmp + _T("hang_ori.dat"); CString path2 = pView->m_data->m_workspace + _T("\\result\\") + fileName2; if(!PathFileExists(path2)) { MessageBox(_T("结果文件") + path2 + _T("不存在!"), MsgCaption); return ; } file.Open(path2, CStdioFile::modeRead); while(file.ReadString(strTmp)) { if(strTmp.GetLength()>0) line = strTmp; } file.Close(); //挂点不平衡张力需乘以绝缘子串数 float unBalanceForce = _ttof(line.Mid(15, 15).TrimLeft())*pView->m_data->m_jyzStringNum; strTmp.Format(_T("%.5f"), unBalanceForce); m_nodeUnbalancedForce.SetWindowText(strTmp); CString path3 = pView->m_data->m_workspace + _T("\\result\\") + fileName3; if(!PathFileExists(path3)) { MessageBox(_T("结果文件") + path3 + _T("不存在!"), MsgCaption); return ; } file.Open(path3, CStdioFile::modeRead); while(file.ReadString(strTmp)) { if(strTmp.GetLength()>0) line = strTmp; } file.Close(); x = _ttof(line.Mid(15, 15).TrimLeft()); y = _ttof(line.Mid(30, 15).TrimLeft()); z = _ttof(line.Mid(45, 15).TrimLeft()); for(int k=0; k<spanRight; k++) { x0 += pView->m_data->m_dxDjgc[k].dj; y0 += pView->m_data->m_dxDjgc[k].gc; } } strTmp.Format(_T("%.5f"), x+x0); m_nodeX.SetWindowText(strTmp); strTmp.Format(_T("%.5f"), y+y0); m_nodeY.SetWindowText(strTmp); strTmp.Format(_T("%.5f"), z+z0); m_nodeZ.SetWindowText(strTmp); strTmp.Format(_T("%.5f"), x0); m_nodeX0.SetWindowText(strTmp); strTmp.Format(_T("%.5f"), y0); m_nodeY0.SetWindowText(strTmp); strTmp.Format(_T("%.5f"), z0); m_nodeZ0.SetWindowText(strTmp); }
bool FileManager::saveBuffer(BufferID id, const TCHAR * filename, bool isCopy) { Buffer * buffer = getBufferByID(id); bool isHidden = false; bool isSys = false; DWORD attrib = 0; TCHAR fullpath[MAX_PATH]; ::GetFullPathName(filename, MAX_PATH, fullpath, NULL); ::GetLongPathName(fullpath, fullpath, MAX_PATH); if (PathFileExists(fullpath)) { attrib = ::GetFileAttributes(fullpath); if (attrib != INVALID_FILE_ATTRIBUTES) { isHidden = (attrib & FILE_ATTRIBUTE_HIDDEN) != 0; if (isHidden) ::SetFileAttributes(filename, attrib & ~FILE_ATTRIBUTE_HIDDEN); isSys = (attrib & FILE_ATTRIBUTE_SYSTEM) != 0; if (isSys) ::SetFileAttributes(filename, attrib & ~FILE_ATTRIBUTE_SYSTEM); } } UniMode mode = buffer->getUnicodeMode(); if (mode == uniCookie) mode = uni8Bit; //set the mode to ANSI to prevent converter from adding BOM and performing conversions, Scintilla's data can be copied directly Utf8_16_Write UnicodeConvertor; UnicodeConvertor.setEncoding(mode); int encoding = buffer->getEncoding(); FILE *fp = UnicodeConvertor.fopen(fullpath, TEXT("wb")); if (fp) { _pscratchTilla->execute(SCI_SETDOCPOINTER, 0, buffer->_doc); //generate new document int lengthDoc = _pscratchTilla->getCurrentDocLen(); char* buf = (char*)_pscratchTilla->execute(SCI_GETCHARACTERPOINTER); //to get characters directly from Scintilla buffer if (encoding == -1) //no special encoding; can be handled directly by Utf8_16_Write { UnicodeConvertor.fwrite(buf, lengthDoc); } else { WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance(); int grabSize; for (int i = 0; i < lengthDoc; i += grabSize) { grabSize = lengthDoc - i; if (grabSize > blockSize) grabSize = blockSize; int newDataLen = 0; int incompleteMultibyteChar = 0; const char *newData = wmc->encode(SC_CP_UTF8, encoding, buf+i, grabSize, &newDataLen, &incompleteMultibyteChar); grabSize -= incompleteMultibyteChar; UnicodeConvertor.fwrite(newData, newDataLen); } } UnicodeConvertor.fclose(); if (isHidden) ::SetFileAttributes(fullpath, attrib | FILE_ATTRIBUTE_HIDDEN); if (isSys) ::SetFileAttributes(fullpath, attrib | FILE_ATTRIBUTE_SYSTEM); if (isCopy) { _pscratchTilla->execute(SCI_SETDOCPOINTER, 0, _scratchDocDefault); return true; //all done } buffer->setFileName(fullpath); buffer->setDirty(false); buffer->setStatus(DOC_REGULAR); buffer->checkFileState(); _pscratchTilla->execute(SCI_SETSAVEPOINT); //_pscratchTilla->markSavedLines(); _pscratchTilla->execute(SCI_SETDOCPOINTER, 0, _scratchDocDefault); return true; } return false; }
void COpenDlg::OnOK() { UpdateData(TRUE); bool bUDiffOnClipboard = false; if (OpenClipboard()) { UINT enumFormat = 0; do { if (enumFormat == m_cFormat) { bUDiffOnClipboard = true; } } while((enumFormat = EnumClipboardFormats(enumFormat))!=0); CloseClipboard(); } if (GetDlgItem(IDC_BASEFILEEDIT)->IsWindowEnabled()) { m_sUnifiedDiffFile.Empty(); m_sPatchDirectory.Empty(); } else { m_sBaseFile.Empty(); m_sYourFile.Empty(); m_sTheirFile.Empty(); } UpdateData(FALSE); CString sFile; if (!m_sUnifiedDiffFile.IsEmpty()) if (!PathFileExists(m_sUnifiedDiffFile)) sFile = m_sUnifiedDiffFile; if (!m_sPatchDirectory.IsEmpty()) if (!PathFileExists(m_sPatchDirectory)) sFile = m_sPatchDirectory; if (!m_sBaseFile.IsEmpty()) if (!PathFileExists(m_sBaseFile)) sFile = m_sBaseFile; if (!m_sYourFile.IsEmpty()) if (!PathFileExists(m_sYourFile)) sFile = m_sYourFile; if (!m_sTheirFile.IsEmpty()) if (!PathFileExists(m_sTheirFile)) sFile = m_sTheirFile; if (bUDiffOnClipboard && m_bFromClipboard) { if (OpenClipboard()) { HGLOBAL hglb = GetClipboardData(m_cFormat); LPCSTR lpstr = (LPCSTR)GlobalLock(hglb); DWORD len = GetTempPath(0, nullptr); auto path = std::make_unique<TCHAR[]>(len + 1); auto tempF = std::make_unique<TCHAR[]>(len + 100); GetTempPath (len+1, path.get()); GetTempFileName(path.get(), L"tsm", 0, tempF.get()); CString sTempFile = CString(tempF.get()); FILE * outFile; size_t patchlen = strlen(lpstr); _wfopen_s(&outFile, sTempFile, L"wb"); if(outFile) { size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile); if (size < patchlen) bUDiffOnClipboard = false; else { m_sUnifiedDiffFile = sTempFile; UpdateData(FALSE); sFile.Empty(); } fclose(outFile); } GlobalUnlock(hglb); CloseClipboard(); } } if (!sFile.IsEmpty()) { CString sErr; sErr.Format(IDS_ERR_PATCH_INVALIDPATCHFILE, (LPCTSTR)sFile); MessageBox(sErr, nullptr, MB_ICONERROR); return; } CRegDWORD lastRadioButton(L"Software\\TortoiseGitMerge\\OpenRadio", IDC_MERGERADIO); lastRadioButton = GetCheckedRadioButton(IDC_MERGERADIO, IDC_APPLYRADIO); CStandAloneDialog::OnOK(); }
///////////////Ajax OnStateChange实现部分 STDMETHODIMP LuaAsynUtil::OnStateChange(CAJAX* pSource, const bool bSucceeded, const int nHttpState, const BSTR /*bstrResponse*/, IDispatch* pDispath) { if(bSucceeded && (nHttpState >= 200 && nHttpState < 300 )) { if (pSource->m_bOutDOM) { g_wndMsg.PostMessage(WM_AJAXDOWNLOADFILESUCCESS, pSource->m_nID, (LPARAM)pSource); } else //存成文件 { if ((AjaxTaskFlag)pSource->m_nID == AJAXTASKFLAG_SENDHTTPSTAT || (AjaxTaskFlag)pSource->m_nID == AJAXTASKFLAG_SENDHTTPSTATEX) { g_wndMsg.PostMessage(WM_AJAXDOWNLOADFILESUCCESS, pSource->m_nID, (LPARAM)pSource); } else { CComBSTR bstrSavedPath = pSource->m_bstrSavedPath; MSXML::IXMLHttpRequestPtr pRequest(pDispath); if ((AjaxTaskFlag)pSource->m_nID == AJAXTASKFLAG_GETHTTPCONTENT) { //try //{ CComBSTR bstrContent; pRequest->get_responseText(&bstrContent); pSource->m_bstrSavedPath = L""; pSource->m_bstrSavedPath.AppendBSTR(bstrContent); g_wndMsg.PostMessage(WM_AJAXDOWNLOADFILESUCCESS, pSource->m_nID, (LPARAM)pSource); //} //catch (...) //{ // g_wndMsg.PostMessage(WM_AJAXDOWNLOADFILEFAILED, pSource->m_nID, (LPARAM)pSource); //} } else if ((AjaxTaskFlag)pSource->m_nID == AJAXTASKFLAG_GETHTTPFILE) { CComVariant varStream; pRequest->get_responseStream(&varStream); if (varStream.vt != VT_UNKNOWN && varStream.vt != VT_STREAM) { g_wndMsg.PostMessage(WM_AJAXDOWNLOADFILEFAILED, pSource->m_nID, (LPARAM)pSource); } else { wchar_t szPath[_MAX_PATH] = {0}; wcsncpy(szPath, bstrSavedPath, _MAX_PATH); PathRemoveFileSpec(szPath); if(!PathFileExists(szPath)) SHCreateDirectory(NULL, szPath); //写文件 HANDLE hFile = ::CreateFile((LPCTSTR)bstrSavedPath,GENERIC_WRITE,0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // 可能目录只读, 存到programdata/temp下 if (hFile == INVALID_HANDLE_VALUE) { static CComBSTR bstrPath; if(bstrPath.Length() <= 0) { wchar_t szPath[MAX_PATH] = {0}; DWORD len = GetTempPath(MAX_PATH, szPath); bstrPath = szPath; } if(!PathFileExists(bstrPath)) SHCreateDirectory(NULL, bstrPath); CComBSTR bstrFileName = PathFindFileName(bstrSavedPath); CComBSTR bstrPath2(bstrPath); bstrPath2.AppendBSTR(bstrFileName); bstrSavedPath = bstrPath2; hFile = ::CreateFile((LPCTSTR)bstrSavedPath,GENERIC_WRITE,0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); } if (hFile != INVALID_HANDLE_VALUE) { DWORD cb, cbRead, cbWritten; BYTE bBuffer[4096]; cb = sizeof bBuffer; CComQIPtr<IStream> pStream(varStream.punkVal); HRESULT hr = pStream->Read(bBuffer, cb, &cbRead); while (SUCCEEDED(hr) && 0 != cbRead) { if (!WriteFile(hFile, bBuffer, cbRead, &cbWritten, NULL)) break; hr = pStream->Read(bBuffer, cb, &cbRead); } } CloseHandle(hFile); pSource->m_bstrSavedPath = bstrSavedPath; g_wndMsg.PostMessage(WM_AJAXDOWNLOADFILESUCCESS, pSource->m_nID, (LPARAM)pSource); } } else { g_wndMsg.PostMessage(WM_AJAXDOWNLOADFILESUCCESS, pSource->m_nID, (LPARAM)pSource); } } } } else { CComBSTR bstrSavedPath(L""); if(!pSource->m_bOutDOM) { bstrSavedPath = pSource->m_bstrSavedPath; } g_wndMsg.PostMessage(WM_AJAXDOWNLOADFILEFAILED, pSource->m_nID, (LPARAM)pSource); } return S_OK; }
LRESULT CChildFrame::OnFileExtractData(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { HRESULT hr = E_FAIL; TREE_ITEM_DATA * pTmp = (TREE_ITEM_DATA *)m_pData.GetData(); if (NULL == pTmp) return 0; TCHAR szText[MAX_PATH] = { 0 }; m_pData.GetText(szText, _countof(szText)); ATLTRACE(_T("---------%s\n"), szText); if (STGTY_STREAM == pTmp->dwStgType) { TCHAR szFileName[MAX_PATH] = { 0 }; if (NULL == _tcschr(szText, '.')) { _tcscat(szText, _T(".bin")); } AdjustFileName(szText); TCHAR szFilter[MAX_PATH] = { 0 }; { // assembling filter string TCHAR szAllFiles[MAX_PATH] = { 0 }; AtlLoadString(IDS_ALL_FILES, szAllFiles, _countof(szAllFiles)); wnsprintf(szFilter, _countof(szFilter), _T("%s(*.*)|*.*||"), szAllFiles); } CModifiedFileDialog fd ( FALSE, _T(""), szText, OFN_HIDEREADONLY, szFilter, m_hWnd ); if ( IDOK != fd.DoModal(this->m_hWnd) ) return 0; lstrcpyn(szFileName, fd.m_szFileName, _countof(szFileName)); if (PathFileExists(szFileName)) { TCHAR szFmt[MAX_PATH] = { 0 }; AtlLoadString(IDS_FILE_EXISTS, szFmt, _countof(szFmt)); TCHAR szMsg[MAX_PATH*2] = { 0 }; wnsprintf(szMsg, _countof(szMsg), szFmt, szFileName); if ( IDYES != AtlMessageBox(m_hWnd, szMsg, IDS_WARNING, MB_YESNO|MB_ICONWARNING)) { return 0; } } CComPtr<IStream> spFile; hr = pTmp->spStgOrStrm->QueryInterface(&spFile); if (FAILED(hr)) return hr; hr = WriteStreamToFile(szFileName, spFile); } else if (STGTY_STORAGE == pTmp->dwStgType) { CModifiedFolderDialog fd ( GetTopLevelParent(), IDS_SELECT_DIR, BIF_RETURNONLYFSDIRS|BIF_NEWDIALOGSTYLE ); TCHAR szCurrPath[MAX_PATH] = { 0 }; GetCurrentDirectory(_countof(szCurrPath), szCurrPath); fd.SetInitialDir( szCurrPath ); if ( IDOK != fd.DoModal() ) return 0; lstrcpyn(szCurrPath, fd.GetFolderPath(), _countof(szCurrPath)); PathAddBackslash(szCurrPath); SHCreateDirectoryEx(*this, szCurrPath, NULL); // recursion _RecursionExtractData(szCurrPath, m_pData, &m_wndCatalog); } return 0; }
BOOL ExcuteWs(CString strWsFile,BOOL bShowProgress) { if (!PathFileExists(strWsFile)) { printf("文件:%s不存在!\n",strWsFile); ZTools::WriteZToolsFormatLog("文件:%s不存在!\n",strWsFile); return FALSE; } CString strUsr,strPassWd; if (!GetLoginConfig(strUsr,strPassWd)) { ZTools::WriteZToolsLog("从配置文件PeraRunWsDemo.ini 获取用户名user 和 passwd 失败"); printf("从配置文件PeraRunWsDemo.ini 获取用户名user 和 passwd 失败\n"); return FALSE; } CString strQueryResult = UploadAndQuery(strWsFile); ZTools::WriteZToolsFormatLog("UploadAndQuery 返回值为:%s",strQueryResult); if (strQueryResult.IsEmpty()) { ZTools::WriteZToolsLog("UploadAndQuery返回空字符串,过程终止...\n"); printf("UploadAndQuery返回空字符串,过程终止...\n"); return FALSE; } /*else if () { }*/ CString strIP = ComGetLocalIp(); CString strLoginResult = Login(strUsr,strPassWd,strIP,"true"); ZTools::WriteZToolsFormatLog("登录本机IP地址为%s,返回值为:%s\n",strIP,strLoginResult); int iPos = strLoginResult.Find("ticket-proxy"); if (iPos!=0 || strLoginResult.GetLength() < 14) { ZTools::WriteZToolsLog("登录出错!\n"); printf("登录出错!\n"); return FALSE; } CString strTicket = strLoginResult.Mid(strLoginResult.Find('=')+1); CDataCallStartWs DataCall(strQueryResult,strIP,strUsr,strUsr/*"超级管理员"*/,strTicket); CString strCallJs = DataCall.GetJsonStr(); ZTools::WriteZToolsFormatLog("InvokeWsMethod输入参数为startLocalModelByWsFile,%s\n",strCallJs); CString strCallStartResult = InvokeWsMethod("startLocalModelByWsFile",strCallJs); ZTools::WriteZToolsFormatLog("InvokeWsMethod返回值为:%s\n",strCallStartResult); CDataCallStartWsResult CallResData; CallResData.FromJson(strCallStartResult); if (!CallResData.GetOptMsg().IsEmpty()) { ZTools::WriteZToolsLog("调用Ws方法startLocalModelByWsFile失败!"); printf("调用Ws方法startLocalModelByWsFile失败!\n"); return FALSE; } if (bShowProgress) { CString strUrl = CallResData.GetOptUrl(); AttachTicket(strUrl,strLoginResult); ZTools::WriteZToolsFormatLog("用IE浏览器打开运行页面:%s\n",strUrl); OpenUrl(strUrl); } return TRUE; }
BOOL CPPgDirectories::OnApply() { bool testtempdirchanged=false; CString testincdirchanged = thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR); CString strIncomingDir; GetDlgItemText(IDC_INCFILES, strIncomingDir); MakeFoldername(strIncomingDir); if (strIncomingDir.IsEmpty()){ strIncomingDir = thePrefs.GetDefaultDirectory(EMULE_INCOMINGDIR, true); // will create the directory here if it doesnt exists SetDlgItemText(IDC_INCFILES, strIncomingDir); } else if (thePrefs.IsInstallationDirectory(strIncomingDir)){ AfxMessageBox(GetResString(IDS_WRN_INCFILE_RESERVED)); return FALSE; } else if (strIncomingDir.CompareNoCase(testincdirchanged) != 0 && strIncomingDir.CompareNoCase(thePrefs.GetDefaultDirectory(EMULE_INCOMINGDIR, false)) != 0){ // if the user chooses a non-default directory which already contains files, inform him that all those files // will be shared CFileFind ff; CString strSearchPath; strSearchPath.Format(_T("%s\\*"),strIncomingDir); bool bEnd = !ff.FindFile(strSearchPath, 0); bool bExistingFile = false; while (!bEnd) { bEnd = !ff.FindNextFile(); if (ff.IsDirectory() || ff.IsDots() || ff.IsSystem() || ff.IsTemporary() || ff.GetLength()==0 || ff.GetLength()>MAX_EMULE_FILE_SIZE) continue; // ignore real LNK files TCHAR szExt[_MAX_EXT]; _tsplitpath(ff.GetFileName(), NULL, NULL, NULL, szExt); if (_tcsicmp(szExt, _T(".lnk")) == 0){ SHFILEINFO info; if (SHGetFileInfo(ff.GetFilePath(), 0, &info, sizeof(info), SHGFI_ATTRIBUTES) && (info.dwAttributes & SFGAO_LINK)){ if (!thePrefs.GetResolveSharedShellLinks()) continue; } } // ignore real THUMBS.DB files -- seems that lot of ppl have 'thumbs.db' files without the 'System' file attribute if (ff.GetFileName().CompareNoCase(_T("thumbs.db")) == 0) continue; bExistingFile = true; break; } if (bExistingFile && AfxMessageBox(GetResString(IDS_WRN_INCFILE_EXISTS), MB_OKCANCEL | MB_ICONINFORMATION) == IDCANCEL) { return FALSE; } } // checking specified tempdir(s) CString strTempDir; GetDlgItemText(IDC_TEMPFILES, strTempDir); if (strTempDir.IsEmpty()){ strTempDir = thePrefs.GetDefaultDirectory(EMULE_TEMPDIR, true); // will create the directory here if it doesnt exists SetDlgItemText(IDC_TEMPFILES, strTempDir); } int curPos=0; CStringArray temptempfolders; CString atmp=strTempDir.Tokenize(_T("|"), curPos); while (!atmp.IsEmpty()) { atmp.Trim(); if (!atmp.IsEmpty()) { if (CompareDirectories(strIncomingDir, atmp)==0){ AfxMessageBox(GetResString(IDS_WRN_INCTEMP_SAME)); return FALSE; } if (thePrefs.IsInstallationDirectory(atmp)){ AfxMessageBox(GetResString(IDS_WRN_TEMPFILES_RESERVED)); return FALSE; } bool doubled=false; for (int i=0;i<temptempfolders.GetCount();i++) // avoid double tempdirs if (temptempfolders.GetAt(i).CompareNoCase(atmp)==0) { doubled=true; break; } if (!doubled) { temptempfolders.Add(atmp); if (thePrefs.tempdir.GetCount()>=temptempfolders.GetCount()) { if( atmp.CompareNoCase(thePrefs.GetTempDir(temptempfolders.GetCount()-1))!=0 ) testtempdirchanged=true; } else testtempdirchanged=true; } } atmp = strTempDir.Tokenize(_T("|"), curPos); } if (temptempfolders.IsEmpty()) temptempfolders.Add(strTempDir = thePrefs.GetDefaultDirectory(EMULE_TEMPDIR, true)); if (temptempfolders.GetCount()!=thePrefs.tempdir.GetCount()) testtempdirchanged=true; // applying tempdirs if (testtempdirchanged) { thePrefs.tempdir.RemoveAll(); for (int i=0;i<temptempfolders.GetCount();i++) { CString toadd=temptempfolders.GetAt(i); MakeFoldername(toadd); if (!PathFileExists(toadd)) CreateDirectory(toadd,NULL); if (PathFileExists(toadd)) thePrefs.tempdir.Add(toadd); } } if (thePrefs.tempdir.IsEmpty()) thePrefs.tempdir.Add(thePrefs.GetDefaultDirectory(EMULE_TEMPDIR, true)); thePrefs.m_strIncomingDir = strIncomingDir; MakeFoldername(thePrefs.m_strIncomingDir); thePrefs.GetCategory(0)->strIncomingPath = thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR); thePrefs.shareddir_list.RemoveAll(); m_ShareSelector.GetSharedDirectories(&thePrefs.shareddir_list); for (int i = 0; i < m_ctlUncPaths.GetItemCount(); i++) thePrefs.shareddir_list.AddTail(m_ctlUncPaths.GetItemText(i, 0)); // check shared directories for reserved folder names POSITION pos = thePrefs.shareddir_list.GetHeadPosition(); while (pos){ POSITION posLast = pos; const CString& rstrDir = thePrefs.shareddir_list.GetNext(pos); if (!thePrefs.IsShareableDirectory(rstrDir)) thePrefs.shareddir_list.RemoveAt(posLast); } if (testtempdirchanged) AfxMessageBox(GetResString(IDS_SETTINGCHANGED_RESTART)); // on changing incoming dir, update incoming dirs of category of the same path if (testincdirchanged.CompareNoCase(thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR)) != 0) { CString oldpath; bool dontaskagain=false; for (int cat=1; cat<=thePrefs.GetCatCount()-1;cat++){ oldpath=CString(thePrefs.GetCatPath(cat)); if (oldpath.Left(testincdirchanged.GetLength()).CompareNoCase(testincdirchanged)==0) { if (!dontaskagain) { dontaskagain=true; if (AfxMessageBox(GetResString(IDS_UPDATECATINCOMINGDIRS),MB_YESNO)==IDNO) break; } thePrefs.GetCategory(cat)->strIncomingPath = thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR) + oldpath.Mid(testincdirchanged.GetLength()); } } } theApp.emuledlg->sharedfileswnd->Reload(); SetModified(0); return CPropertyPage::OnApply(); }
int CPartFileConvert::performConvertToeMule(CString folder) { BOOL bWorking; CString filepartindex,newfilename; CString buffer; UINT fileindex; CFileFind finder; CString partfile=folder; folder.Delete(folder.ReverseFind('\\'),folder.GetLength()); partfile=partfile.Mid(partfile.ReverseFind('\\')+1,partfile.GetLength()); UpdateGUI(0,GetResString(IDS_IMP_STEPREADPF),true); filepartindex=partfile.Left(partfile.Find('.')); //int pos=filepartindex.ReverseFind('\\'); //if (pos>-1) filepartindex=filepartindex.Mid(pos+1,filepartindex.GetLength()-pos); UpdateGUI(4,GetResString(IDS_IMP_STEPBASICINF)); CPartFile* file=new CPartFile(); pfconverting->partmettype = file->LoadPartFile(folder,partfile,true); switch (pfconverting->partmettype) { case PMT_UNKNOWN: case PMT_BADFORMAT: delete file; return CONV_BADFORMAT; break; } CString oldfile=folder+_T("\\")+partfile.Left(partfile.GetLength()- ((pfconverting->partmettype==PMT_SHAREAZA)?3:4) ); pfconverting->size=file->GetFileSize(); pfconverting->filename=file->GetFileName(); pfconverting->filehash= EncodeBase16( file->GetFileHash() ,16); UpdateGUI(pfconverting); if (theApp.downloadqueue->GetFileByID(file->GetFileHash())!=0) { delete file; return CONV_ALREADYEXISTS; } if (pfconverting->partmettype==PMT_SPLITTED ) { try { CByteArray ba; ba.SetSize(PARTSIZE); CFile inputfile; int pos1,pos2; CString filename; // just count UINT maxindex=0; UINT partfilecount=0; bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part")); while (bWorking) { bWorking = finder.FindNextFile(); ++partfilecount; buffer=finder.GetFileName(); pos1=buffer.Find('.'); pos2=buffer.Find('.',pos1+1); fileindex=_tstoi(buffer.Mid(pos1+1,pos2-pos1) ); if (fileindex==0) continue; if (fileindex>maxindex) maxindex=fileindex; } float stepperpart; if (partfilecount>0) { stepperpart=(80.0f / partfilecount ); if ((uint64)maxindex*PARTSIZE<=pfconverting->size) pfconverting->spaceneeded=(uint64)maxindex*PARTSIZE; else pfconverting->spaceneeded=((uint64)(pfconverting->size / PARTSIZE) * PARTSIZE)+(pfconverting->size % PARTSIZE); } else { stepperpart=80.0f; pfconverting->spaceneeded=0; } UpdateGUI(pfconverting); if (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < ((uint64)maxindex*PARTSIZE) ) { delete file; return CONV_OUTOFDISKSPACE; } // create new partmetfile, and remember the new name file->CreatePartFile(); newfilename=file->GetFullName(); UpdateGUI(8,GetResString(IDS_IMP_STEPCRDESTFILE)); file->m_hpartfile.SetLength( pfconverting->spaceneeded ); uint16 curindex=0; bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part")); while (bWorking) { bWorking = finder.FindNextFile(); //stats ++curindex; buffer.Format(GetResString(IDS_IMP_LOADDATA),curindex,partfilecount); UpdateGUI( 10+(curindex*stepperpart) ,buffer); filename=finder.GetFileName(); pos1=filename.Find('.'); pos2=filename.Find('.',pos1+1); fileindex=_tstoi(filename.Mid(pos1+1,pos2-pos1) ); if (fileindex==0) continue; uint32 chunkstart=(uint32)(fileindex-1) * PARTSIZE ; // open, read data of the part-part-file into buffer, close file inputfile.Open(finder.GetFilePath(),CFile::modeRead|CFile::shareDenyWrite); uint32 readed=inputfile.Read( ba.GetData() ,PARTSIZE); inputfile.Close(); buffer.Format(GetResString(IDS_IMP_SAVEDATA),curindex,partfilecount); UpdateGUI( 10+(curindex*stepperpart) ,buffer); // write the buffered data file->m_hpartfile.Seek(chunkstart, CFile::begin ); file->m_hpartfile.Write(ba.GetData(),readed); } } catch(CFileException* error) { CString strError(GetResString(IDS_IMP_IOERROR)); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (error->GetErrorMessage(szError, ARRSIZE(szError))){ strError += _T(" - "); strError += szError; } LogError(false, _T("%s"), strError); error->Delete(); delete file; return CONV_IOERROR; } file->m_hpartfile.Close(); } // import an external common format partdownload else //if (pfconverting->partmettype==PMT_DEFAULTOLD || pfconverting->partmettype==PMT_NEWOLD || Shareaza ) { if (!pfconverting->removeSource) pfconverting->spaceneeded = (UINT)GetDiskFileSize(oldfile); UpdateGUI(pfconverting); if (!pfconverting->removeSource && (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < pfconverting->spaceneeded) ) { delete file; return CONV_OUTOFDISKSPACE; } file->CreatePartFile(); newfilename=file->GetFullName(); file->m_hpartfile.Close(); BOOL ret=FALSE; UpdateGUI( 92 ,GetResString(IDS_COPY)); DeleteFile(newfilename.Left(newfilename.GetLength()-4)); if (!PathFileExists(oldfile)) { // data file does not exist. well, then create a 0 byte big one HANDLE hFile = CreateFile( newfilename.Left(newfilename.GetLength()-4) , // file to open GENERIC_WRITE, // open for reading FILE_SHARE_READ, // share for reading NULL, // default security CREATE_NEW, // existing file only FILE_ATTRIBUTE_NORMAL, // normal file NULL); // no attr. template ret= !(hFile == INVALID_HANDLE_VALUE) ; CloseHandle(hFile); } else if (pfconverting->removeSource) ret=MoveFile( oldfile, newfilename.Left(newfilename.GetLength()-4) ); else ret=CopyFile( oldfile, newfilename.Left(newfilename.GetLength()-4) ,false); if (!ret) { file->DeleteFile(); //delete file; return CONV_FAILED; } } UpdateGUI( 94 ,GetResString(IDS_IMP_GETPFINFO)); DeleteFile(newfilename); if (pfconverting->removeSource) MoveFile(folder+_T("\\")+partfile,newfilename); else CopyFile(folder+_T("\\")+partfile,newfilename,false); for (int i = 0; i < file->hashlist.GetSize(); i++) delete[] file->hashlist[i]; file->hashlist.RemoveAll(); while (file->gaplist.GetCount()>0 ) { delete file->gaplist.GetAt(file->gaplist.GetHeadPosition()); file->gaplist.RemoveAt(file->gaplist.GetHeadPosition()); } if (!file->LoadPartFile(thePrefs.GetTempDir(), file->GetPartMetFileName(), false)) { //delete file; file->DeleteFile(); return CONV_BADFORMAT; } if (pfconverting->partmettype==PMT_NEWOLD || pfconverting->partmettype==PMT_SPLITTED ) { file->completedsize = file->m_uTransferred; file->m_uCompressionGain = 0; file->m_uCorruptionLoss = 0; } UpdateGUI( 100 ,GetResString(IDS_IMP_ADDDWL)); theApp.downloadqueue->AddDownload(file,thePrefs.AddNewFilesPaused()); file->SavePartFile(); if (file->GetStatus(true) == PS_READY) theApp.sharedfiles->SafeAddKFile(file); // part files are always shared files if (pfconverting->removeSource) { bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*")); while (bWorking) { bWorking = finder.FindNextFile(); VERIFY( _tunlink(finder.GetFilePath()) == 0 ); } if (pfconverting->partmettype==PMT_SPLITTED) RemoveDirectory(folder+_T("\\")); } return CONV_OK; }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nCmdShow*/) { SetDllDirectory(L""); SetTaskIDPerUUID(); CRegStdDWORD loc = CRegStdDWORD(L"Software\\TortoiseGit\\LanguageID", 1033); long langId = loc; CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); CLangDll langDLL; hResource = langDLL.Init(L"TortoiseIDiff", langId); if (!hResource) hResource = hInstance; git_libgit2_init(); CCmdLineParser parser(lpCmdLine); if (parser.HasKey(L"?") || parser.HasKey(L"help")) { TCHAR buf[1024] = { 0 }; LoadString(hResource, IDS_COMMANDLINEHELP, buf, _countof(buf)); MessageBox(nullptr, buf, L"TortoiseIDiff", MB_ICONINFORMATION); langDLL.Close(); return 0; } MSG msg; hInst = hInstance; INITCOMMONCONTROLSEX used = { sizeof(INITCOMMONCONTROLSEX), ICC_STANDARD_CLASSES | ICC_BAR_CLASSES | ICC_WIN95_CLASSES }; InitCommonControlsEx(&used); // load the cursors we need curHand = static_cast<HCURSOR>(LoadImage(hInst, MAKEINTRESOURCE(IDC_PANCUR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE)); curHandDown = static_cast<HCURSOR>(LoadImage(hInst, MAKEINTRESOURCE(IDC_PANDOWNCUR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE)); auto mainWindow = std::make_unique<CMainWindow>(hResource); mainWindow->SetRegistryPath(L"Software\\TortoiseGit\\TortoiseIDiffWindowPos"); std::wstring leftfile = parser.HasVal(L"left") ? parser.GetVal(L"left") : L""; std::wstring rightfile = parser.HasVal(L"right") ? parser.GetVal(L"right") : L""; if ((leftfile.empty()) && (lpCmdLine[0] != 0)) { int nArgs; LPWSTR * szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if (szArglist) { if (nArgs == 3) { // Four parameters: // [0]: Program name // [1]: left file // [2]: right file if (PathFileExists(szArglist[1]) && PathFileExists(szArglist[2])) { leftfile = szArglist[1]; rightfile = szArglist[2]; } } } // Free memory allocated for CommandLineToArgvW arguments. LocalFree(szArglist); } mainWindow->SetLeft(leftfile.c_str(), parser.HasVal(L"lefttitle") ? parser.GetVal(L"lefttitle") : L""); mainWindow->SetRight(rightfile.c_str(), parser.HasVal(L"righttitle") ? parser.GetVal(L"righttitle") : L""); if (parser.HasVal(L"base")) mainWindow->SetSelectionImage(FileTypeBase, parser.GetVal(L"base"), parser.HasVal(L"basetitle") ? parser.GetVal(L"basetitle") : L""); if (parser.HasVal(L"mine")) mainWindow->SetSelectionImage(FileTypeMine, parser.GetVal(L"mine"), parser.HasVal(L"minetitle") ? parser.GetVal(L"minetitle") : L""); if (parser.HasVal(L"theirs")) mainWindow->SetSelectionImage(FileTypeTheirs, parser.GetVal(L"theirs"), parser.HasVal(L"theirstitle") ? parser.GetVal(L"theirstitle") : L""); if (parser.HasVal(L"result")) mainWindow->SetSelectionResult(parser.GetVal(L"result")); mainWindow->resolveMsgWnd = parser.HasVal(L"resolvemsghwnd") ? reinterpret_cast<HWND>(parser.GetLongLongVal(L"resolvemsghwnd")) : 0; mainWindow->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? static_cast<WPARAM>(parser.GetLongLongVal(L"resolvemsgwparam")) : 0; mainWindow->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? static_cast<LPARAM>(parser.GetLongLongVal(L"resolvemsglparam")) : 0; if (mainWindow->RegisterAndCreateWindow()) { HACCEL hAccelTable = LoadAccelerators(hResource, MAKEINTRESOURCE(IDR_TORTOISEIDIFF)); if (!parser.HasVal(L"left") && parser.HasVal(L"base") && !parser.HasVal(L"mine") && !parser.HasVal(L"theirs")) { PostMessage(*mainWindow, WM_COMMAND, ID_FILE_OPEN, 0); } if (parser.HasKey(L"overlay")) { PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_OVERLAPIMAGES, 0); } if (parser.HasKey(L"fit")) { PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEHEIGHTS, 0); PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEWIDTHS, 0); } if (parser.HasKey(L"fitwidth")) { PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEWIDTHS, 0); } if (parser.HasKey(L"fitheight")) { PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEHEIGHTS, 0); } if (parser.HasKey(L"showinfo")) { PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_IMAGEINFO, 0); } // Main message loop: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(*mainWindow, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return static_cast<int>(msg.wParam); } langDLL.Close(); DestroyCursor(curHand); DestroyCursor(curHandDown); CoUninitialize(); git_libgit2_shutdown(); return 1; }
//------------------------------------------------------------------------------------- void disk_log(LOG_LEVEL level, const char* message, ...) { assert(level >= 0 && level < L_MAXIMUM_LEVEL); if (level < 0 || level >= L_MAXIMUM_LEVEL)return; DiskLogFile& thefile = _get_disk_log(); sys_api::auto_mutex guard(thefile.lock); //check the level if (level < thefile.level_threshold) return; //check dir #ifdef CY_SYS_WINDOWS if (!thefile.logpath_created && PathFileExists(LOG_PATH)!=TRUE) { if (0 == CreateDirectory(LOG_PATH, NULL)) #else if (!thefile.logpath_created && access(LOG_PATH, F_OK)!=0) { if (mkdir(LOG_PATH, 0755) != 0) #endif { //create log path failed! return; } thefile.logpath_created = true; } FILE* fp = fopen(thefile.file_name, "a"); if (fp == 0) { //create the log file first fp = fopen(thefile.file_name, "w"); } if (fp == 0) return; char timebuf[32] = { 0 }; #ifdef CY_SYS_WINDOWS //current time SYSTEMTIME time; ::GetLocalTime(&time); snprintf(timebuf, sizeof(timebuf), "%04d_%02d_%02d-%02d:%02d:%02d", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond); #else time_t t = time(0); struct tm tm_now; localtime_r(&t, &tm_now); strftime(timebuf, sizeof(timebuf), "%Y_%m_%d-%H:%M:%S", &tm_now); #endif static const int32_t STATIC_BUF_LENGTH = 2048; char szTemp[STATIC_BUF_LENGTH] = { 0 }; char* p = szTemp; va_list ptr; va_start(ptr, message); int len = vsnprintf(p, STATIC_BUF_LENGTH, message, ptr); if (len < 0) { va_start(ptr, message); len = vsnprintf(0, 0, message, ptr); if (len > 0) { p = new char[len + 1]; va_start(ptr, message); vsnprintf(p, (size_t)len + 1, message, ptr); p[len] = 0; } } else if (len >= STATIC_BUF_LENGTH) { p = new char[len + 1]; va_start(ptr, message); vsnprintf(p, (size_t)len + 1, message, ptr); p[len] = 0; } va_end(ptr); fprintf(fp, "%s %s [%s] %s\n", timebuf, thefile.level_name[level], sys_api::thread_get_current_name(), p); fclose(fp); //print to stand output last fprintf(level >= L_ERROR ? stderr : stdout, "%s %s [%s] %s\n", timebuf, thefile.level_name[level], sys_api::thread_get_current_name(), p); if (p != szTemp) { delete[] p; } } }
BOOL SpySrv_InstallDriver (BOOL bPermanently) { SC_HANDLE hManager ; SC_HANDLE hService ; BOOL bSuccess ; TCHAR szDriverPath[MAX_PATH] ; _SpySrv_GetAbsolutePath (szDriverPath, g_szDriverFileName) ; if( !PathFileExists(szDriverPath) ) { TRACE_ERROR (TEXT("File not found : %s\n"), szDriverPath) ; SetLastError (ERROR_FILE_NOT_FOUND) ; return FALSE ; } TRACE_INFO (TEXT("Driver path = %s\n"), szDriverPath) ; hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS) ; if( hManager==NULL ) { TRACE_ERROR (TEXT("OpenSCManager failed (error=%u)\n"), GetLastError()) ; return FALSE ; } create: hService = CreateService (hManager, g_szServiceName, TEXT("Winpooch kernel spy"), SERVICE_START|DELETE, SERVICE_KERNEL_DRIVER, bPermanently? SERVICE_SYSTEM_START:SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, szDriverPath, NULL, NULL, NULL, NULL, NULL) ; if( hService==NULL ) { DWORD dwLastError = GetLastError() ; if( dwLastError == ERROR_SERVICE_EXISTS ) { hService = OpenService (hManager, g_szServiceName, SERVICE_STOP|DELETE) ; if( hService!=NULL ) { SERVICE_STATUS srvstatus ; ControlService (hService, SERVICE_CONTROL_STOP, &srvstatus) ; bSuccess = DeleteService(hService) ; CloseServiceHandle (hService) ; if( bSuccess ) { TRACE_WARNING (TEXT("Service deleted. Try to re-create it\n")) ; goto create ; } } } TRACE_ERROR (TEXT("CreateService failed (error=%u)\n"), dwLastError) ; CloseServiceHandle (hManager) ; SetLastError (dwLastError) ; return FALSE ; } bSuccess = StartService (hService, 0, NULL) ; if( ! bSuccess ) { DWORD dwLastError = GetLastError() ; TRACE_ERROR (TEXT("StartService failed (error=%u)\n"), dwLastError) ; DeleteService(hService) ; CloseServiceHandle (hService) ; CloseServiceHandle (hManager) ; SetLastError (dwLastError) ; return FALSE ; } CloseServiceHandle (hService) ; CloseServiceHandle (hManager) ; return TRUE ; }
// Set IP, DNS, u32 CDeviceMgr_i::SetAdapterIpInfo(LPCTSTR pszConnectionName, NET_ADAPTER_IP_INFO* pIpInfoArray, u8 ulIpInfoArrayCnt, u32 nTimeOut) { u32 ret = ERR_OK_I; if(pszConnectionName == NULL) { return ERR_INVALID_PARAM_I; } #define IPINFO_FILE_NAME _T("C:\\l3230_ipinfo.txt") FILE* f = _tfopen(IPINFO_FILE_NAME, _T("wt")); if (f) { fprintf(f, _T("pushd interface ip\n\n")); fprintf(f, _T("# Interface IP Configuration for \"%s\"\n\n"), pszConnectionName); if((pIpInfoArray == NULL) || (ulIpInfoArrayCnt == 0)) { fprintf(f, _T("set address name=\"%s\" source=dhcp\n") _T("set dns name=\"%s\" source=dhcp register=PRIMARY\n") _T("set wins name=\"%s\" source=dhcp\n"), pszConnectionName,pszConnectionName,pszConnectionName); } else { if(ulIpInfoArrayCnt == 1) { if(pIpInfoArray->pszIpAdd) { fprintf(f, _T("set address name=\"%s\" source=static addr=%s mask=%s\n"), pszConnectionName, pIpInfoArray->pszIpAdd, pIpInfoArray->pszIpMask?pIpInfoArray->pszIpMask:_T("255.255.255.0") ); } if(pIpInfoArray->pszGateway) { fprintf(f, _T("set address name=\"%s\" gateway=%s gwmetric=0\n"), pszConnectionName, pIpInfoArray->pszGateway ); } if(pIpInfoArray->pszDnsAdd) { fprintf(f, _T("set dns name=\"%s\" source=static addr=%s register=PRIMARY\n"), pszConnectionName, pIpInfoArray->pszDnsAdd ); } } else { for (s32 i = 0; i< ulIpInfoArrayCnt; i++) { if(i == 0) { if(pIpInfoArray->pszIpAdd) { fprintf(f, _T("set address name=\"%s\" source=static addr=%s mask=%s\n"), pszConnectionName, pIpInfoArray->pszIpAdd, pIpInfoArray->pszIpMask?pIpInfoArray->pszIpMask:_T("255.255.255.0") ); } if(pIpInfoArray->pszGateway) { fprintf(f, _T("set address name=\"%s\" gateway=%s gwmetric=0\n") , pszConnectionName, pIpInfoArray->pszGateway ); } if(pIpInfoArray->pszDnsAdd) { fprintf(f, _T("set dns name=\"%s\" source=static addr=%s register=PRIMARY\n"), pszConnectionName, pIpInfoArray->pszDnsAdd ); } } else { if(pIpInfoArray->pszIpAdd) { fprintf(f, _T("add address name=\"%s\" addr=%s mask=%s\n"), pszConnectionName, pIpInfoArray->pszIpAdd, pIpInfoArray->pszIpMask?pIpInfoArray->pszIpMask:_T("255.255.255.0") ); } if(pIpInfoArray->pszGateway) { fprintf(f, _T("add address name=\"%s\" gateway=%s gwmetric=0\n") , pszConnectionName, pIpInfoArray->pszGateway ); } if(pIpInfoArray->pszDnsAdd) { fprintf(f, _T("add dns name=\"%s\" addr=%s index=%d\n"), pszConnectionName, pIpInfoArray->pszDnsAdd, i+2 ); } } pIpInfoArray ++; } } } fprintf(f, _T("\npopd\n\n")); fclose(f); f = NULL; } if(PathFileExists(IPINFO_FILE_NAME)) { CString strCmd; strCmd.Format(_T("netsh exec \"%s\""), IPINFO_FILE_NAME); ret = CProcessUtil_i::RunSilentProcess(strCmd, NULL , nTimeOut); } return ret; }
BOOL CPOFile::ParseFile(LPCTSTR szPath, BOOL bUpdateExisting, bool bAdjustEOLs) { if (!PathFileExists(szPath)) return FALSE; m_bAdjustEOLs = bAdjustEOLs; if (!m_bQuiet) _ftprintf(stdout, L"parsing file %s...\n", szPath); int nEntries = 0; int nDeleted = 0; int nTranslated = 0; //since stream classes still expect the filepath in char and not wchar_t //we need to convert the filepath to multibyte char filepath[MAX_PATH + 1] = { 0 }; SecureZeroMemory(filepath, sizeof(filepath)); WideCharToMultiByte(CP_ACP, NULL, szPath, -1, filepath, _countof(filepath)-1, NULL, NULL); std::wifstream File; File.imbue(std::locale(std::locale(), new utf8_conversion())); File.open(filepath); if (!File.good()) { _ftprintf(stderr, L"can't open input file %s\n", szPath); return FALSE; } std::unique_ptr<TCHAR[]> line(new TCHAR[2*MAX_STRING_LENGTH]); std::vector<std::wstring> entry; do { File.getline(line.get(), 2*MAX_STRING_LENGTH); if (line.get()[0]==0) { //empty line means end of entry! RESOURCEENTRY resEntry = {0}; std::wstring msgid; int type = 0; for (std::vector<std::wstring>::iterator I = entry.begin(); I != entry.end(); ++I) { if (wcsncmp(I->c_str(), L"# ", 2)==0) { //user comment resEntry.translatorcomments.push_back(I->c_str()); type = 0; } if (wcsncmp(I->c_str(), L"#.", 2)==0) { //automatic comments resEntry.automaticcomments.push_back(I->c_str()); type = 0; } if (wcsncmp(I->c_str(), L"#,", 2)==0) { //flag resEntry.flag = I->c_str(); type = 0; } if (wcsncmp(I->c_str(), L"msgid", 5)==0) { //message id msgid = I->c_str(); msgid = std::wstring(msgid.substr(7, msgid.size() - 8)); std::wstring s = msgid; s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<wint_t, int>(iswspace)))); if (s.size()) nEntries++; type = 1; } if (wcsncmp(I->c_str(), L"msgstr", 6)==0) { //message string resEntry.msgstr = I->c_str(); resEntry.msgstr = resEntry.msgstr.substr(8, resEntry.msgstr.length() - 9); if (!resEntry.msgstr.empty()) nTranslated++; type = 2; } if (wcsncmp(I->c_str(), L"\"", 1)==0) { if (type == 1) { std::wstring temp = I->c_str(); temp = temp.substr(1, temp.length()-2); msgid += temp; } if (type == 2) { if (resEntry.msgstr.empty()) nTranslated++; std::wstring temp = I->c_str(); temp = temp.substr(1, temp.length()-2); resEntry.msgstr += temp; } } } entry.clear(); if ((bUpdateExisting)&&(this->count(msgid) == 0)) nDeleted++; else { if ((m_bAdjustEOLs)&&(msgid.find(L"\\r\\n") != std::string::npos)) { AdjustEOLs(resEntry.msgstr); } // always use the new data for generated comments/flags auto newEntry = (*this)[msgid]; resEntry.automaticcomments = newEntry.automaticcomments; resEntry.flag = newEntry.flag; resEntry.resourceIDs = newEntry.resourceIDs; (*this)[msgid] = resEntry; } msgid.clear(); } else { entry.push_back(line.get()); } } while (File.gcount() > 0); printf(File.getloc().name().c_str()); File.close(); RESOURCEENTRY emptyentry = {0}; (*this)[std::wstring(L"")] = emptyentry; if (!m_bQuiet) _ftprintf(stdout, L"%d Entries found, %d were already translated and %d got deleted\n", nEntries, nTranslated, nDeleted); return TRUE; }
bool DropCopyCommand::Execute() { CString sDroppath = parser.GetVal(_T("droptarget")); if (CTGitPath(sDroppath).IsAdminDir()) { CMessageBox::Show(NULL,_T("Can't drop to .git repository directory\n"), _T("TortoiseGit"),MB_OK|MB_ICONERROR); return FALSE; } unsigned long count = 0; CString sNewName; pathList.RemoveAdminPaths(); if ((parser.HasKey(_T("rename")))&&(pathList.GetCount()==1)) { // ask for a new name of the source item do { CRenameDlg renDlg; renDlg.m_windowtitle.LoadString(IDS_PROC_COPYRENAME); renDlg.m_name = pathList[0].GetFileOrDirectoryName(); if (renDlg.DoModal() != IDOK) { return FALSE; } sNewName = renDlg.m_name; } while(sNewName.IsEmpty() || PathFileExists(sDroppath+_T("\\")+sNewName)); } CSysProgressDlg progress; progress.SetTitle(IDS_PROC_COPYING); progress.SetAnimation(IDR_MOVEANI); progress.SetTime(true); progress.ShowModeless(CWnd::FromHandle(hwndExplorer)); for (int nPath = 0; nPath < pathList.GetCount(); ++nPath) { const CTGitPath& sourcePath = orgPathList[nPath]; CTGitPath fullDropPath(sDroppath); if (sNewName.IsEmpty()) fullDropPath.AppendPathString(sourcePath.GetFileOrDirectoryName()); else fullDropPath.AppendPathString(sNewName); // Check for a drop-on-to-ourselves if (sourcePath.IsEquivalentTo(fullDropPath)) { // Offer a rename progress.Stop(); CRenameDlg dlg; dlg.m_windowtitle.Format(IDS_PROC_NEWNAMECOPY, (LPCTSTR)sourcePath.GetUIFileOrDirectoryName()); if (dlg.DoModal() != IDOK) { return FALSE; } // rebuild the progress dialog progress.EnsureValid(); progress.SetTitle(IDS_PROC_COPYING); progress.SetAnimation(IDR_MOVEANI); progress.SetTime(true); progress.SetProgress(count, pathList.GetCount()); progress.ShowModeless(CWnd::FromHandle(hwndExplorer)); // Rebuild the destination path, with the new name fullDropPath.SetFromUnknown(sDroppath); fullDropPath.AppendPathString(dlg.m_name); } if( CopyFile( sourcePath.GetWinPath(), fullDropPath.GetWinPath(), true)) { CString ProjectTopDir; if(fullDropPath.HasAdminDir(&ProjectTopDir)) { g_Git.SetCurrentDir(ProjectTopDir); SetCurrentDirectory(ProjectTopDir); CString cmd; cmd = _T("git.exe add \""); CString path; path=fullDropPath.GetGitPathString().Mid(ProjectTopDir.GetLength()); if(path.GetLength()>0) if(path[0]==_T('\\') || path[0]==_T('/')) path=path.Mid(1); cmd += path; cmd +=_T('\"'); CString output; if (g_Git.Run(cmd, &output, CP_UTF8)) { CMessageBox::Show(NULL, output, _T("TortoiseGit"), MB_OK|MB_ICONERROR); }else CShellUpdater::Instance().AddPathForUpdate(fullDropPath); } }else { CString str; str+=_T("Copy file fail:"); str+=sourcePath.GetWinPath(); CMessageBox::Show(NULL, str, _T("TortoiseGit"), MB_OK|MB_ICONERROR); } ++count; if (progress.IsValid()) { progress.FormatPathLine(1, IDS_PROC_COPYINGPROG, sourcePath.GetWinPath()); progress.FormatPathLine(2, IDS_PROC_CPYMVPROG2, fullDropPath.GetWinPath()); progress.SetProgress(count, pathList.GetCount()); } if ((progress.IsValid())&&(progress.HasUserCancelled())) { CMessageBox::Show(hwndExplorer, IDS_SVN_USERCANCELLED, IDS_APPNAME, MB_ICONINFORMATION); return false; } } return true; }
void CExportDlg::OnOK() { if (!UpdateData(TRUE)) return; // don't dismiss dialog (error message already shown by MFC framework) if (::IsWindow(m_pLogDlg->GetSafeHwnd())&&(m_pLogDlg->IsWindowVisible())) { m_pLogDlg->SendMessage(WM_CLOSE); return; } // check it the export path is a valid windows path CTSVNPath ExportDirectory; if (::PathIsRelative(m_strExportDirectory)) { ExportDirectory = CTSVNPath(sOrigCWD); ExportDirectory.AppendPathString(L"\\" + m_strExportDirectory); m_strExportDirectory = ExportDirectory.GetWinPathString(); } else ExportDirectory = CTSVNPath(m_strExportDirectory); if (!ExportDirectory.IsValidOnWindows()) { ShowEditBalloon(IDC_CHECKOUTDIRECTORY, IDS_ERR_NOVALIDPATH, IDS_ERR_ERROR, TTI_ERROR); return; } // check if the specified revision is valid if (GetCheckedRadioButton(IDC_REVISION_HEAD, IDC_REVISION_N) == IDC_REVISION_HEAD) { Revision = SVNRev(L"HEAD"); } else Revision = SVNRev(m_sRevision); if (!Revision.IsValid()) { ShowEditBalloon(IDC_REVISION_NUM, IDS_ERR_INVALIDREV, IDS_ERR_ERROR, TTI_ERROR); return; } bool bAutoCreateTargetName = m_bAutoCreateTargetName; m_bAutoCreateTargetName = false; m_URLCombo.SaveHistory(); m_URL = m_URLCombo.GetString(); // we need an url to export from - local paths won't work if (!SVN::PathIsURL(CTSVNPath(m_URL))) { m_tooltips.ShowBalloon(IDC_URLCOMBO, IDS_ERR_MUSTBEURL, IDS_ERR_ERROR, TTI_ERROR); m_bAutoCreateTargetName = bAutoCreateTargetName; return; } if (m_strExportDirectory.IsEmpty()) { m_bAutoCreateTargetName = bAutoCreateTargetName; return; } // if the export directory does not exist, where should we export to? // We ask if the directory should be created... if (!PathFileExists(m_strExportDirectory)) { CPathUtils::MakeSureDirectoryPathExists(m_strExportDirectory); } // if the directory we should export to is not empty, show a warning: // maybe the user doesn't want to overwrite the existing files. if (!PathIsDirectoryEmpty(m_strExportDirectory)) { CString message; message.Format(CString(MAKEINTRESOURCE(IDS_WARN_FOLDERNOTEMPTY)),(LPCTSTR)m_strExportDirectory); CTaskDialog taskdlg(message, CString(MAKEINTRESOURCE(IDS_WARN_FOLDERNOTEMPTY_TASK2)), L"TortoiseSVN", 0, TDF_ENABLE_HYPERLINKS | TDF_USE_COMMAND_LINKS | TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW | TDF_SIZE_TO_CONTENT); taskdlg.AddCommandControl(1, CString(MAKEINTRESOURCE(IDS_WARN_FOLDERNOTEMPTY_TASK3_1))); taskdlg.AddCommandControl(2, CString(MAKEINTRESOURCE(IDS_WARN_FOLDERNOTEMPTY_TASK4))); taskdlg.SetCommonButtons(TDCBF_CANCEL_BUTTON); taskdlg.SetDefaultCommandControl(2); taskdlg.SetMainIcon(TD_WARNING_ICON); bool doIt = (taskdlg.DoModal(GetExplorerHWND()) == 1); if (!doIt) { m_bAutoCreateTargetName = bAutoCreateTargetName; return; //don't dismiss the dialog } } m_eolCombo.GetWindowText(m_eolStyle); if (m_eolStyle.Compare(L"default")==0) m_eolStyle.Empty(); switch (m_depthCombo.GetCurSel()) { case 0: m_depth = svn_depth_infinity; break; case 1: m_depth = svn_depth_immediates; break; case 2: m_depth = svn_depth_files; break; case 3: m_depth = svn_depth_empty; break; default: m_depth = svn_depth_empty; break; } UpdateData(FALSE); CRegDWORD regNoExt(L"Software\\TortoiseSVN\\noext"); regNoExt = m_bNoExternals; CResizableStandAloneDialog::OnOK(); }
BOOL CTortoiseGitBlameApp::InitInstance() { { DWORD len = GetCurrentDirectory(0, NULL); if (len) { std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]); if (GetCurrentDirectory(len, originalCurrentDirectory.get())) { sOrigCWD = originalCurrentDirectory.get(); sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD); } } } //set the resource dll for the required language CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033); long langId = loc; CString langDll; HINSTANCE hInst = NULL; do { langDll.Format(_T("%sLanguages\\TortoiseGitBlame%ld.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId); hInst = LoadLibrary(langDll); CString sVer = _T(STRPRODUCTVER); CString sFileVer = CPathUtils::GetVersionFromFile(langDll); if (sFileVer.Compare(sVer)!=0) { FreeLibrary(hInst); hInst = NULL; } if (hInst != NULL) AfxSetResourceHandle(hInst); else { DWORD lid = SUBLANGID(langId); lid--; if (lid > 0) { langId = MAKELANGID(PRIMARYLANGID(langId), lid); } else langId = 0; } } while ((hInst == NULL) && (langId != 0)); TCHAR buf[6] = { 0 }; _tcscpy_s(buf, _T("en")); langId = loc; CString sHelppath; sHelppath = this->m_pszHelpFilePath; sHelppath = sHelppath.MakeLower(); sHelppath.Replace(_T(".chm"), _T("_en.chm")); free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseGitBlame_en.chm"); do { GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf)); CString sLang = _T("_"); sLang += buf; sHelppath.Replace(_T("_en"), sLang); if (PathFileExists(sHelppath)) { free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); break; } sHelppath.Replace(sLang, _T("_en")); GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf)); sLang += _T("_"); sLang += buf; sHelppath.Replace(_T("_en"), sLang); if (PathFileExists(sHelppath)) { free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); break; } sHelppath.Replace(sLang, _T("_en")); DWORD lid = SUBLANGID(langId); lid--; if (lid > 0) { langId = MAKELANGID(PRIMARYLANGID(langId), lid); } else langId = 0; } while (langId); setlocale(LC_ALL, ""); // We need to explicitly set the thread locale to the system default one to avoid possible problems with saving files in its original codepage // The problems occures when the language of OS differs from the regional settings // See the details here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100887 SetThreadLocale(LOCALE_SYSTEM_DEFAULT); // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); Gdiplus::GdiplusStartupInput gdiplusStartupInput; Gdiplus::GdiplusStartup(&m_gdiplusToken,&gdiplusStartupInput,NULL); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored SetRegistryKey(_T("TortoiseGit")); LoadStdProfileSettings(4); // Load standard INI file options (including MRU) InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_TORTOISE_GIT_BLAME_MAINFRAME, RUNTIME_CLASS(CTortoiseGitBlameDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CTortoiseGitBlameView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); CCmdLineParser parser = CCmdLineParser(this->m_lpCmdLine); g_sGroupingUUID = parser.GetVal(L"groupuuid"); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand return TRUE; }
bool RunCmd(LPCWSTR lpszCmdLine, wstring& strOutput, int nShowCmd, DWORD dwWaitTime) { bool fRet = false; DWORD dwRet = 0; UINT nRet = 0; HANDLE hEvent = INVALID_HANDLE_VALUE; HANDLE hFileOutputSize = NULL; HANDLE hFile = NULL; DWORD* pdwOutputSize = NULL; DWORD dwOutputSize = 0; BYTE* pOutput = NULL; wstring strMyCmdExePath; strOutput.clear(); if ((!lpszCmdLine) || (!_tcslen(lpszCmdLine))) goto END; fRet = GetFullPathRelativeToCurrentModule(MY_CMD_EXE, strMyCmdExePath); if ((!fRet) || (!PathFileExists(strMyCmdExePath.c_str()))) goto END; nRet = (UINT)ShellExecute(NULL, NULL, strMyCmdExePath.c_str(), lpszCmdLine, NULL, nShowCmd); if (nRet <= 32) goto END; hEvent = CreateEvent(NULL, false, false, MY_CMD_OUTPUT_EVENT); if (hEvent == INVALID_HANDLE_VALUE) goto END; dwRet = WaitForSingleObject(hEvent, dwWaitTime); if (dwRet != WAIT_OBJECT_0) goto END; hFileOutputSize = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, MY_CMD_OUTPUT_SIZE_FILE_MAPPING); if (!hFileOutputSize) goto END; pdwOutputSize = (DWORD*)MapViewOfFile(hFileOutputSize, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(DWORD)); if (!pdwOutputSize) goto END; dwOutputSize = *pdwOutputSize; hFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, MY_CMD_OUTPUT_FILE_MAPPING); if (!hFile) goto END; pOutput = (BYTE*)MapViewOfFile(hFile, FILE_MAP_ALL_ACCESS, 0, 0, dwOutputSize); if (dwOutputSize) strOutput = (TCHAR*)pOutput; // ---------- Done ----------- fRet = true; END: if ((hEvent) && (hEvent != INVALID_HANDLE_VALUE)) CloseHandle(hEvent); if (pdwOutputSize) UnmapViewOfFile(pdwOutputSize); if (pOutput) UnmapViewOfFile(pOutput); if (hFileOutputSize) CloseHandle(hFileOutputSize); if (hFile) CloseHandle(hFile); return fRet; }
int CGitDiff::Diff(CTGitPath * pPath,CTGitPath * pPath2, git_revnum_t rev1, git_revnum_t rev2, bool /*blame*/, bool /*unified*/) { CString temppath; GetTempPath(temppath); // make sure we have HASHes here, otherwise filenames might be invalid if (rev1 != GIT_REV_ZERO) { CGitHash rev1Hash; if (g_Git.GetHash(rev1Hash, rev1)) { MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get hash of \"") + rev1 + _T("\".")), _T("TortoiseGit"), MB_ICONERROR); return -1; } rev1 = rev1Hash.ToString(); } if (rev2 != GIT_REV_ZERO) { CGitHash rev2Hash; if (g_Git.GetHash(rev2Hash, rev2)) { MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get hash of \"") + rev2 + _T("\".")), _T("TortoiseGit"), MB_ICONERROR); return -1; } rev2 = rev2Hash.ToString(); } CString file1; CString title1; CString cmd; if(pPath->IsDirectory() || pPath2->IsDirectory()) { return SubmoduleDiff(pPath,pPath2,rev1,rev2); } if(rev1 != GIT_REV_ZERO ) { TCHAR szTempName[MAX_PATH]; GetTempFileName(temppath, pPath->GetBaseFilename(), 0, szTempName); CString temp(szTempName); DeleteFile(szTempName); CreateDirectory(szTempName, NULL); // use original file extension, an external diff tool might need it file1.Format(_T("%s\\%s-%s-right%s"), temp, pPath->GetBaseFilename(), rev1.Left(g_Git.GetShortHASHLength()), pPath->GetFileExtension()); title1 = pPath->GetFileOrDirectoryName() + _T(":") + rev1.Left(g_Git.GetShortHASHLength()); g_Git.GetOneFile(rev1,*pPath,file1); ::SetFileAttributes(file1, FILE_ATTRIBUTE_READONLY); } else { file1=g_Git.m_CurrentDir+_T("\\")+pPath->GetWinPathString(); title1.Format( IDS_DIFF_WCNAME, pPath->GetFileOrDirectoryName() ); if (!PathFileExists(file1)) { CString sMsg; sMsg.Format(IDS_PROC_DIFFERROR_FILENOTINWORKINGTREE, file1); if (MessageBox(NULL, sMsg, _T("TortoiseGit"), MB_ICONEXCLAMATION | MB_YESNO) == IDNO) return 1; if (!CCommonAppUtils::FileOpenSave(file1, NULL, IDS_DIFF_WCNAME, IDS_COMMONFILEFILTER, true)) return 1; title1.Format(IDS_DIFF_WCNAME, CTGitPath(file1).GetUIFileOrDirectoryName()); } } CString file2; CString title2; if(rev2 != GIT_REV_ZERO) { TCHAR szTempName[MAX_PATH]; GetTempFileName(temppath, pPath2->GetBaseFilename(), 0, szTempName); CString temp(szTempName); DeleteFile(szTempName); CreateDirectory(szTempName, NULL); CTGitPath fileName = *pPath2; if (rev1 == GIT_REV_ZERO && pPath2->m_Action & CTGitPath::LOGACTIONS_REPLACED) fileName = CTGitPath(pPath2->GetGitOldPathString()); // use original file extension, an external diff tool might need it file2.Format(_T("%s\\%s-%s-left%s"), temp, fileName.GetBaseFilename(), rev2.Left(g_Git.GetShortHASHLength()), fileName.GetFileExtension()); title2 = fileName.GetFileOrDirectoryName() + _T(":") + rev2.Left(g_Git.GetShortHASHLength()); g_Git.GetOneFile(rev2, fileName, file2); ::SetFileAttributes(file2, FILE_ATTRIBUTE_READONLY); } else { file2=g_Git.m_CurrentDir+_T("\\")+pPath2->GetWinPathString(); title2.Format( IDS_DIFF_WCNAME, pPath2->GetFileOrDirectoryName() ); } if (pPath->m_Action == pPath->LOGACTIONS_ADDED) { CGitDiff::DiffNull(pPath, rev1, true); } else if (pPath->m_Action == pPath->LOGACTIONS_DELETED) { CGitDiff::DiffNull(pPath, rev2, false); } else { CAppUtils::DiffFlags flags; CAppUtils::StartExtDiff(file2,file1, title2, title1, g_Git.m_CurrentDir + _T("\\") + pPath2->GetWinPathString(), g_Git.m_CurrentDir + _T("\\") + pPath->GetWinPathString(), rev2, rev1, flags); } return 0; }