BOOL CFilePath::IsDirectory() const { return PathIsDirectory(msPath) != 0; }
bool GitAdminDir::HasAdminDir(const CString& path) const { return HasAdminDir(path, !!PathIsDirectory(path)); }
void recurse_dir(MediaScan *s, const char *path, int recurse_count) { char *dir, *p; #if defined(__unix__) || defined(__unix) // char *realdir; #endif char tmp_full_path[MAX_PATH_STR_LEN]; DIR *dirp; struct dirent *dp; struct dirq *subdirq; // list of subdirs of the current directory struct dirq_entry *parent_entry = NULL; // entry for current dir in s->_dirq char redirect_dir[MAX_PATH_STR_LEN]; if (recurse_count > RECURSE_LIMIT) { LOG_ERROR("Hit recurse limit of %d scanning path %s\n", RECURSE_LIMIT, path); return; } if (path[0] != '/') { // XXX Win32 // Get full path char *buf = (char *)malloc((size_t)MAX_PATH_STR_LEN); if (buf == NULL) { FATAL("Out of memory for directory scan\n"); return; } dir = getcwd(buf, (size_t)MAX_PATH_STR_LEN); strcat(dir, "/"); strcat(dir, path); } else { #ifdef USING_TCMALLOC // strdup will cause tcmalloc to crash on free dir = (char *)malloc((size_t)MAX_PATH_STR_LEN); strcpy(dir, path); #else dir = strdup(path); #endif } // Strip trailing slash if any p = &dir[0]; while (*p != 0) { if (p[1] == 0 && *p == '/') *p = 0; p++; } LOG_INFO("Recursed into %s\n", dir); #if (defined(__APPLE__) && defined(__MACH__)) if (isAlias(dir)) { if (CheckMacAlias(dir, redirect_dir)) { LOG_INFO("Resolving Alias %s to %s\n", dir, redirect_dir); strcpy(dir, redirect_dir); } else { LOG_ERROR("Failure to follow symlink or alias, skipping directory\n"); goto out; } } #elif (defined(__unix__) || defined(__unix)) if (isAlias(dir)) { FollowLink(dir, redirect_dir); LOG_INFO("Resolving symlink %s to %s\n", dir, redirect_dir); // realdir = redirect_dir; } else { // realdir = dir; } #endif if ((dirp = opendir(dir)) == NULL) { LOG_ERROR("Unable to open directory %s: %s\n", dir, strerror(errno)); goto out; } subdirq = malloc(sizeof(struct dirq)); SIMPLEQ_INIT(subdirq); while ((dp = readdir(dirp)) != NULL) { char *name = dp->d_name; // skip all dot files if (name[0] != '.') { // Check if scan should be aborted if (unlikely(s->_want_abort)) break; // Construct full path //*tmp_full_path = 0; strcpy(tmp_full_path, dir); strcat(tmp_full_path, "/"); strcat(tmp_full_path, name); // XXX some platforms may be missing d_type/DT_DIR #if (defined(__APPLE__) && defined(__MACH__)) || (defined(__unix__) || defined(__unix)) && !defined(__sun__) if (dp->d_type == DT_DIR) { #elif defined(__sun__) if (PathIsDirectory(tmp_full_path)) { #endif // Add to list of subdirectories we need to recurse into struct dirq_entry *subdir_entry = malloc(sizeof(struct dirq_entry)); if (_should_scan_dir(s, tmp_full_path)) { subdir_entry->dir = strdup(tmp_full_path); SIMPLEQ_INSERT_TAIL(subdirq, subdir_entry, entries); LOG_INFO(" subdir: %s\n", tmp_full_path); } else { LOG_INFO(" skipping subdir: %s\n", tmp_full_path); } } else { enum media_type type = _should_scan(s, name); LOG_INFO("name %s = type %d\n", name, type); if (type) { struct fileq_entry *entry; // Check if this file is a shortcut and if so resolve it #if (defined(__APPLE__) && defined(__MACH__)) if (isAlias(name)) { char full_name[MAX_PATH_STR_LEN]; LOG_INFO("Mac Alias detected\n"); strcpy(full_name, dir); strcat(full_name, "\\"); strcat(full_name, name); parse_lnk(full_name, redirect_dir, MAX_PATH_STR_LEN); if (PathIsDirectory(redirect_dir)) { struct dirq_entry *subdir_entry = malloc(sizeof(struct dirq_entry)); subdir_entry->dir = strdup(redirect_dir); SIMPLEQ_INSERT_TAIL(subdirq, subdir_entry, entries); LOG_INFO(" subdir: %s\n", tmp_full_path); type = 0; } } #elif (defined(__unix__) || defined(__unix)) if (isAlias(name)) { char full_name[MAX_PATH_STR_LEN]; printf("Unix alias detected for %s\n", name); strcpy(full_name, dir); strcat(full_name, "/"); strcat(full_name, name); FollowLink(full_name, redirect_dir); if (PathIsDirectory(redirect_dir)) { struct dirq_entry *subdir_entry = malloc(sizeof(struct dirq_entry)); subdir_entry->dir = strdup(full_name); SIMPLEQ_INSERT_TAIL(subdirq, subdir_entry, entries); LOG_INFO(" subdir: %s\n", tmp_full_path); type = 0; } } #endif if (parent_entry == NULL) { // Add parent directory to list of dirs with files parent_entry = malloc(sizeof(struct dirq_entry)); parent_entry->dir = strdup(dir); parent_entry->files = malloc(sizeof(struct fileq)); SIMPLEQ_INIT(parent_entry->files); SIMPLEQ_INSERT_TAIL((struct dirq *)s->_dirq, parent_entry, entries); } // Add scannable file to this directory list entry = malloc(sizeof(struct fileq_entry)); entry->file = strdup(name); entry->type = type; SIMPLEQ_INSERT_TAIL(parent_entry->files, entry, entries); s->progress->total++; LOG_INFO(" [%5d] file: %s\n", s->progress->total, entry->file); } } } } closedir(dirp); // Send progress update if (s->on_progress && !s->_want_abort) if (progress_update(s->progress, dir)) send_progress(s); // process subdirs while (!SIMPLEQ_EMPTY(subdirq)) { struct dirq_entry *subdir_entry = SIMPLEQ_FIRST(subdirq); SIMPLEQ_REMOVE_HEAD(subdirq, entries); if (!s->_want_abort) recurse_dir(s, subdir_entry->dir, recurse_count); free(subdir_entry); } free(subdirq); out: free(dir); }
void CFcastWinDlg::OnParamsUpdate() { CString Args, ValuePort; BYTE IPField1, IPField2, IPField3, IPField4; UpdateData(TRUE); if(m_TabCtrl.GetCurSel() == IDTAB_SEND) { m_FcastCmdLine = "-send -P"; } else if(m_TabCtrl.GetCurSel() == IDTAB_RECV) { m_FcastCmdLine = "-recv -P"; } else { return; } m_EditPort.GetWindowText(ValuePort); m_IPAddr.GetAddress(IPField1, IPField2, IPField3, IPField4); Args.Format(" -a%d.%d.%d.%d/%s",IPField1 , IPField2 , IPField3 , IPField4, ValuePort); switch( m_ComboOptimize.GetCurSel()) { case 0: break; case 1: Args += " -ospeed"; break; case 2: Args += " -ospace"; break; case 3: Args += " -ocpu"; break; default: break; } switch( m_ComboProfile.GetCurSel()) { case 0: break; case 1: Args += " -plow"; break; case 2: Args += " -pmed"; break; case 3: Args += " -phig"; break; case 4: Args += " -plan"; break; case 5: Args += " -p" + m_ValueDSize; if(m_TabCtrl.GetCurSel()==IDTAB_SEND && m_ValueBW!="") { Args += "/" + m_ValueBW; } default: break; } if( m_CheckNlayer.GetCheck() == BST_CHECKED && m_ValueNLvl!="" ) { Args += " -l" + m_ValueNLvl; } else if ( m_CheckSingleLayer.GetCheck() == BST_CHECKED ) { Args += " -singlelayer"; } if(m_CheckSilent.GetCheck() == BST_CHECKED) { Args += " -silent"; } else { CString ValueTraceLvl; CString ValueStatLvl; m_EditTraceLvl.GetWindowText(ValueTraceLvl); m_EditStatLvl.GetWindowText(ValueStatLvl); if( ValueTraceLvl != "" ) { Args += " -v" + ValueTraceLvl; } if( ValueStatLvl != "" ) { Args += " -stat" + ValueStatLvl; } } if(m_CheckDemux.GetCheck() == BST_CHECKED && m_ValueDemux!="") { Args += " -demux" + m_ValueDemux; } if(m_ValueTmpDir!="") { Args += " -tmpdir" + m_ValueTmpDir; } if(m_TabCtrl.GetCurSel() == IDTAB_SEND) { if(!m_ValuePathSend.IsEmpty()) { if(PathFileExists(m_ValuePathSend) && PathIsDirectory(m_ValuePathSend)) { m_CheckRecursive.EnableWindow(TRUE); m_CheckRecursive.SetCheck(BST_CHECKED); } else if(PathFileExists(m_ValuePathSend)) { m_CheckRecursive.EnableWindow(TRUE); m_CheckRecursive.SetCheck(BST_UNCHECKED); } else { m_CheckRecursive.SetCheck(BST_UNCHECKED); m_CheckRecursive.EnableWindow(FALSE); } } if(m_CheckRecursive.GetCheck() == BST_CHECKED) { Args += " -R"; } if( m_CheckTTL.GetCheck() && m_ValueTTL!="") { Args += " -t" + m_ValueTTL; } if( m_CheckFEC.GetCheck() && m_ValueFEC!="") { Args += " -fec" + m_ValueFEC; } if( m_CheckHuge.GetCheck() ) { Args += " -huge"; } if(m_CheckCont.GetCheck()) { Args += " -cont"; } else if( m_CheckRepeat.GetCheck() && m_ValueRepeat!="") { Args += " -repeat" + m_ValueRepeat; } } else if(m_TabCtrl.GetCurSel() == IDTAB_RECV) { switch( m_ComboOverwrite.GetCurSel()) { case 0: Args += " -int"; break; case 1: Args += " -never"; break; case 2: Args += " -force"; break; default: break; } } m_FcastCmdLine += Args; UpdateData(FALSE); }
HRESULT _stdcall CContainer::CBookmarkToolbarDrop::Drop(IDataObject *pDataObject, DWORD grfKeyState,POINTL pt,DWORD *pdwEffect) { FORMATETC ftc; STGMEDIUM stg; DROPFILES *pdf = NULL; TBINSERTMARK tbim; Bookmark_t RootBookmark; Bookmark_t NewBookmark; TCHAR szBookmarkName[MAX_PATH]; HRESULT hr; int nDroppedFiles; tbim.iButton = -1; SendMessage(m_pContainer->m_hBookmarksToolbar, TB_SETINSERTMARK,0,(LPARAM)&tbim); ftc.cfFormat = CF_HDROP; ftc.ptd = NULL; ftc.dwAspect = DVASPECT_CONTENT; ftc.lindex = -1; ftc.tymed = TYMED_HGLOBAL; /* Does the dropped object contain the type of data we need? */ hr = pDataObject->GetData(&ftc,&stg); if(hr == S_OK) { /* Need to remove the drag image before any files are copied/moved. This is because a copy/replace dialog may need to shown (if there is a collision), and the drag image no longer needs to be there. The insertion mark may stay until the end. */ m_pDropTargetHelper->Drop(pDataObject,(POINT *)&pt,*pdwEffect); pdf = (DROPFILES *)GlobalLock(stg.hGlobal); if(pdf != NULL) { /* Request a count of the number of files that have been dropped. */ nDroppedFiles = DragQueryFile((HDROP)pdf,0xFFFFFFFF,NULL,NULL); TCHAR szFullFileName[MAX_PATH]; int i = 0; m_pContainer->m_Bookmark.GetRoot(&RootBookmark); /* For each folder item, create a new bookmark. */ for(i = 0;i < nDroppedFiles;i++) { /* Determine the name of the dropped file. */ DragQueryFile((HDROP)pdf,i,szFullFileName, SIZEOF_ARRAY(szFullFileName)); if(PathIsDirectory(szFullFileName)) { /* The name of the bookmark is the stripped folder name. */ StringCchCopy(szBookmarkName,SIZEOF_ARRAY(szBookmarkName),szFullFileName); PathStripPath(szBookmarkName); StringCchCopy(NewBookmark.szItemName,SIZEOF_ARRAY(NewBookmark.szItemName),szBookmarkName); StringCchCopy(NewBookmark.szItemDescription,SIZEOF_ARRAY(NewBookmark.szItemDescription),EMPTY_STRING); StringCchCopy(NewBookmark.szLocation,SIZEOF_ARRAY(NewBookmark.szLocation),szFullFileName); NewBookmark.Type = BOOKMARK_TYPE_BOOKMARK; NewBookmark.bShowOnToolbar = TRUE; /* Create the bookmark. */ m_pContainer->m_Bookmark.CreateNewBookmark((void *)RootBookmark.pHandle,&NewBookmark); /* ...and add it to the toolbar. */ m_pContainer->InsertBookmarkIntoToolbar(&NewBookmark, m_pContainer->GenerateUniqueBookmarkToolbarId()); } } GlobalUnlock(stg.hGlobal); } ReleaseStgMedium(&stg); } /* Rebuild the bookmarks menu. */ m_pContainer->InsertBookmarksIntoMenu(); return S_OK; }
BOOL CRecorderApp::InitInstance() { // 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); CWinApp::InitInstance(); AfxEnableControlContainer(); // Create the shell manager, in case the dialog contains // any shell tree view or shell list view controls. CShellManager *pShellManager = new CShellManager; // 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 // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); //the Initialization for the call of external dll and lib!!! bool res = false,res1=false,res2=false,res3=false; res = mclInitializeApplication(NULL,0); if (!res) { AfxMessageBox(_T("��ʼ��Application������")); } res = InitializeInitialize(); res1 = TrainingInitialize(); res2 = IncTrainInitialize(); res3 = TestSpeechInitialize(); if (!res||!res1||!res2||!res3) { AfxMessageBox(_T("��ʼ��Lib������")); } CString sPath; GetModuleFileName(NULL,sPath.GetBufferSetLength(MAX_PATH+1),MAX_PATH); sPath.ReleaseBuffer(); int nPos; nPos=sPath.ReverseFind ('\\'); sPath=sPath.Left (nPos); CString lpszFile = sPath + "\\SR1.accdb"; //AfxMessageBox(lpszFile);// CString str; str.Format(_T("DSN=%s? DBQ=%s? FIL=MicrosoftAccess? DEFAULTDIR=%s?? "),_T("SRDSN"),lpszFile,sPath); int mlen = str.GetLength(); for (int i=0; i<mlen; i++) { if (str.GetAt(i) == '?') str.SetAt(i,'\0'); } if (FALSE == SQLConfigDataSource(NULL,ODBC_ADD_DSN,_T("Microsoft Access Driver (*.mdb, *.accdb)\0"),str)) AfxMessageBox(_T("SQLConfigDataSource Failed")); //seek for the folder,if not exist,create it. CString folderName = _T("E:\\Speechdata"); if(!PathIsDirectory(folderName)){ CreateDirectory(folderName,NULL); } folderName = _T("E:\\Speechdata\\Test"); if(!PathIsDirectory(folderName)){ CreateDirectory(folderName,NULL); } CFirstPageDlg cfpdlg; cfpdlg.DoModal(); // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. InitializeTerminate(); TrainingTerminate(); IncTrainTerminate(); TestSpeechTerminate(); res = mclTerminateApplication(); if (!res) { AfxMessageBox(_T("����Application����!")); } return FALSE; }
HRESULT __stdcall CBookmarksToolbarDropHandler::Drop(IDataObject *pDataObject, DWORD grfKeyState,POINTL pt,DWORD *pdwEffect) { UNREFERENCED_PARAMETER(grfKeyState); FORMATETC ftc = {CF_HDROP,0,DVASPECT_CONTENT,-1,TYMED_HGLOBAL}; STGMEDIUM stg; HRESULT hr = pDataObject->GetData(&ftc,&stg); if(hr == S_OK) { DROPFILES *pdf = reinterpret_cast<DROPFILES *>(GlobalLock(stg.hGlobal)); if(pdf != NULL) { bool bAfter; int iPosition = GetToolbarPositionIndex(pt,bAfter); if(iPosition < 0) { iPosition = static_cast<int>(SendMessage(m_hToolbar,TB_BUTTONCOUNT,0,0)); } else { if(bAfter) { iPosition++; } } UINT nDroppedFiles = DragQueryFile(reinterpret_cast<HDROP>(pdf),0xFFFFFFFF,NULL,NULL); for(UINT i = 0;i < nDroppedFiles;i++) { TCHAR szFullFileName[MAX_PATH]; DragQueryFile(reinterpret_cast<HDROP>(pdf),i,szFullFileName, SIZEOF_ARRAY(szFullFileName)); if(PathIsDirectory(szFullFileName)) { TCHAR szDisplayName[MAX_PATH]; GetDisplayName(szFullFileName,szDisplayName,SIZEOF_ARRAY(szDisplayName),SHGDN_INFOLDER); CBookmark Bookmark(szDisplayName,szFullFileName,EMPTY_STRING); auto variantBookmarksToolbar = NBookmarkHelper::GetBookmarkItem(m_AllBookmarks,m_guidBookmarksToolbar); assert(variantBookmarksToolbar.type() == typeid(CBookmarkFolder)); CBookmarkFolder &BookmarksToolbarFolder = boost::get<CBookmarkFolder>(variantBookmarksToolbar); BookmarksToolbarFolder.InsertBookmark(Bookmark,iPosition + i); } } GlobalUnlock(stg.hGlobal); } ReleaseStgMedium(&stg); } RemoveInsertionMark(); m_pDropTargetHelper->Drop(pDataObject,reinterpret_cast<POINT *>(&pt),*pdwEffect); return S_OK; }
BOOL IsDirExist(LPCTSTR szFilePath) { return PathIsDirectory(szFilePath); }
int CTGitPathList::FillBasedOnIndexFlags(unsigned short flag, CTGitPathList* list /*nullptr*/) { Clear(); CTGitPath path; CAutoRepository repository(g_Git.GetGitRepository()); if (!repository) return -1; CAutoIndex index; if (git_repository_index(index.GetPointer(), repository)) return -1; int count; if (list == nullptr) count = 1; else count = list->GetCount(); for (int j = 0; j < count; ++j) { for (size_t i = 0, ecount = git_index_entrycount(index); i < ecount; ++i) { const git_index_entry *e = git_index_get_byindex(index, i); if (!e || !((e->flags | e->flags_extended) & flag) || !e->path) continue; CString one = CUnicodeUtils::GetUnicode(e->path); if (!(!list || (*list)[j].GetWinPathString().IsEmpty() || one == (*list)[j].GetGitPathString() || (PathIsDirectory(g_Git.CombinePath((*list)[j].GetWinPathString())) && one.Find((*list)[j].GetGitPathString() + _T("/")) == 0))) continue; //SetFromGit will clear all status path.SetFromGit(one); if ((e->flags | e->flags_extended) & GIT_IDXENTRY_SKIP_WORKTREE) path.m_Action = CTGitPath::LOGACTIONS_SKIPWORKTREE; else if ((e->flags | e->flags_extended) & GIT_IDXENTRY_VALID) path.m_Action = CTGitPath::LOGACTIONS_ASSUMEVALID; AddPath(path); } } RemoveDuplicates(); return 0; }
bool PerigeeMove::DoIt() { file_list::size_type num = 0, cnt = m_files.size(); m_progress.m_Progress.SetRange32(0, cnt); m_progress.m_Progress.SetPos(0); m_progress.m_Progress.SetStep(1); for(file_list::iterator it = m_files.begin(); it != m_files.end(); ++it) { CString dest_name = PsAppendPath(it->dest, PathFindFileName(it->source)); m_progress.SetSourceDest(it->source, dest_name); // first make sure the destination isn't the source; otherwise, there's nothing to do if (0 != it->source.CompareNoCase(dest_name)) { // check whether the destination is a subfolder of the source, and skip if ( PathIsDirectory(it->source) && DestIsSubfolderOfSource(dest_name, it->source) ) { file_info fi; fi.source = it->source; fi.dest = dest_name; fi.error_code = ERROR_INVALID_PARAMETER; fi.error_type = warn_move_dest_is_subfolder_of_source; m_error_files.push_back(fi); continue; } TargetState state = CheckTarget(dest_name, it->source); if ( targetCanBeOverwritten == state ) { if ( m_options.overwrite_read_only ) PrepareOverwrite(dest_name); if ( m_options.recycle ) PsRecycle(dest_name); else DeleteFile(dest_name); } else if ( targetCannotBeOverwritten == state ) { if (m_options.overwrite == CPerigeeCopyOptions::overwrite_postpone) { // put the file in the error list for now file_info fi; fi.source = it->source; fi.dest = it->dest; fi.error_code = ERROR_FILE_EXISTS; fi.error_type = err_move; m_error_files.push_back(fi); continue; } else { // exclude the file from the job --cnt; m_progress.m_Progress.SetRange32(0, cnt); ProcessMessages(); m_cancel = m_cancel || m_progress.m_CancelRequest; if ( m_cancel ) break; continue; } } while ( !MoveFile(it->source, dest_name) ) { file_info fi; fi.source = it->source; fi.dest = it->dest; fi.error_code = GetLastError(); fi.error_type = err_move; if ( !HandleError(fi) ) break; } } m_progress.m_Progress.StepIt(); UpdateTitleBar(m_progress, IDS_MOVING_FILES, num++, cnt); ProcessMessages(); m_cancel = m_cancel || m_progress.m_CancelRequest; if ( m_cancel ) break; } return m_error_files.empty(); }
BOOL IsFileExists( LPCTSTR pszFile ) { return ::PathFileExists( pszFile ) && !PathIsDirectory( pszFile ); }
bool UnixDirectoryReader::EntryIsDirectory() { return PathIsDirectory(this->fpath); }
int CPatch::PatchFile(int nIndex, const CString& sPatchPath, const CString& sSavePath, const CString& sBaseFile, const bool force) { CString sPath = GetFullPath(sPatchPath, nIndex); if (PathIsDirectory(sPath)) { m_sErrorMessage.Format(IDS_ERR_PATCH_INVALIDPATCHFILE, (LPCTSTR)sPath); return FALSE; } if (nIndex < 0) { m_sErrorMessage.Format(IDS_ERR_PATCH_FILENOTINPATCH, (LPCTSTR)sPath); return FALSE; } if (!force && sPath == _T("NUL") && PathFileExists(GetFullPath(sPatchPath, nIndex, 1))) return FALSE; if (GetFullPath(sPatchPath, nIndex, 1) == _T("NUL") && !PathFileExists(sPath)) return 2; CString sLine; CString sPatchFile = sBaseFile.IsEmpty() ? sPath : sBaseFile; if (PathFileExists(sPatchFile)) { CCrashReport::Instance().AddFile2(sPatchFile, NULL, _T("File to patch"), CR_AF_MAKE_FILE_COPY); } CFileTextLines PatchLines; CFileTextLines PatchLinesResult; PatchLines.Load(sPatchFile); PatchLinesResult = PatchLines; //.Copy(PatchLines); PatchLines.CopySettings(&PatchLinesResult); Chunks * chunks = m_arFileDiffs.GetAt(nIndex); for (int i=0; i<chunks->chunks.GetCount(); i++) { Chunk * chunk = chunks->chunks.GetAt(i); LONG lRemoveLine = chunk->lRemoveStart; LONG lAddLine = chunk->lAddStart; for (int j=0; j<chunk->arLines.GetCount(); j++) { CString sPatchLine = chunk->arLines.GetAt(j); EOL ending = chunk->arEOLs[j]; if ((m_UnicodeType != CFileTextLines::UTF8)&&(m_UnicodeType != CFileTextLines::UTF8BOM)) { if ((PatchLines.GetUnicodeType()==CFileTextLines::UTF8)||(m_UnicodeType == CFileTextLines::UTF8BOM)) { // convert the UTF-8 contents in CString sPatchLine into a CStringA sPatchLine = CUnicodeUtils::GetUnicode(CStringA(sPatchLine)); } } int nPatchState = (int)chunk->arLinesStates.GetAt(j); switch (nPatchState) { case PATCHSTATE_REMOVED: { if ((lAddLine > PatchLines.GetCount())||(PatchLines.GetCount()==0)) { m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, _T(""), (LPCTSTR)sPatchLine); return FALSE; } if (lAddLine == 0) lAddLine = 1; if ((sPatchLine.Compare(PatchLines.GetAt(lAddLine-1))!=0)&&(!HasExpandedKeyWords(sPatchLine))) { m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, (LPCTSTR)sPatchLine, (LPCTSTR)PatchLines.GetAt(lAddLine-1)); return FALSE; } if (lAddLine > PatchLines.GetCount()) { m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, (LPCTSTR)sPatchLine, _T("")); return FALSE; } PatchLines.RemoveAt(lAddLine-1); } break; case PATCHSTATE_ADDED: { if (lAddLine == 0) lAddLine = 1; PatchLines.InsertAt(lAddLine-1, sPatchLine, ending); lAddLine++; } break; case PATCHSTATE_CONTEXT: { if (lAddLine > PatchLines.GetCount()) { m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, _T(""), (LPCTSTR)sPatchLine); return FALSE; } if (lAddLine == 0) lAddLine++; if (lRemoveLine == 0) lRemoveLine++; if ((sPatchLine.Compare(PatchLines.GetAt(lAddLine-1))!=0) && (!HasExpandedKeyWords(sPatchLine)) && (lRemoveLine <= PatchLines.GetCount()) && (sPatchLine.Compare(PatchLines.GetAt(lRemoveLine-1))!=0)) { if ((lAddLine < PatchLines.GetCount())&&(sPatchLine.Compare(PatchLines.GetAt(lAddLine))==0)) lAddLine++; else if (((lAddLine + 1) < PatchLines.GetCount())&&(sPatchLine.Compare(PatchLines.GetAt(lAddLine+1))==0)) lAddLine += 2; else if ((lRemoveLine < PatchLines.GetCount())&&(sPatchLine.Compare(PatchLines.GetAt(lRemoveLine))==0)) lRemoveLine++; else { m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, (LPCTSTR)sPatchLine, (LPCTSTR)PatchLines.GetAt(lAddLine-1)); return FALSE; } } lAddLine++; lRemoveLine++; } break; default: ASSERT(FALSE); break; } // switch (nPatchState) } // for (j=0; j<chunk->arLines.GetCount(); j++) } // for (int i=0; i<chunks->chunks.GetCount(); i++) if (!sSavePath.IsEmpty()) { PatchLines.Save(sSavePath, false); } return TRUE; }
//暗号化 CIPHER_RESULT PmCipher::Encrypt(const char *source_path, const char *cipher_path, bool compress, bool recursive) { //戻り値・・・ステータス //第1引数・・・暗号化するファイル/ディレクトリのパス //第2引数・・・暗号化ファイルのパス //第3引数・・・圧縮フラグ(true:圧縮, false:無圧縮) //第4引数・・・再帰処理フラグ(true:再帰処理あり(デフォルト), false:再帰処理なし) //ファイルストリーム fstream fs_cipher, fs_cipher_idx, fs_cipher_temp; //パス string str_find_path, str_source_path, str_idx_path, str_idx2_path, str_temp_path, str_cipher_path; //ファイルソート用 unsigned int depth = 0, directory_num = 0; //ファイル検索続行フラグ BOOL next = TRUE; //戻り値 CIPHER_RESULT cr = CIPHER_OK; //再帰処理用スタック stack<HANDLE> stack_handle; stack<BOOL> stack_next; stack<string> stack_directory; hash_map<string, unsigned int> map_directory_num; pair<string, unsigned int> pair_directory_num; //カレントディレクトリ string current_directory; //ファイル検索用変数 WIN32_FIND_DATA FindFileData; HANDLE hFind; //ファイルの位置 unsigned long offset = 0; //圧縮フラグ保存 m_compress = compress; char key_word[] = CIPHER_KEY_WORD; char cipher_key_word[CIPHER_KEY_WORD_SIZE]; m_blow_fish.Encode((unsigned char *)key_word, (unsigned char *)cipher_key_word, 8); //ファイルプロパティクラス変数 PmCipherProperty *cipher_property = NULL; //元ファイルパス、中間ファイルパスの生成 str_source_path = string(source_path); if(str_source_path.rfind("\\") == str_source_path.size() - 1) { str_source_path = str_source_path.substr(0, str_source_path.size() - 1); } str_cipher_path = string(cipher_path); str_idx_path = str_cipher_path + string(".idx"); str_idx2_path = str_cipher_path + string(".idx2"); str_temp_path = str_cipher_path + string(".tmp"); if(!PathFileExists(str_cipher_path.substr(0, str_cipher_path.rfind("\\")).c_str()) || !PathIsDirectory(str_cipher_path.substr(0, str_cipher_path.rfind("\\")).c_str())) { return CIPHER_ERR_FILE_NOT_FOUND; } //最初のファイル検索 hFind = FindFirstFile(str_source_path.c_str(), &FindFileData); current_directory = str_source_path; //暗号化ファイル(中間ファイル)のオープン fs_cipher_temp.open(str_temp_path.c_str(), ios::out|ios::binary); //検索が成功した場合 if(hFind != INVALID_HANDLE_VALUE) { //引数で指定されたパスがファイルの場合 if(!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { //サイズチェック if(FindFileData.nFileSizeHigh > 0 || Over2GB(FindFileData.nFileSizeLow)) { cr = CIPHER_ERR_INVALID_FILE_SIZE; } else { //ファイルを暗号化 if((cr = PmCipher::EncryptFile(str_source_path.c_str(), FindFileData.nFileSizeLow, compress, &fs_cipher_temp, &cipher_property)) == CIPHER_OK) { cipher_property->SetOffset(offset); m_property_list->AddProperty(cipher_property); offset += cipher_property->GetCipherSize(); cipher_property = NULL; FindClose(hFind); } } next = FALSE; } //引数で指定されたパスがディレクトリの場合 else { //ワイルドカードを付加して再検索 str_find_path = str_source_path + string("\\*"); hFind = FindFirstFile(str_find_path.c_str(), &FindFileData); pair_directory_num.first = current_directory; pair_directory_num.second = directory_num; map_directory_num.insert(pair_directory_num); } } //検索が失敗した場合エラー終了 else { cr = CIPHER_ERR_FILE_NOT_FOUND; next = FALSE; } //再帰処理が終了しかつ、ファイル検索が終了するまでループ while(!stack_handle.empty() || next) { //ディレクトリのすべてのファイルを検索し終わったら検索処理終了 if(!next) { FindClose(hFind); //再帰処理の途中の場合、上位フォルダを復帰 if(!stack_handle.empty()) { hFind = stack_handle.top(); stack_handle.pop(); next = stack_next.top(); stack_next.pop(); current_directory = stack_directory.top(); stack_directory.pop(); depth--; if(next) { next = FindNextFile(hFind, &FindFileData); } } } //検索したファイル属性がディレクトリの場合でかつ、再帰処理を行う場合 if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && recursive && next) { //下位ディレクトリの場合は再帰処理 if(strcmp(FindFileData.cFileName, ".") && strcmp(FindFileData.cFileName, "..")) { stack_handle.push(hFind); stack_next.push(next); stack_directory.push(current_directory); current_directory = current_directory + string("\\") + string(FindFileData.cFileName); depth++; directory_num++; pair_directory_num.first = current_directory; pair_directory_num.second = directory_num; map_directory_num.insert(pair_directory_num); str_find_path = current_directory + string("\\*"); hFind = FindFirstFile(str_find_path.c_str(), &FindFileData); if(hFind != INVALID_HANDLE_VALUE) { next = TRUE; continue; } else { next = FALSE; cr = CIPHER_ERR_INVALID_FILE; } } } //検索したファイル属性がファイルの場合は暗号化 if(!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && next) { //サイズチェック if(FindFileData.nFileSizeHigh > 0 || Over2GB(FindFileData.nFileSizeLow + offset)) { next = FALSE; cr = CIPHER_ERR_INVALID_FILE_SIZE; } else { str_find_path = current_directory + string("\\") + string(FindFileData.cFileName); if((cr = PmCipher::EncryptFile(str_find_path.c_str(), FindFileData.nFileSizeLow, compress, &fs_cipher_temp, &cipher_property)) == CIPHER_OK) { cipher_property->SetOffset(offset); offset += cipher_property->GetCipherSize(); cipher_property->SetDepth(depth); hash_map<string, unsigned int>::iterator it; if((it = map_directory_num.find(current_directory)) != map_directory_num.end()) { cipher_property->SetDirectoryNum(it->second); } else { cr = CIPHER_ERR_FATAL; next = FALSE; } m_property_list->AddProperty(cipher_property); cipher_property = NULL; } } } //エラーが起きたら直ちに終了 if(cr != CIPHER_OK) { while(!stack_handle.empty()) { hFind = stack_handle.top(); FindClose(hFind); stack_handle.pop(); } next = FALSE; } //次のファイルを検索 if(next) { next = FindNextFile(hFind, &FindFileData); } } //暗号化ファイル(中間ファイル)のクローズ fs_cipher_temp.close(); //暗号化が正常に終了した場合 if(cr == CIPHER_OK) { //ファイル、バッファ等のサイズ unsigned long index_size = 0, cipher_index_size, compress_index_size, buf_size, total_buf_size; //バッファメモリの確保 unsigned char *input_buf = new unsigned char[PmCipher::CIPHER_BUF_SIZE]; unsigned char *output_buf = new unsigned char[PmCipher::CIPHER_BUF_SIZE]; //文字列 char str[CIPHER_MAX_INDEX_SIZE]; //インデックスのソート m_property_list->SortProperty(); //インデックス書き込み(平文中間ファイル) fs_cipher_idx.open(str_idx_path.c_str(), ios::out|ios::binary); //ルートディレクトリ書き込み sprintf_s(str, MAX_PATH + 1, "%s\n", str_source_path.c_str()); index_size += str_source_path.length() + 1; fs_cipher_idx.write(str, str_source_path.length() + 1); for(unsigned int i = 0; i < m_property_list->GetPropertySize(); i++) { unsigned int str_size = 40 + m_property_list->GetProperty(i)->GetPath().length() + 1; sprintf_s(str, CIPHER_MAX_INDEX_SIZE, "%010lu%010lu%010lu%010lu%s\n", m_property_list->GetProperty(i)->GetOffset(), m_property_list->GetProperty(i)->GetSourceSize(), m_property_list->GetProperty(i)->GetCompressSize(), m_property_list->GetProperty(i)->GetCipherSize(), m_property_list->GetProperty(i)->GetPath().c_str()); fs_cipher_idx.write(str, str_size); index_size += (unsigned long)str_size; } fs_cipher_idx.close(); //インデックス書き込み(暗号化中間ファイル) fs_cipher_idx.open(str_idx2_path.c_str(), ios::out|ios::binary); if((cr = EncryptFile(str_idx_path.c_str(), index_size, compress, &fs_cipher_idx, &cipher_property)) == CIPHER_OK) { if(!Over2GB(cipher_property->GetCipherSize() + offset + CIPHER_HEADER_SIZE + CIPHER_KEY_WORD_SIZE)) { compress_index_size = cipher_property->GetCompressSize(); cipher_index_size = cipher_property->GetCipherSize(); SAFE_DELETE(cipher_property); fs_cipher_idx.close(); fs_cipher.open(str_cipher_path.c_str(), ios::out|ios::binary); //キーワード書き込み fs_cipher.write(cipher_key_word, CIPHER_KEY_WORD_SIZE); //ヘッダの書き込み sprintf_s(str, CIPHER_MAX_INDEX_SIZE, "%d%010lu%010lu%010lu%010lu", compress?1:0, index_size, compress_index_size, cipher_index_size, offset); fs_cipher.write(str, CIPHER_HEADER_SIZE); fs_cipher_idx.open(str_idx2_path.c_str(), ios::in|ios::binary); //ヘッダと暗号化したインデックス、データファイルの結合 total_buf_size = 0; while(!fs_cipher_idx.eof()) { buf_size = (total_buf_size + CIPHER_BUF_SIZE > cipher_index_size)?(cipher_index_size - total_buf_size):CIPHER_BUF_SIZE; fs_cipher_idx.read((char *)input_buf, buf_size); fs_cipher.write((char *)input_buf, buf_size); total_buf_size += buf_size; if(cipher_index_size <= total_buf_size) { break; } } fs_cipher_idx.close(); fs_cipher_temp.open(str_temp_path.c_str(), ios::in|ios::binary); total_buf_size = 0; while(!fs_cipher_temp.eof()) { buf_size = (total_buf_size + CIPHER_BUF_SIZE > offset)?(offset - total_buf_size):CIPHER_BUF_SIZE; fs_cipher_temp.read((char *)input_buf, buf_size); fs_cipher.write((char *)input_buf, buf_size); total_buf_size += buf_size; if(offset <= total_buf_size) { break; } } fs_cipher << std::flush; } else { cr = CIPHER_ERR_INVALID_FILE_SIZE; } } //ファイルのクローズ fs_cipher_temp.close(); fs_cipher.close(); m_cipher_index_size = cipher_index_size; //バッファメモリの解放 SAFE_DELETE_ARRAY(input_buf); SAFE_DELETE_ARRAY(output_buf); } return cr; }
INT_PTR CDropbox::ProtoSendFile(WPARAM, LPARAM lParam) { CCSDATA *pccsd = (CCSDATA*)lParam; if (!HasAccessToken()) { ProtoBroadcastAck(MODULE, pccsd->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, NULL, (LPARAM)"You cannot send files when you are not authorized."); return 0; } FileTransferParam *ftp = new FileTransferParam(); ftp->pfts.flags |= PFTS_SENDING; ftp->pfts.hContact = pccsd->hContact; ftp->hContact = (hTransferContact) ? hTransferContact : pccsd->hContact; hTransferContact = 0; TCHAR **paths = (TCHAR**)pccsd->lParam; for (int i = 0; paths[i]; i++) { if (PathIsDirectory(paths[i])) ftp->totalFolders++; else ftp->pfts.totalFiles++; } ftp->ptszFolders = (TCHAR**)mir_alloc(sizeof(TCHAR*) * (ftp->totalFolders + 1)); ftp->ptszFolders[ftp->totalFolders] = NULL; ftp->pfts.ptszFiles = (TCHAR**)mir_alloc(sizeof(TCHAR*) * (ftp->pfts.totalFiles + 1)); ftp->pfts.ptszFiles[ftp->pfts.totalFiles] = NULL; for (int i = 0, j = 0, k = 0; paths[i]; i++) { if (PathIsDirectory(paths[i])) { if (!ftp->relativePathStart) { TCHAR *rootFolder = paths[j]; TCHAR *relativePath = _tcsrchr(rootFolder, '\\') + 1; ftp->relativePathStart = relativePath - rootFolder; } ftp->ptszFolders[j] = mir_tstrdup(&paths[i][ftp->relativePathStart]); j++; } else { if (!ftp->pfts.tszWorkingDir) { TCHAR *path = paths[j]; int length = _tcsrchr(path, '\\') - path; ftp->pfts.tszWorkingDir = (TCHAR*)mir_alloc(sizeof(TCHAR) * (length + 1)); mir_tstrncpy(ftp->pfts.tszWorkingDir, paths[j], length + 1); ftp->pfts.tszWorkingDir[length] = '\0'; } ftp->pfts.ptszFiles[k] = mir_wstrdup(paths[i]); FILE *file = _wfopen(paths[i], L"rb"); if (file != NULL) { fseek(file, 0, SEEK_END); ftp->pfts.totalBytes += ftell(file); fseek(file, 0, SEEK_SET); fclose(file); } k++; } } ULONG fileId = InterlockedIncrement(&hFileProcess); ftp->hProcess = (HANDLE)fileId; transfers.insert(ftp); mir_forkthreadowner(CDropbox::SendFilesAndReportAsync, this, ftp, 0); return fileId; }
VOID GetIniFilePath(TCHAR *inPath, const TCHAR *inINIFileName, const TCHAR *inAppName) { TCHAR szFilePath[MAX_PATH_SIZE + 100]; UINT nRet = 0; *szFilePath = '\0'; #if _MSC_VER < 1500 if(GetVerifyVersionInfo(5, 0, 0)) { HMODULE hDll; UINT nLen; TCHAR *szPath; const TCHAR *szFile = _T("SHELL32.DLL"); #ifdef _UNICODE const char *szFunc = "SHGetFolderPathW"; #else const char *szFunc = "SHGetFolderPathA"; #endif nLen = GetSystemDirectory(0, 0); if(nLen < 1) goto FOUL; nLen += (UINT)_tcslen(szFile) + 1; szPath = (TCHAR*)malloc(nLen * sizeof(TCHAR)); if(szPath == NULL) goto FOUL; nRet = GetSystemDirectory(szPath, nLen); if(nRet < 0) goto FOUL; TCHAR *p = szPath + nRet; *(p++) = _T('\\'); _tcscpy(p, szFile); hDll = LoadLibrary(szPath); if(hDll != NULL) { HRESULT (WINAPI *SHGetFolderPath)(HWND, int, HANDLE, DWORD, LPTSTR); SHGetFolderPath = reinterpret_cast<HRESULT(WINAPI*)(HWND, int, HANDLE, DWORD, LPTSTR)>(GetProcAddress(hDll, szFunc)); if(SHGetFolderPath != NULL) { #endif /* _MSC_VER < 1500 */ HRESULT hRet; if(GetModuleFileName(NULL, inPath, MAX_PATH_SIZE + 100) != NULL) { hRet = SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, 0, szFilePath); if (SUCCEEDED(hRet)) { TCHAR *p; // Program File から実行されているか確認。 p = _tcsstr(inPath, szFilePath); // 実行されていたら Appdata のパスにする。 if(p != NULL) { hRet = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, szFilePath); if(SUCCEEDED(hRet)) { // inPath に Appdata のパスをコピーする。 p = _qtcscpy(inPath, szFilePath); *(p++) = _T('\\'); // inPath に inAppName のパスを追記する。 p = _qtcscpy(p, inAppName); *(p++) = _T('\\'); *p = _T('\0'); // inAppName のフォルダーがない場合は作成する。 if(!PathIsDirectory(inPath)) { CreateDirectory(inPath, NULL); } // 最後に inINIFileName を追記してINIファイルのパスが完成。 _tcscpy(p, inINIFileName); nRet = 1; } } #if _MSC_VER < 1500 else { nRet = 0; } #endif /* _MSC_VER < 1500 */ } } #if _MSC_VER < 1500 } FreeLibrary(hDll); } FOUL: if(szPath) free(szPath); } #endif /* _MSC_VER < 1500 */ if(!nRet) { TCHAR *p; if(GetModuleFileName(NULL, szFilePath, MAX_PATH_SIZE + 100) != NULL) { PathRemoveFileSpec(szFilePath); p = _qtcscpy(inPath, szFilePath); *(p++) = _T('\\'); _tcscpy(p, inINIFileName); } } return; }
// Downloads file from the net unsigned __stdcall NetworkDownloadThreadProc(void* pParam) { MeasureData* measure = (MeasureData*)pParam; const bool download = !measure->downloadFile.empty(); bool ready = false; std::wstring url; if (measure->regExp.empty() && measure->resultString.empty()) { if (!measure->url.empty() && measure->url[0] != L'[') { url = measure->url; } } else { EnterCriticalSection(&g_CriticalSection); url = measure->resultString; LeaveCriticalSection(&g_CriticalSection); std::wstring::size_type pos = url.find(L':'); if (pos == std::wstring::npos && !url.empty()) // No protocol { // Add the base url to the string if (url[0] == L'/') { // Absolute path pos = measure->url.find(L'/', 7); // Assume "http://" (=7) if (pos != std::wstring::npos) { std::wstring path(measure->url.substr(0, pos)); url = path + url; } } else { // Relative path pos = measure->url.rfind(L'/'); if (pos != std::wstring::npos) { std::wstring path(measure->url.substr(0, pos + 1)); url = path + url; } } } } if (!url.empty()) { // Create the filename WCHAR buffer[MAX_PATH] = {0}; std::wstring fullpath, directory; if (download) // download mode { PathCanonicalize(buffer, measure->downloadFile.c_str()); std::wstring path = buffer; std::wstring::size_type pos = path.find_first_not_of(L'\\'); if (pos != std::wstring::npos) { path.erase(0, pos); } PathCanonicalize(buffer, measure->downloadFolder.c_str()); CreateDirectory(buffer, nullptr); // Make sure that the folder exists wcscat(buffer, path.c_str()); if (buffer[wcslen(buffer)-1] != L'\\') // path is a file { fullpath = buffer; PathRemoveFileSpec(buffer); } PathAddBackslash(buffer); } else // cache mode { GetTempPath(MAX_PATH, buffer); wcscat(buffer, L"Rainmeter-Cache\\"); // "%TEMP%\Rainmeter-Cache\" } CreateDirectory(buffer, nullptr); // Make sure that the folder exists directory = buffer; if (fullpath.empty()) { fullpath = directory; std::wstring::size_type pos2 = url.find_first_of(L"?#"); std::wstring::size_type pos1 = url.find_last_of(L'/', pos2); pos1 = (pos1 != std::wstring::npos) ? pos1 + 1 : 0; std::wstring name; if (pos2 != std::wstring::npos) { name.assign(url, pos1, pos2 - pos1); } else { name.assign(url, pos1, url.length() - pos1); } if (!name.empty()) { // Replace reserved characters to "_" pos1 = 0; while ((pos1 = name.find_first_of(L"\\/:*?\"<>|", pos1)) != std::wstring::npos) { name[pos1] = L'_'; } fullpath += name; } else { fullpath += L"index"; } } ready = true; if (download) // download mode { if (!PathFileExists(directory.c_str()) || !PathIsDirectory(directory.c_str())) { ready = false; RmLogF( measure->rm, LOG_ERROR, L"WebParser: Directory does not exist: %s", directory.c_str()); } else if (PathIsDirectory(fullpath.c_str())) { ready = false; RmLogF( measure->rm, LOG_ERROR, L"WebParser: Path is a directory, not a file: %s", fullpath.c_str()); } else if (PathFileExists(fullpath.c_str())) { DWORD attr = GetFileAttributes(fullpath.c_str()); if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_READONLY)) { ready = false; RmLogF( measure->rm, LOG_ERROR, L"WebParser: File is read-only: %s", fullpath.c_str()); } } } else // cache mode { EnterCriticalSection(&g_CriticalSection); if (PathFileExists(fullpath.c_str())) { std::wstring::size_type pos = fullpath.find_last_of(L'.'); std::wstring path, ext; if (pos != std::wstring::npos) { path.assign(fullpath, 0, pos); ext.assign(fullpath, pos, fullpath.length() - pos); } else { path = fullpath; } // Assign a serial number int i = 1; do { wsprintf(buffer, L"_%i", i++); fullpath = path; fullpath += buffer; if (!ext.empty()) { fullpath += ext; } } while (PathFileExists(fullpath.c_str())); } // Create empty file HANDLE hFile = CreateFile(fullpath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile); LeaveCriticalSection(&g_CriticalSection); } if (ready) { // Delete IE cache before download if "SyncMode5" is not 3 (every visit to the page) { // Check "Temporary Internet Files" sync mode (SyncMode5) // Values: // Every visit to the page 3 // Every time you start Internet Explorer 2 // Automatically (default) 4 // Never 0 // http://support.microsoft.com/kb/263070/en HKEY hKey; LONG ret; DWORD mode; ret = RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", 0, KEY_QUERY_VALUE, &hKey); if (ret == ERROR_SUCCESS) { DWORD size = sizeof(mode); ret = RegQueryValueEx(hKey, L"SyncMode5", nullptr, nullptr, (LPBYTE)&mode, &size); RegCloseKey(hKey); } if (ret != ERROR_SUCCESS || mode != 3) { std::wstring::size_type pos = url.find_first_of(L'#'); if (pos != std::wstring::npos) { DeleteUrlCacheEntry(url.substr(0, pos).c_str()); } else { DeleteUrlCacheEntry(url.c_str()); } } } RmLogF( measure->rm, LOG_DEBUG, L"WebParser: Downloading url '%s' to: %s", url.c_str(), fullpath.c_str()); HRESULT resultCoInitialize = CoInitialize(nullptr); // requires before calling URLDownloadToFile function // Download the file HRESULT result = URLDownloadToFile(nullptr, url.c_str(), fullpath.c_str(), 0, nullptr); if (result == S_OK) { EnterCriticalSection(&g_CriticalSection); if (!download) // cache mode { if (!measure->downloadedFile.empty()) { // Delete old downloaded file DeleteFile(measure->downloadedFile.c_str()); } } // Convert LFN to 8.3 filename if the path contains blank character if (fullpath.find_first_of(L' ') != std::wstring::npos) { DWORD size = GetShortPathName(fullpath.c_str(), buffer, MAX_PATH); if (size > 0 && size <= MAX_PATH) { fullpath = buffer; } } measure->downloadedFile = fullpath; LeaveCriticalSection(&g_CriticalSection); if (!measure->finishAction.empty()) { RmExecute(measure->skin, measure->finishAction.c_str()); } } else { ready = false; if (!download) // cache mode { // Delete empty file DeleteFile(fullpath.c_str()); } RmLogF( measure->rm, LOG_ERROR, L"WebParser: Download failed (res=0x%08X, COM=0x%08X): %s", result, resultCoInitialize, url.c_str()); if (!measure->onDownloadErrAction.empty()) { RmExecute(measure->skin, measure->onDownloadErrAction.c_str()); } } if (SUCCEEDED(resultCoInitialize)) { CoUninitialize(); } } else { RmLogF(measure->rm, LOG_ERROR, L"WebParser: Download failed: %s", url.c_str()); if (!measure->onDownloadErrAction.empty()) { RmExecute(measure->skin, measure->onDownloadErrAction.c_str()); } } } else { RmLog(measure->rm, LOG_ERROR, L"WebParser: Url is empty"); } if (!ready) // download failed { EnterCriticalSection(&g_CriticalSection); if (!download) // cache mode { if (!measure->downloadedFile.empty()) { // Delete old downloaded file DeleteFile(measure->downloadedFile.c_str()); } } // Clear old downloaded filename measure->downloadedFile.clear(); LeaveCriticalSection(&g_CriticalSection); } EnterCriticalSection(&g_CriticalSection); CloseHandle(measure->dlThreadHandle); measure->dlThreadHandle = 0; LeaveCriticalSection(&g_CriticalSection); return 0; // thread completed successfully }
bool UMPath::is_folder(const umstring& absolute_path) { std::wstring inpath = UMStringUtil::utf16_to_wstring(absolute_path); return !!PathIsDirectory(inpath.c_str()); }
//递归遍历文件夹 //pArchive: MPQ包指针 strDir:原资源目录 VecExt:扩展名集合 int CMpqPackGen::BrowseDirectory(TKPMArchive* pArchive,string &strDir,vector<string> &VecExt,bool IsPack) { int FileNum = 0; intptr_t ptrFile; struct _finddata_t file; string strFindTemp = ""; if ( strDir == "./" || strDir =="/" || strDir == "../" ) strFindTemp = strDir + "*.*"; else strFindTemp = strDir + "/*.*"; if ( strDir == "./" || strDir =="/" ) strDir = "."; if ( strDir == "../" ) strDir = ".."; bool bAddFileTag = false; if( (ptrFile = _findfirst( strFindTemp.c_str(), &file )) != -1L ) { while( _findnext( ptrFile, &file ) == 0 ) { if (file.name[0] == '.') continue; //忽略 _mbslwr((byte*)file.name); string FilePath = strDir + "/" + file.name; if( PathIsDirectory( FilePath.c_str() ) ) { //如果是目录,进入此目录进行递归 FileNum = FileNum + BrowseDirectory(pArchive,strDir+"/"+file.name,VecExt,IsPack); } else { //得到文件扩展名 string::size_type ExtPos = FilePath.find_last_of("."); string::size_type TmpPos = FilePath.find_last_of("/"); if ( ExtPos != string::npos ) { string Ext = FilePath.substr(ExtPos,FilePath.size()-ExtPos); if (Ext == ".exe") { // } string tmp = FilePath.substr(TmpPos+1,tmp.size()-TmpPos); //转为小写 if ( find(VecExt.begin(),VecExt.end(),Ext) != VecExt.end() || VecExt.at(0) == "*.*" || find(VecExt.begin(),VecExt.end(),tmp) != VecExt.end() ) { //指定KPM_FILE_IMPLODE/KPM_FILE_COMPRESS:表示使用压缩算法(同时指定速度较慢) //遇有已压缩的数据时,不要指定KPM_FILE_IMPLODE/KPM_FILE_COMPRESS //KPM_FILE_ENCRYPTED:表示加密 //KPM_FILE_REPLACEEXISTING:表示有同名文件时替换,有同名文件但未指定此参数,则返回错误 //FILE_TYPE_DATA:目前只支持两种格式:普通数据/WAVE数据,今后需扩展 DWORD Flags = KPM_FILE_COMPRESS; DWORD FileType = FILE_TYPE_DATA; if( ".wav" == Ext ) { FileType = FILE_TYPE_WAVE; } else if( ".mp3" == Ext || ".zip" == Ext || ".rar" == Ext || ".mpq" == Ext || ".jpg" == Ext || ".dds" == Ext ) { Flags &= ~KPM_FILE_COMPRESS; } else if( ".db" == Ext ) { continue; } FileNum++; if ( IsPack && pArchive ) { m_iFileNum++; if ( !m_bTestVersion ) { //最终的发行版不带路径信息 bAddFileTag = KPM_AddFile( pArchive, FilePath.c_str(), file.name, Flags, 0, FileType ); } else { //内部调试版带路径信息 bAddFileTag = KPM_AddFile( pArchive, FilePath.c_str(), FilePath.c_str(), Flags, 0, FileType ); } if( bAddFileTag ) { printf( "\n AddFile PackPath: %s", FilePath.c_str() ); fprintf( m_pGenLogFile, "%d: AddFile ( %s ) \n", m_iFileNum, FilePath.c_str() ); m_vFilePath.push_back( FilePath ); } else { string str = "无"; vector<string>::iterator it = m_vFilePath.begin(); for( ; it != m_vFilePath.end(); it++ ) { if( string::npos != (*it).find( file.name ) ) { str = (*it); break; } } fprintf( m_pErrorLogFile, "%d: Error ( %s 已经存在 %s ) \n", m_iFileNum, FilePath.c_str(), str.c_str() ); // assert(false); } } } } } }//while end //关闭查找句柄 _findclose( ptrFile ); }//if end return FileNum; }//BrowseDirectory end
UINT CPage6::AddDirectoryNodes(HTREEITEM hItem, CString &strPathName) { WCHAR wBuf[60]; DWORD bytesReturned=0; ULONG num=0; PDIRECTORY_INFO temp={0}; DIRECTORY_INFO_EX DIRECTORY_INFO_b; CString str,str1,strFileSpec = strPathName; if (strFileSpec.Right (1) != "\\") strFileSpec += "\\"; char a[MAX_PATH]; str1=strFileSpec; CMySystem::WCHARToChar(a,strFileSpec.GetBuffer(strFileSpec.GetLength())); strFileSpec += "*.*"; DeviceIoControl(hDevice,(DWORD)IOCTL_MT_GETDIRNUMINF,a,sizeof(a),&num,sizeof(ULONG),&bytesReturned,NULL); if(num==0) { AfxMessageBox(L"驱动未加载,列举出错!"); return 0; } temp=(PDIRECTORY_INFO)calloc(num,sizeof(DIRECTORY_INFO)); if(temp==NULL) { return 0; } DeviceIoControl(hDevice,(DWORD)IOCTL_MT_GETDIRINF,a,sizeof(a),temp,num*sizeof(DIRECTORY_INFO),&bytesReturned,NULL); CWaitCursor wait; WCHAR wTemp[MAX_PATH]={'\0'}; m_FileList.DeleteAllItems(); index=0; SetPath(str1,hDevice); for(ULONG i=0;i<num;i++) { TRACE("AddDirectoryNode:%d\n",i); CMySystem::CharToWCHAR(wTemp,temp[i].FileName); str.Format(L"%s",wTemp); str=str1+str; CString strFileName = (LPCTSTR) &temp[i].FileName; if(PathIsDirectory(str)) { if(strcmp(temp[i].FileName,".")) { if(strcmp(temp[i].FileName,"..")) { CMySystem::CharToWCHAR(wTemp,temp[i].FileName); HTREEITEM hChild = m_FileTree.InsertItem ((LPCTSTR) wTemp,//&fd.cFileName, ILI_CLSDFLD , ILI_OPENFLD , hItem , TVI_SORT); CString strNewPathName = strPathName; if (strNewPathName.Right (1) != "\\") {strNewPathName += "\\";} CMySystem::CharToWCHAR(wBuf,temp[i].FileName); strNewPathName += wBuf;//fd.cFileName; SetButtonState (hChild, strNewPathName); } } } else { DIRECTORY_INFO_b.DirectoryInfo=temp[i]; DIRECTORY_INFO_b.path=str1; AddToListView(&DIRECTORY_INFO_b); } } delete temp; return num; }
void CFcastWinDlg::OnBnClickedStart() { UpdateData(TRUE); if(m_TabCtrl.GetCurSel() == IDTAB_RECV) { if(!m_ValuePathRecv.IsEmpty() && PathFileExists(m_ValuePathRecv) && PathIsDirectory(m_ValuePathRecv)) { m_EditStatus.SetWindowText("Executing fcast " + m_FcastCmdLine + "\r\n(working dir: " + m_ValuePathRecv + ")."); ShellExecute(NULL, NULL, m_EXEFullPath + "\\fcast.exe", m_FcastCmdLine, m_ValuePathRecv, SW_SHOW ); } else { MessageBox("Invalid destination directory: " + m_ValuePathRecv, "Error", MB_OK+MB_ICONERROR); } } else if(m_TabCtrl.GetCurSel() == IDTAB_SEND) { if(!m_ValuePathSend.IsEmpty() && PathFileExists(m_ValuePathSend)) { CString PathSendFrom, ObjSendName; int ind2=-1; int ind; ObjSendName.Empty(); if(PathIsDirectory(m_ValuePathSend)) { if(m_ValuePathSend[m_ValuePathSend.GetLength()-1] == '\\') { m_ValuePathSend = m_ValuePathSend.Left(m_ValuePathSend.GetLength()-1); } ind = m_ValuePathSend.Find('\\', 0); while( ind != -1) { ind2 = ind; ind = m_ValuePathSend.Find('\\', ind2+1); } if(ind2>=0) { PathSendFrom = m_ValuePathSend.Left(ind2+1); if(ind2+1 < m_ValuePathSend.GetLength()) { ObjSendName = m_ValuePathSend.Right(m_ValuePathSend.GetLength() - ind2 - 1); } } else { PathSendFrom = m_ValuePathSend; ObjSendName = "."; } } else { ind = m_ValuePathSend.Find('\\', 0); while( ind != -1) { ind2 = ind; ind = m_ValuePathSend.Find('\\', ind2+1); } if(ind2>=0) { PathSendFrom = m_ValuePathSend.Left(ind2+1); if(ind2+1 < m_ValuePathSend.GetLength()) { ObjSendName = m_ValuePathSend.Right(m_ValuePathSend.GetLength() - ind2 - 1); } } else { PathSendFrom.Empty(); ObjSendName = m_ValuePathSend; } } m_EditStatus.SetWindowText("Executing fcast " + m_FcastCmdLine + " " + ObjSendName + "\r\n(working dir: " + PathSendFrom + ")."); ShellExecute(NULL, NULL, m_EXEFullPath + "\\fcast.exe", m_FcastCmdLine + " " + ObjSendName, PathSendFrom, SW_SHOW ); } else { MessageBox("No such file or directory: " + m_ValuePathSend, "Error", MB_OK+MB_ICONERROR); } } }
BOOL CFileTextLines::Load(const CString& sFilePath, int lengthHint /* = 0*/) { m_LineEndings = EOL_AUTOLINE; m_UnicodeType = CFileTextLines::AUTOTYPE; RemoveAll(); m_endings.clear(); if(lengthHint != 0) { Reserve(lengthHint); } if (PathIsDirectory(sFilePath)) { m_sErrorString.Format(IDS_ERR_FILE_NOTAFILE, (LPCTSTR)sFilePath); return FALSE; } if (!PathFileExists(sFilePath)) { //file does not exist, so just return SUCCESS return TRUE; } CAutoFile hFile = CreateFile(sFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if (!hFile) { SetErrorString(); return FALSE; } LARGE_INTEGER fsize; if (!GetFileSizeEx(hFile, &fsize)) { SetErrorString(); return false; } if (fsize.HighPart) { // file is way too big for us m_sErrorString.LoadString(IDS_ERR_FILE_TOOBIG); return FALSE; } // If new[] was done for type T delete[] must be called on a pointer of type T*, // otherwise the behavior is undefined. // +1 is to address possible truncation when integer division is done wchar_t* pFileBuf = new wchar_t[fsize.LowPart/sizeof(wchar_t) + 1]; DWORD dwReadBytes = 0; if (!ReadFile(hFile, pFileBuf, fsize.LowPart, &dwReadBytes, NULL)) { delete [] pFileBuf; SetErrorString(); return FALSE; } if (m_UnicodeType == CFileTextLines::AUTOTYPE) { m_UnicodeType = this->CheckUnicodeType(pFileBuf, dwReadBytes); } if (m_LineEndings == EOL_AUTOLINE) { m_LineEndings = CheckLineEndings(pFileBuf, min(10000, dwReadBytes)); } hFile.CloseHandle(); if (m_UnicodeType == CFileTextLines::BINARY) { m_sErrorString.Format(IDS_ERR_FILE_BINARY, (LPCTSTR)sFilePath); delete [] pFileBuf; return FALSE; } // we may have to convert the file content if ((m_UnicodeType == UTF8)||(m_UnicodeType == UTF8BOM)) { int ret = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pFileBuf, dwReadBytes, NULL, 0); wchar_t * pWideBuf = new wchar_t[ret]; int ret2 = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pFileBuf, dwReadBytes, pWideBuf, ret); if (ret2 == ret) { delete [] pFileBuf; pFileBuf = pWideBuf; dwReadBytes = ret2; } else delete [] pWideBuf; } else if (m_UnicodeType == ASCII) { int ret = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)pFileBuf, dwReadBytes, NULL, 0); wchar_t * pWideBuf = new wchar_t[ret]; int ret2 = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)pFileBuf, dwReadBytes, pWideBuf, ret); if (ret2 == ret) { delete [] pFileBuf; pFileBuf = pWideBuf; dwReadBytes = ret2; } else delete [] pWideBuf; } // fill in the lines into the array wchar_t * pTextBuf = pFileBuf; wchar_t * pLineStart = pFileBuf; if (m_UnicodeType == UNICODE_LE) { // UTF16 have two bytes per char dwReadBytes/=2; } if ((m_UnicodeType == UTF8BOM)||(m_UnicodeType == UNICODE_LE)) { // ignore the BOM ++pTextBuf; ++pLineStart; --dwReadBytes; } for (DWORD i = 0; i<dwReadBytes; ++i) { if (*pTextBuf == '\r') { if ((i + 1) < dwReadBytes) { if (*(pTextBuf+1) == '\n') { // crlf line ending CString line(pLineStart, (int)(pTextBuf-pLineStart)); Add(line, EOL_CRLF); pLineStart = pTextBuf+2; ++pTextBuf; ++i; } else { // cr line ending CString line(pLineStart, (int)(pTextBuf-pLineStart)); Add(line, EOL_CR); pLineStart =pTextBuf+1; } } } else if (*pTextBuf == '\n') { // lf line ending CString line(pLineStart, (int)(pTextBuf-pLineStart)); Add(line, EOL_LF); pLineStart =pTextBuf+1; } ++pTextBuf; } if (pLineStart < pTextBuf) { CString line(pLineStart, (int)(pTextBuf-pLineStart)); Add(line, EOL_NOENDING); m_bReturnAtEnd = false; } else m_bReturnAtEnd = true; delete [] pFileBuf; return TRUE; }
// // LoadLSIcon(LPCSTR pszIconPath, LPCSTR pszFile) // // Takes strings of the form: // File.ico // libary.icl,3 <- libary extraction in imagesfolder // c:\path\ <- icon extraction for path out of desktop.ini // .extract // .extract=file.exe[,3] ... and returns an icon HICON LoadLSIcon(LPCSTR pszIconPath, LPCSTR pszFile) { HICON hIcon = NULL; if (pszIconPath != NULL) { if (_stricmp(pszIconPath, ".none") != 0) { char szIconPath[MAX_PATH]; char szIconLSImagePath[MAX_PATH]; LPSTR pszIconFile = (LPSTR)pszIconPath; int nIcon = 0; // here comes a large block which does nothing but turning it into // the form <absolute path>[,<iconIndex>] // if .extract but nothing else is there... // then take the file specified as an icon (could probably be done // earlier, but anyhow) if (_stricmp(pszIconPath, ".extract") == 0) { pszIconFile = (LPSTR)pszFile; } else if (_strnicmp(pszIconPath, ".extract=", 9) == 0) { // remove ".extract=" (as we won't use it anyway) pszIconFile = (LPSTR)pszIconPath + 9; } VarExpansionEx(szIconPath, pszIconFile, MAX_PATH); if (PathIsRelative(szIconPath)) { LSGetImagePath(szIconLSImagePath, MAX_PATH); PathAppend(szIconLSImagePath, szIconPath); pszIconFile = szIconLSImagePath; } else { pszIconFile = szIconPath; } // large block ends here, now time to separate path and index (if we // have an index) nIcon = PathParseIconLocation(pszIconFile); // now we have the two vars we would like, and the loading can begin // well not really, if it's a path, where we're going to get the // icon form desktop.ini there is just a little bit more we have to // do before we can start loading if (PathIsDirectory(pszIconFile)) { char szTemp[MAX_PATH]; PathAppend(pszIconFile, "desktop.ini"); nIcon = GetPrivateProfileInt(".ShellClassInfo", "IconIndex", 0, pszIconFile); GetPrivateProfileString(".ShellClassInfo", "IconFile", "", szTemp, MAX_PATH, pszIconFile); StringCchCopy(pszIconFile, MAX_PATH, szTemp); } // okay, now it's really time to load the icon... if it's an .ico // file we want to do an LoadImage() thing, otherwise it's // extracticon so lets find out the extension if (PathMatchSpec(pszIconFile, "*.ico")) { hIcon = (HICON)LoadImage( NULL, pszIconFile, IMAGE_ICON, 0, 0, LR_LOADFROMFILE); } else { hIcon = ExtractIcon(GetModuleHandle(NULL), pszIconFile, nIcon); if (hIcon == (HICON)1) { hIcon = NULL; } } } } return hIcon; }
BOOL CFileTextLines::Save(const CString& sFilePath, bool bSaveAsUTF8, DWORD dwIgnoreWhitespaces /*=0*/, BOOL bIgnoreCase /*= FALSE*/, bool bBlame /*= false*/) { try { CString destPath = sFilePath; // now make sure that the destination directory exists int ind = 0; while (destPath.Find('\\', ind)>=2) { if (!PathIsDirectory(destPath.Left(destPath.Find('\\', ind)))) { if (!CreateDirectory(destPath.Left(destPath.Find('\\', ind)), NULL)) return FALSE; } ind = destPath.Find('\\', ind)+1; } CStdioFile file; // Hugely faster than CFile for big file writes - because it uses buffering if (!file.Open(sFilePath, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary)) { m_sErrorString.Format(IDS_ERR_FILE_OPEN, (LPCTSTR)sFilePath); return FALSE; } if ((!bSaveAsUTF8)&&(m_UnicodeType == CFileTextLines::UNICODE_LE)) { //first write the BOM UINT16 wBOM = 0xFEFF; file.Write(&wBOM, 2); for (int i=0; i<GetCount(); i++) { CString sLine = GetAt(i); EOL ending = GetLineEnding(i); StripWhiteSpace(sLine,dwIgnoreWhitespaces, bBlame); if (bIgnoreCase) sLine = sLine.MakeLower(); file.Write((LPCTSTR)sLine, sLine.GetLength()*sizeof(TCHAR)); if (ending == EOL_AUTOLINE) ending = m_LineEndings; switch (ending) { case EOL_CR: sLine = _T("\x0d"); break; case EOL_CRLF: case EOL_AUTOLINE: sLine = _T("\x0d\x0a"); break; case EOL_LF: sLine = _T("\x0a"); break; case EOL_LFCR: sLine = _T("\x0a\x0d"); break; default: sLine.Empty(); break; } if ((m_bReturnAtEnd)||(i != GetCount()-1)) file.Write((LPCTSTR)sLine, sLine.GetLength()*sizeof(TCHAR)); } } else if ((!bSaveAsUTF8)&&((m_UnicodeType == CFileTextLines::ASCII)||(m_UnicodeType == CFileTextLines::AUTOTYPE))) { for (int i=0; i< GetCount(); i++) { // Copy CString to 8 bit without conversion CString sLineT = GetAt(i); CStringA sLine = CStringA(sLineT); EOL ending = GetLineEnding(i); StripAsciiWhiteSpace(sLine,dwIgnoreWhitespaces, bBlame); if (bIgnoreCase) sLine = sLine.MakeLower(); if ((m_bReturnAtEnd)||(i != GetCount()-1)) { if (ending == EOL_AUTOLINE) ending = m_LineEndings; switch (ending) { case EOL_CR: sLine += '\x0d'; break; case EOL_CRLF: case EOL_AUTOLINE: sLine.Append("\x0d\x0a", 2); break; case EOL_LF: sLine += '\x0a'; break; case EOL_LFCR: sLine.Append("\x0a\x0d", 2); break; } } file.Write((LPCSTR)sLine, sLine.GetLength()); } } else if ((bSaveAsUTF8)||((m_UnicodeType == CFileTextLines::UTF8BOM)||(m_UnicodeType == CFileTextLines::UTF8))) { if (m_UnicodeType == CFileTextLines::UTF8BOM) { //first write the BOM UINT16 wBOM = 0xBBEF; file.Write(&wBOM, 2); UINT8 uBOM = 0xBF; file.Write(&uBOM, 1); } for (int i=0; i<GetCount(); i++) { CStringA sLine = CUnicodeUtils::GetUTF8(GetAt(i)); EOL ending = GetLineEnding(i); StripAsciiWhiteSpace(sLine,dwIgnoreWhitespaces, bBlame); if (bIgnoreCase) sLine = sLine.MakeLower(); if ((m_bReturnAtEnd)||(i != GetCount()-1)) { if (ending == EOL_AUTOLINE) ending = m_LineEndings; switch (ending) { case EOL_CR: sLine += '\x0d'; break; case EOL_CRLF: case EOL_AUTOLINE: sLine.Append("\x0d\x0a",2); break; case EOL_LF: sLine += '\x0a'; break; case EOL_LFCR: sLine.Append("\x0a\x0d",2); break; } } file.Write((LPCSTR)sLine, sLine.GetLength()); } } file.Close(); } catch (CException * e) { e->GetErrorMessage(m_sErrorString.GetBuffer(4096), 4096); m_sErrorString.ReleaseBuffer(); e->Delete(); return FALSE; } return TRUE; }
HRESULT _stdcall CContainer::CBookmarkToolbarDrop::DragEnter(IDataObject *pDataObject, DWORD grfKeyStat,POINTL pt,DWORD *pdwEffect) { FORMATETC ftc = {CF_HDROP,0,DVASPECT_CONTENT,-1,TYMED_HGLOBAL}; STGMEDIUM stg; DROPFILES *pdf = NULL; TCHAR szFullFileName[MAX_PATH]; HRESULT hr; BOOL bAllFolders = FALSE; int nDroppedFiles; int i = 0; /* Check whether the drop source has the type of data (CF_HDROP) that is needed for this drag operation. */ hr = pDataObject->GetData(&ftc,&stg); if(hr == S_OK) { bAllFolders = TRUE; pdf = (DROPFILES *)GlobalLock(stg.hGlobal); if(pdf != NULL) { /* Request a count of the number of files that have been dropped. */ nDroppedFiles = DragQueryFile((HDROP)pdf,0xFFFFFFFF,NULL,NULL); /* Only accept dropped folders, NOT files. */ for(i = 0;i < nDroppedFiles;i++) { /* Determine the name of the dropped file. */ DragQueryFile((HDROP)pdf,i,szFullFileName, SIZEOF_ARRAY(szFullFileName)); if(!PathIsDirectory(szFullFileName)) { bAllFolders = FALSE; break; } } GlobalUnlock(stg.hGlobal); } ReleaseStgMedium(&stg); } if(bAllFolders) { m_bAcceptData = TRUE; *pdwEffect = DROPEFFECT_COPY; } else { m_bAcceptData = FALSE; *pdwEffect = DROPEFFECT_NONE; } /* Notify the drop target helper that an object has been dragged into the window. */ m_pDropTargetHelper->DragEnter(m_pContainer->m_hBookmarksToolbar, pDataObject,(POINT *)&pt,*pdwEffect); return hr; }
//---------------------------------------------------------------------------- // Init STDMETHODIMP CAnchoAddon::Init(LPCOLESTR lpsExtensionID, IAnchoAddonService * pService, IWebBrowser2 * pWebBrowser) { m_pWebBrowser = pWebBrowser; m_pAnchoService = pService; m_sExtensionName = lpsExtensionID; // lookup ID in registry CRegKey regKey; CString sKey; sKey.Format(_T("%s\\%s"), s_AnchoExtensionsRegistryKey, m_sExtensionName); LONG res = regKey.Open(HKEY_CURRENT_USER, sKey, KEY_READ); if (ERROR_SUCCESS != res) { return HRESULT_FROM_WIN32(res); } // load flags to see if the addon is disabled DWORD flags = 0; res = regKey.QueryDWORDValue(s_AnchoExtensionsRegistryEntryFlags, flags); // to stay compatible with older versions we treat "no flags at all" as "enabled" if ( (ERROR_SUCCESS == res) && !(flags & ENABLED)) { // ... means: only when flag is present AND ENABLED is not set // the addon is disabled return E_ABORT; } // get addon GUID ULONG nChars = 37; // length of a GUID + terminator res = regKey.QueryStringValue(s_AnchoExtensionsRegistryEntryGUID, m_sExtensionID.GetBuffer(nChars), &nChars); m_sExtensionID.ReleaseBuffer(); if (ERROR_SUCCESS != res) { return HRESULT_FROM_WIN32(res); } // get addon path nChars = _MAX_PATH; LPTSTR pst = m_sExtensionPath.GetBuffer(nChars+1); res = regKey.QueryStringValue(s_AnchoExtensionsRegistryEntryPath, pst, &nChars); pst[nChars] = 0; PathAddBackslash(pst); m_sExtensionPath.ReleaseBuffer(); if (ERROR_SUCCESS != res) { return HRESULT_FROM_WIN32(res); } if (!PathIsDirectory(m_sExtensionPath)) { return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); } IF_FAILED_RET(CProtocolHandlerRegistrar:: RegisterTemporaryFolderHandler(s_AnchoProtocolHandlerScheme, m_sExtensionName, m_sExtensionPath)); // get addon instance //IF_FAILED_RET(m_pAnchoService->GetAddonBackground(CComBSTR(m_sExtensionName), &m_pAddonBackground)); // The addon can be a resource DLL or simply a folder in the filesystem. // TODO: Load the DLL if there is any. // create content script engine #ifdef MAGPIE_REGISTERED IF_FAILED_RET(m_Magpie.CoCreateInstance(CLSID_MagpieApplication)); #else CComBSTR bs; IF_FAILED_RET(m_pAnchoService->GetModulePath(&bs)); // Load magpie from the same path where this exe file is. CString s(bs); s += _T("Magpie.dll"); HMODULE hModMagpie = ::LoadLibrary(s); if (!hModMagpie) { return E_FAIL; } fnCreateMagpieInstance CreateMagpieInstance = (fnCreateMagpieInstance)::GetProcAddress(hModMagpie, "CreateMagpieInstance"); if (!CreateMagpieInstance) { return E_FAIL; } IF_FAILED_RET(CreateMagpieInstance(&m_Magpie)); #endif return S_OK; }
bool GitAdminDir::HasAdminDir(const CString& path,CString *ProjectTopDir) const { return HasAdminDir(path, !!PathIsDirectory(path),ProjectTopDir); }
STDMETHODIMP CShellExt::IsMemberOf(LPCWSTR pwszPath, DWORD /*dwAttrib*/) { PreserveChdir preserveChdir; git_wc_status_kind status = git_wc_status_none; bool readonlyoverlay = false; bool lockedoverlay = false; if (pwszPath == NULL) return S_FALSE; const TCHAR* pPath = pwszPath; // the shell sometimes asks overlays for invalid paths, e.g. for network // printers (in that case the path is "0", at least for me here). if (_tcslen(pPath)<2) return S_FALSE; // since the shell calls each and every overlay handler with the same filepath // we use a small 'fast' cache of just one path here. // To make sure that cache expires, clear it as soon as one handler is used. AutoLocker lock(g_csGlobalCOMGuard); if (_tcscmp(pPath, g_filepath.c_str())==0) { status = g_filestatus; readonlyoverlay = g_readonlyoverlay; lockedoverlay = g_lockedoverlay; } else { if (!g_ShellCache.IsPathAllowed(pPath)) { int drivenumber = -1; if ((m_State == FileStateVersioned) && g_ShellCache.ShowExcludedAsNormal() && ((drivenumber=PathGetDriveNumber(pPath))!=0)&&(drivenumber!=1) && PathIsDirectory(pPath) && g_ShellCache.HasSVNAdminDir(pPath, true)) { return S_OK; } return S_FALSE; } switch (g_ShellCache.GetCacheType()) { case ShellCache::exe: { CTGitPath tpath(pPath); if(!tpath.HasAdminDir()) { status = git_wc_status_none; break; } if(tpath.IsAdminDir()) { status = git_wc_status_none; break; } TSVNCacheResponse itemStatus; SecureZeroMemory(&itemStatus, sizeof(itemStatus)); if (m_remoteCacheLink.GetStatusFromRemoteCache(tpath, &itemStatus, true)) { status = GitStatus::GetMoreImportant(itemStatus.m_status.text_status, itemStatus.m_status.prop_status); /* if ((itemStatus.m_kind == git_node_file)&&(status == git_wc_status_normal)&&((itemStatus.m_needslock && itemStatus.m_owner[0]==0)||(itemStatus.m_readonly))) readonlyoverlay = true; if (itemStatus.m_owner[0]!=0) lockedoverlay = true;*/ } } break; case ShellCache::dll: case ShellCache::dllFull: { // Look in our caches for this item const FileStatusCacheEntry * s = m_CachedStatus.GetCachedItem(CTGitPath(pPath)); if (s) { status = s->status; } else { // No cached status available // since the dwAttrib param of the IsMemberOf() function does not // have the SFGAO_FOLDER flag set at all (it's 0 for files and folders!) // we have to check if the path is a folder ourselves :( if (PathIsDirectory(pPath)) { if (g_ShellCache.HasSVNAdminDir(pPath, TRUE)) { if ((!g_ShellCache.IsRecursive()) && (!g_ShellCache.IsFolderOverlay())) { status = git_wc_status_normal; } else { const FileStatusCacheEntry * s = m_CachedStatus.GetFullStatus(CTGitPath(pPath), TRUE); status = s->status; // GitFolderStatus does not list unversioned files/dir so they would always end up as normal below // so let's assume file/dir is unversioned if not found in cache /*// sub-dirs that are empty (or contain no versioned files) are reported as unversioned (and should be kept as such) if (status != git_wc_status_unversioned) { // if get status fails then display status as 'normal' on folder (since it contains .git) // TODO: works for svn since each folder has .svn, not sure if git needs additinoal processing status = GitStatus::GetMoreImportant(git_wc_status_normal, status); }*/ } } else { status = git_wc_status_none; } } else { const FileStatusCacheEntry * s = m_CachedStatus.GetFullStatus(CTGitPath(pPath), FALSE); status = s->status; } } #if 0 if ((s)&&(status == git_wc_status_normal)&&(s->needslock)&&(s->owner[0]==0)) readonlyoverlay = true; if ((s)&&(s->owner[0]!=0)) lockedoverlay = true; #endif } break; default: case ShellCache::none: { // no cache means we only show a 'versioned' overlay on folders // with an admin directory if (PathIsDirectory(pPath)) { if (g_ShellCache.HasSVNAdminDir(pPath, TRUE)) { status = git_wc_status_normal; } else { status = git_wc_status_none; } } else { status = git_wc_status_none; } } break; } ATLTRACE(_T("Status %d for file %s\n"), status, pwszPath); } g_filepath.clear(); g_filepath = pPath; g_filestatus = status; g_readonlyoverlay = readonlyoverlay; g_lockedoverlay = lockedoverlay; //the priority system of the shell doesn't seem to work as expected (or as I expected): //as it seems that if one handler returns S_OK then that handler is used, no matter //if other handlers would return S_OK too (they're never called on my machine!) //So we return S_OK for ONLY ONE handler! switch (status) { // note: we can show other overlays if due to lack of enough free overlay // slots some of our overlays aren't loaded. But we assume that // at least the 'normal' and 'modified' overlay are available. case git_wc_status_none: return S_FALSE; case git_wc_status_unversioned: if (g_ShellCache.ShowUnversionedOverlay() && g_unversionedovlloaded && (m_State == FileStateUnversionedOverlay)) { g_filepath.clear(); return S_OK; } return S_FALSE; case git_wc_status_ignored: if (g_ShellCache.ShowIgnoredOverlay() && g_ignoredovlloaded && (m_State == FileStateIgnoredOverlay)) { g_filepath.clear(); return S_OK; } return S_FALSE; case git_wc_status_normal: case git_wc_status_external: case git_wc_status_incomplete: if ((readonlyoverlay)&&(g_readonlyovlloaded)) { if (m_State == FileStateReadOnly) { g_filepath.clear(); return S_OK; } else return S_FALSE; } else if ((lockedoverlay)&&(g_lockedovlloaded)) { if (m_State == FileStateLockedOverlay) { g_filepath.clear(); return S_OK; } else return S_FALSE; } else if (m_State == FileStateVersioned) { g_filepath.clear(); return S_OK; } else return S_FALSE; case git_wc_status_missing: case git_wc_status_deleted: if (g_deletedovlloaded) { if (m_State == FileStateDeleted) { g_filepath.clear(); return S_OK; } else return S_FALSE; } else { // the 'deleted' overlay isn't available (due to lack of enough // overlay slots). So just show the 'modified' overlay instead. if (m_State == FileStateModified) { g_filepath.clear(); return S_OK; } else return S_FALSE; } case git_wc_status_replaced: case git_wc_status_modified: if (m_State == FileStateModified) { g_filepath.clear(); return S_OK; } else return S_FALSE; case git_wc_status_merged: if (m_State == FileStateReadOnly) { g_filepath.clear(); return S_OK; } else return S_FALSE; case git_wc_status_added: if (g_addedovlloaded) { if (m_State== FileStateAddedOverlay) { g_filepath.clear(); return S_OK; } else return S_FALSE; } else { // the 'added' overlay isn't available (due to lack of enough // overlay slots). So just show the 'modified' overlay instead. if (m_State == FileStateModified) { g_filepath.clear(); return S_OK; } else return S_FALSE; } case git_wc_status_conflicted: case git_wc_status_obstructed: if (g_conflictedovlloaded) { if (m_State == FileStateConflict) { g_filepath.clear(); return S_OK; } else return S_FALSE; } else { // the 'conflicted' overlay isn't available (due to lack of enough // overlay slots). So just show the 'modified' overlay instead. if (m_State == FileStateModified) { g_filepath.clear(); return S_OK; } else return S_FALSE; } default: return S_FALSE; } // switch (status) //return S_FALSE; }
BOOL CSettingGitConfig::OnInitDialog() { ISettingsPropPage::OnInitDialog(); m_cSafeCrLf.AddString(_T("false")); m_cSafeCrLf.AddString(_T("true")); m_cSafeCrLf.AddString(_T("warn")); m_UserName = g_Git.GetUserName(); m_UserEmail = g_Git.GetUserEmail(); m_UserSigningKey = g_Git.GetConfigValue(_T("user.signingkey")); m_bAutoCrlf = g_Git.GetConfigValueBool(_T("core.autocrlf")); bool bSafeCrLf = g_Git.GetConfigValueBool(_T("core.safecrlf")); if (bSafeCrLf) m_cSafeCrLf.SetCurSel(1); else { CString sSafeCrLf = g_Git.GetConfigValue(_T("core.safecrlf")); sSafeCrLf = sSafeCrLf.MakeLower().Trim(); if (sSafeCrLf == _T("warn")) m_cSafeCrLf.SetCurSel(2); else m_cSafeCrLf.SetCurSel(0); } CString str = ((CSettings*)GetParent())->m_CmdPath.GetWinPath(); bool isBareRepo = g_GitAdminDir.IsBareRepo(str); CString proj; if (g_GitAdminDir.HasAdminDir(str, &proj) || isBareRepo) { CString title; this->GetWindowText(title); this->SetWindowText(title + _T(" - ") + proj); this->GetDlgItem(IDC_CHECK_GLOBAL)->EnableWindow(TRUE); this->GetDlgItem(IDC_EDITLOCALGITCONFIG)->EnableWindow(TRUE); ProjectProperties props; props.ReadProps(proj); m_bWarnNoSignedOffBy = props.bWarnNoSignedOffBy; } else { m_bGlobal = TRUE; this->GetDlgItem(IDC_CHECK_GLOBAL)->EnableWindow(FALSE); this->GetDlgItem(IDC_EDITLOCALGITCONFIG)->EnableWindow(FALSE); m_bWarnNoSignedOffBy = g_Git.GetConfigValueBool(_T("tgit.warnnosignedoffby")); } if (isBareRepo) this->GetDlgItem(IDC_EDITLOCALGITCONFIG)->SetWindowText(CString(MAKEINTRESOURCE(IDS_PROC_GITCONFIG_EDITLOCALGONCFIG))); if (!CAppUtils::IsAdminLogin()) { ((CButton *)this->GetDlgItem(IDC_EDITSYSTEMGITCONFIG))->SetShield(TRUE); this->GetDlgItem(IDC_VIEWSYSTEMGITCONFIG)->ShowWindow(SW_SHOW); } if (PathIsDirectory(g_Git.GetGitGlobalXDGConfigPath())) this->GetDlgItem(IDC_EDITGLOBALXDGGITCONFIG)->ShowWindow(SW_SHOW); this->UpdateData(FALSE); return TRUE; }
/////////////////////////////////////////////////////////// //功能: 压缩指定文件或文件夹 /////////////////////////////////////////////////////////// DWORD Compress(char* szInFilePath,char* szOutCabPath,char* pkey) { CCompress i_Compress; //压缩后的文件cab路径 if(szOutCabPath == NULL) { OutputDebugString("Compress ERROR: Output file name can not be NULL!"); return 2; } //设置加密KEY if(pkey != NULL) { i_Compress.SetEncryptionKey(pkey, (DWORD)strlen(pkey)); } else { #ifdef ENCRYPE_VERSION i_Compress.SetEncryptionKey("HYResources", (DWORD)strlen("HYResources")); #endif } //单字符串转换为宽字符串 szOutCabPath int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szOutCabPath, -1, NULL, 0 ); wchar_t* szOutCabPathW = new wchar_t[nLen+1]; MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szOutCabPath, -1, szOutCabPathW, nLen ); //初始化 if(!i_Compress.CreateFCIContextW(szOutCabPathW)) { OutputDebugString("Compress ERROR: Could not create FCI context!"); return 3; } //单字符串转换为宽字符串 szInFilePath nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szInFilePath, -1, NULL, 0 ); wchar_t* szInFilePathW = new wchar_t[nLen+1]; MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szInFilePath, -1, szInFilePathW, nLen ); //开始压缩 //要压缩的文件夹或文件夹 if(PathIsDirectory(szInFilePath)) { if (!i_Compress.AddFolderW(szInFilePathW)) { OutputDebugString("Compress ERROR:AddFolder fail!\n"); return 4; } } else { wchar_t * wpNameInCab= wcsrchr(szInFilePathW,'\\'); if(wpNameInCab != NULL) wpNameInCab++; if(!i_Compress.AddFileW(szInFilePathW,wpNameInCab)) { OutputDebugString("Compress ERROR:AddFile fail!\n"); return 4; } } //释放资源 if (!i_Compress.DestroyFCIContext()) { OutputDebugString("Compress ERROR: Could not flush Cabinet!\n"); return 5; } delete [] szInFilePathW; delete [] szOutCabPathW; return 0; }